context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// Mono.System.Xml.XmlAttribute
//
// Authors:
// Jason Diamond ([email protected])
// Atsushi Enomoto ([email protected])
//
// (C) 2002 Jason Diamond http://injektilo.org/
// (C) 2003 Atsushi Enomoto
//
//
// 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 Mono.System.Xml.XPath;
using Mono.Xml;
#if NET_2_0
using Mono.System.Xml.Schema;
#endif
namespace Mono.System.Xml
{
public class XmlAttribute : XmlNode, IHasXmlChildNode
{
#region Fields
private XmlNameEntry name;
internal bool isDefault;
XmlLinkedNode lastLinkedChild;
#if NET_2_0
private IXmlSchemaInfo schemaInfo;
#endif
#endregion
#region Constructor
protected internal XmlAttribute (
string prefix,
string localName,
string namespaceURI,
XmlDocument doc) : this (prefix, localName, namespaceURI, doc, false, true)
{
}
internal XmlAttribute (
string prefix,
string localName,
string namespaceURI,
XmlDocument doc,
bool atomizedNames, bool checkNamespace) : base (doc)
{
if (!atomizedNames) {
if (prefix == null)
prefix = String.Empty;
if (namespaceURI == null)
namespaceURI = String.Empty;
}
// Prefix "xml" should be also checked (http://www.w3.org/XML/xml-names-19990114-errata#NE05)
// but MS.NET ignores such case
if (checkNamespace) {
if (prefix == "xmlns" || (prefix == "" && localName == "xmlns"))
if (namespaceURI != XmlNamespaceManager.XmlnsXmlns)
throw new ArgumentException ("Invalid attribute namespace for namespace declaration.");
else if (prefix == "xml" && namespaceURI != XmlNamespaceManager.XmlnsXml)
throw new ArgumentException ("Invalid attribute namespace for namespace declaration.");
}
if (!atomizedNames) {
// There are no means to identify the DOM is
// namespace-aware or not, so we can only
// check Name validity.
if (prefix != "" && !XmlChar.IsName (prefix))
throw new ArgumentException ("Invalid attribute prefix.");
else if (!XmlChar.IsName (localName))
throw new ArgumentException ("Invalid attribute local name.");
prefix = doc.NameTable.Add (prefix);
localName = doc.NameTable.Add (localName);
namespaceURI = doc.NameTable.Add (namespaceURI);
}
name = doc.NameCache.Add (prefix, localName, namespaceURI, true);
}
#endregion
#region Properties
XmlLinkedNode IHasXmlChildNode.LastLinkedChild {
get { return lastLinkedChild; }
set { lastLinkedChild = value; }
}
public override string BaseURI {
get { return OwnerElement != null ? OwnerElement.BaseURI : String.Empty; }
}
public override string InnerText {
set {
Value = value;
}
}
public override string InnerXml {
set {
RemoveAll ();
XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
XmlParserContext ctx = new XmlParserContext (OwnerDocument.NameTable, nsmgr,
OwnerDocument.DocumentType != null ? OwnerDocument.DocumentType.DTD : null,
BaseURI, XmlLang, XmlSpace, null);
XmlTextReader xtr = new XmlTextReader (value, XmlNodeType.Attribute, ctx);
xtr.XmlResolver = OwnerDocument.Resolver;
xtr.Read ();
OwnerDocument.ReadAttributeNodeValue (xtr, this);
}
}
public override string LocalName {
get {
return name.LocalName;
}
}
public override string Name {
get { return name.GetPrefixedName (OwnerDocument.NameCache); }
}
public override string NamespaceURI {
get {
return name.NS;
}
}
public override XmlNodeType NodeType {
get {
return XmlNodeType.Attribute;
}
}
internal override XPathNodeType XPathNodeType {
get {
return XPathNodeType.Attribute;
}
}
public override XmlDocument OwnerDocument {
get {
return base.OwnerDocument;
}
}
public virtual XmlElement OwnerElement {
get { return AttributeOwnerElement; }
}
public override XmlNode ParentNode {
get {
// It always returns null (by specification).
return null;
}
}
// We gotta do more in the set block here
// We need to do the proper tests and throw
// the correct Exceptions
//
// Wrong cases are: (1)check readonly, (2)check character validity,
// (3)check format validity, (4)this is attribute and qualifiedName != "xmlns"
public override string Prefix {
set {
if (IsReadOnly)
throw new XmlException ("This node is readonly.");
if (name.Prefix == "xmlns" && value != "xmlns")
throw new ArgumentException ("Cannot bind to the reserved namespace.");
value = OwnerDocument.NameTable.Add (value);
name = OwnerDocument.NameCache.Add (value,
name.LocalName, name.NS, true);
}
get {
return name.Prefix;
}
}
#if NET_2_0
public override IXmlSchemaInfo SchemaInfo {
get { return schemaInfo; }
internal set { schemaInfo = value; }
}
#endif
public virtual bool Specified {
get {
return !isDefault;
}
}
public override string Value {
get { return InnerText; }
set {
if (this.IsReadOnly)
throw new ArgumentException ("Attempt to modify a read-only node.");
OwnerDocument.CheckIdTableUpdate (this, InnerText, value);
XmlNode textChild = FirstChild as XmlCharacterData;
if (textChild == null) {
this.RemoveAll ();
AppendChild (OwnerDocument.CreateTextNode (value), false);
}
else if (FirstChild.NextSibling != null) {
this.RemoveAll ();
AppendChild (OwnerDocument.CreateTextNode (value), false);
}
else
textChild.Value = value;
isDefault = false;
}
}
internal override string XmlLang {
get { return OwnerElement != null ? OwnerElement.XmlLang : String.Empty; }
}
internal override XmlSpace XmlSpace {
get { return OwnerElement != null ? OwnerElement.XmlSpace : XmlSpace.None; }
}
#endregion
#region Methods
#if NET_2_0
public override XmlNode AppendChild (XmlNode newChild)
{
return base.AppendChild (newChild);
}
public override XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
{
return base.InsertBefore (newChild, refChild);
}
public override XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
{
return base.InsertAfter (newChild, refChild);
}
public override XmlNode PrependChild (XmlNode newChild)
{
return base.PrependChild (newChild);
}
public override XmlNode RemoveChild (XmlNode oldChild)
{
return base.RemoveChild (oldChild);
}
public override XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
{
return base.ReplaceChild (newChild, oldChild);
}
#endif
public override XmlNode CloneNode (bool deep)
{
XmlNode node = OwnerDocument.CreateAttribute (name.Prefix, name.LocalName, name.NS, true, false);
if (deep) {
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
node.AppendChild (n.CloneNode (deep), false);
}
return node;
}
internal void SetDefault ()
{
isDefault = true;
}
public override void WriteContentTo (XmlWriter w)
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
n.WriteTo (w);
}
public override void WriteTo (XmlWriter w)
{
if (isDefault)
return; // Write nothing.
w.WriteStartAttribute (name.NS.Length > 0 ? name.Prefix : String.Empty, name.LocalName, name.NS);
WriteContentTo (w);
w.WriteEndAttribute ();
}
internal DTDAttributeDefinition GetAttributeDefinition ()
{
if (OwnerElement == null)
return null;
// If it is default, then directly create new attribute.
DTDAttListDeclaration attList = OwnerDocument.DocumentType != null ? OwnerDocument.DocumentType.DTD.AttListDecls [OwnerElement.Name] : null;
return attList != null ? attList [Name] : null;
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ratings/ratings_events.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace KillrVideo.Ratings.Events {
/// <summary>Holder for reflection information generated from ratings/ratings_events.proto</summary>
public static partial class RatingsEventsReflection {
#region Descriptor
/// <summary>File descriptor for ratings/ratings_events.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RatingsEventsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChxyYXRpbmdzL3JhdGluZ3NfZXZlbnRzLnByb3RvEhlraWxscnZpZGVvLnJh",
"dGluZ3MuZXZlbnRzGhljb21tb24vY29tbW9uX3R5cGVzLnByb3RvGh9nb29n",
"bGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvIqsBCg5Vc2VyUmF0ZWRWaWRl",
"bxIpCgh2aWRlb19pZBgBIAEoCzIXLmtpbGxydmlkZW8uY29tbW9uLlV1aWQS",
"KAoHdXNlcl9pZBgCIAEoCzIXLmtpbGxydmlkZW8uY29tbW9uLlV1aWQSDgoG",
"cmF0aW5nGAMgASgFEjQKEHJhdGluZ190aW1lc3RhbXAYBCABKAsyGi5nb29n",
"bGUucHJvdG9idWYuVGltZXN0YW1wQhyqAhlLaWxsclZpZGVvLlJhdGluZ3Mu",
"RXZlbnRzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::KillrVideo.Protobuf.CommonTypesReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Ratings.Events.UserRatedVideo), global::KillrVideo.Ratings.Events.UserRatedVideo.Parser, new[]{ "VideoId", "UserId", "Rating", "RatingTimestamp" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Event published when a user rates a video
/// </summary>
public sealed partial class UserRatedVideo : pb::IMessage<UserRatedVideo> {
private static readonly pb::MessageParser<UserRatedVideo> _parser = new pb::MessageParser<UserRatedVideo>(() => new UserRatedVideo());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UserRatedVideo> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Ratings.Events.RatingsEventsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UserRatedVideo() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UserRatedVideo(UserRatedVideo other) : this() {
VideoId = other.videoId_ != null ? other.VideoId.Clone() : null;
UserId = other.userId_ != null ? other.UserId.Clone() : null;
rating_ = other.rating_;
RatingTimestamp = other.ratingTimestamp_ != null ? other.RatingTimestamp.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UserRatedVideo Clone() {
return new UserRatedVideo(this);
}
/// <summary>Field number for the "video_id" field.</summary>
public const int VideoIdFieldNumber = 1;
private global::KillrVideo.Protobuf.Uuid videoId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::KillrVideo.Protobuf.Uuid VideoId {
get { return videoId_; }
set {
videoId_ = value;
}
}
/// <summary>Field number for the "user_id" field.</summary>
public const int UserIdFieldNumber = 2;
private global::KillrVideo.Protobuf.Uuid userId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::KillrVideo.Protobuf.Uuid UserId {
get { return userId_; }
set {
userId_ = value;
}
}
/// <summary>Field number for the "rating" field.</summary>
public const int RatingFieldNumber = 3;
private int rating_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Rating {
get { return rating_; }
set {
rating_ = value;
}
}
/// <summary>Field number for the "rating_timestamp" field.</summary>
public const int RatingTimestampFieldNumber = 4;
private global::Google.Protobuf.WellKnownTypes.Timestamp ratingTimestamp_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp RatingTimestamp {
get { return ratingTimestamp_; }
set {
ratingTimestamp_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UserRatedVideo);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UserRatedVideo other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(VideoId, other.VideoId)) return false;
if (!object.Equals(UserId, other.UserId)) return false;
if (Rating != other.Rating) return false;
if (!object.Equals(RatingTimestamp, other.RatingTimestamp)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (videoId_ != null) hash ^= VideoId.GetHashCode();
if (userId_ != null) hash ^= UserId.GetHashCode();
if (Rating != 0) hash ^= Rating.GetHashCode();
if (ratingTimestamp_ != null) hash ^= RatingTimestamp.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (videoId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(VideoId);
}
if (userId_ != null) {
output.WriteRawTag(18);
output.WriteMessage(UserId);
}
if (Rating != 0) {
output.WriteRawTag(24);
output.WriteInt32(Rating);
}
if (ratingTimestamp_ != null) {
output.WriteRawTag(34);
output.WriteMessage(RatingTimestamp);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (videoId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VideoId);
}
if (userId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UserId);
}
if (Rating != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Rating);
}
if (ratingTimestamp_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RatingTimestamp);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UserRatedVideo other) {
if (other == null) {
return;
}
if (other.videoId_ != null) {
if (videoId_ == null) {
videoId_ = new global::KillrVideo.Protobuf.Uuid();
}
VideoId.MergeFrom(other.VideoId);
}
if (other.userId_ != null) {
if (userId_ == null) {
userId_ = new global::KillrVideo.Protobuf.Uuid();
}
UserId.MergeFrom(other.UserId);
}
if (other.Rating != 0) {
Rating = other.Rating;
}
if (other.ratingTimestamp_ != null) {
if (ratingTimestamp_ == null) {
ratingTimestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
RatingTimestamp.MergeFrom(other.RatingTimestamp);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (videoId_ == null) {
videoId_ = new global::KillrVideo.Protobuf.Uuid();
}
input.ReadMessage(videoId_);
break;
}
case 18: {
if (userId_ == null) {
userId_ = new global::KillrVideo.Protobuf.Uuid();
}
input.ReadMessage(userId_);
break;
}
case 24: {
Rating = input.ReadInt32();
break;
}
case 34: {
if (ratingTimestamp_ == null) {
ratingTimestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(ratingTimestamp_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Text;
using Xunit;
using Infrastructure.Common;
public class Https_ClientCredentialTypeTests : ConditionalWcfTest
{
private static string s_username;
private static string s_password;
private const string BasicUsernameHeaderName = "BasicUsername";
private const string BasicPasswordHeaderName = "BasicPassword";
static Https_ClientCredentialTypeTests()
{
s_username = TestProperties.GetProperty(TestProperties.ExplicitUserName_PropertyName);
s_password = TestProperties.GetProperty(TestProperties.ExplicitPassword_PropertyName);
}
[WcfFact]
[Condition(nameof(Root_Certificate_Installed))]
[Issue(3572, OS = OSID.OSX_10_14)]
[Issue(2561, OS = OSID.SLES_12)] // Active Issue - needs investigation
[OuterLoop]
public static void BasicAuthentication_RoundTrips_Echo()
{
BasicHttpBinding basicHttpBinding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfCustomUserNameService> factory = null;
string username = null;
string password = null;
IWcfCustomUserNameService serviceProxy = null;
string testString = null;
string result = null;
try
{
// *** SETUP *** \\
basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
endpointAddress = new EndpointAddress(Endpoints.Https_BasicAuth_Address);
factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, endpointAddress);
username = Guid.NewGuid().ToString("n").Substring(0, 8);
password = Guid.NewGuid().ToString("n").Substring(0, 16);
factory.Credentials.UserName.UserName = username;
factory.Credentials.UserName.Password = password;
serviceProxy = factory.CreateChannel();
testString = "I am a test";
// *** EXECUTE *** \\
using (var scope = new OperationContextScope((IContextChannel)serviceProxy))
{
HttpRequestMessageProperty requestMessageProperty;
if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
{
requestMessageProperty = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessageProperty;
}
else
{
requestMessageProperty = (HttpRequestMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name];
}
requestMessageProperty.Headers[BasicUsernameHeaderName] = username;
requestMessageProperty.Headers[BasicPasswordHeaderName] = password;
result = serviceProxy.Echo(testString);
}
// *** VALIDATE *** \\
Assert.True(String.Equals(result, testString),
String.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'\nError: expected response from service: '{2}' Actual was: '{3}'",
"BasicAuthentication_RoundTrips_Echo",
Endpoints.Https_BasicAuth_Address,
testString,
result));
// *** CLEANUP *** \\
factory.Close();
((ICommunicationObject)serviceProxy).Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Root_Certificate_Installed))]
[Issue(3572, OS = OSID.OSX_10_14)]
[Issue(2561, OS = OSID.SLES_12)] // Active Issue - needs investigation
[OuterLoop]
public static void BasicAuthenticationInvalidPwd_throw_MessageSecurityException()
{
BasicHttpBinding basicHttpBinding = null;
ChannelFactory<IWcfCustomUserNameService> factory = null;
EndpointAddress endpointAddress = null;
string username = null;
string password = null;
IWcfCustomUserNameService serviceProxy = null;
string testString = null;
// Will need to use localized string once it is available
// On Native retail, the message is stripped to 'HttpAuthorizationForbidden, Basic'
// On Debug or .Net Core, the entire message is "The HTTP request was forbidden with client authentication scheme 'Basic'."
// Thus we will only check message contains "forbidden"
string message = "forbidden";
// *** VALIDATE *** \\
MessageSecurityException exception = Assert.Throws<MessageSecurityException>(() =>
{
// *** SETUP *** \\
basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
endpointAddress = new EndpointAddress(Endpoints.Https_BasicAuth_Address);
factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, endpointAddress);
username = Guid.NewGuid().ToString("n").Substring(0, 8);
password = Guid.NewGuid().ToString("n").Substring(0, 16);
factory.Credentials.UserName.UserName = username;
factory.Credentials.UserName.Password = password + "Invalid";
serviceProxy = factory.CreateChannel();
testString = "I am a test";
// *** EXECUTE *** \\
using (var scope = new OperationContextScope((IContextChannel)serviceProxy))
{
HttpRequestMessageProperty requestMessageProperty;
if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
{
requestMessageProperty = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessageProperty;
}
else
{
requestMessageProperty = (HttpRequestMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name];
}
requestMessageProperty.Headers[BasicUsernameHeaderName] = username;
requestMessageProperty.Headers[BasicPasswordHeaderName] = password;
try
{
string result = serviceProxy.Echo(testString);
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
});
// *** ADDITIONAL VALIDATION *** \\
Assert.True(exception.Message.ToLower().Contains(message), string.Format("Expected exception message to contain: '{0}', actual message is: '{1}'", message, exception.Message));
}
[WcfFact]
[Condition(nameof(Root_Certificate_Installed))]
[OuterLoop]
public static void BasicAuthenticationEmptyUser_throw_ArgumentException()
{
BasicHttpBinding basicHttpBinding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfCustomUserNameService> factory = null;
IWcfCustomUserNameService serviceProxy = null;
string testString = null;
string paraMessage = "username";
ArgumentException exception = Assert.Throws<ArgumentException>(() =>
{
// *** SETUP *** \\
basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
endpointAddress = new EndpointAddress(Endpoints.Https_BasicAuth_Address);
factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, endpointAddress);
factory.Credentials.UserName.UserName = "";
factory.Credentials.UserName.Password = "NoUserName";
serviceProxy = factory.CreateChannel();
testString = "I am a test";
// *** EXECUTE *** \\
try
{
string result = serviceProxy.Echo(testString);
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
});
Assert.True(exception.Message.ToLower().Contains(paraMessage), string.Format("Expected exception message to contain: '{0}', actual: '{1}'", paraMessage, exception.Message));
}
[WcfFact]
[Condition(nameof(Server_Domain_Joined),
nameof(Root_Certificate_Installed),
nameof(Digest_Authentication_Available),
nameof(Explicit_Credentials_Available))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "ExplicitUserName"
// "ExplicitPassword"
public static void DigestAuthentication_RoundTrips_Echo()
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
Action<ChannelFactory> credentials = (factory) =>
{
factory.Credentials.HttpDigest.ClientCredential.UserName = s_username;
factory.Credentials.HttpDigest.ClientCredential.Password = s_password;
};
ScenarioTestHelpers.RunBasicEchoTest(basicHttpBinding, Endpoints.Https_DigestAuth_Address, "BasicHttpBinding - Digest auth ", credentials);
}
[WcfFact]
[Condition(nameof(NTLM_Available), nameof(Root_Certificate_Installed))]
[OuterLoop]
public static void NtlmAuthentication_RoundTrips_Echo()
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
ScenarioTestHelpers.RunBasicEchoTest(basicHttpBinding, Endpoints.Https_NtlmAuth_Address, "BasicHttpBinding with NTLM authentication", null);
}
[WcfFact]
[Condition(nameof(NTLM_Available), nameof(Root_Certificate_Installed))]
[OuterLoop]
public static void IntegratedWindowsAuthentication_Ntlm_RoundTrips_Echo()
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var binding = new CustomBinding(basicHttpBinding);
var htbe = binding.Elements.Find<HttpsTransportBindingElement>();
htbe.AuthenticationScheme = System.Net.AuthenticationSchemes.IntegratedWindowsAuthentication;
ScenarioTestHelpers.RunBasicEchoTest(binding, Endpoints.Https_NtlmAuth_Address, "BasicHttpBinding with IntegratedWindowsAuthentication authentication and Ntlm endpoint", null);
}
}
| |
using NBitcoin;
using System;
using System.Threading.Tasks;
using System.Linq;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionBuilding;
using WalletWasabi.Tests.UnitTests.Clients;
using WalletWasabi.WebClients.PayJoin;
using Xunit;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Collections.Specialized;
using WalletWasabi.Tests.Helpers;
namespace WalletWasabi.Tests.UnitTests.Transactions
{
public class PayjoinTests
{
public static PSBT GenerateRandomTransaction()
{
var key = new Key();
var tx =
Network.Main.CreateTransactionBuilder()
.AddCoins(Coin(0.5m, key.PubKey.WitHash.ScriptPubKey))
.AddKeys(key)
.Send(BitcoinFactory.CreateScript(), Money.Coins(0.5m))
.BuildPSBT(true);
tx.Finalize();
return tx;
}
private static ICoin Coin(decimal amount, Script scriptPubKey)
{
return new Coin(GetRandomOutPoint(), new TxOut(Money.Coins(amount), scriptPubKey));
}
private static OutPoint GetRandomOutPoint()
{
return new OutPoint(RandomUtils.GetUInt256(), 0);
}
private static Func<HttpMethod, string, NameValueCollection, string, Task<HttpResponseMessage>> PayjoinServerOk(Func<PSBT, PSBT> transformPsbt, HttpStatusCode statusCode = HttpStatusCode.OK)
=> new Func<HttpMethod, string, NameValueCollection, string, Task<HttpResponseMessage>>((method, path, parameters, requestBody) =>
{
var psbt = PSBT.Parse(requestBody, Network.Main);
var newPsbt = transformPsbt(psbt);
var message = new HttpResponseMessage(statusCode);
message.Content = new StringContent(newPsbt.ToHex(), Encoding.UTF8, "text/plain");
return Task.FromResult(message);
});
private static Func<HttpMethod, string, NameValueCollection, string, Task<HttpResponseMessage>> PayjoinServerError(HttpStatusCode statusCode, string errorCode, string description = "")
=> new Func<HttpMethod, string, NameValueCollection, string, Task<HttpResponseMessage>>((method, path, parameters, requestBody) =>
{
var message = new HttpResponseMessage(statusCode);
message.ReasonPhrase = "";
message.Content = new StringContent("{ \"errorCode\": \"" + errorCode + "\", \"message\": \"" + description + "\"}");
return Task.FromResult(message);
});
[Fact]
public void ApplyOptionalParametersTest()
{
var clientParameters = new PayjoinClientParameters();
clientParameters.Version = 1;
clientParameters.MaxAdditionalFeeContribution = new Money(50, MoneyUnit.MilliBTC);
Uri result = PayjoinClient.ApplyOptionalParameters(new Uri("http://test.me/btc/?something=1"), clientParameters);
// Assert that the final URI does not contain `something=1` and that it contains proper parameters (in lowercase!).
Assert.Equal("http://test.me/btc/?v=1&disableoutputsubstitution=false&maxadditionalfeecontribution=5000000", result.AbsoluteUri);
}
[Fact]
public void LazyPayjoinServerTest()
{
// This tests the scenario where the payjoin server returns the same
// transaction that we sent to it and adds no inputs. This can give
// us the fake sense of privacy but it should be valid.
var httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt => psbt)
};
var payjoinClient = NewPayjoinClient(httpClient);
var transactionFactory = ServiceFactory.CreateTransactionFactory(new[]
{
("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1)
});
var allowedCoins = transactionFactory.Coins.ToArray();
var amount = Money.Coins(0.001m);
using Key key = new();
PaymentIntent payment = new(key.ScriptPubKey, amount);
var tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), allowedCoins.Select(x => x.OutPoint), payjoinClient);
Assert.Equal(TransactionCheckResult.Success, tx.Transaction.Transaction.Check());
Assert.True(tx.Signed);
Assert.Single(tx.InnerWalletOutputs);
Assert.Single(tx.OuterWalletOutputs);
}
[Fact]
public void HonestPayjoinServerTest()
{
var amountToPay = Money.Coins(0.001m);
// This tests the scenario where the payjoin server behaves as expected.
var httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var clientTx = psbt.ExtractTransaction();
foreach (var input in clientTx.Inputs)
{
input.WitScript = WitScript.Empty;
}
var serverCoinKey = new Key();
var serverCoin = Coin(0.345m, serverCoinKey.PubKey.WitHash.ScriptPubKey);
clientTx.Inputs.Add(serverCoin.Outpoint);
var paymentOutput = clientTx.Outputs.First(x => x.Value == amountToPay);
paymentOutput.Value += (Money)serverCoin.Amount;
var newPsbt = PSBT.FromTransaction(clientTx, Network.Main);
var serverCoinToSign = newPsbt.Inputs.FindIndexedInput(serverCoin.Outpoint);
serverCoinToSign.UpdateFromCoin(serverCoin);
serverCoinToSign.Sign(serverCoinKey);
serverCoinToSign.FinalizeInput();
return newPsbt;
})
};
var payjoinClient = NewPayjoinClient(httpClient);
var transactionFactory = ServiceFactory.CreateTransactionFactory(new[]
{
("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1)
});
var allowedCoins = transactionFactory.Coins.ToArray();
var payment = new PaymentIntent(BitcoinFactory.CreateScript(), amountToPay);
var tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), allowedCoins.Select(x => x.OutPoint), payjoinClient);
Assert.Equal(TransactionCheckResult.Success, tx.Transaction.Transaction.Check());
Assert.True(tx.Signed);
var innerOutput = Assert.Single(tx.InnerWalletOutputs);
var outerOutput = Assert.Single(tx.OuterWalletOutputs);
// The payment output is the sum of the original wallet output and the value added by the payee.
Assert.Equal(0.346m, outerOutput.Amount.ToUnit(MoneyUnit.BTC));
Assert.Equal(0.09899718m, innerOutput.Amount.ToUnit(MoneyUnit.BTC));
transactionFactory = ServiceFactory.CreateTransactionFactory(
new[]
{
("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1)
},
watchOnly: true);
allowedCoins = transactionFactory.Coins.ToArray();
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), allowedCoins.Select(x => x.OutPoint), payjoinClient);
Assert.Equal(TransactionCheckResult.Success, tx.Transaction.Transaction.Check());
Assert.False(tx.Signed);
innerOutput = Assert.Single(tx.InnerWalletOutputs);
outerOutput = Assert.Single(tx.OuterWalletOutputs);
// No payjoin was involved
Assert.Equal(amountToPay, outerOutput.Amount);
Assert.Equal(allowedCoins[0].Amount - amountToPay - tx.Fee, innerOutput.Amount);
}
[Fact]
public void DishonestPayjoinServerTest()
{
// The server knows one of our utxos and tries to fool the wallet to make it sign the utxo
var walletCoins = new[] { ("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1) };
var amountToPay = Money.Coins(0.001m);
var payment = new PaymentIntent(BitcoinFactory.CreateScript(), amountToPay);
// This tests the scenario where the payjoin server wants to make us sign one of our own inputs!!!!!.
var httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var newCoin = psbt.Inputs[0].GetCoin();
if (newCoin is { })
{
newCoin.Outpoint.N = newCoin.Outpoint.N + 1;
psbt.AddCoins(newCoin);
}
return psbt;
})
};
var transactionFactory = ServiceFactory.CreateTransactionFactory(walletCoins);
var tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
///////
// The server tries to pay more to itself by taking from the change output
var destination = BitcoinFactory.CreateScript();
payment = new PaymentIntent(destination, amountToPay);
// This tests the scenario where the payjoin server wants to make us sign one of our own inputs!!!!!.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
var diff = Money.Coins(0.0007m);
var paymentOutput = globalTx.Outputs.Single(x => x.ScriptPubKey == destination);
var changeOutput = globalTx.Outputs.Single(x => x.ScriptPubKey != destination);
changeOutput.Value -= diff;
paymentOutput.Value += diff;
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
}
[Fact]
public void BadImplementedPayjoinServerTest()
{
var walletCoins = new[] { ("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1) };
var amountToPay = Money.Coins(0.001m);
var payment = new PaymentIntent(BitcoinFactory.CreateScript(), amountToPay);
// This tests the scenario where the payjoin server does not clean GloablXPubs.
var httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var extPubkey = new ExtKey().Neuter().GetWif(Network.Main);
psbt.GlobalXPubs.Add(extPubkey, new RootedKeyPath(extPubkey.GetPublicKey().GetHDFingerPrint(), KeyManager.DefaultAccountKeyPath));
return psbt;
})
};
var transactionFactory = ServiceFactory.CreateTransactionFactory(walletCoins);
var tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server includes keypath info in the inputs.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var extPubkey = new ExtKey().Neuter().GetWif(Network.Main);
psbt.Inputs[0].AddKeyPath(new Key().PubKey, new RootedKeyPath(extPubkey.GetPublicKey().GetHDFingerPrint(), KeyManager.DefaultAccountKeyPath));
return psbt;
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server modifies the inputs sequence.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
globalTx.Inputs[0].Sequence = globalTx.Inputs[0].Sequence + 1;
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server returns an unsigned input (fucking bastard).
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
globalTx.Inputs.Add(GetRandomOutPoint());
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server removes one of our inputs (probably to optimize it).
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
globalTx.Inputs.Clear(); // remove all the inputs
globalTx.Inputs.Add(GetRandomOutPoint());
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server includes keypath info in the outputs.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var extPubkey = new ExtKey().Neuter().GetWif(Network.Main);
psbt.Outputs[0].AddKeyPath(new Key().PubKey, new RootedKeyPath(extPubkey.GetPublicKey().GetHDFingerPrint(), KeyManager.DefaultAccountKeyPath));
return psbt;
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server includes partial signatures.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var extPubkey = new ExtKey().Neuter().GetWif(Network.Main);
psbt.Inputs[0].PartialSigs.Add(new Key().PubKey, new TransactionSignature(new Key().Sign(uint256.One)));
return psbt;
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server modifies the original tx version.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
globalTx.Version += 1;
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
////////
// This tests the scenario where the payjoin server modifies the original tx locktime value.
httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
globalTx.LockTime = new LockTime(globalTx.LockTime + 1);
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
}
[Fact]
public void MinersLoverPayjoinServerTest()
{
// The server wants to make us sign a transaction that pays too much fee
var walletCoins = new[] { ("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1) };
var amountToPay = Money.Coins(0.001m);
var destination = BitcoinFactory.CreateScript();
var payment = new PaymentIntent(destination, amountToPay);
// This tests the scenario where the payjoin server wants to make us sign one of our own inputs!!!!!.
var httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerOk(psbt =>
{
var globalTx = psbt.GetGlobalTransaction();
var changeOutput = globalTx.Outputs.Single(x => x.ScriptPubKey != destination);
changeOutput.Value -= Money.Coins(0.0007m);
return PSBT.FromTransaction(globalTx, Network.Main);
})
};
var transactionFactory = ServiceFactory.CreateTransactionFactory(walletCoins);
var tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
}
[Fact]
public void BrokenPayjoinServerTest()
{
// The server wants to make us sign a transaction that pays too much fee.
var walletCoins = new[] { ("Pablo", 0, 0.1m, confirmed: true, anonymitySet: 1) };
var amountToPay = Money.Coins(0.001m);
var payment = new PaymentIntent(BitcoinFactory.CreateScript(), amountToPay);
// This tests the scenario where the payjoin server wants to make us sign one of our own inputs!!!!!.
var httpClient = new MockTorHttpClient
{
OnSendAsync = PayjoinServerError(statusCode: HttpStatusCode.InternalServerError, "Internal Server Error")
};
var transactionFactory = ServiceFactory.CreateTransactionFactory(walletCoins);
var tx = transactionFactory.BuildTransaction(payment, new FeeRate(2m), transactionFactory.Coins.Select(x => x.OutPoint), NewPayjoinClient(httpClient));
Assert.Single(tx.Transaction.Transaction.Inputs);
}
private static PayjoinClient NewPayjoinClient(MockTorHttpClient client)
=> new PayjoinClient(client.BaseUriGetter.Invoke(), client);
}
}
| |
--- /dev/null 2016-08-22 06:38:27.000000000 -0400
+++ src/System.IO.Compression/src/SR.cs 2016-08-22 06:39:21.344262000 -0400
@@ -0,0 +1,656 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.IO.Compression
+{
+ internal static class SR
+ {
+
+ }
+}
+
+namespace System
+{
+ internal static class SR
+ {
+ private static ResourceManager s_resourceManager;
+
+ private const String s_resourcesName = "FxResources.System.IO.Compression.SR";
+
+ internal static string UnsupportedCompressionMethod { get { return SR.GetResourceString("UnsupportedCompressionMethod", null); } }
+
+ internal static String Argument_InvalidPathChars
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidPathChars", null);
+ }
+ }
+
+ internal static String ArgumentNeedNonNegative
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentNeedNonNegative", null);
+ }
+ }
+
+ internal static String ArgumentOutOfRange_Enum
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_Enum", null);
+ }
+ }
+
+ internal static String ArgumentOutOfRange_NeedPosNum
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_NeedPosNum", null);
+ }
+ }
+
+ internal static String CannotBeEmpty
+ {
+ get
+ {
+ return SR.GetResourceString("CannotBeEmpty", null);
+ }
+ }
+
+ internal static String CannotReadFromDeflateStream
+ {
+ get
+ {
+ return SR.GetResourceString("CannotReadFromDeflateStream", null);
+ }
+ }
+
+ internal static String CannotWriteToDeflateStream
+ {
+ get
+ {
+ return SR.GetResourceString("CannotWriteToDeflateStream", null);
+ }
+ }
+
+ internal static String CDCorrupt
+ {
+ get
+ {
+ return SR.GetResourceString("CDCorrupt", null);
+ }
+ }
+
+ internal static String CentralDirectoryInvalid
+ {
+ get
+ {
+ return SR.GetResourceString("CentralDirectoryInvalid", null);
+ }
+ }
+
+ internal static String CorruptedGZipHeader
+ {
+ get
+ {
+ return SR.GetResourceString("CorruptedGZipHeader", null);
+ }
+ }
+
+ internal static String CreateInReadMode
+ {
+ get
+ {
+ return SR.GetResourceString("CreateInReadMode", null);
+ }
+ }
+
+ internal static String CreateModeCapabilities
+ {
+ get
+ {
+ return SR.GetResourceString("CreateModeCapabilities", null);
+ }
+ }
+
+ internal static String CreateModeCreateEntryWhileOpen
+ {
+ get
+ {
+ return SR.GetResourceString("CreateModeCreateEntryWhileOpen", null);
+ }
+ }
+
+ internal static String CreateModeWriteOnceAndOneEntryAtATime
+ {
+ get
+ {
+ return SR.GetResourceString("CreateModeWriteOnceAndOneEntryAtATime", null);
+ }
+ }
+
+ internal static String DateTimeOutOfRange
+ {
+ get
+ {
+ return SR.GetResourceString("DateTimeOutOfRange", null);
+ }
+ }
+
+ internal static String DeletedEntry
+ {
+ get
+ {
+ return SR.GetResourceString("DeletedEntry", null);
+ }
+ }
+
+ internal static String DeleteOnlyInUpdate
+ {
+ get
+ {
+ return SR.GetResourceString("DeleteOnlyInUpdate", null);
+ }
+ }
+
+ internal static String DeleteOpenEntry
+ {
+ get
+ {
+ return SR.GetResourceString("DeleteOpenEntry", null);
+ }
+ }
+
+ internal static String EntriesInCreateMode
+ {
+ get
+ {
+ return SR.GetResourceString("EntriesInCreateMode", null);
+ }
+ }
+
+ internal static String EntryNameEncodingNotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("EntryNameEncodingNotSupported", null);
+ }
+ }
+
+ internal static String EntryNamesTooLong
+ {
+ get
+ {
+ return SR.GetResourceString("EntryNamesTooLong", null);
+ }
+ }
+
+ internal static String EntryTooLarge
+ {
+ get
+ {
+ return SR.GetResourceString("EntryTooLarge", null);
+ }
+ }
+
+ internal static String EOCDNotFound
+ {
+ get
+ {
+ return SR.GetResourceString("EOCDNotFound", null);
+ }
+ }
+
+ internal static String FieldTooBigCompressedSize
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigCompressedSize", null);
+ }
+ }
+
+ internal static String FieldTooBigLocalHeaderOffset
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigLocalHeaderOffset", null);
+ }
+ }
+
+ internal static String FieldTooBigNumEntries
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigNumEntries", null);
+ }
+ }
+
+ internal static String FieldTooBigOffsetToCD
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigOffsetToCD", null);
+ }
+ }
+
+ internal static String FieldTooBigOffsetToZip64EOCD
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigOffsetToZip64EOCD", null);
+ }
+ }
+
+ internal static String FieldTooBigStartDiskNumber
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigStartDiskNumber", null);
+ }
+ }
+
+ internal static String FieldTooBigUncompressedSize
+ {
+ get
+ {
+ return SR.GetResourceString("FieldTooBigUncompressedSize", null);
+ }
+ }
+
+ internal static String FileNameContainsInvalidCharacters
+ {
+ get
+ {
+ return SR.GetResourceString("FileNameContainsInvalidCharacters", null);
+ }
+ }
+
+ internal static String FrozenAfterWrite
+ {
+ get
+ {
+ return SR.GetResourceString("FrozenAfterWrite", null);
+ }
+ }
+
+ internal static String GenericInvalidData
+ {
+ get
+ {
+ return SR.GetResourceString("GenericInvalidData", null);
+ }
+ }
+
+ internal static String HiddenStreamName
+ {
+ get
+ {
+ return SR.GetResourceString("HiddenStreamName", null);
+ }
+ }
+
+ internal static String InvalidArgumentOffsetCount
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidArgumentOffsetCount", null);
+ }
+ }
+
+ internal static String InvalidBeginCall
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidBeginCall", null);
+ }
+ }
+
+ internal static String InvalidBlockLength
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidBlockLength", null);
+ }
+ }
+
+ internal static String InvalidCRC
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidCRC", null);
+ }
+ }
+
+ internal static String InvalidHuffmanData
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidHuffmanData", null);
+ }
+ }
+
+ internal static String InvalidStreamSize
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidStreamSize", null);
+ }
+ }
+
+ internal static String LengthAfterWrite
+ {
+ get
+ {
+ return SR.GetResourceString("LengthAfterWrite", null);
+ }
+ }
+
+ internal static String LocalFileHeaderCorrupt
+ {
+ get
+ {
+ return SR.GetResourceString("LocalFileHeaderCorrupt", null);
+ }
+ }
+
+ internal static String NotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported", null);
+ }
+ }
+
+ internal static String NotSupported_UnreadableStream
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_UnreadableStream", null);
+ }
+ }
+
+ internal static String NotSupported_UnwritableStream
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_UnwritableStream", null);
+ }
+ }
+
+ internal static String NumEntriesWrong
+ {
+ get
+ {
+ return SR.GetResourceString("NumEntriesWrong", null);
+ }
+ }
+
+ internal static String ObjectDisposed_StreamClosed
+ {
+ get
+ {
+ return SR.GetResourceString("ObjectDisposed_StreamClosed", null);
+ }
+ }
+
+ internal static String OffsetLengthInvalid
+ {
+ get
+ {
+ return SR.GetResourceString("OffsetLengthInvalid", null);
+ }
+ }
+
+ internal static String ReadingNotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("ReadingNotSupported", null);
+ }
+ }
+
+ internal static String ReadModeCapabilities
+ {
+ get
+ {
+ return SR.GetResourceString("ReadModeCapabilities", null);
+ }
+ }
+
+ internal static String ReadOnlyArchive
+ {
+ get
+ {
+ return SR.GetResourceString("ReadOnlyArchive", null);
+ }
+ }
+
+ private static ResourceManager ResourceManager
+ {
+ get
+ {
+ if (SR.s_resourceManager == null)
+ {
+ SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+ }
+ return SR.s_resourceManager;
+ }
+ }
+
+ internal static Type ResourceType
+ {
+ get
+ {
+ return typeof(FxResources.System.IO.Compression.SR);
+ }
+ }
+
+ internal static String SeekingNotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("SeekingNotSupported", null);
+ }
+ }
+
+ internal static String SetLengthRequiresSeekingAndWriting
+ {
+ get
+ {
+ return SR.GetResourceString("SetLengthRequiresSeekingAndWriting", null);
+ }
+ }
+
+ internal static String SplitSpanned
+ {
+ get
+ {
+ return SR.GetResourceString("SplitSpanned", null);
+ }
+ }
+
+ internal static String UnexpectedEndOfStream
+ {
+ get
+ {
+ return SR.GetResourceString("UnexpectedEndOfStream", null);
+ }
+ }
+
+ internal static String UnknownBlockType
+ {
+ get
+ {
+ return SR.GetResourceString("UnknownBlockType", null);
+ }
+ }
+
+ internal static String UnknownCompressionMode
+ {
+ get
+ {
+ return SR.GetResourceString("UnknownCompressionMode", null);
+ }
+ }
+
+ internal static String UnknownState
+ {
+ get
+ {
+ return SR.GetResourceString("UnknownState", null);
+ }
+ }
+
+ internal static String UnsupportedCompression
+ {
+ get
+ {
+ return SR.GetResourceString("UnsupportedCompression", null);
+ }
+ }
+
+ internal static String UpdateModeCapabilities
+ {
+ get
+ {
+ return SR.GetResourceString("UpdateModeCapabilities", null);
+ }
+ }
+
+ internal static String UpdateModeOneStream
+ {
+ get
+ {
+ return SR.GetResourceString("UpdateModeOneStream", null);
+ }
+ }
+
+ internal static String WritingNotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("WritingNotSupported", null);
+ }
+ }
+
+ internal static String Zip64EOCDNotWhereExpected
+ {
+ get
+ {
+ return SR.GetResourceString("Zip64EOCDNotWhereExpected", null);
+ }
+ }
+
+ internal static String ZLibErrorDLLLoadError
+ {
+ get
+ {
+ return SR.GetResourceString("ZLibErrorDLLLoadError", null);
+ }
+ }
+
+ internal static String ZLibErrorInconsistentStream
+ {
+ get
+ {
+ return SR.GetResourceString("ZLibErrorInconsistentStream", null);
+ }
+ }
+
+ internal static String ZLibErrorIncorrectInitParameters
+ {
+ get
+ {
+ return SR.GetResourceString("ZLibErrorIncorrectInitParameters", null);
+ }
+ }
+
+ internal static String ZLibErrorNotEnoughMemory
+ {
+ get
+ {
+ return SR.GetResourceString("ZLibErrorNotEnoughMemory", null);
+ }
+ }
+
+ internal static String ZLibErrorUnexpected
+ {
+ get
+ {
+ return SR.GetResourceString("ZLibErrorUnexpected", null);
+ }
+ }
+
+ internal static String ZLibErrorVersionMismatch
+ {
+ get
+ {
+ return SR.GetResourceString("ZLibErrorVersionMismatch", null);
+ }
+ }
+
+ internal static String Format(String resourceFormat, params Object[] args)
+ {
+ if (args == null)
+ {
+ return resourceFormat;
+ }
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, args);
+ }
+ return String.Concat(resourceFormat, String.Join(", ", args));
+ }
+
+ internal static String Format(String resourceFormat, Object p1)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2, Object p3)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2, p3);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 });
+ }
+
+ internal static String GetResourceString(String resourceKey, String defaultString)
+ {
+ String str = null;
+ try
+ {
+ str = SR.ResourceManager.GetString(resourceKey);
+ }
+ catch (MissingManifestResourceException missingManifestResourceException)
+ {
+ }
+ if (defaultString != null && resourceKey.Equals(str))
+ {
+ return defaultString;
+ }
+ return str;
+ }
+
+ private static Boolean UsingResourceKeys()
+ {
+ return false;
+ }
+ }
+}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Common.Concurrency
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Thread = DotNetty.Common.Concurrency.XThread;
public interface IEventExecutor
{
/// <summary>
/// Returns <c>true</c> if the current <see cref="Thread" /> belongs to this event loop,
/// <c>false</c> otherwise.
/// </summary>
/// <remarks>
/// It is a convenient way to determine whether code can be executed directly or if it
/// should be posted for execution to this executor instance explicitly to ensure execution in the loop.
/// </remarks>
bool InEventLoop { get; }
/// <summary>
/// Returns <c>true</c> if and only if this executor is being shut down via <see cref="ShutdownGracefullyAsync()" />.
/// </summary>
bool IsShuttingDown { get; }
/// <summary>
/// Gets a <see cref="Task" /> object that represents the asynchronous completion of this executor's termination.
/// </summary>
Task TerminationCompletion { get; }
/// <summary>
/// Returns <c>true</c> if this executor has been shut down, <c>false</c> otherwise.
/// </summary>
bool IsShutdown { get; }
/// <summary>
/// Returns <c>true</c> if all tasks have completed following shut down.
/// </summary>
/// <remarks>
/// Note that <see cref="IsTerminated" /> is never <c>true</c> unless <see cref="ShutdownGracefullyAsync()" /> was called first.
/// </remarks>
bool IsTerminated { get; }
/// <summary>
/// Parent <see cref="IEventExecutorGroup"/>.
/// </summary>
IEventExecutorGroup Parent { get; }
/// <summary>
/// Returns <c>true</c> if the given <see cref="Thread" /> belongs to this event loop,
/// <c>false></c> otherwise.
/// </summary>
bool IsInEventLoop(Thread thread);
/// <summary>
/// Executes the given task.
/// </summary>
/// <remarks>Threading specifics are determined by <c>IEventExecutor</c> implementation.</remarks>
void Execute(IRunnable task);
/// <summary>
/// Executes the given action.
/// </summary>
/// <remarks>
/// <paramref name="state" /> parameter is useful to when repeated execution of an action against
/// different objects is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
void Execute(Action<object> action, object state);
/// <summary>
/// Executes the given <paramref name="action" />.
/// </summary>
/// <remarks>Threading specifics are determined by <c>IEventExecutor</c> implementation.</remarks>
void Execute(Action action);
/// <summary>
/// Executes the given action.
/// </summary>
/// <remarks>
/// <paramref name="context" /> and <paramref name="state" /> parameters are useful when repeated execution of
/// an action against different objects in different context is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
void Execute(Action<object, object> action, object context, object state);
/// <summary>
/// Creates and executes a one-shot action that becomes enabled after the given delay.
/// </summary>
/// <param name="action">the task to execute</param>
/// <param name="delay">the time from now to delay execution</param>
/// <returns>an <see cref="IScheduledTask" /> representing pending completion of the task.</returns>
IScheduledTask Schedule(IRunnable action, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
IScheduledTask Schedule(Action action, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <paramref name="state" /> parameter is useful to when repeated execution of an action against
/// different objects is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
IScheduledTask Schedule(Action<object> action, object state, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <paramref name="context" /> and <paramref name="state" /> parameters are useful when repeated execution of
/// an action against different objects in different context is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
IScheduledTask Schedule(Action<object, object> action, object context, object state, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <paramref name="state" /> parameter is useful to when repeated execution of an action against
/// different objects is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task ScheduleAsync(Action<object> action, object state, TimeSpan delay, CancellationToken cancellationToken);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <paramref name="state" /> parameter is useful to when repeated execution of an action against
/// different objects is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task ScheduleAsync(Action<object> action, object state, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task ScheduleAsync(Action action, TimeSpan delay, CancellationToken cancellationToken);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task ScheduleAsync(Action action, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <paramref name="context" /> and <paramref name="state" /> parameters are useful when repeated execution of
/// an action against different objects in different context is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task ScheduleAsync(Action<object, object> action, object context, object state, TimeSpan delay);
/// <summary>
/// Schedules the given action for execution after the specified delay would pass.
/// </summary>
/// <remarks>
/// <paramref name="context" /> and <paramref name="state" /> parameters are useful when repeated execution of
/// an action against different objects in different context is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task ScheduleAsync(Action<object, object> action, object context, object state, TimeSpan delay, CancellationToken cancellationToken);
/// <summary>
/// Executes the given function and returns <see cref="Task{T}" /> indicating completion status and result of
/// execution.
/// </summary>
/// <remarks>
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task<T> SubmitAsync<T>(Func<T> func);
/// <summary>
/// Executes the given action and returns <see cref="Task{T}" /> indicating completion status and result of execution.
/// </summary>
/// <remarks>
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task<T> SubmitAsync<T>(Func<T> func, CancellationToken cancellationToken);
/// <summary>
/// Executes the given action and returns <see cref="Task{T}" /> indicating completion status and result of execution.
/// </summary>
/// <remarks>
/// <paramref name="state" /> parameter is useful to when repeated execution of an action against
/// different objects is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task<T> SubmitAsync<T>(Func<object, T> func, object state);
/// <summary>
/// Executes the given action and returns <see cref="Task{T}" /> indicating completion status and result of execution.
/// </summary>
/// <remarks>
/// <paramref name="state" /> parameter is useful to when repeated execution of an action against
/// different objects is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task<T> SubmitAsync<T>(Func<object, T> func, object state, CancellationToken cancellationToken);
/// <summary>
/// Executes the given action and returns <see cref="Task{T}" /> indicating completion status and result of execution.
/// </summary>
/// <remarks>
/// <paramref name="context" /> and <paramref name="state" /> parameters are useful when repeated execution of
/// an action against different objects in different context is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task<T> SubmitAsync<T>(Func<object, object, T> func, object context, object state);
/// <summary>
/// Executes the given action and returns <see cref="Task{T}" /> indicating completion status and result of execution.
/// </summary>
/// <remarks>
/// <paramref name="context" /> and <paramref name="state" /> parameters are useful when repeated execution of
/// an action against different objects in different context is needed.
/// <para>Threading specifics are determined by <c>IEventExecutor</c> implementation.</para>
/// </remarks>
Task<T> SubmitAsync<T>(Func<object, object, T> func, object context, object state, CancellationToken cancellationToken);
/// <summary>
/// Shortcut method for <see cref="ShutdownGracefullyAsync(TimeSpan,TimeSpan)" /> with sensible default values.
/// </summary>
Task ShutdownGracefullyAsync();
/// <summary>
/// Signals this executor that the caller wants the executor to be shut down. Once this method is called,
/// <see cref="IsShuttingDown" /> starts to return <c>true</c>, and the executor prepares to shut itself down.
/// Graceful shutdown ensures that no tasks are submitted for <i>'the quiet period'</i>
/// (usually a couple seconds) before it shuts itself down. If a task is submitted during the quiet period,
/// it is guaranteed to be accepted and the quiet period will start over.
/// </summary>
/// <param name="quietPeriod">the quiet period as described in the documentation.</param>
/// <param name="timeout">
/// the maximum amount of time to wait until the executor <see cref="IsShutdown" />
/// regardless if a task was submitted during the quiet period.
/// </param>
/// <returns>the <see cref="TerminationCompletion" /> task.</returns>
Task ShutdownGracefullyAsync(TimeSpan quietPeriod, TimeSpan timeout);
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <[email protected]>
using System;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Threading;
namespace AmplifyShaderEditor
{
public enum ShaderLoadResult
{
LOADED,
FILE_NOT_FOUND,
ASE_INFO_NOT_FOUND,
UNITY_NATIVE_PATHS
}
public class Worker
{
public static readonly object locker = new object();
public void DoWork()
{
while ( IOUtils.ActiveThread )
{
if ( IOUtils.SaveInThreadFlag )
{
IOUtils.SaveInThreadFlag = false;
lock ( locker )
{
IOUtils.SaveInThreadShaderBody = IOUtils.ShaderCopywriteMessage + IOUtils.SaveInThreadShaderBody;
// Add checksum
string checksum = IOUtils.CreateChecksum( IOUtils.SaveInThreadShaderBody );
IOUtils.SaveInThreadShaderBody += IOUtils.CHECKSUM + IOUtils.VALUE_SEPARATOR + checksum;
// Write to disk
StreamWriter fileWriter = new StreamWriter( IOUtils.SaveInThreadPathName );
try
{
fileWriter.Write( IOUtils.SaveInThreadShaderBody );
Debug.Log( "Saving complete" );
}
catch ( Exception e )
{
Debug.LogException( e );
}
finally
{
fileWriter.Close();
}
}
}
}
Debug.Log( "Thread closed" );
}
}
public static class IOUtils
{
public static readonly string ShaderCopywriteMessage = "// Made with Amplify Shader Editor\n// Available at the Unity Asset Store - http://u3d.as/y3X \n";
public static readonly string GrabPassEmpty = "\t\tGrabPass{ }\n";
public static readonly string GrabPassBegin = "\t\tGrabPass{ \"";
public static readonly string GrabPassEnd = "\" }\n";
public static readonly string PropertiesBegin = "\tProperties\n\t{\n";
public static readonly string PropertiesEnd = "\t}\n";
public static readonly string PropertiesElement = "\t\t{0}\n";
public static readonly string PragmaTargetHeader = "\t\t#pragma target {0}\n";
public static readonly string InstancedPropertiesHeader = "\t\t#pragma multi_compile_instancing\n";
public static readonly string VirtualTexturePragmaHeader = "multi_compile _ _VT_SINGLE_MODE";
public static readonly string InstancedPropertiesBegin = "\t\tUNITY_INSTANCING_CBUFFER_START({0})\n";
public static readonly string InstancedPropertiesEnd = "\t\tUNITY_INSTANCING_CBUFFER_END\n";
public static readonly string InstancedPropertiesElement = "\t\t\tUNITY_DEFINE_INSTANCED_PROP({0}, {1})\n";
public static readonly string InstancedPropertiesData = "UNITY_ACCESS_INSTANCED_PROP({0})";
public static readonly string MetaBegin = "defaultTextures:";
public static readonly string MetaEnd = "userData:";
public static readonly string ShaderBodyBegin = "/*ASEBEGIN";
public static readonly string ShaderBodyEnd = "ASEEND*/";
//public static readonly float CurrentVersionFlt = 0.4f;
//public static readonly string CurrentVersionStr = "Version=" + CurrentVersionFlt;
public static readonly string CHECKSUM = "//CHKSM";
public static readonly string LAST_OPENED_OBJ_ID = "ASELASTOPENOBJID";
public static readonly string MAT_CLIPBOARD_ID = "ASEMATCLIPBRDID";
public static readonly char FIELD_SEPARATOR = ';';
public static readonly char VALUE_SEPARATOR = '=';
public static readonly char LINE_TERMINATOR = '\n';
public static readonly char VECTOR_SEPARATOR = ',';
public static readonly char FLOAT_SEPARATOR = '.';
public static readonly char CLIPBOARD_DATA_SEPARATOR = '|';
public static readonly char MATRIX_DATA_SEPARATOR = '|';
public readonly static string NO_TEXTURES = "<None>";
public static readonly string SaveShaderStr = "Please enter shader name to save";
public static readonly string FloatifyStr = ".0";
// Node parameter names
public const string NodeParam = "Node";
public const string NodePosition = "Position";
public const string NodeId = "Id";
public const string NodeType = "Type";
public const string WireConnectionParam = "WireConnection";
public static readonly uint NodeTypeId = 1;
public static readonly int InNodeId = 1;
public static readonly int InPortId = 2;
public static readonly int OutNodeId = 3;
public static readonly int OutPortId = 4;
public readonly static string DefaultASEDirtyCheckName = "__dirty";
public readonly static string DefaultASEDirtyCheckProperty = "[HideInInspector] " + DefaultASEDirtyCheckName + "( \"\", Int ) = 1";
public readonly static string DefaultASEDirtyCheckUniform = "uniform int " + DefaultASEDirtyCheckName + " = 1;";
public readonly static string MaskClipValueName = "_MaskClipValue";
public readonly static string MaskClipValueProperty = MaskClipValueName + "( \"{0}\", Float ) = {1}";
public readonly static string MaskClipValueUniform = "uniform float " + MaskClipValueName + " = {0};";
//public static readonly string ASEFolderGUID = "daca988099666ec40aaa2cde22bb4935";
//public static string ASEResourcesPath = "/Plugins/EditorResources/";
//public static string ASEFolderPath;
public static int DefaultASEDirtyCheckId;
// this is to be used in combination with AssetDatabase.GetAssetPath, both of these include the Assets/ path so we need to remove from one of them
public static string dataPath;
public static string EditorResourcesGUID = "0932db7ec1402c2489679c4b72eab5eb";
public static string GraphBgTextureGUID = "881c304491028ea48b5027ac6c62cf73";
public static string GraphFgTextureGUID = "8c4a7fca2884fab419769ccc0355c0c1";
public static string WireTextureGUID = "06e687f68dd96f0448c6d8217bbcf608";
public static string MasterNodeOnTextureGUID = "26c64fcee91024a49980ea2ee9d1a2fb";
public static string MasterNodeOffTextureGUID = "712aee08d999c16438e2d694f42428e8";
public static string GPUInstancedOnTextureGUID = "4b0c2926cc71c5846ae2a29652d54fb6";
public static string GPUInstancedOffTextureGUID = "486c7766baaf21b46afb63c1121ef03e";
public static string MainSkinGUID = "57482289c346f104a8162a3a79aaff9d";
public static string UpdateOutdatedGUID = "cce638be049286c41bcbd0a26c356b18";
public static string UpdateOFFGUID = "99d70ac09b4db9742b404c3f92d8564b";
public static string UpdateUpToDatedGUID = "ce30b12fbb3223746bcfef9ea82effe3";
public static string LiveOffGUID = "bb16faf366bcc6c4fbf0d7666b105354";
public static string LiveOnGUID = "6a0ae1d7892333142aeb09585572202c";
public static string LivePendingGUID = "e3182200efb67114eb5050f8955e1746";
public static string CleanupOFFGUID = "f62c0c3a5ddcd844e905fb2632fdcb15";
public static string CleanUpOnGUID = "615d853995cf2344d8641fd19cb09b5d";
public static string OpenSourceCodeOFFGUID = "f7e8834b42791124095a8b7f2d4daac2";
public static string OpenSourceCodeONGUID = "8b114792ff84f6546880c031eda42bc0";
public static string FocusNodeGUID = "da673e6179c67d346abb220a6935e359";
public static string FitViewGUID = "1def740f2314c6b4691529cadeee2e9c";
public static string ShowInfoWindowGUID = "77af20044e9766840a6be568806dc22e";
private static readonly string AmplifyShaderEditorDefineSymbol = "AMPLIFY_SHADER_EDITOR";
/////////////////////////////////////////////////////////////////////////////
// THREAD IO UTILS
public static bool SaveInThreadFlag = false;
public static string SaveInThreadShaderBody;
public static string SaveInThreadPathName;
public static Thread SaveInThreadMainThread;
public static bool ActiveThread = true;
private static bool UseSaveThread = false;
private static bool Initialized = false;
public static void StartSaveThread( string shaderBody, string pathName )
{
if ( UseSaveThread )
{
if ( !SaveInThreadFlag )
{
if ( SaveInThreadMainThread == null )
{
Worker worker = new Worker();
SaveInThreadMainThread = new Thread( worker.DoWork );
SaveInThreadMainThread.Start();
Debug.Log( "Thread created" );
}
SaveInThreadShaderBody = shaderBody;
SaveInThreadPathName = pathName;
SaveInThreadFlag = true;
}
}
else
{
SaveTextfileToDisk( shaderBody, pathName );
}
}
////////////////////////////////////////////////////////////////////////////
private static void SetAmplifyDefineSymbolOnBuildTargetGroup( BuildTargetGroup targetGroup )
{
string currData = PlayerSettings.GetScriptingDefineSymbolsForGroup( targetGroup );
if ( !currData.Contains( AmplifyShaderEditorDefineSymbol ) )
{
if ( string.IsNullOrEmpty( currData ) )
{
PlayerSettings.SetScriptingDefineSymbolsForGroup( targetGroup, AmplifyShaderEditorDefineSymbol );
}
else
{
if ( !currData[ currData.Length - 1 ].Equals( ';' ) )
{
currData += ';';
}
currData += AmplifyShaderEditorDefineSymbol;
PlayerSettings.SetScriptingDefineSymbolsForGroup( targetGroup, currData );
}
}
}
public static void Init()
{
if ( !Initialized )
{
Initialized = true;
SetAmplifyDefineSymbolOnBuildTargetGroup( EditorUserBuildSettings.selectedBuildTargetGroup );
//Array BuildTargetGroupValues = Enum.GetValues( typeof( BuildTargetGroup ));
//for ( int i = 0; i < BuildTargetGroupValues.Length; i++ )
//{
// if( i != 0 && i != 15 && i != 16 )
// SetAmplifyDefineSymbolOnBuildTargetGroup( ( BuildTargetGroup ) BuildTargetGroupValues.GetValue( i ) );
//}
DefaultASEDirtyCheckId = Shader.PropertyToID( DefaultASEDirtyCheckName );
dataPath = Application.dataPath.Remove( Application.dataPath.Length - 6 );
//ASEFolderPath = AssetDatabase.GUIDToAssetPath( ASEFolderGUID );
//ASEResourcesPath = ASEFolderPath + ASEResourcesPath;
}
}
public static void Destroy()
{
ActiveThread = false;
if ( SaveInThreadMainThread != null )
{
SaveInThreadMainThread.Abort();
SaveInThreadMainThread = null;
}
}
public static void GetShaderName( out string shaderName, out string fullPathname, string defaultName, string customDatapath )
{
string currDatapath = String.IsNullOrEmpty( customDatapath ) ? Application.dataPath : customDatapath;
fullPathname = EditorUtility.SaveFilePanelInProject( "Select Shader to save", defaultName, "shader", SaveShaderStr, currDatapath );
if ( !String.IsNullOrEmpty( fullPathname ) )
{
shaderName = fullPathname.Remove( fullPathname.Length - 7 ); // -7 remove .shader extension
string[] subStr = shaderName.Split( '/' );
if ( subStr.Length > 0 )
{
shaderName = subStr[ subStr.Length - 1 ]; // Remove pathname
}
}
else
{
shaderName = string.Empty;
}
}
public static void AddTypeToString( ref string myString, string typeName )
{
myString += typeName;
}
public static void AddFieldToString( ref string myString, string fieldName, object fieldValue )
{
myString += FIELD_SEPARATOR + fieldName + VALUE_SEPARATOR + fieldValue;
}
public static void AddFieldValueToString( ref string myString, object fieldValue )
{
myString += FIELD_SEPARATOR + fieldValue.ToString();
}
public static void AddLineTerminator( ref string myString )
{
myString += LINE_TERMINATOR;
}
public static string CreateChecksum( string buffer )
{
SHA1 sha1 = SHA1.Create();
byte[] buf = System.Text.Encoding.UTF8.GetBytes( buffer );
byte[] hash = sha1.ComputeHash( buf, 0, buf.Length );
string hashstr = BitConverter.ToString( hash ).Replace( "-", "" );
return hashstr;
}
public static void SaveTextfileToDisk( string shaderBody, string pathName, bool addAdditionalInfo = true)
{
if ( addAdditionalInfo )
{
shaderBody = ShaderCopywriteMessage + shaderBody;
// Add checksum
string checksum = CreateChecksum( shaderBody );
shaderBody += CHECKSUM + VALUE_SEPARATOR + checksum;
}
// Write to disk
StreamWriter fileWriter = new StreamWriter( pathName );
try
{
fileWriter.Write( shaderBody );
}
catch ( Exception e )
{
Debug.LogException( e );
}
finally
{
fileWriter.Close();
}
}
public static string LoadTextFileFromDisk( string pathName )
{
string result = string.Empty;
StreamReader fileReader = new StreamReader( pathName );
try
{
result = fileReader.ReadToEnd();
}
catch ( Exception e )
{
Debug.LogException( e );
}
finally
{
fileReader.Close();
}
return result;
}
public static bool IsASEShader( Shader shader )
{
string datapath = AssetDatabase.GetAssetPath( shader );
if ( UIUtils.IsUnityNativeShader( datapath ) )
{
return false;
}
string buffer = LoadTextFileFromDisk( datapath );
if ( String.IsNullOrEmpty( buffer ) || !IOUtils.HasValidShaderBody( ref buffer ) )
{
return false;
}
return true;
}
public static bool HasValidShaderBody( ref string shaderBody )
{
int shaderBodyBeginId = shaderBody.IndexOf( ShaderBodyBegin );
if ( shaderBodyBeginId > -1 )
{
int shaderBodyEndId = shaderBody.IndexOf( ShaderBodyEnd );
return ( shaderBodyEndId > -1 && shaderBodyEndId > shaderBodyBeginId );
}
return false;
}
public static int[] AllIndexesOf( this string str, string substr, bool ignoreCase = false )
{
if ( string.IsNullOrEmpty( str ) || string.IsNullOrEmpty( substr ) )
{
throw new ArgumentException( "String or substring is not specified." );
}
List<int> indexes = new List<int>();
int index = 0;
while ( ( index = str.IndexOf( substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal ) ) != -1 )
{
indexes.Add( index++ );
}
return indexes.ToArray();
}
public static void AddFunctionHeader( ref string function, string header )
{
function += "\t\t" + header + "\n\t\t{\n";
}
public static void AddSingleLineFunction( ref string function, string header )
{
function += "\t\t" + header;
}
public static void AddFunctionLine( ref string function, string line )
{
function += "\t\t\t" + line + "\n";
}
public static void CloseFunctionBody( ref string function )
{
function += "\t\t}\n";
}
public static string CreateFullFunction( string header, params string[] functionLines )
{
string result = string.Empty;
AddFunctionHeader( ref result, header );
for ( int i = 0; i > functionLines.Length; i++ )
{
AddFunctionLine( ref result, functionLines[ i ] );
}
CloseFunctionBody( ref result );
return result;
}
public static string CreateCodeComments( bool forceForwardSlash, params string[] comments )
{
string finalComment = string.Empty;
if ( comments.Length == 1 )
{
finalComment = "//" + comments[ 0 ];
}
else
{
if ( forceForwardSlash )
{
for ( int i = 0; i < comments.Length; i++ )
{
finalComment += "//" + comments[ i ];
if ( i < comments.Length - 1 )
{
finalComment += "\n\t\t\t";
}
}
}
else
{
finalComment = "/*";
for ( int i = 0; i < comments.Length; i++ )
{
if ( i != 0 )
finalComment += "\t\t\t";
finalComment += comments[ i ];
if( i <comments.Length -1 )
finalComment += "\n";
}
finalComment += "*/";
}
}
return finalComment;
}
public static string GetUVChannelDeclaration( string uvName, int channelId, int set )
{
string uvSetStr = ( set == 0 ) ? "uv" : "uv" + Constants.AvailableUVSetsStr[ set ];
return "float2 " + uvSetStr + uvName /*+ " : TEXCOORD" + channelId*/;
}
public static string GetUVChannelName( string uvName, int set )
{
string uvSetStr = ( set == 0 ) ? "uv" : "uv" + Constants.AvailableUVSetsStr[set];
return uvSetStr + uvName;
}
public static string GetVertexUVChannelName( int set )
{
string uvSetStr = ( set == 0 ) ? "texcoord" : ("texcoord" +set.ToString());
return uvSetStr;
}
public static string Floatify( float value )
{
return ( value % 1 ) != 0 ? value.ToString() : ( value.ToString() + FloatifyStr );
}
public static string Vector2ToString( Vector2 data )
{
return data.x.ToString() + VECTOR_SEPARATOR + data.y.ToString();
}
public static string Vector3ToString( Vector3 data )
{
return data.x.ToString() + VECTOR_SEPARATOR + data.y.ToString() + VECTOR_SEPARATOR + data.z.ToString();
}
public static string Vector4ToString( Vector4 data )
{
return data.x.ToString() + VECTOR_SEPARATOR + data.y.ToString() + VECTOR_SEPARATOR + data.z.ToString() + VECTOR_SEPARATOR + data.w.ToString();
}
public static string ColorToString( Color data )
{
return data.r.ToString() + VECTOR_SEPARATOR + data.g.ToString() + VECTOR_SEPARATOR + data.b.ToString() + VECTOR_SEPARATOR + data.a.ToString();
}
public static Vector2 StringToVector2( string data )
{
string[] parsedData = data.Split( VECTOR_SEPARATOR );
if ( parsedData.Length >= 2 )
{
return new Vector2( Convert.ToSingle( parsedData[ 0 ] ),
Convert.ToSingle( parsedData[ 1 ] ) );
}
return Vector2.zero;
}
public static Vector3 StringToVector3( string data )
{
string[] parsedData = data.Split( VECTOR_SEPARATOR );
if ( parsedData.Length >= 3 )
{
return new Vector3( Convert.ToSingle( parsedData[ 0 ] ),
Convert.ToSingle( parsedData[ 1 ] ),
Convert.ToSingle( parsedData[ 2 ] ) );
}
return Vector3.zero;
}
public static Vector4 StringToVector4( string data )
{
string[] parsedData = data.Split( VECTOR_SEPARATOR );
if ( parsedData.Length >= 4 )
{
return new Vector4( Convert.ToSingle( parsedData[ 0 ] ),
Convert.ToSingle( parsedData[ 1 ] ),
Convert.ToSingle( parsedData[ 2 ] ),
Convert.ToSingle( parsedData[ 3 ] ) );
}
return Vector4.zero;
}
public static Color StringToColor( string data )
{
string[] parsedData = data.Split( VECTOR_SEPARATOR );
if ( parsedData.Length >= 4 )
{
return new Color( Convert.ToSingle( parsedData[ 0 ] ),
Convert.ToSingle( parsedData[ 1 ] ),
Convert.ToSingle( parsedData[ 2 ] ),
Convert.ToSingle( parsedData[ 3 ] ) );
}
return Color.white;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 UIKit;
using Foundation;
using System;
using System.IO;
using System.Threading;
using Sensus.Probes;
using Sensus.Context;
using Sensus.Probes.Movement;
using Sensus.Probes.Location;
using Xamarin.Forms;
using MessageUI;
using AVFoundation;
using CoreBluetooth;
using System.Threading.Tasks;
using TTGSnackBar;
using WindowsAzure.Messaging;
using Newtonsoft.Json;
using Sensus.Exceptions;
using Plugin.Geolocator.Abstractions;
using MobileCoreServices;
namespace Sensus.iOS
{
public class iOSSensusServiceHelper : SensusServiceHelper
{
#region static members
private const int BLUETOOTH_ENABLE_TIMEOUT_MS = 15000;
#endregion
private readonly string _deviceId;
private readonly string _deviceModel;
private readonly string _operatingSystem;
private NSData _pushNotificationTokenData;
private bool _keepAwakeEnabled;
private object _keepAwakeLocker = new object();
public override bool IsCharging
{
get
{
return UIDevice.CurrentDevice.BatteryState == UIDeviceBatteryState.Charging || UIDevice.CurrentDevice.BatteryState == UIDeviceBatteryState.Full;
}
}
public override float BatteryChargePercent
{
get
{
return UIDevice.CurrentDevice.BatteryLevel * 100f;
}
}
public override bool WiFiConnected
{
get
{
return NetworkConnectivity.LocalWifiConnectionStatus() == NetworkStatus.ReachableViaWiFiNetwork;
}
}
public override string DeviceId
{
get
{
return _deviceId;
}
}
public override string DeviceManufacturer
{
get { return "Apple"; }
}
public override string DeviceModel
{
get { return _deviceModel; }
}
public override string OperatingSystem
{
get
{
return _operatingSystem;
}
}
public override string Version
{
get
{
return NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"].ToString();
}
}
public override string PushNotificationToken
{
get
{
return _pushNotificationTokenData == null ? null : BitConverter.ToString(_pushNotificationTokenData.ToArray()).Replace("-", "").ToUpperInvariant();
}
}
[JsonIgnore]
public NSData PushNotificationTokenData
{
get
{
return _pushNotificationTokenData;
}
set
{
_pushNotificationTokenData = value;
}
}
public iOSSensusServiceHelper()
{
// we've seen one case of a null reference when getting the identifier.
try
{
_deviceId = UIDevice.CurrentDevice.IdentifierForVendor.AsString();
if (string.IsNullOrWhiteSpace(_deviceId))
{
throw new NullReferenceException("Null device ID.");
}
}
catch (Exception ex)
{
SensusException.Report("Exception while obtaining device ID: " + ex.Message, ex);
// set an arbitrary identifier, since we couldn't get one above. this will change each
// time the app is killed and restarted. but the NRE condition above should be very rare.
_deviceId = Guid.NewGuid().ToString();
}
try
{
_deviceModel = Xamarin.iOS.DeviceHardware.Version;
}
catch(Exception)
{
}
try
{
_operatingSystem = UIDevice.CurrentDevice.SystemName + " " + UIDevice.CurrentDevice.SystemVersion;
}
catch(Exception)
{
}
}
public override async Task KeepDeviceAwakeAsync()
{
lock (_keepAwakeLocker)
{
if (_keepAwakeEnabled)
{
Logger.Log("Attempted to keep device awake, but keep-awake is already enabled.", LoggingLevel.Normal, GetType());
return;
}
else
{
_keepAwakeEnabled = true;
}
}
Logger.Log("Enabling keep-awake by adding GPS listener.", LoggingLevel.Normal, GetType());
await GpsReceiver.Get().AddListenerAsync(KeepAwakePositionChanged, false);
}
public override async Task LetDeviceSleepAsync()
{
lock (_keepAwakeLocker)
{
if (_keepAwakeEnabled)
{
_keepAwakeEnabled = false;
}
else
{
Logger.Log("Attempted to let device sleep, but keep-awake was already disabled.", LoggingLevel.Normal, GetType());
return;
}
}
Logger.Log("Disabling keep-awake by removing GPS listener.", LoggingLevel.Normal, GetType());
await GpsReceiver.Get().RemoveListenerAsync(KeepAwakePositionChanged);
}
private void KeepAwakePositionChanged(object sender, PositionEventArgs position)
{
Logger.Log("Received keep-awake position change.", LoggingLevel.Normal, GetType());
}
protected override Task ProtectedFlashNotificationAsync(string message)
{
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
TTGSnackbar snackbar = new TTGSnackbar(message);
snackbar.Duration = TimeSpan.FromSeconds(5);
snackbar.Show();
});
return Task.CompletedTask;
}
public override Task ShareFileAsync(string path, string subject, string mimeType)
{
return SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
{
if (!MFMailComposeViewController.CanSendMail)
{
await FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
return;
}
NSData data = NSData.FromUrl(NSUrl.FromFilename(path));
if (data == null)
{
await FlashNotificationAsync("No file to share.");
return;
}
MFMailComposeViewController mailer = new MFMailComposeViewController();
mailer.SetSubject(subject);
mailer.AddAttachmentData(data, mimeType, Path.GetFileName(path));
mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
});
}
public override Task SendEmailAsync(string toAddress, string subject, string message)
{
return SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
{
if (MFMailComposeViewController.CanSendMail)
{
MFMailComposeViewController mailer = new MFMailComposeViewController();
mailer.SetToRecipients(new string[] { toAddress });
mailer.SetSubject(subject);
mailer.SetMessageBody(message, false);
mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
}
else
{
await FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
}
});
}
public override Task TextToSpeechAsync(string text)
{
return Task.Run(() =>
{
try
{
new AVSpeechSynthesizer().SpeakUtterance(new AVSpeechUtterance(text));
}
catch (Exception ex)
{
Logger.Log("Failed to speak utterance: " + ex.Message, LoggingLevel.Normal, GetType());
}
});
}
public override Task<string> RunVoicePromptAsync(string prompt, Action postDisplayCallback)
{
return Task.Run(() =>
{
string input = null;
ManualResetEvent dialogDismissWait = new ManualResetEvent(false);
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
#region set up dialog
ManualResetEvent dialogShowWait = new ManualResetEvent(false);
UIAlertView dialog = new UIAlertView("Sensus is requesting input...", prompt, default(IUIAlertViewDelegate), "Cancel", "OK");
dialog.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
dialog.Dismissed += (o, e) =>
{
dialogDismissWait.Set();
};
dialog.Presented += (o, e) =>
{
dialogShowWait.Set();
postDisplayCallback?.Invoke();
};
dialog.Clicked += (o, e) =>
{
if (e.ButtonIndex == 1)
{
input = dialog.GetTextField(0).Text;
}
};
dialog.Show();
#endregion
#region voice recognizer
Task.Run(() =>
{
// wait for the dialog to be shown so it doesn't hide our speech recognizer activity
dialogShowWait.WaitOne();
// there's a slight race condition between the dialog showing and speech recognition showing. pause here to prevent the dialog from hiding the speech recognizer.
Thread.Sleep(1000);
// TODO: Add speech recognition
});
#endregion
});
dialogDismissWait.WaitOne();
return input;
});
}
public override bool EnableProbeWhenEnablingAll(Probe probe)
{
// polling for locations doesn't work very well in iOS, since it depends on the user. don't enable probes that need location polling by default.
return !(probe is PollingLocationProbe) &&
!(probe is PollingSpeedProbe) &&
!(probe is PollingPointsOfInterestProximityProbe);
}
public override ImageSource GetQrCodeImageSource(string contents)
{
return ImageSource.FromStream(() =>
{
UIImage bitmap = BarcodeWriter.Write(contents);
MemoryStream ms = new MemoryStream();
bitmap.AsPNG().AsStream().CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
return ms;
});
}
protected override async Task RegisterWithNotificationHubAsync(Tuple<string, string> hubSas)
{
SBNotificationHub notificationHub = new SBNotificationHub(hubSas.Item2, hubSas.Item1);
await notificationHub.RegisterNativeAsyncAsync(_pushNotificationTokenData, new NSSet());
}
protected override async Task UnregisterFromNotificationHubAsync(Tuple<string, string> hubSas)
{
SBNotificationHub notificationHub = new SBNotificationHub(hubSas.Item2, hubSas.Item1);
await notificationHub.UnregisterAllAsyncAsync(_pushNotificationTokenData);
}
protected override void RequestNewPushNotificationToken()
{
// reregister for remote notifications to get a new token
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
UIApplication.SharedApplication.UnregisterForRemoteNotifications();
UIApplication.SharedApplication.RegisterForRemoteNotifications();
});
}
/// <summary>
/// Enables the Bluetooth adapter, or prompts the user to do so if we cannot do this programmatically.
/// </summary>
/// <returns><c>true</c>, if Bluetooth was enabled, <c>false</c> otherwise.</returns>
/// <param name="lowEnergy">If set to <c>true</c> low energy.</param>
/// <param name="rationale">Rationale.</param>
public override async Task<bool> EnableBluetoothAsync(bool lowEnergy, string rationale)
{
return await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
{
try
{
TaskCompletionSource<bool> enableTaskCompletionSource = new TaskCompletionSource<bool>();
CBCentralManager manager = new CBCentralManager();
manager.UpdatedState += (sender, e) =>
{
if (manager.State == CBCentralManagerState.PoweredOn)
{
enableTaskCompletionSource.TrySetResult(true);
}
};
if (manager.State == CBCentralManagerState.PoweredOn)
{
enableTaskCompletionSource.TrySetResult(true);
}
Task timeoutTask = Task.Delay(BLUETOOTH_ENABLE_TIMEOUT_MS);
if (await Task.WhenAny(enableTaskCompletionSource.Task, timeoutTask) == timeoutTask)
{
Logger.Log("Timed out while waiting for user to enable Bluetooth.", LoggingLevel.Normal, GetType());
enableTaskCompletionSource.TrySetResult(false);
}
return await enableTaskCompletionSource.Task;
}
catch (Exception ex)
{
Logger.Log("Failed while requesting Bluetooth enable: " + ex.Message, LoggingLevel.Normal, GetType());
return false;
}
});
}
/// <summary>
/// Not available on iOS. Will always return a completed <see cref="Task"/> with a result of false.
/// </summary>
/// <returns>False</returns>
/// <param name="reenable">If set to <c>true</c> reenable.</param>
/// <param name="lowEnergy">If set to <c>true</c> low energy.</param>
/// <param name="rationale">Rationale.</param>
public override Task<bool> DisableBluetoothAsync(bool reenable, bool lowEnergy, string rationale)
{
return Task.FromResult(false);
}
public override string GetMimeType(string path)
{
string extension = NSUrl.FromString(path).PathExtension;
string uniformTypeIdentifier = UTType.CreatePreferredIdentifier(UTType.TagClassFilenameExtension, extension, null);
return UTType.GetPreferredTag(uniformTypeIdentifier, UTType.TagClassMIMEType);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrDouble()
{
var test = new SimpleBinaryOpTest__OrDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrDouble
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__OrDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__OrDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Or(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Or(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Or(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrDouble();
var result = Avx.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if ((BitConverter.DoubleToInt64Bits(left[0]) | BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.DoubleToInt64Bits(left[i]) | BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Or)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using DarkMultiPlayerCommon;
using System.Reflection;
using DarkMultiPlayer.Utilities;
namespace DarkMultiPlayer
{
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class Client : MonoBehaviour
{
private static Client singleton;
//Global state vars
public string status;
public bool startGame;
public bool forceQuit;
public bool showGUI = true;
public bool toolbarShowGUI = true;
public bool modDisabled = false;
public bool dmpSaveChecked = false;
public string assemblyPath;
//Game running is directly set from NetworkWorker.fetch after a successful connection
public bool gameRunning;
public bool fireReset;
public GameMode gameMode;
public bool serverAllowCheats = true;
//Disconnect message
public bool displayDisconnectMessage;
private ScreenMessage disconnectMessage;
private float lastDisconnectMessageCheck;
public static List<Action> updateEvent = new List<Action>();
public static List<Action> fixedUpdateEvent = new List<Action>();
public static List<Action> drawEvent = new List<Action>();
public static List<Action> resetEvent = new List<Action>();
public static object eventLock = new object();
//Chosen by a 2147483647 sided dice roll. Guaranteed to be random.
public const int WINDOW_OFFSET = 1664952404;
//Hack gravity fix.
private Dictionary<CelestialBody, double> bodiesGees = new Dictionary<CelestialBody,double>();
//Command line connect
public static ServerEntry commandLineConnect;
// Server setting
public GameDifficulty serverDifficulty;
public GameParameters serverParameters;
public Client()
{
singleton = this;
}
public static Client fetch
{
get
{
return singleton;
}
}
public void Awake()
{
if (!CompatibilityChecker.IsCompatible() || !InstallChecker.IsCorrectlyInstalled()) modDisabled = true;
if (Settings.fetch.disclaimerAccepted != 1)
{
modDisabled = true;
DisclaimerWindow.SpawnDialog();
}
Profiler.DMPReferenceTime.Start();
DontDestroyOnLoad(this);
// Prevents symlink warning for development.
SetupDirectoriesIfNeeded();
// UniverseSyncCache needs to run expiry here
UniverseSyncCache.fetch.ExpireCache();
// Register events needed to bootstrap the workers.
lock (eventLock)
{
resetEvent.Add(LockSystem.Reset);
resetEvent.Add(AdminSystem.Reset);
resetEvent.Add(AsteroidWorker.Reset);
resetEvent.Add(ChatWorker.Reset);
resetEvent.Add(CraftLibraryWorker.Reset);
resetEvent.Add(DebugWindow.Reset);
resetEvent.Add(DynamicTickWorker.Reset);
resetEvent.Add(FlagSyncer.Reset);
resetEvent.Add(HackyInAtmoLoader.Reset);
resetEvent.Add(KerbalReassigner.Reset);
resetEvent.Add(PlayerColorWorker.Reset);
resetEvent.Add(PlayerStatusWindow.Reset);
resetEvent.Add(PlayerStatusWorker.Reset);
resetEvent.Add(PartKiller.Reset);
resetEvent.Add(ScenarioWorker.Reset);
resetEvent.Add(ScreenshotWorker.Reset);
resetEvent.Add(TimeSyncer.Reset);
resetEvent.Add(ToolbarSupport.Reset);
resetEvent.Add(VesselWorker.Reset);
resetEvent.Add(WarpWorker.Reset);
GameEvents.onHideUI.Add(() =>
{
showGUI = false;
});
GameEvents.onShowUI.Add(() =>
{
showGUI = true;
});
}
FireResetEvent();
HandleCommandLineArgs();
long testTime = Compression.TestSysIOCompression();
DarkLog.Debug("System.IO compression works: " + Compression.sysIOCompressionWorks + ", test time: " + testTime + " ms.");
DarkLog.Debug("DarkMultiPlayer " + Common.PROGRAM_VERSION + ", protocol " + Common.PROTOCOL_VERSION + " Initialized!");
}
private void HandleCommandLineArgs()
{
bool nextLineIsAddress = false;
bool valid = false;
string address = null;
int port = 6702;
foreach (string commandLineArg in Environment.GetCommandLineArgs())
{
//Supporting IPv6 is FUN!
if (nextLineIsAddress)
{
valid = true;
nextLineIsAddress = false;
if (commandLineArg.Contains("dmp://"))
{
if (commandLineArg.Contains("[") && commandLineArg.Contains("]"))
{
//IPv6 literal
address = commandLineArg.Substring("dmp://[".Length);
address = address.Substring(0, address.LastIndexOf("]"));
if (commandLineArg.Contains("]:"))
{
//With port
string portString = commandLineArg.Substring(commandLineArg.LastIndexOf("]:") + 1);
if (!Int32.TryParse(portString, out port))
{
valid = false;
}
}
}
else
{
//IPv4 literal or hostname
if (commandLineArg.Substring("dmp://".Length).Contains(":"))
{
//With port
address = commandLineArg.Substring("dmp://".Length);
address = address.Substring(0, address.LastIndexOf(":"));
string portString = commandLineArg.Substring(commandLineArg.LastIndexOf(":") + 1);
if (!Int32.TryParse(portString, out port))
{
valid = false;
}
}
else
{
//Without port
address = commandLineArg.Substring("dmp://".Length);
}
}
}
else
{
valid = false;
}
}
if (commandLineArg == "-dmp")
{
nextLineIsAddress = true;
}
}
if (valid)
{
commandLineConnect = new ServerEntry();
commandLineConnect.address = address;
commandLineConnect.port = port;
DarkLog.Debug("Connecting via command line to: " + address + ", port: " + port);
}
else
{
DarkLog.Debug("Command line address is invalid: " + address + ", port: " + port);
}
}
public void Update()
{
long startClock = Profiler.DMPReferenceTime.ElapsedTicks;
DarkLog.Update();
if (modDisabled)
{
return;
}
try
{
if (HighLogic.LoadedScene == GameScenes.MAINMENU)
{
if (!ModWorker.fetch.dllListBuilt)
{
ModWorker.fetch.dllListBuilt = true;
ModWorker.fetch.BuildDllFileList();
}
if (!dmpSaveChecked)
{
dmpSaveChecked = true;
SetupBlankGameIfNeeded();
}
}
//Handle GUI events
if (!PlayerStatusWindow.fetch.disconnectEventHandled)
{
PlayerStatusWindow.fetch.disconnectEventHandled = true;
forceQuit = true;
ScenarioWorker.fetch.SendScenarioModules(true); // Send scenario modules before disconnecting
NetworkWorker.fetch.SendDisconnect("Quit");
}
if (!ConnectionWindow.fetch.renameEventHandled)
{
PlayerStatusWorker.fetch.myPlayerStatus.playerName = Settings.fetch.playerName;
Settings.fetch.SaveSettings();
ConnectionWindow.fetch.renameEventHandled = true;
}
if (!ConnectionWindow.fetch.addEventHandled)
{
Settings.fetch.servers.Add(ConnectionWindow.fetch.addEntry);
ConnectionWindow.fetch.addEntry = null;
Settings.fetch.SaveSettings();
ConnectionWindow.fetch.addingServer = false;
ConnectionWindow.fetch.addEventHandled = true;
}
if (!ConnectionWindow.fetch.editEventHandled)
{
Settings.fetch.servers[ConnectionWindow.fetch.selected].name = ConnectionWindow.fetch.editEntry.name;
Settings.fetch.servers[ConnectionWindow.fetch.selected].address = ConnectionWindow.fetch.editEntry.address;
Settings.fetch.servers[ConnectionWindow.fetch.selected].port = ConnectionWindow.fetch.editEntry.port;
ConnectionWindow.fetch.editEntry = null;
Settings.fetch.SaveSettings();
ConnectionWindow.fetch.addingServer = false;
ConnectionWindow.fetch.editEventHandled = true;
}
if (!ConnectionWindow.fetch.removeEventHandled)
{
Settings.fetch.servers.RemoveAt(ConnectionWindow.fetch.selected);
ConnectionWindow.fetch.selected = -1;
Settings.fetch.SaveSettings();
ConnectionWindow.fetch.removeEventHandled = true;
}
if (!ConnectionWindow.fetch.connectEventHandled)
{
ConnectionWindow.fetch.connectEventHandled = true;
NetworkWorker.fetch.ConnectToServer(Settings.fetch.servers[ConnectionWindow.fetch.selected].address, Settings.fetch.servers[ConnectionWindow.fetch.selected].port);
}
if (commandLineConnect != null && HighLogic.LoadedScene == GameScenes.MAINMENU && Time.timeSinceLevelLoad > 1f)
{
NetworkWorker.fetch.ConnectToServer(commandLineConnect.address, commandLineConnect.port);
commandLineConnect = null;
}
if (!ConnectionWindow.fetch.disconnectEventHandled)
{
ConnectionWindow.fetch.disconnectEventHandled = true;
gameRunning = false;
fireReset = true;
if (NetworkWorker.fetch.state == ClientState.CONNECTING)
{
NetworkWorker.fetch.Disconnect("Cancelled connection to server");
}
else
{
NetworkWorker.fetch.SendDisconnect("Quit during initial sync");
}
}
foreach (Action updateAction in updateEvent)
{
try
{
updateAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in UpdateEvent, exception: " + e);
if (NetworkWorker.fetch.state != ClientState.RUNNING)
{
if (NetworkWorker.fetch.state != ClientState.DISCONNECTED)
{
NetworkWorker.fetch.SendDisconnect("Unhandled error while syncing!");
}
else
{
NetworkWorker.fetch.Disconnect("Unhandled error while syncing!");
}
}
}
}
//Force quit
if (forceQuit)
{
forceQuit = false;
gameRunning = false;
fireReset = true;
StopGame();
}
if (displayDisconnectMessage)
{
if (HighLogic.LoadedScene != GameScenes.MAINMENU)
{
if ((UnityEngine.Time.realtimeSinceStartup - lastDisconnectMessageCheck) > 1f)
{
lastDisconnectMessageCheck = UnityEngine.Time.realtimeSinceStartup;
if (disconnectMessage != null)
{
disconnectMessage.duration = 0;
}
disconnectMessage = ScreenMessages.PostScreenMessage("You have been disconnected!", 2f, ScreenMessageStyle.UPPER_CENTER);
}
}
else
{
displayDisconnectMessage = false;
}
}
//Normal quit
if (gameRunning)
{
if (HighLogic.LoadedScene == GameScenes.MAINMENU)
{
gameRunning = false;
fireReset = true;
NetworkWorker.fetch.SendDisconnect("Quit to main menu");
}
if (ScreenshotWorker.fetch.uploadScreenshot)
{
ScreenshotWorker.fetch.uploadScreenshot = false;
StartCoroutine(UploadScreenshot());
}
if (HighLogic.CurrentGame.flagURL != Settings.fetch.selectedFlag)
{
DarkLog.Debug("Saving selected flag");
Settings.fetch.selectedFlag = HighLogic.CurrentGame.flagURL;
Settings.fetch.SaveSettings();
FlagSyncer.fetch.flagChangeEvent = true;
}
// save every GeeASL from each body in FlightGlobals
if (HighLogic.LoadedScene == GameScenes.FLIGHT && bodiesGees.Count == 0)
{
foreach (CelestialBody body in FlightGlobals.fetch.bodies)
{
bodiesGees.Add(body, body.GeeASL);
}
}
//handle use of cheats
if (!serverAllowCheats)
{
CheatOptions.InfinitePropellant = false;
CheatOptions.NoCrashDamage = false;
CheatOptions.IgnoreAgencyMindsetOnContracts = false;
CheatOptions.IgnoreMaxTemperature = false;
CheatOptions.InfiniteElectricity = false;
CheatOptions.NoCrashDamage = false;
CheatOptions.UnbreakableJoints = false;
foreach (KeyValuePair<CelestialBody, double> gravityEntry in bodiesGees)
{
gravityEntry.Key.GeeASL = gravityEntry.Value;
}
}
if (HighLogic.LoadedScene == GameScenes.FLIGHT && FlightGlobals.ready)
{
HighLogic.CurrentGame.Parameters.Flight.CanLeaveToSpaceCenter = !VesselWorker.fetch.isSpectating && Settings.fetch.revertEnabled || (PauseMenu.canSaveAndExit == ClearToSaveStatus.CLEAR);
}
else
{
HighLogic.CurrentGame.Parameters.Flight.CanLeaveToSpaceCenter = true;
}
}
if (fireReset)
{
fireReset = false;
FireResetEvent();
}
if (startGame)
{
startGame = false;
StartGame();
}
}
catch (Exception e)
{
DarkLog.Debug("Threw in Update, state " + NetworkWorker.fetch.state.ToString() + ", exception" + e);
if (NetworkWorker.fetch.state != ClientState.RUNNING)
{
if (NetworkWorker.fetch.state != ClientState.DISCONNECTED)
{
NetworkWorker.fetch.SendDisconnect("Unhandled error while syncing!");
}
else
{
NetworkWorker.fetch.Disconnect("Unhandled error while syncing!");
}
}
}
Profiler.updateData.ReportTime(startClock);
}
public IEnumerator<WaitForEndOfFrame> UploadScreenshot()
{
yield return new WaitForEndOfFrame();
ScreenshotWorker.fetch.SendScreenshot();
ScreenshotWorker.fetch.screenshotTaken = true;
}
public void FixedUpdate()
{
long startClock = Profiler.DMPReferenceTime.ElapsedTicks;
if (modDisabled)
{
return;
}
foreach (Action fixedUpdateAction in fixedUpdateEvent)
{
try
{
fixedUpdateAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in FixedUpdate event, exception: " + e);
if (NetworkWorker.fetch.state != ClientState.RUNNING)
{
if (NetworkWorker.fetch.state != ClientState.DISCONNECTED)
{
NetworkWorker.fetch.SendDisconnect("Unhandled error while syncing!");
}
else
{
NetworkWorker.fetch.Disconnect("Unhandled error while syncing!");
}
}
}
}
Profiler.fixedUpdateData.ReportTime(startClock);
}
public void OnGUI()
{
//Window ID's - Doesn't include "random" offset.
//Connection window: 6702
//Status window: 6703
//Chat window: 6704
//Debug window: 6705
//Mod windw: 6706
//Craft library window: 6707
//Craft upload window: 6708
//Screenshot window: 6710
//Options window: 6711
//Converter window: 6712
//Disclaimer window: 6713
long startClock = Profiler.DMPReferenceTime.ElapsedTicks;
if (showGUI && toolbarShowGUI)
{
foreach (Action drawAction in drawEvent)
{
try
{
drawAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in OnGUI event, exception: " + e);
}
}
}
Profiler.guiData.ReportTime(startClock);
}
private void StartGame()
{
//Create new game object for our DMP session.
HighLogic.CurrentGame = CreateBlankGame();
//Set the game mode
HighLogic.CurrentGame.Mode = ConvertGameMode(gameMode);
//Set difficulty
HighLogic.CurrentGame.Parameters = serverParameters;
//Set universe time
HighLogic.CurrentGame.flightState.universalTime = TimeSyncer.fetch.GetUniverseTime();
//Load DMP stuff
VesselWorker.fetch.LoadKerbalsIntoGame();
VesselWorker.fetch.LoadVesselsIntoGame();
//Load the scenarios from the server
ScenarioWorker.fetch.LoadScenarioDataIntoGame();
//Load the missing scenarios as well (Eg, Contracts and stuff for career mode
ScenarioWorker.fetch.LoadMissingScenarioDataIntoGame();
//This only makes KSP complain
HighLogic.CurrentGame.CrewRoster.ValidateAssignments(HighLogic.CurrentGame);
DarkLog.Debug("Starting " + gameMode + " game...");
//.Start() seems to stupidly .Load() somewhere - Let's overwrite it so it loads correctly.
GamePersistence.SaveGame(HighLogic.CurrentGame, "persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
HighLogic.CurrentGame.Start();
ChatWorker.fetch.display = true;
DarkLog.Debug("Started!");
}
private void StopGame()
{
HighLogic.SaveFolder = "DarkMultiPlayer";
if (HighLogic.LoadedScene != GameScenes.MAINMENU)
{
HighLogic.LoadScene(GameScenes.MAINMENU);
}
//HighLogic.CurrentGame = null; This is no bueno
bodiesGees.Clear();
}
public Game.Modes ConvertGameMode(GameMode inputMode)
{
if (inputMode == GameMode.SANDBOX)
{
return Game.Modes.SANDBOX;
}
if (inputMode == GameMode.SCIENCE)
{
return Game.Modes.SCIENCE_SANDBOX;
}
if (inputMode == GameMode.CAREER)
{
return Game.Modes.CAREER;
}
return Game.Modes.SANDBOX;
}
private void FireResetEvent()
{
foreach (Action resetAction in resetEvent)
{
try
{
resetAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in FireResetEvent, exception: " + e);
}
}
}
private void OnApplicationQuit()
{
if (gameRunning && NetworkWorker.fetch.state == ClientState.RUNNING)
{
Application.CancelQuit();
ScenarioWorker.fetch.SendScenarioModules(true);
HighLogic.LoadScene(GameScenes.MAINMENU);
}
}
private void SetupDirectoriesIfNeeded()
{
string darkMultiPlayerSavesDirectory = Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "saves"), "DarkMultiPlayer");
CreateIfNeeded(darkMultiPlayerSavesDirectory);
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, "Ships"));
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, Path.Combine("Ships", "VAB")));
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, Path.Combine("Ships", "SPH")));
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, "Subassemblies"));
string darkMultiPlayerCacheDirectory = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Cache");
CreateIfNeeded(darkMultiPlayerCacheDirectory);
string darkMultiPlayerIncomingCacheDirectory = Path.Combine(Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Cache"), "Incoming");
CreateIfNeeded(darkMultiPlayerIncomingCacheDirectory);
string darkMultiPlayerFlagsDirectory = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Flags");
CreateIfNeeded(darkMultiPlayerFlagsDirectory);
}
private void SetupBlankGameIfNeeded()
{
string persistentFile = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "saves"), "DarkMultiPlayer"), "persistent.sfs");
if (!File.Exists(persistentFile))
{
DarkLog.Debug("Creating new blank persistent.sfs file");
Game blankGame = CreateBlankGame();
HighLogic.SaveFolder = "DarkMultiPlayer";
GamePersistence.SaveGame(blankGame, "persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
}
}
private Game CreateBlankGame()
{
Game returnGame = new Game();
//KSP complains about a missing message system if we don't do this.
returnGame.additionalSystems = new ConfigNode();
returnGame.additionalSystems.AddNode("MESSAGESYSTEM");
//Flightstate is null on new Game();
returnGame.flightState = new FlightState();
if (returnGame.flightState.mapViewFilterState == 0)
{
returnGame.flightState.mapViewFilterState = -1026;
}
//DMP stuff
returnGame.startScene = GameScenes.SPACECENTER;
returnGame.flagURL = Settings.fetch.selectedFlag;
returnGame.Title = "DarkMultiPlayer";
if (WarpWorker.fetch.warpMode == WarpMode.SUBSPACE)
{
returnGame.Parameters.Flight.CanQuickLoad = true;
returnGame.Parameters.Flight.CanRestart = true;
returnGame.Parameters.Flight.CanLeaveToEditor = true;
}
else
{
returnGame.Parameters.Flight.CanQuickLoad = false;
returnGame.Parameters.Flight.CanRestart = false;
returnGame.Parameters.Flight.CanLeaveToEditor = false;
}
HighLogic.SaveFolder = "DarkMultiPlayer";
return returnGame;
}
private void CreateIfNeeded(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using ModestTree.Util;
using ModestTree.Util.Debugging;
namespace Zenject
{
public class TickableManager
{
[InjectOptional]
readonly List<ITickable> _tickables = null;
[InjectOptional]
readonly List<IFixedTickable> _fixedTickables = null;
[InjectOptional]
readonly List<ILateTickable> _lateTickables = null;
[InjectOptional]
readonly List<ModestTree.Util.Tuple<Type, int>> _priorities = null;
[InjectOptional("Fixed")]
readonly List<ModestTree.Util.Tuple<Type, int>> _fixedPriorities = null;
[InjectOptional("Late")]
readonly List<ModestTree.Util.Tuple<Type, int>> _latePriorities = null;
[Inject]
readonly SingletonInstanceHelper _singletonInstanceHelper = null;
TaskUpdater<ITickable> _updater;
TaskUpdater<IFixedTickable> _fixedUpdater;
TaskUpdater<ILateTickable> _lateUpdater;
[InjectOptional]
bool _warnForMissing = false;
[PostInject]
public void Initialize()
{
InitTickables();
InitFixedTickables();
InitLateTickables();
if (_warnForMissing)
{
WarnForMissingBindings();
}
}
void WarnForMissingBindings()
{
var boundTypes = _tickables.Select(x => x.GetType()).Distinct();
var unboundTypes = _singletonInstanceHelper.GetActiveSingletonTypesDerivingFrom<ITickable>(boundTypes);
foreach (var objType in unboundTypes)
{
Log.Warn("Found unbound ITickable with type '" + objType.Name() + "'");
}
}
void InitFixedTickables()
{
_fixedUpdater = new TaskUpdater<IFixedTickable>(UpdateFixedTickable);
foreach (var type in _fixedPriorities.Select(x => x.First))
{
Assert.That(type.DerivesFrom<IFixedTickable>(),
"Expected type '{0}' to drive from IFixedTickable while checking priorities in TickableHandler", type.Name());
}
foreach (var tickable in _fixedTickables)
{
// Note that we use zero for unspecified priority
// This is nice because you can use negative or positive for before/after unspecified
var matches = _fixedPriorities.Where(x => tickable.GetType().DerivesFromOrEqual(x.First)).Select(x => x.Second).ToList();
int priority = matches.IsEmpty() ? 0 : matches.Single();
_fixedUpdater.AddTask(tickable, priority);
}
}
void InitTickables()
{
_updater = new TaskUpdater<ITickable>(UpdateTickable);
foreach (var type in _priorities.Select(x => x.First))
{
Assert.That(type.DerivesFrom<ITickable>(),
"Expected type '{0}' to drive from ITickable while checking priorities in TickableHandler", type.Name());
}
foreach (var tickable in _tickables)
{
// Note that we use zero for unspecified priority
// This is nice because you can use negative or positive for before/after unspecified
var matches = _priorities.Where(x => tickable.GetType().DerivesFromOrEqual(x.First)).Select(x => x.Second).ToList();
int priority = matches.IsEmpty() ? 0 : matches.Single();
_updater.AddTask(tickable, priority);
}
}
void InitLateTickables()
{
_lateUpdater = new TaskUpdater<ILateTickable>(UpdateLateTickable);
foreach (var type in _latePriorities.Select(x => x.First))
{
Assert.That(type.DerivesFrom<ILateTickable>(),
"Expected type '{0}' to drive from ILateTickable while checking priorities in TickableHandler", type.Name());
}
foreach (var tickable in _lateTickables)
{
// Note that we use zero for unspecified priority
// This is nice because you can use negative or positive for before/after unspecified
var matches = _latePriorities.Where(x => tickable.GetType().DerivesFromOrEqual(x.First)).Select(x => x.Second).ToList();
int priority = matches.IsEmpty() ? 0 : matches.Single();
_lateUpdater.AddTask(tickable, priority);
}
}
void UpdateLateTickable(ILateTickable tickable)
{
#if PROFILING_ENABLED
using (ProfileBlock.Start("{0}.LateTick()".Fmt(tickable.GetType().Name())))
#endif
{
tickable.LateTick();
}
}
void UpdateFixedTickable(IFixedTickable tickable)
{
#if PROFILING_ENABLED
using (ProfileBlock.Start("{0}.FixedTick()".Fmt(tickable.GetType().Name())))
#endif
{
tickable.FixedTick();
}
}
void UpdateTickable(ITickable tickable)
{
#if PROFILING_ENABLED
using (ProfileBlock.Start("{0}.Tick()".Fmt(tickable.GetType().Name())))
#endif
{
tickable.Tick();
}
}
public void Add(ITickable tickable, int priority)
{
_updater.AddTask(tickable, priority);
}
public void Add(ITickable tickable)
{
Add(tickable, 0);
}
public void AddLate(ILateTickable tickable, int priority)
{
_lateUpdater.AddTask(tickable, priority);
}
public void AddLate(ILateTickable tickable)
{
AddLate(tickable, 0);
}
public void AddFixed(IFixedTickable tickable, int priority)
{
_fixedUpdater.AddTask(tickable, priority);
}
public void AddFixed(IFixedTickable tickable)
{
_fixedUpdater.AddTask(tickable, 0);
}
public void Remove(ITickable tickable)
{
_updater.RemoveTask(tickable);
}
public void RemoveLate(ILateTickable tickable)
{
_lateUpdater.RemoveTask(tickable);
}
public void RemoveFixed(IFixedTickable tickable)
{
_fixedUpdater.RemoveTask(tickable);
}
public void Update()
{
_updater.OnFrameStart();
_updater.UpdateAll();
}
public void FixedUpdate()
{
_fixedUpdater.OnFrameStart();
_fixedUpdater.UpdateAll();
}
public void LateUpdate()
{
_lateUpdater.OnFrameStart();
_lateUpdater.UpdateAll();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
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>
/// The Azure SQL Database management API provides a RESTful set of web
/// services that interact with Azure SQL Database services to manage your
/// databases. The API enables you to create, retrieve, update, and delete
/// databases.
/// </summary>
public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription ID that identifies an Azure subscription.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the ICapabilitiesOperations.
/// </summary>
public virtual ICapabilitiesOperations Capabilities { get; private set; }
/// <summary>
/// Gets the IFirewallRulesOperations.
/// </summary>
public virtual IFirewallRulesOperations FirewallRules { get; private set; }
/// <summary>
/// Gets the IDatabasesOperations.
/// </summary>
public virtual IDatabasesOperations Databases { get; private set; }
/// <summary>
/// Gets the IServersOperations.
/// </summary>
public virtual IServersOperations Servers { get; private set; }
/// <summary>
/// Gets the IElasticPoolsOperations.
/// </summary>
public virtual IElasticPoolsOperations ElasticPools { get; private set; }
/// <summary>
/// Gets the IRecommendedElasticPoolsOperations.
/// </summary>
public virtual IRecommendedElasticPoolsOperations RecommendedElasticPools { get; private set; }
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SqlManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SqlManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SqlManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SqlManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SqlManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Capabilities = new CapabilitiesOperations(this);
FirewallRules = new FirewallRulesOperations(this);
Databases = new DatabasesOperations(this);
Servers = new ServersOperations(this);
ElasticPools = new ElasticPoolsOperations(this);
RecommendedElasticPools = new RecommendedElasticPoolsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Lists all of the available SQL Rest API operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<OperationListResult>> ListOperationsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2014-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("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListOperations", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Sql/operations").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
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 (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<OperationListResult>();
_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 = SafeJsonConvert.DeserializeObject<OperationListResult>(_responseContent, 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;
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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;
namespace Spine {
public class IkConstraint : IUpdatable {
internal IkConstraintData data;
internal ExposedList<Bone> bones = new ExposedList<Bone>();
internal Bone target;
internal int bendDirection;
internal float mix;
public IkConstraintData Data { get { return data; } }
public ExposedList<Bone> Bones { get { return bones; } }
public Bone Target { get { return target; } set { target = value; } }
public int BendDirection { get { return bendDirection; } set { bendDirection = value; } }
public float Mix { get { return mix; } set { mix = value; } }
public IkConstraint (IkConstraintData data, Skeleton skeleton) {
if (data == null) throw new ArgumentNullException("data cannot be null.");
if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null.");
this.data = data;
mix = data.mix;
bendDirection = data.bendDirection;
bones = new ExposedList<Bone>(data.bones.Count);
foreach (BoneData boneData in data.bones)
bones.Add(skeleton.FindBone(boneData.name));
target = skeleton.FindBone(data.target.name);
}
public void Update () {
Apply();
}
public void Apply () {
Bone target = this.target;
ExposedList<Bone> bones = this.bones;
switch (bones.Count) {
case 1:
Apply(bones.Items[0], target.worldX, target.worldY, mix);
break;
case 2:
Apply(bones.Items[0], bones.Items[1], target.worldX, target.worldY, bendDirection, mix);
break;
}
}
override public String ToString () {
return data.name;
}
/// <summary>Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified
/// in the world coordinate system.</summary>
static public void Apply (Bone bone, float targetX, float targetY, float alpha) {
float parentRotation = bone.parent == null ? 0 : bone.parent.WorldRotationX;
float rotation = bone.rotation;
float rotationIK = MathUtils.Atan2(targetY - bone.worldY, targetX - bone.worldX) * MathUtils.radDeg - parentRotation;
if (bone.worldSignX != bone.worldSignY) rotationIK = 360 - rotationIK;
if (rotationIK > 180) rotationIK -= 360;
else if (rotationIK < -180) rotationIK += 360;
bone.UpdateWorldTransform(bone.x, bone.y, rotation + (rotationIK - rotation) * alpha, bone.scaleX, bone.scaleY);
}
/// <summary>Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as
/// possible. The target is specified in the world coordinate system.</summary>
/// <param name="child">A direct descendant of the parent bone.</param>
static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, float alpha) {
if (alpha == 0) return;
float px = parent.x, py = parent.y, psx = parent.scaleX, psy = parent.scaleY, csx = child.scaleX, cy = child.y;
int offset1, offset2, sign2;
if (psx < 0) {
psx = -psx;
offset1 = 180;
sign2 = -1;
} else {
offset1 = 0;
sign2 = 1;
}
if (psy < 0) {
psy = -psy;
sign2 = -sign2;
}
if (csx < 0) {
csx = -csx;
offset2 = 180;
} else
offset2 = 0;
Bone pp = parent.parent;
float tx, ty, dx, dy;
if (pp == null) {
tx = targetX - px;
ty = targetY - py;
dx = child.worldX - px;
dy = child.worldY - py;
} else {
float a = pp.a, b = pp.b, c = pp.c, d = pp.d, invDet = 1 / (a * d - b * c);
float wx = pp.worldX, wy = pp.worldY, x = targetX - wx, y = targetY - wy;
tx = (x * d - y * b) * invDet - px;
ty = (y * a - x * c) * invDet - py;
x = child.worldX - wx;
y = child.worldY - wy;
dx = (x * d - y * b) * invDet - px;
dy = (y * a - x * c) * invDet - py;
}
float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2;
if (Math.Abs(psx - psy) <= 0.0001f) {
l2 *= psx;
float cos = (tx * tx + ty * ty - l1 * l1 - l2 * l2) / (2 * l1 * l2);
if (cos < -1) cos = -1;
else if (cos > 1) cos = 1;
a2 = (float)Math.Acos(cos) * bendDir;
float a = l1 + l2 * cos, o = l2 * MathUtils.Sin(a2);
a1 = MathUtils.Atan2(ty * a - tx * o, tx * a + ty * o);
} else {
cy = 0;
float a = psx * l2, b = psy * l2, ta = MathUtils.Atan2(ty, tx);
float aa = a * a, bb = b * b, ll = l1 * l1, dd = tx * tx + ty * ty;
float c0 = bb * ll + aa * dd - aa * bb, c1 = -2 * bb * l1, c2 = bb - aa;
float d = c1 * c1 - 4 * c2 * c0;
if (d >= 0) {
float q = (float)Math.Sqrt(d);
if (c1 < 0) q = -q;
q = -(c1 + q) / 2;
float r0 = q / c2, r1 = c0 / q;
float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1;
if (r * r <= dd) {
float y1 = (float)Math.Sqrt(dd - r * r) * bendDir;
a1 = ta - MathUtils.Atan2(y1, r);
a2 = MathUtils.Atan2(y1 / psy, (r - l1) / psx);
goto outer;
}
}
float minAngle = 0, minDist = float.MaxValue, minX = 0, minY = 0;
float maxAngle = 0, maxDist = 0, maxX = 0, maxY = 0;
float x = l1 + a, dist = x * x;
if (dist > maxDist) {
maxAngle = 0;
maxDist = dist;
maxX = x;
}
x = l1 - a;
dist = x * x;
if (dist < minDist) {
minAngle = MathUtils.PI;
minDist = dist;
minX = x;
}
float angle = (float)Math.Acos(-a * l1 / (aa - bb));
x = a * MathUtils.Cos(angle) + l1;
float y = b * MathUtils.Sin(angle);
dist = x * x + y * y;
if (dist < minDist) {
minAngle = angle;
minDist = dist;
minX = x;
minY = y;
}
if (dist > maxDist) {
maxAngle = angle;
maxDist = dist;
maxX = x;
maxY = y;
}
if (dd <= (minDist + maxDist) / 2) {
a1 = ta - MathUtils.Atan2(minY * bendDir, minX);
a2 = minAngle * bendDir;
} else {
a1 = ta - MathUtils.Atan2(maxY * bendDir, maxX);
a2 = maxAngle * bendDir;
}
}
outer:
float offset = MathUtils.Atan2(cy, child.x) * sign2;
a1 = (a1 - offset) * MathUtils.radDeg + offset1;
a2 = (a2 + offset) * MathUtils.radDeg * sign2 + offset2;
if (a1 > 180) a1 -= 360;
else if (a1 < -180) a1 += 360;
if (a2 > 180) a2 -= 360;
else if (a2 < -180) a2 += 360;
float rotation = parent.rotation;
parent.UpdateWorldTransform(parent.x, parent.y, rotation + (a1 - rotation) * alpha, parent.scaleX, parent.scaleY);
rotation = child.rotation;
child.UpdateWorldTransform(child.x, cy, rotation + (a2 - rotation) * alpha, child.scaleX, child.scaleY);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ClientConfigurationHost.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using System.Configuration.Internal;
using System.IO;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Threading;
using System.Security;
using System.Net;
using System.Security.Principal;
using System.Diagnostics.CodeAnalysis;
internal sealed class ClientConfigurationHost : DelegatingConfigHost, IInternalConfigClientHost {
internal const string MachineConfigName = "MACHINE";
internal const string ExeConfigName = "EXE";
internal const string RoamingUserConfigName = "ROAMING_USER";
internal const string LocalUserConfigName = "LOCAL_USER";
internal const string MachineConfigPath = MachineConfigName;
internal const string ExeConfigPath = MachineConfigPath + "/" + ExeConfigName;
internal const string RoamingUserConfigPath = ExeConfigPath + "/" + RoamingUserConfigName;
internal const string LocalUserConfigPath = RoamingUserConfigPath + "/" + LocalUserConfigName;
private const string ConfigExtension = ".config";
private const string MachineConfigFilename = "machine.config";
private const string MachineConfigSubdirectory = "Config";
private static object s_init = new object();
private static object s_version = new object();
private static volatile string s_machineConfigFilePath;
private string _exePath; // the physical path to the exe being configured
private ClientConfigPaths _configPaths; // physical paths to client config files
private ExeConfigurationFileMap _fileMap; // optional file map
private bool _initComplete;
internal ClientConfigurationHost() {
Host = new InternalConfigHost();
}
internal ClientConfigPaths ConfigPaths {
get {
if (_configPaths == null) {
_configPaths = ClientConfigPaths.GetPaths(_exePath, _initComplete);
}
return _configPaths;
}
}
internal void RefreshConfigPaths() {
// Refresh current config paths.
if (_configPaths != null && !_configPaths.HasEntryAssembly && _exePath == null) {
ClientConfigPaths.RefreshCurrent();
_configPaths = null;
}
}
static internal string MachineConfigFilePath {
[FileIOPermissionAttribute(SecurityAction.Assert, AllFiles = FileIOPermissionAccess.PathDiscovery)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "The callers do not expose this information without performing the appropriate demands themselves.")]
get {
if (s_machineConfigFilePath == null) {
string directory = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
s_machineConfigFilePath = Path.Combine(Path.Combine(directory, MachineConfigSubdirectory), MachineConfigFilename);
}
return s_machineConfigFilePath;
}
}
internal bool HasRoamingConfig {
get {
if (_fileMap != null) {
return !String.IsNullOrEmpty(_fileMap.RoamingUserConfigFilename);
}
else {
return ConfigPaths.HasRoamingConfig;
}
}
}
internal bool HasLocalConfig {
get {
if (_fileMap != null) {
return !String.IsNullOrEmpty(_fileMap.LocalUserConfigFilename);
}
else {
return ConfigPaths.HasLocalConfig;
}
}
}
internal bool IsAppConfigHttp {
get {
return !IsFile(GetStreamName(ExeConfigPath));
}
}
// IInternalConfigClientHost methods are used by Venus and Whitehorse
// so as not to require explicit knowledge of the contents of the
// config path.
// return true if the config path is for an exe config, false otherwise.
bool IInternalConfigClientHost.IsExeConfig(string configPath) {
return StringUtil.EqualsIgnoreCase(configPath, ExeConfigPath);
}
bool IInternalConfigClientHost.IsRoamingUserConfig(string configPath) {
return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath);
}
bool IInternalConfigClientHost.IsLocalUserConfig(string configPath) {
return StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath);
}
// Return true if the config path is for a user.config file, false otherwise.
private bool IsUserConfig(string configPath) {
return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath) ||
StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath);
}
string IInternalConfigClientHost.GetExeConfigPath() {
return ExeConfigPath;
}
string IInternalConfigClientHost.GetRoamingUserConfigPath() {
return RoamingUserConfigPath;
}
string IInternalConfigClientHost.GetLocalUserConfigPath() {
return LocalUserConfigPath;
}
public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams) {
try {
ConfigurationFileMap fileMap = (ConfigurationFileMap) hostInitParams[0];
_exePath = (string) hostInitParams[1];
Host.Init(configRoot, hostInitParams);
// Do not complete initialization in runtime config, to avoid expense of
// loading user.config files that may not be required.
_initComplete = configRoot.IsDesignTime;
if (fileMap != null && !String.IsNullOrEmpty(_exePath)) {
throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init");
}
if (String.IsNullOrEmpty(_exePath)) {
_exePath = null;
}
// Initialize the fileMap, if provided.
if (fileMap != null) {
_fileMap = new ExeConfigurationFileMap();
if (!String.IsNullOrEmpty(fileMap.MachineConfigFilename)) {
_fileMap.MachineConfigFilename = Path.GetFullPath(fileMap.MachineConfigFilename);
}
ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap;
if (exeFileMap != null) {
if (!String.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) {
_fileMap.ExeConfigFilename = Path.GetFullPath(exeFileMap.ExeConfigFilename);
}
if (!String.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename)) {
_fileMap.RoamingUserConfigFilename = Path.GetFullPath(exeFileMap.RoamingUserConfigFilename);
}
if (!String.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename)) {
_fileMap.LocalUserConfigFilename = Path.GetFullPath(exeFileMap.LocalUserConfigFilename);
}
}
}
}
catch (SecurityException) {
// Lets try to give them some information telling them
// they don't have enough security privileges
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_client_config_init_security));
}
catch {
throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init");
}
}
public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath,
IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) {
locationSubPath = null;
configPath = (string) hostInitConfigurationParams[2];
locationConfigPath = null;
Init(configRoot, hostInitConfigurationParams);
}
// Delay init if we have not been asked to complete init, and it is a user.config file.
public override bool IsInitDelayed(IInternalConfigRecord configRecord) {
return !_initComplete && IsUserConfig(configRecord.ConfigPath);
}
public override void RequireCompleteInit(IInternalConfigRecord record) {
// Loading information about user.config files is expensive,
// so do it just once by locking.
lock (this) {
if (!_initComplete) {
// Note that all future requests for config must be complete.
_initComplete = true;
// Throw out the ConfigPath for this exe.
ClientConfigPaths.RefreshCurrent();
// Throw out our cached copy.
_configPaths = null;
// Force loading of user.config file information under lock.
ClientConfigPaths configPaths = ConfigPaths;
}
}
}
// config path support
public override bool IsConfigRecordRequired(string configPath) {
string configName = ConfigPathUtility.GetName(configPath);
switch (configName) {
default:
// should never get here
return false;
case MachineConfigName:
case ExeConfigName:
return true;
case RoamingUserConfigName:
// Makes the design easier even if we only have an empty Roaming config record.
return HasRoamingConfig || HasLocalConfig;
case LocalUserConfigName:
return HasLocalConfig;
}
}
// stream support
public override string GetStreamName(string configPath) {
string configName = ConfigPathUtility.GetName(configPath);
if (_fileMap != null) {
switch (configName) {
default:
// should never get here
goto case MachineConfigName;
case MachineConfigName:
return _fileMap.MachineConfigFilename;
case ExeConfigName:
return _fileMap.ExeConfigFilename;
case RoamingUserConfigName:
return _fileMap.RoamingUserConfigFilename;
case LocalUserConfigName:
return _fileMap.LocalUserConfigFilename;
}
}
else {
switch (configName) {
default:
// should never get here
goto case MachineConfigName;
case MachineConfigName:
return MachineConfigFilePath;
case ExeConfigName:
return ConfigPaths.ApplicationConfigUri;
case RoamingUserConfigName:
return ConfigPaths.RoamingConfigFilename;
case LocalUserConfigName:
return ConfigPaths.LocalConfigFilename;
}
}
}
public override string GetStreamNameForConfigSource(string streamName, string configSource) {
if (IsFile(streamName)) {
return Host.GetStreamNameForConfigSource(streamName, configSource);
}
int index = streamName.LastIndexOf('/');
if (index < 0)
return null;
string parentUri = streamName.Substring(0, index + 1);
string result = parentUri + configSource.Replace('\\', '/');
return result;
}
public override object GetStreamVersion(string streamName) {
if (IsFile(streamName)) {
return Host.GetStreamVersion(streamName);
}
// assume it is the same
return s_version;
}
// default impl treats name as a file name
// null means stream doesn't exist for this name
public override Stream OpenStreamForRead(string streamName) {
// the streamName can either be a file name, or a URI
if (IsFile(streamName)) {
return Host.OpenStreamForRead(streamName);
}
if (streamName == null) {
return null;
}
// scheme is http
WebClient client = new WebClient();
// Try using default credentials
try {
client.Credentials = CredentialCache.DefaultCredentials;
}
catch {
}
byte[] fileData = null;
try {
fileData = client.DownloadData(streamName);
}
catch {
}
if (fileData == null) {
return null;
}
MemoryStream stream = new MemoryStream(fileData);
return stream;
}
public override Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) {
// only support files, not URIs
if (!IsFile(streamName)) {
throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::OpenStreamForWrite");
}
return Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext);
}
public override void DeleteStream(string streamName) {
// only support files, not URIs
if (!IsFile(streamName)) {
throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Delete");
}
Host.DeleteStream(streamName);
}
// RefreshConfig support - runtime only
public override bool SupportsRefresh {
get {return true;}
}
// path support
public override bool SupportsPath {
get {return false;}
}
// Do we support location tags?
public override bool SupportsLocation {
get {return false;}
}
public override bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) {
string allowedConfigPath;
switch (allowExeDefinition) {
case ConfigurationAllowExeDefinition.MachineOnly:
allowedConfigPath = MachineConfigPath;
break;
case ConfigurationAllowExeDefinition.MachineToApplication:
allowedConfigPath = ExeConfigPath;
break;
case ConfigurationAllowExeDefinition.MachineToRoamingUser:
allowedConfigPath = RoamingUserConfigPath;
break;
// MachineToLocalUser does not current have any definition restrictions
case ConfigurationAllowExeDefinition.MachineToLocalUser:
return true;
default:
// If we have extended ConfigurationAllowExeDefinition
// make sure to update this switch accordingly
throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::IsDefinitionAllowed");
}
return configPath.Length <= allowedConfigPath.Length;
}
public override void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) {
if (!IsDefinitionAllowed(configPath, allowDefinition, allowExeDefinition)) {
switch (allowExeDefinition) {
case ConfigurationAllowExeDefinition.MachineOnly:
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_allow_exedefinition_error_machine), errorInfo);
case ConfigurationAllowExeDefinition.MachineToApplication:
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_allow_exedefinition_error_application), errorInfo);
case ConfigurationAllowExeDefinition.MachineToRoamingUser:
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_allow_exedefinition_error_roaminguser), errorInfo);
default:
// If we have extended ConfigurationAllowExeDefinition
// make sure to update this switch accordingly
throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::VerifyDefinitionAllowed");
}
}
}
// prefetch support
public override bool PrefetchAll(string configPath, string streamName) {
// If it's a file, we don't need to. Otherwise (e.g. it's from the web), we'll prefetch everything.
return !IsFile(streamName);
}
public override bool PrefetchSection(string sectionGroupName, string sectionName) {
return sectionGroupName == "system.net";
}
// we trust machine.config - admins settings do not have security restrictions.
public override bool IsTrustedConfigPath(string configPath) {
return configPath == MachineConfigPath;
}
[SecurityPermission(SecurityAction.Assert, ControlEvidence=true)]
public override void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady) {
// Get the stream name as a URL
string url;
bool isFile = IsFile(configRecord.StreamName);
if (isFile) {
url = UrlPath.ConvertFileNameToUrl(configRecord.StreamName);
}
else {
url = configRecord.StreamName;
}
Evidence evidence = new Evidence();
// Add Url evidence, which is simply the URL.
evidence.AddHostEvidence(new Url(url));
// Add Zone evidence - My Computer, Intranet, Internet, etc.
evidence.AddHostEvidence(Zone.CreateFromUrl(url));
// Add Site evidence if the url is http.
if (!isFile) {
evidence.AddHostEvidence(Site.CreateFromUrl(url));
}
// Get the resulting permission set.
permissionSet = SecurityManager.GetStandardSandbox(evidence);
// Client host is always ready to return permissions.
isHostReady = true;
}
//
// Impersonate for Client Config
// Use the process identity
//
[SecurityPermissionAttribute(SecurityAction.Assert, Flags=SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.UnmanagedCode)]
public override IDisposable Impersonate() {
// Use the process identity
return WindowsIdentity.Impersonate(IntPtr.Zero);
}
// context support
public override object CreateDeprecatedConfigContext(string configPath) {
return null;
}
// CreateConfigurationContext
//
// Create the new context
//
public override object
CreateConfigurationContext( string configPath,
string locationSubPath )
{
return new ExeContext(GetUserLevel(configPath), ConfigPaths.ApplicationUri);
}
// GetUserLevel
//
// Given a configPath, determine what the user level is?
//
private ConfigurationUserLevel GetUserLevel(string configPath)
{
ConfigurationUserLevel level;
switch (ConfigPathUtility.GetName(configPath)) {
case MachineConfigName:
// Machine Level
level = ConfigurationUserLevel.None;
break;
case ExeConfigName:
// Exe Level
level = ConfigurationUserLevel.None;
break;
case LocalUserConfigName:
// User Level
level = ConfigurationUserLevel.PerUserRoamingAndLocal;
break;
case RoamingUserConfigName:
// Roaming Level
level = ConfigurationUserLevel.PerUserRoaming;
break;
default:
Debug.Fail("unrecognized configPath " + configPath);
level = ConfigurationUserLevel.None;
break;
}
return level;
}
//
// Create a Configuration object.
//
static internal Configuration OpenExeConfiguration(ConfigurationFileMap fileMap, bool isMachine, ConfigurationUserLevel userLevel, string exePath) {
// validate userLevel argument
switch (userLevel) {
default:
throw ExceptionUtil.ParameterInvalid("userLevel");
case ConfigurationUserLevel.None:
case ConfigurationUserLevel.PerUserRoaming:
case ConfigurationUserLevel.PerUserRoamingAndLocal:
break;
}
// validate fileMap arguments
if (fileMap != null) {
if (String.IsNullOrEmpty(fileMap.MachineConfigFilename)) {
throw ExceptionUtil.ParameterNullOrEmpty("fileMap.MachineConfigFilename");
}
ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap;
if (exeFileMap != null) {
switch (userLevel) {
case ConfigurationUserLevel.None:
if (String.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) {
throw ExceptionUtil.ParameterNullOrEmpty("fileMap.ExeConfigFilename");
}
break;
case ConfigurationUserLevel.PerUserRoaming:
if (String.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename)) {
throw ExceptionUtil.ParameterNullOrEmpty("fileMap.RoamingUserConfigFilename");
}
goto case ConfigurationUserLevel.None;
case ConfigurationUserLevel.PerUserRoamingAndLocal:
if (String.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename)) {
throw ExceptionUtil.ParameterNullOrEmpty("fileMap.LocalUserConfigFilename");
}
goto case ConfigurationUserLevel.PerUserRoaming;
}
}
}
string configPath = null;
if (isMachine) {
configPath = MachineConfigPath;
}
else {
switch (userLevel) {
case ConfigurationUserLevel.None:
configPath = ExeConfigPath;
break;
case ConfigurationUserLevel.PerUserRoaming:
configPath = RoamingUserConfigPath;
break;
case ConfigurationUserLevel.PerUserRoamingAndLocal:
configPath = LocalUserConfigPath;
break;
}
}
Configuration configuration = new Configuration(null, typeof(ClientConfigurationHost), fileMap, exePath, configPath);
return configuration;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
namespace System.Data
{
/// <summary>
/// Represents a collection of constraints for a <see cref='System.Data.DataTable'/>.
/// </summary>
[DefaultEvent(nameof(CollectionChanged))]
public sealed class ConstraintCollection : InternalDataCollectionBase
{
private readonly DataTable _table;
private readonly ArrayList _list = new ArrayList();
private int _defaultNameIndex = 1;
private CollectionChangeEventHandler _onCollectionChanged;
private Constraint[] _delayLoadingConstraints;
private bool _fLoadForeignKeyConstraintsOnly = false;
/// <summary>
/// ConstraintCollection constructor. Used only by DataTable.
/// </summary>
internal ConstraintCollection(DataTable table)
{
_table = table;
}
/// <summary>
/// Gets the list of objects contained by the collection.
/// </summary>
protected override ArrayList List => _list;
/// <summary>
/// Gets the <see cref='System.Data.Constraint'/>
/// from the collection at the specified index.
/// </summary>
public Constraint this[int index]
{
get
{
if (index >= 0 && index < List.Count)
{
return (Constraint)List[index];
}
throw ExceptionBuilder.ConstraintOutOfRange(index);
}
}
/// <summary>
/// The DataTable with which this ConstraintCollection is associated
/// </summary>
internal DataTable Table => _table;
/// <summary>
/// Gets the <see cref='System.Data.Constraint'/> from the collection with the specified name.
/// </summary>
public Constraint this[string name]
{
get
{
int index = InternalIndexOf(name);
if (index == -2)
{
throw ExceptionBuilder.CaseInsensitiveNameConflict(name);
}
return (index < 0) ? null : (Constraint)List[index];
}
}
/// <summary>
/// Adds the constraint to the collection.
/// </summary>
public void Add(Constraint constraint) => Add(constraint, true);
// To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting
internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign)
{
if (constraint == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
}
// It is an error if we find an equivalent constraint already in collection
if (FindConstraint(constraint) != null)
{
throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName);
}
if (1 < _table.NestedParentRelations.Length)
{
if (!AutoGenerated(constraint))
{
throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(_table.TableName);
}
}
if (constraint is UniqueConstraint)
{
if (((UniqueConstraint)constraint)._bPrimaryKey)
{
if (Table._primaryKey != null)
{
throw ExceptionBuilder.AddPrimaryKeyConstraint();
}
}
AddUniqueConstraint((UniqueConstraint)constraint);
}
else if (constraint is ForeignKeyConstraint)
{
ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint;
if (addUniqueWhenAddingForeign)
{
UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference);
if (key == null)
{
if (constraint.ConstraintName.Length == 0)
constraint.ConstraintName = AssignName();
else
RegisterName(constraint.ConstraintName);
key = new UniqueConstraint(fk.RelatedColumnsReference);
fk.RelatedTable.Constraints.Add(key);
}
}
AddForeignKeyConstraint((ForeignKeyConstraint)constraint);
}
BaseAdd(constraint);
ArrayAdd(constraint);
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint));
if (constraint is UniqueConstraint)
{
if (((UniqueConstraint)constraint)._bPrimaryKey)
{
Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference;
}
}
}
/// <summary>
/// Constructs a new <see cref='System.Data.UniqueConstraint'/> using the
/// specified array of <see cref='System.Data.DataColumn'/>
/// objects and adds it to the collection.
/// </summary>
public Constraint Add(string name, DataColumn[] columns, bool primaryKey)
{
UniqueConstraint constraint = new UniqueConstraint(name, columns);
Add(constraint);
if (primaryKey)
Table.PrimaryKey = columns;
return constraint;
}
/// <summary>
/// Constructs a new <see cref='System.Data.UniqueConstraint'/> using the
/// specified <see cref='System.Data.DataColumn'/> and adds it to the collection.
/// </summary>
public Constraint Add(string name, DataColumn column, bool primaryKey)
{
UniqueConstraint constraint = new UniqueConstraint(name, column);
Add(constraint);
if (primaryKey)
Table.PrimaryKey = constraint.ColumnsReference;
return constraint;
}
/// <summary>
/// Constructs a new <see cref='System.Data.ForeignKeyConstraint'/>
/// with the
/// specified parent and child
/// columns and adds the constraint to the collection.
/// </summary>
public Constraint Add(string name, DataColumn primaryKeyColumn, DataColumn foreignKeyColumn)
{
ForeignKeyConstraint constraint = new ForeignKeyConstraint(name, primaryKeyColumn, foreignKeyColumn);
Add(constraint);
return constraint;
}
/// <summary>
/// Constructs a new <see cref='System.Data.ForeignKeyConstraint'/> with the specified parent columns and
/// child columns and adds the constraint to the collection.
/// </summary>
public Constraint Add(string name, DataColumn[] primaryKeyColumns, DataColumn[] foreignKeyColumns)
{
ForeignKeyConstraint constraint = new ForeignKeyConstraint(name, primaryKeyColumns, foreignKeyColumns);
Add(constraint);
return constraint;
}
public void AddRange(Constraint[] constraints)
{
if (_table.fInitInProgress)
{
_delayLoadingConstraints = constraints;
_fLoadForeignKeyConstraintsOnly = false;
return;
}
if (constraints != null)
{
foreach (Constraint constr in constraints)
{
if (constr != null)
{
Add(constr);
}
}
}
}
private void AddUniqueConstraint(UniqueConstraint constraint)
{
DataColumn[] columns = constraint.ColumnsReference;
for (int i = 0; i < columns.Length; i++)
{
if (columns[i].Table != _table)
{
throw ExceptionBuilder.ConstraintForeignTable();
}
}
constraint.ConstraintIndexInitialize();
if (!constraint.CanEnableConstraint())
{
constraint.ConstraintIndexClear();
throw ExceptionBuilder.UniqueConstraintViolation();
}
}
private void AddForeignKeyConstraint(ForeignKeyConstraint constraint)
{
if (!constraint.CanEnableConstraint())
{
throw ExceptionBuilder.ConstraintParentValues();
}
constraint.CheckCanAddToCollection(this);
}
private bool AutoGenerated(Constraint constraint)
{
ForeignKeyConstraint fk = (constraint as ForeignKeyConstraint);
if (null != fk)
{
return XmlTreeGen.AutoGenerated(fk, false);
}
else
{
UniqueConstraint unique = (UniqueConstraint)constraint;
return XmlTreeGen.AutoGenerated(unique);
}
}
/// <summary>
/// Occurs when the <see cref='System.Data.ConstraintCollection'/> is changed through additions or
/// removals.
/// </summary>
public event CollectionChangeEventHandler CollectionChanged
{
add
{
_onCollectionChanged += value;
}
remove
{
_onCollectionChanged -= value;
}
}
/// <summary>
/// Adds the constraint to the constraints array.
/// </summary>
private void ArrayAdd(Constraint constraint)
{
Debug.Assert(constraint != null, "Attempt to add null constraint to constraint array");
List.Add(constraint);
}
private void ArrayRemove(Constraint constraint)
{
List.Remove(constraint);
}
/// <summary>
/// Creates a new default name.
/// </summary>
internal string AssignName()
{
string newName = MakeName(_defaultNameIndex);
_defaultNameIndex++;
return newName;
}
/// <summary>
/// Does verification on the constraint and it's name.
/// An ArgumentNullException is thrown if this constraint is null. An ArgumentException is thrown if this constraint
/// already belongs to this collection, belongs to another collection.
/// A DuplicateNameException is thrown if this collection already has a constraint with the same
/// name (case insensitive).
/// </summary>
private void BaseAdd(Constraint constraint)
{
if (constraint == null)
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
if (constraint.ConstraintName.Length == 0)
constraint.ConstraintName = AssignName();
else
RegisterName(constraint.ConstraintName);
constraint.InCollection = true;
}
/// <summary>
/// BaseGroupSwitch will intelligently remove and add tables from the collection.
/// </summary>
private void BaseGroupSwitch(Constraint[] oldArray, int oldLength, Constraint[] newArray, int newLength)
{
// We're doing a smart diff of oldArray and newArray to find out what
// should be removed. We'll pass through oldArray and see if it exists
// in newArray, and if not, do remove work. newBase is an opt. in case
// the arrays have similar prefixes.
int newBase = 0;
for (int oldCur = 0; oldCur < oldLength; oldCur++)
{
bool found = false;
for (int newCur = newBase; newCur < newLength; newCur++)
{
if (oldArray[oldCur] == newArray[newCur])
{
if (newBase == newCur)
{
newBase++;
}
found = true;
break;
}
}
if (!found)
{
// This means it's in oldArray and not newArray. Remove it.
BaseRemove(oldArray[oldCur]);
List.Remove(oldArray[oldCur]);
}
}
// Now, let's pass through news and those that don't belong, add them.
for (int newCur = 0; newCur < newLength; newCur++)
{
if (!newArray[newCur].InCollection)
BaseAdd(newArray[newCur]);
List.Add(newArray[newCur]);
}
}
/// <summary>
/// Does verification on the constraint and it's name.
/// An ArgumentNullException is thrown if this constraint is null. An ArgumentException is thrown
/// if this constraint doesn't belong to this collection or if this constraint is part of a relationship.
/// </summary>
private void BaseRemove(Constraint constraint)
{
if (constraint == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
}
if (constraint.Table != _table)
{
throw ExceptionBuilder.ConstraintRemoveFailed();
}
UnregisterName(constraint.ConstraintName);
constraint.InCollection = false;
if (constraint is UniqueConstraint)
{
for (int i = 0; i < Table.ChildRelations.Count; i++)
{
DataRelation rel = Table.ChildRelations[i];
if (rel.ParentKeyConstraint == constraint)
rel.SetParentKeyConstraint(null);
}
((UniqueConstraint)constraint).ConstraintIndexClear();
}
else if (constraint is ForeignKeyConstraint)
{
for (int i = 0; i < Table.ParentRelations.Count; i++)
{
DataRelation rel = Table.ParentRelations[i];
if (rel.ChildKeyConstraint == constraint)
rel.SetChildKeyConstraint(null);
}
}
}
/// <summary>
/// Indicates if a <see cref='System.Data.Constraint'/> can be removed.
/// </summary>
// PUBLIC because called by design-time... need to consider this.
public bool CanRemove(Constraint constraint)
{
return CanRemove(constraint, fThrowException: false);
}
internal bool CanRemove(Constraint constraint, bool fThrowException)
{
return constraint.CanBeRemovedFromCollection(this, fThrowException);
}
/// <summary>
/// Clears the collection of any <see cref='System.Data.Constraint'/>
/// objects.
/// </summary>
public void Clear()
{
if (_table != null)
{
_table.PrimaryKey = null;
for (int i = 0; i < _table.ParentRelations.Count; i++)
{
_table.ParentRelations[i].SetChildKeyConstraint(null);
}
for (int i = 0; i < _table.ChildRelations.Count; i++)
{
_table.ChildRelations[i].SetParentKeyConstraint(null);
}
}
if (_table.fInitInProgress && _delayLoadingConstraints != null)
{
_delayLoadingConstraints = null;
_fLoadForeignKeyConstraintsOnly = false;
}
int oldLength = List.Count;
Constraint[] constraints = new Constraint[List.Count];
List.CopyTo(constraints, 0);
try
{
// this will smartly add and remove the appropriate tables.
BaseGroupSwitch(constraints, oldLength, null, 0);
}
catch (Exception e) when (Common.ADP.IsCatchableOrSecurityExceptionType(e))
{
// something messed up. restore to original state.
BaseGroupSwitch(null, 0, constraints, oldLength);
List.Clear();
for (int i = 0; i < oldLength; i++)
{
List.Add(constraints[i]);
}
throw;
}
List.Clear();
OnCollectionChanged(s_refreshEventArgs);
}
/// <summary>
/// Indicates whether the <see cref='System.Data.Constraint'/>, specified by name, exists in the collection.
/// </summary>
public bool Contains(string name)
{
return (InternalIndexOf(name) >= 0);
}
internal bool Contains(string name, bool caseSensitive)
{
if (!caseSensitive)
return Contains(name);
int index = InternalIndexOf(name);
if (index < 0)
return false;
return (name == ((Constraint)List[index]).ConstraintName);
}
public void CopyTo(Constraint[] array, int index)
{
if (array == null)
throw ExceptionBuilder.ArgumentNull(nameof(array));
if (index < 0)
throw ExceptionBuilder.ArgumentOutOfRange(nameof(index));
if (array.Length - index < _list.Count)
throw ExceptionBuilder.InvalidOffsetLength();
for (int i = 0; i < _list.Count; ++i)
{
array[index + i] = (Constraint)_list[i];
}
}
/// <summary>
/// Returns a matching constriant object.
/// </summary>
internal Constraint FindConstraint(Constraint constraint)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
if (((Constraint)List[i]).Equals(constraint))
return (Constraint)List[i];
}
return null;
}
/// <summary>
/// Returns a matching constriant object.
/// </summary>
internal UniqueConstraint FindKeyConstraint(DataColumn[] columns)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
UniqueConstraint constraint = (List[i] as UniqueConstraint);
if ((null != constraint) && CompareArrays(constraint.Key.ColumnsReference, columns))
{
return constraint;
}
}
return null;
}
/// <summary>
/// Returns a matching constriant object.
/// </summary>
internal UniqueConstraint FindKeyConstraint(DataColumn column)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
UniqueConstraint constraint = (List[i] as UniqueConstraint);
if ((null != constraint) && (constraint.Key.ColumnsReference.Length == 1) && (constraint.Key.ColumnsReference[0] == column))
return constraint;
}
return null;
}
/// <summary>
/// Returns a matching constriant object.
/// </summary>
internal ForeignKeyConstraint FindForeignKeyConstraint(DataColumn[] parentColumns, DataColumn[] childColumns)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
ForeignKeyConstraint constraint = (List[i] as ForeignKeyConstraint);
if ((null != constraint) &&
CompareArrays(constraint.ParentKey.ColumnsReference, parentColumns) &&
CompareArrays(constraint.ChildKey.ColumnsReference, childColumns))
return constraint;
}
return null;
}
private static bool CompareArrays(DataColumn[] a1, DataColumn[] a2)
{
Debug.Assert(a1 != null && a2 != null, "Invalid Arguments");
if (a1.Length != a2.Length)
return false;
int i, j;
for (i = 0; i < a1.Length; i++)
{
bool check = false;
for (j = 0; j < a2.Length; j++)
{
if (a1[i] == a2[j])
{
check = true;
break;
}
}
if (!check)
{
return false;
}
}
return true;
}
/// <summary>
/// Returns the index of the specified <see cref='System.Data.Constraint'/> .
/// </summary>
public int IndexOf(Constraint constraint)
{
if (null != constraint)
{
int count = Count;
for (int i = 0; i < count; ++i)
{
if (constraint == (Constraint)List[i])
return i;
}
// didn't find the constraint
}
return -1;
}
/// <summary>
/// Returns the index of the <see cref='System.Data.Constraint'/>, specified by name.
/// </summary>
public int IndexOf(string constraintName)
{
int index = InternalIndexOf(constraintName);
return (index < 0) ? -1 : index;
}
// Return value:
// >= 0: find the match
// -1: No match
// -2: At least two matches with different cases
internal int InternalIndexOf(string constraintName)
{
int cachedI = -1;
if ((null != constraintName) && (0 < constraintName.Length))
{
int constraintCount = List.Count;
int result = 0;
for (int i = 0; i < constraintCount; i++)
{
Constraint constraint = (Constraint)List[i];
result = NamesEqual(constraint.ConstraintName, constraintName, false, _table.Locale);
if (result == 1)
return i;
if (result == -1)
cachedI = (cachedI == -1) ? i : -2;
}
}
return cachedI;
}
/// <summary>
/// Makes a default name with the given index. e.g. Constraint1, Constraint2, ... Constrainti
/// </summary>
private string MakeName(int index)
{
if (1 == index)
{
return "Constraint1";
}
return "Constraint" + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// Raises the <see cref='System.Data.ConstraintCollection.CollectionChanged'/> event.
/// </summary>
private void OnCollectionChanged(CollectionChangeEventArgs ccevent)
{
_onCollectionChanged?.Invoke(this, ccevent);
}
/// <summary>
/// Registers this name as being used in the collection. Will throw an ArgumentException
/// if the name is already being used. Called by Add, All property, and Constraint.ConstraintName property.
/// if the name is equivalent to the next default name to hand out, we increment our defaultNameIndex.
/// </summary>
internal void RegisterName(string name)
{
Debug.Assert(name != null);
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
if (NamesEqual(name, ((Constraint)List[i]).ConstraintName, true, _table.Locale) != 0)
{
throw ExceptionBuilder.DuplicateConstraintName(((Constraint)List[i]).ConstraintName);
}
}
if (NamesEqual(name, MakeName(_defaultNameIndex), true, _table.Locale) != 0)
{
_defaultNameIndex++;
}
}
/// <summary>
/// Removes the specified <see cref='System.Data.Constraint'/> from the collection.
/// </summary>
public void Remove(Constraint constraint)
{
if (constraint == null)
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
// this will throw an exception if it can't be removed, otherwise indicates
// whether we need to remove it from the collection.
if (CanRemove(constraint, true))
{
// constraint can be removed
BaseRemove(constraint);
ArrayRemove(constraint);
if (constraint is UniqueConstraint && ((UniqueConstraint)constraint).IsPrimaryKey)
{
Table.PrimaryKey = null;
}
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, constraint));
}
}
/// <summary>
/// Removes the constraint at the specified index from the collection.
/// </summary>
public void RemoveAt(int index)
{
Constraint c = this[index];
if (c == null)
throw ExceptionBuilder.ConstraintOutOfRange(index);
Remove(c);
}
/// <summary>
/// Removes the constraint, specified by name, from the collection.
/// </summary>
public void Remove(string name)
{
Constraint c = this[name];
if (c == null)
throw ExceptionBuilder.ConstraintNotInTheTable(name);
Remove(c);
}
/// <summary>
/// Unregisters this name as no longer being used in the collection. Called by Remove, All property, and
/// Constraint.ConstraintName property. If the name is equivalent to the last proposed default name, we walk backwards
/// to find the next proper default name to use.
/// </summary>
internal void UnregisterName(string name)
{
if (NamesEqual(name, MakeName(_defaultNameIndex - 1), true, _table.Locale) != 0)
{
do
{
_defaultNameIndex--;
} while (_defaultNameIndex > 1 &&
!Contains(MakeName(_defaultNameIndex - 1)));
}
}
internal void FinishInitConstraints()
{
if (_delayLoadingConstraints == null)
return;
int colCount;
DataColumn[] parents, childs;
for (int i = 0; i < _delayLoadingConstraints.Length; i++)
{
if (_delayLoadingConstraints[i] is UniqueConstraint)
{
if (_fLoadForeignKeyConstraintsOnly)
continue;
UniqueConstraint constr = (UniqueConstraint)_delayLoadingConstraints[i];
if (constr._columnNames == null)
{
Add(constr);
continue;
}
colCount = constr._columnNames.Length;
parents = new DataColumn[colCount];
for (int j = 0; j < colCount; j++)
parents[j] = _table.Columns[constr._columnNames[j]];
if (constr._bPrimaryKey)
{
if (_table._primaryKey != null)
{
throw ExceptionBuilder.AddPrimaryKeyConstraint();
}
else
{
Add(constr.ConstraintName, parents, true);
}
continue;
}
UniqueConstraint newConstraint = new UniqueConstraint(constr._constraintName, parents);
if (FindConstraint(newConstraint) == null)
Add(newConstraint);
}
else
{
ForeignKeyConstraint constr = (ForeignKeyConstraint)_delayLoadingConstraints[i];
if (constr._parentColumnNames == null || constr._childColumnNames == null)
{
Add(constr);
continue;
}
if (_table.DataSet == null)
{
_fLoadForeignKeyConstraintsOnly = true;
continue;
}
colCount = constr._parentColumnNames.Length;
parents = new DataColumn[colCount];
childs = new DataColumn[colCount];
for (int j = 0; j < colCount; j++)
{
if (constr._parentTableNamespace == null)
parents[j] = _table.DataSet.Tables[constr._parentTableName].Columns[constr._parentColumnNames[j]];
else
parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace].Columns[constr._parentColumnNames[j]];
childs[j] = _table.Columns[constr._childColumnNames[j]];
}
ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(constr._constraintName, parents, childs);
newConstraint.AcceptRejectRule = constr._acceptRejectRule;
newConstraint.DeleteRule = constr._deleteRule;
newConstraint.UpdateRule = constr._updateRule;
Add(newConstraint);
}
}
if (!_fLoadForeignKeyConstraintsOnly)
_delayLoadingConstraints = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using Palaso.Data;
using Palaso.WritingSystems;
using System.Linq;
namespace Palaso.Tests.WritingSystems
{
[TestFixture]
public class WritingSystemDefinitionVariantTests
{
[Test]
public void LatestVersion_IsTwo()
{
Assert.AreEqual(2, WritingSystemDefinition.LatestWritingSystemDefinitionVersion);
}
[Test]
public void IpaStatus_SetToIpaWhenVariantIsEmpty_VariantNowFonIpa()
{
var ws = new WritingSystemDefinition();
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.AreEqual("fonipa", ws.Variant);
}
[Test]
public void IpaStatus_SetToIpaWasAlreadyIpaAndOnyVariant_NoChange()
{
var ws = new WritingSystemDefinition();
ws.IpaStatus = IpaStatusChoices.Ipa;
ws.Variant = "fonipa";
Assert.AreEqual("fonipa", ws.Variant);
}
[Test]
public void IpaStatus_SetToIpaWasAlreadyIpaWithOtherVariants_NoChange()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske-fonipa";
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.AreEqual("1901-biske-fonipa", ws.Variant);
}
[Test]
public void IpaStatus_SetToPhoneticOnEntirelyPrivateUseWritingSystem_MarkerForUnlistedLanguageIsInserted()
{
var ws = WritingSystemDefinition.Parse("x-private");
Assert.That(ws.Variant, Is.EqualTo("x-private"));
ws.IpaStatus = IpaStatusChoices.IpaPhonetic;
Assert.That(ws.Language, Is.EqualTo(WellKnownSubTags.Unlisted.Language));
Assert.That(ws.Script, Is.EqualTo(""));
Assert.That(ws.Region, Is.EqualTo(""));
Assert.That(ws.Variant, Is.EqualTo("fonipa-x-private-etic"));
}
[Test]
public void IpaStatus_SetToIpaOnEntirelyPrivateUseWritingSystem_MarkerForUnlistedLanguageIsInserted()
{
var ws = WritingSystemDefinition.Parse("x-private");
Assert.That(ws.Variant, Is.EqualTo("x-private"));
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.That(ws.Language, Is.EqualTo(WellKnownSubTags.Unlisted.Language));
Assert.That(ws.Script, Is.EqualTo(""));
Assert.That(ws.Region, Is.EqualTo(""));
Assert.That(ws.Variant, Is.EqualTo("fonipa-x-private"));
}
[Test]
public void IpaStatus_SetToPhonemicOnEntirelyPrivateUseWritingSystem_MarkerForUnlistedLanguageIsInserted()
{
var ws = WritingSystemDefinition.Parse("x-private");
Assert.That(ws.Variant, Is.EqualTo("x-private"));
ws.IpaStatus = IpaStatusChoices.IpaPhonemic;
Assert.That(ws.Language, Is.EqualTo(WellKnownSubTags.Unlisted.Language));
Assert.That(ws.Script, Is.EqualTo(""));
Assert.That(ws.Region, Is.EqualTo(""));
Assert.That(ws.Variant, Is.EqualTo("fonipa-x-private-emic"));
}
[Test]
public void IpaStatus_VariantSetWithNumerousVariantIpaWasAlreadyIpa_VariantIsSet()
{
var ws = new WritingSystemDefinition();
ws.IpaStatus = IpaStatusChoices.Ipa;
ws.Variant = "1901-biske-fonipa";
Assert.AreEqual("1901-biske-fonipa", ws.Variant);
}
[Test]
public void IpaStatus_SetToIpaWhenVariantHasContents_FonIpaAtEnd()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske";
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.AreEqual("1901-biske-fonipa", ws.Variant);
}
[Test]
public void IpaStatus_SetToNotIpaWhenWasOnlyVariant_FonIpaRemoved()
{
var ws = new WritingSystemDefinition();
ws.Variant = "fonipa";
ws.IpaStatus = IpaStatusChoices.NotIpa;
Assert.AreEqual("", ws.Variant);
}
[Test]
public void IpaStatus_SetToNotIpaWhenVariantEmpty_NothingChanges()
{
var ws = new WritingSystemDefinition();
ws.IpaStatus = IpaStatusChoices.NotIpa;
Assert.AreEqual("", ws.Variant);
}
[Test]
public void IpaStatus_SetToNotIpaWhenVariantNotEmpty_NothingChanges()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske";
ws.IpaStatus = IpaStatusChoices.NotIpa;
Assert.AreEqual("1901-biske", ws.Variant);
}
[Test]
public void IpaStatus_SetToNotIpaWhenVariantHasContents_FonIpaRemoved()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske-fonipa";
ws.IpaStatus = IpaStatusChoices.NotIpa;
Assert.AreEqual("1901-biske", ws.Variant);
}
[Test]
public void IpaStatus_SetToNotIpaWhenVariantHasContentsWithIpaInMiddle_FonIpaRemoved()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske-fonipa-bauddha";//this is actually a bad tag as of 2009, fonipa can't be extended
ws.IpaStatus = IpaStatusChoices.NotIpa;
Assert.AreEqual("1901-biske-bauddha", ws.Variant);
}
[Test]
public void IpaStatus_IpaPhonetic_RoundTrips()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske";
ws.IpaStatus = IpaStatusChoices.IpaPhonetic;
Assert.AreEqual(IpaStatusChoices.IpaPhonetic, ws.IpaStatus);
Assert.AreEqual("1901-biske-fonipa-x-etic", ws.Variant);
}
[Test]
public void IpaStatus_IpaPhonemic_RoundTrips()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske";
ws.IpaStatus = IpaStatusChoices.IpaPhonemic;
Assert.AreEqual(IpaStatusChoices.IpaPhonemic, ws.IpaStatus);
Assert.AreEqual("1901-biske-fonipa-x-emic", ws.Variant);
}
[Test]
public void IpaStatus_IpaPhoneticToPhonemic_MakesChange()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske";
ws.IpaStatus = IpaStatusChoices.IpaPhonetic;
ws.IpaStatus = IpaStatusChoices.IpaPhonemic;
Assert.AreEqual(IpaStatusChoices.IpaPhonemic, ws.IpaStatus);
Assert.AreEqual("1901-biske-fonipa-x-emic", ws.Variant);
}
[Test]
public void SetIpaStatus_SetIpaWasVoice_RemovesVoice()
{
var ws = new WritingSystemDefinition();
ws.Variant = "1901-biske";
ws.IsVoice=true;
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.IsFalse(ws.IsVoice);
}
[Test]
public void IpaStatus_PrivateUseSetToPrefixEticPostfix_ReturnsIpa()
{
var ws = new WritingSystemDefinition();
ws.Variant = "fonipa-x-PrefixEticPostfix";
Assert.AreEqual(IpaStatusChoices.Ipa, ws.IpaStatus);
}
[Test]
public void IpaStatus_VariantSetToFoNiPa_ReturnsIpa()
{
var ws = new WritingSystemDefinition();
ws.Variant = "FoNiPa";
Assert.AreEqual(IpaStatusChoices.Ipa, ws.IpaStatus);
}
[Test]
public void IpaStatus_VariantSetToPrefixFonipaDashXDashEticPostfix_Throws()
{
var ws = new WritingSystemDefinition();
Assert.Throws<ValidationException>(()=>ws.Variant = "Prefixfonipa-x-eticPostfix");
}
[Test]
public void IpaStatus_VariantSetToPrefixFonipaDashXDashEticPostfix_ReturnsIpa()
{
var ws = new WritingSystemDefinition();
ws.Variant = "fonipa-x-PrefixeticPostfix";
Assert.AreEqual(IpaStatusChoices.Ipa, ws.IpaStatus);
}
[Test]
public void IpaStatus_VariantSetToFoNiPaDashXDasheTiC_ReturnsIpaPhonetic()
{
var ws = new WritingSystemDefinition();
ws.Variant = "FoNiPa-x-eTiC";
Assert.AreEqual(IpaStatusChoices.IpaPhonetic, ws.IpaStatus);
}
[Test]
public void IpaStatus_VariantSetToFonipaDashXDashPrefixemicPostfix_ReturnsIpa()
{
var ws = new WritingSystemDefinition();
ws.Variant = "fonipa-x-PrefixemicPostfix";
Assert.AreEqual(IpaStatusChoices.Ipa, ws.IpaStatus);
}
[Test]
public void IpaStatus_VariantSetToFoNiPaDashXDasheMiC_ReturnsIpaPhonemic()
{
var ws = new WritingSystemDefinition();
ws.Variant = "FoNiPa-x-eMiC";
Assert.AreEqual(IpaStatusChoices.IpaPhonemic, ws.IpaStatus);
}
[Test]
public void IpaStatus_SetToIpaWhileIsVoiceIsTrue_IpaStatusIsIpa()
{
WritingSystemDefinition ws = new WritingSystemDefinition();
ws.IsVoice = true;
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.AreEqual(IpaStatusChoices.Ipa, ws.IpaStatus);
}
[Test]
public void IpaStatus_SetToIpaWhileIsVoiceIsTrue_IsVoiceIsFalse()
{
WritingSystemDefinition ws = new WritingSystemDefinition();
ws.IsVoice = true;
ws.IpaStatus = IpaStatusChoices.Ipa;
Assert.IsFalse(ws.IsVoice);
}
[Test]
public void IpaStatus_SetToPhoneticWhileIsVoiceIsTrue_IpaStatusIsPhonetic()
{
WritingSystemDefinition ws = new WritingSystemDefinition();
ws.IsVoice = true;
ws.IpaStatus = IpaStatusChoices.IpaPhonetic;
Assert.AreEqual(IpaStatusChoices.IpaPhonetic, ws.IpaStatus);
}
[Test]
public void IpaStatus_SetToPhoneticWhileIsVoiceIsTrue_IsVoiceIsFalse()
{
WritingSystemDefinition ws = new WritingSystemDefinition();
ws.IsVoice = true;
ws.IpaStatus = IpaStatusChoices.IpaPhonetic;
Assert.IsFalse(ws.IsVoice);
}
[Test]
public void IpaStatus_SetToPhonemicWhileIsVoiceIsTrue_IpaStatusIsPhonemic()
{
WritingSystemDefinition ws = new WritingSystemDefinition();
ws.IsVoice = true;
ws.IpaStatus = IpaStatusChoices.IpaPhonemic;
Assert.AreEqual(IpaStatusChoices.IpaPhonemic, ws.IpaStatus);
}
[Test]
public void IpaStatus_SetToPhonemicWhileIsVoiceIsTrue_IsVoiceIsFalse()
{
WritingSystemDefinition ws = new WritingSystemDefinition();
ws.IsVoice = true;
ws.IpaStatus = IpaStatusChoices.IpaPhonemic;
Assert.IsFalse(ws.IsVoice);
}
[Test]
[Ignore("Flex doesn't seem to mind if you set Arabic or some other script for ipa.")]
public void IpaStatus_SetToAnyThingButNotIpaWhileScriptIsNotDontKnowWhatScriptItShouldBe_Throws()
{
throw new NotImplementedException();
}
[Test]
[Ignore("Flex doesn't seem to mind if you set Arabic or some other script for ipa.")]
public void Script_SetToIDontKnowWhatScriptItShouldBewhileIpaStatusIsSetToAnyThingButNotIpa_Throws()
{
throw new NotImplementedException();
}
[Test]
public void FilterWellKnownPrivateUseTags_HasOnlyWellKnownTags_EmptyList()
{
string[] listToFilter = {WellKnownSubTags.Audio.PrivateUseSubtag,
WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag,
WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag
};
IEnumerable<string> result = WritingSystemDefinition.FilterWellKnownPrivateUseTags(listToFilter);
Assert.That(result, Is.Empty);
}
[Test]
public void FilterWellKnownPrivateUseTags_HasWellKnownTagsAndUnknownTags_ListWithUnknownTags()
{
string[] listToFilter = { "v", WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag, WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag };
IEnumerable<string> result = WritingSystemDefinition.FilterWellKnownPrivateUseTags(listToFilter);
Assert.That(result, Has.Member("v"));
Assert.That(result, Has.No.Member(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag));
Assert.That(result, Has.No.Member(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag));
}
[Test]
public void FilterWellKnownPrivateUseTags_HasUpperCaseWellKnownTagsAndUnknownTags_ListWithUnknownTags()
{
string[] listToFilter = { "v", WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag.ToUpper(), WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag.ToUpper() };
IEnumerable<string> result = WritingSystemDefinition.FilterWellKnownPrivateUseTags(listToFilter);
Assert.That(result, Has.Member("v"));
Assert.That(result, Has.No.Member(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag.ToUpper()));
Assert.That(result, Has.No.Member(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag.ToUpper()));
}
[Test]
public void FilterWellKnownPrivateUseTags_EmptyList_EmptyList()
{
string[] listToFilter = {};
IEnumerable<string> result = WritingSystemDefinition.FilterWellKnownPrivateUseTags(listToFilter);
Assert.That(result, Is.Empty);
}
[Test]
public void FilterWellKnownPrivateUseTags_HasOnlyUnknownTags_ListWithUnknownTags()
{
string[] listToFilter = { "v", "puu", "yuu" };
IEnumerable<string> result = WritingSystemDefinition.FilterWellKnownPrivateUseTags(listToFilter);
Assert.That(result, Has.Member("v"));
Assert.That(result, Has.Member("puu"));
Assert.That(result, Has.Member("yuu"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_VariantOnly_ReturnsVariant()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("1901", String.Empty);
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("1901"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_VariantAndPrivateUseWithxDash_ReturnsConcatenatedVariantAndPrivateUse()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("1901", "x-audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("1901-x-audio"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_VariantAndPrivateUseWithoutxDash_ReturnsConcatenatedVariantAndPrivateUse()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("1901", "audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("1901-x-audio"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_PrivateUseWithoutxDashOnly_ReturnsPrivateUseWithxDash()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("", "audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("x-audio"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_PrivateUseWithxDashOnly_ReturnsPrivateUseWithxDash()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("", "x-audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("x-audio"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_PrivateUseWithCapitalXDashOnly_ReturnsPrivateUseWithxDash()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("", "X-audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("X-audio"));
}
[Test]
public void ConcatenateVariantAndPrivateUse_VariantAndPrivateUseWithCapitalXDash_ReturnsConcatenatedVariantAndPrivateUse()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("1901", "X-audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("1901-X-audio"));
}
//this test shows that there is no checking involved as to wether your variants and private use are rfc/writingsystemdefinition conform. All the method does is glue two strings together while handling the "x-"
[Test]
public void ConcatenateVariantAndPrivateUse_BogusVariantBadprivateUse_HappilyGluesTheTwoTogether()
{
string concatenatedVariantAndPrivateUse = WritingSystemDefinition.ConcatenateVariantAndPrivateUse("bogusvariant", "etic-emic-audio");
Assert.That(concatenatedVariantAndPrivateUse, Is.EqualTo("bogusvariant-x-etic-emic-audio"));
}
//Split
[Test]
public void SplitVariantAndPrivateUse_VariantOnly_ReturnsVariant()
{
string variant;
string privateUse;
WritingSystemDefinition.SplitVariantAndPrivateUse("1901", out variant, out privateUse);
Assert.That(variant, Is.EqualTo("1901"));
Assert.That(privateUse, Is.EqualTo(String.Empty));
}
[Test]
public void SplitVariantAndPrivateUse_VariantAndPrivateUse_ReturnsVariantAndPrivateUse()
{
string variant;
string privateUse;
WritingSystemDefinition.SplitVariantAndPrivateUse("1901-x-audio", out variant, out privateUse);
Assert.That(variant, Is.EqualTo("1901"));
Assert.That(privateUse, Is.EqualTo("audio"));
}
[Test]
public void SplitVariantAndPrivateUse_NoxDash_ReturnsVariantOnly()
{
string variant;
string privateUse;
WritingSystemDefinition.SplitVariantAndPrivateUse("1901-audio", out variant, out privateUse);
Assert.That(variant, Is.EqualTo("1901-audio"));
Assert.That(privateUse, Is.EqualTo(String.Empty));
}
[Test]
public void SplitVariantAndPrivateUse_PrivateUseWithxDashOnly_ReturnsPrivateUseWithxDash()
{
string variant;
string privateUse;
WritingSystemDefinition.SplitVariantAndPrivateUse("x-audio", out variant, out privateUse);
Assert.That(variant, Is.EqualTo(String.Empty));
Assert.That(privateUse, Is.EqualTo("audio"));
}
[Test]
public void SplitVariantAndPrivateUse_PrivateUseWithCapitalXDashOnly_ReturnsPrivateUseWithxDash()
{
string variant;
string privateUse;
WritingSystemDefinition.SplitVariantAndPrivateUse("X-audio", out variant, out privateUse);
Assert.That(variant, Is.EqualTo(String.Empty));
Assert.That(privateUse, Is.EqualTo("audio"));
}
[Test]
public void SplitVariantAndPrivateUse_VariantAndPrivateUseWithCapitalXDash_ReturnsConcatenatedVariantAndPrivateUse()
{
string variant = String.Empty;
string privateUse = String.Empty;
WritingSystemDefinition.SplitVariantAndPrivateUse("1901-X-audio", out variant, out privateUse);
Assert.That(variant, Is.EqualTo("1901"));
Assert.That(privateUse, Is.EqualTo("audio"));
}
//this test shows that there is no checking involved as to wether your variants and private use are rfc/writingsystemdefinition conform. All the method does is split on x-
[Test]
public void SplitVariantAndPrivateUse_BogusVariantBadPrivateUse_HappilysplitsOnxDash()
{
string variant;
string privateUse;
WritingSystemDefinition.SplitVariantAndPrivateUse("bogusVariant-X-audio-emic-etic", out variant, out privateUse);
Assert.That(variant, Is.EqualTo("bogusVariant"));
Assert.That(privateUse, Is.EqualTo("audio-emic-etic"));
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.DotNet.Internal.ProjectModel.FileSystemGlobbing.Internal.PathSegments;
using Microsoft.DotNet.Internal.ProjectModel.FileSystemGlobbing.Internal.PatternContexts;
namespace Microsoft.DotNet.Internal.ProjectModel.FileSystemGlobbing.Internal.Patterns
{
internal class PatternBuilder
{
private static readonly char[] _slashes = new[] { '/', '\\' };
private static readonly char[] _star = new[] { '*' };
public PatternBuilder()
{
ComparisonType = StringComparison.OrdinalIgnoreCase;
}
public PatternBuilder(StringComparison comparisonType)
{
ComparisonType = comparisonType;
}
public StringComparison ComparisonType { get; }
public IPattern Build(string pattern)
{
if (pattern == null)
{
throw new ArgumentNullException("pattern");
}
pattern = pattern.TrimStart(_slashes);
if (pattern.TrimEnd(_slashes).Length < pattern.Length)
{
// If the pattern end with a slash, it is considered as
// a directory.
pattern = pattern.TrimEnd(_slashes) + "/**";
}
var allSegments = new List<IPathSegment>();
var isParentSegmentLegal = true;
IList<IPathSegment> segmentsPatternStartsWith = null;
IList<IList<IPathSegment>> segmentsPatternContains = null;
IList<IPathSegment> segmentsPatternEndsWith = null;
var endPattern = pattern.Length;
for (int scanPattern = 0; scanPattern < endPattern;)
{
var beginSegment = scanPattern;
var endSegment = NextIndex(pattern, _slashes, scanPattern, endPattern);
IPathSegment segment = null;
if (segment == null && endSegment - beginSegment == 3)
{
if (pattern[beginSegment] == '*' &&
pattern[beginSegment + 1] == '.' &&
pattern[beginSegment + 2] == '*')
{
// turn *.* into *
beginSegment += 2;
}
}
if (segment == null && endSegment - beginSegment == 2)
{
if (pattern[beginSegment] == '*' &&
pattern[beginSegment + 1] == '*')
{
// recognized **
segment = new RecursiveWildcardSegment();
}
else if (pattern[beginSegment] == '.' &&
pattern[beginSegment + 1] == '.')
{
// recognized ..
if (!isParentSegmentLegal)
{
throw new ArgumentException("\"..\" can be only added at the beginning of the pattern.");
}
segment = new ParentPathSegment();
}
}
if (segment == null && endSegment - beginSegment == 1)
{
if (pattern[beginSegment] == '.')
{
// recognized .
segment = new CurrentPathSegment();
}
}
if (segment == null && endSegment - beginSegment > 2)
{
if (pattern[beginSegment] == '*' &&
pattern[beginSegment + 1] == '*' &&
pattern[beginSegment + 2] == '.')
{
// recognize **.
// swallow the first *, add the recursive path segment and
// the remaining part will be treat as wild card in next loop.
segment = new RecursiveWildcardSegment();
endSegment = beginSegment;
}
}
if (segment == null)
{
var beginsWith = string.Empty;
var contains = new List<string>();
var endsWith = string.Empty;
for (int scanSegment = beginSegment; scanSegment < endSegment;)
{
var beginLiteral = scanSegment;
var endLiteral = NextIndex(pattern, _star, scanSegment, endSegment);
if (beginLiteral == beginSegment)
{
if (endLiteral == endSegment)
{
// and the only bit
segment = new LiteralPathSegment(Portion(pattern, beginLiteral, endLiteral), ComparisonType);
}
else
{
// this is the first bit
beginsWith = Portion(pattern, beginLiteral, endLiteral);
}
}
else if (endLiteral == endSegment)
{
// this is the last bit
endsWith = Portion(pattern, beginLiteral, endLiteral);
}
else
{
if (beginLiteral != endLiteral)
{
// this is a middle bit
contains.Add(Portion(pattern, beginLiteral, endLiteral));
}
else
{
// note: NOOP here, adjacent *'s are collapsed when they
// are mixed with literal text in a path segment
}
}
scanSegment = endLiteral + 1;
}
if (segment == null)
{
segment = new WildcardPathSegment(beginsWith, contains, endsWith, ComparisonType);
}
}
if (!(segment is ParentPathSegment))
{
isParentSegmentLegal = false;
}
if (segment is CurrentPathSegment)
{
// ignore ".\"
}
else
{
if (segment is RecursiveWildcardSegment)
{
if (segmentsPatternStartsWith == null)
{
segmentsPatternStartsWith = new List<IPathSegment>(allSegments);
segmentsPatternEndsWith = new List<IPathSegment>();
segmentsPatternContains = new List<IList<IPathSegment>>();
}
else if (segmentsPatternEndsWith.Count != 0)
{
segmentsPatternContains.Add(segmentsPatternEndsWith);
segmentsPatternEndsWith = new List<IPathSegment>();
}
}
else if (segmentsPatternEndsWith != null)
{
segmentsPatternEndsWith.Add(segment);
}
allSegments.Add(segment);
}
scanPattern = endSegment + 1;
}
if (segmentsPatternStartsWith == null)
{
return new LinearPattern(allSegments);
}
else
{
return new RaggedPattern(allSegments, segmentsPatternStartsWith, segmentsPatternEndsWith, segmentsPatternContains);
}
}
private static int NextIndex(string pattern, char[] anyOf, int beginIndex, int endIndex)
{
var index = pattern.IndexOfAny(anyOf, beginIndex, endIndex - beginIndex);
return index == -1 ? endIndex : index;
}
private static string Portion(string pattern, int beginIndex, int endIndex)
{
return pattern.Substring(beginIndex, endIndex - beginIndex);
}
private class LinearPattern : ILinearPattern
{
public LinearPattern(List<IPathSegment> allSegments)
{
Segments = allSegments;
}
public IList<IPathSegment> Segments { get; }
public IPatternContext CreatePatternContextForInclude()
{
return new PatternContextLinearInclude(this);
}
public IPatternContext CreatePatternContextForExclude()
{
return new PatternContextLinearExclude(this);
}
}
private class RaggedPattern : IRaggedPattern
{
public RaggedPattern(List<IPathSegment> allSegments, IList<IPathSegment> segmentsPatternStartsWith, IList<IPathSegment> segmentsPatternEndsWith, IList<IList<IPathSegment>> segmentsPatternContains)
{
Segments = allSegments;
StartsWith = segmentsPatternStartsWith;
Contains = segmentsPatternContains;
EndsWith = segmentsPatternEndsWith;
}
public IList<IList<IPathSegment>> Contains { get; }
public IList<IPathSegment> EndsWith { get; }
public IList<IPathSegment> Segments { get; }
public IList<IPathSegment> StartsWith { get; }
public IPatternContext CreatePatternContextForInclude()
{
return new PatternContextRaggedInclude(this);
}
public IPatternContext CreatePatternContextForExclude()
{
return new PatternContextRaggedExclude(this);
}
}
}
}
| |
/*
Threading example
Copyright 2017, Sjors van Gelderen
Resources used:
https://msdn.microsoft.com/en-us/library/mt679040.aspx - Thread pool
https://msdn.microsoft.com/en-us/library/ms228964.aspx - Synchronization mechanisms
https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx - Exclusive lock
https://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx - Mutex
https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx - ReadWriterLockSlim
https://msdn.microsoft.com/en-us/library/system.threading.semaphore(v=vs.110).aspx - Semaphore
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Program
{
// Used by general thread (Fibonacci) demo
class FibonacciWorker
{
public int N { get; } // Which number in the sequence to generate
public int Result { get; set; } // Result of the algorithm
private ManualResetEvent done; // Flag to set when done
public FibonacciWorker(int _n, ManualResetEvent _done)
{
N = _n;
done = _done;
}
// Thread pool callback
public void Callback(Object _threadContext)
{
// Get thread ID
int thread_id = (int)_threadContext;
Console.WriteLine("Thread {0} started", thread_id);
// Run the work
Result = Fibonacci(N);
// Set done flag
Console.WriteLine("Thread {0} finished", thread_id);
done.Set();
}
// Inefficient recursive Fibonacci implementation
private static int Fibonacci(int _n)
{
return _n < 2 ? _n : Fibonacci(_n - 1) + Fibonacci(_n - 2);
}
}
// Used by exclusive lock demo
class Hero
{
private int health = 100; // The property to be manipulated by the threads
private Object health_lock = new Object(); // Lock object for health property
public void Damage(int _amount, int _delay)
{
Console.WriteLine("Hero is in contest with {0}!",
Thread.CurrentThread.Name);
// Sleep an arbitrary amount of time
Thread.Sleep(_delay);
// Locks the health property so only this thread may manipulate it
lock(health_lock)
{
health -= _amount;
if(health <= 0)
{
health = 0;
Console.WriteLine("The hero perished...");
}
Console.WriteLine("The hero suffers {0} damage!"
+ Environment.NewLine
+ "{1} health points remain.",
_amount, health);
}
}
}
// Used by Mutex demo
class MutexThread
{
// Static mutex means its not owned by any particular instance
private static Mutex mutex = new Mutex();
// Dummy work procedure for the thread
public static void Work()
{
Console.WriteLine("{0} is preparing to use the resource",
Thread.CurrentThread.Name);
UseResource();
Console.WriteLine("{0} is done with its work",
Thread.CurrentThread.Name);
}
// Safe access to the resource is done through this procedure
static void UseResource()
{
// Block with WaitOne until mutex is freed
Console.WriteLine("{0} is requesting the mutex",
Thread.CurrentThread.Name);
mutex.WaitOne();
// Do some dummy work, here sleep for 1 second
Thread.Sleep(1000);
Console.WriteLine("{0} is done with the resource",
Thread.CurrentThread.Name);
// Free the mutex for other threads
mutex.ReleaseMutex();
Console.WriteLine("{0} has released the mutex",
Thread.CurrentThread.Name);
}
}
// Used by ReadWriterLockSlim demo
class HiscoreTable
{
private ReaderWriterLockSlim hiscore_table_lock = new ReaderWriterLockSlim();
private Dictionary<string, int> hiscore_table = new Dictionary<string, int>();
// Read a score from the table
public void Read(string _name)
{
hiscore_table_lock.EnterReadLock();
try
{
if(hiscore_table.ContainsKey(_name))
{
Console.WriteLine("{0} read {1}: {2}",
Thread.CurrentThread.Name,
_name,
hiscore_table[_name]);
}
else
{
Console.WriteLine("{0} tried to read {1}, "
+ "but no corresponding entry exists!",
Thread.CurrentThread.Name, _name);
}
}
finally
{
hiscore_table_lock.ExitReadLock();
}
}
// Update or add a score to the table
public void Enter(string _name, int _score)
{
// Lock resource for other threads, open for reading in current thread
hiscore_table_lock.EnterUpgradeableReadLock();
try
{
if(hiscore_table.ContainsKey(_name))
{
if(hiscore_table[_name] != _score)
{
// Record must be updated
hiscore_table_lock.EnterWriteLock();
try
{
hiscore_table[_name] = _score;
Console.WriteLine("{0} updated {1}: {2}",
Thread.CurrentThread.Name,
_name,
_score);
}
finally
{
hiscore_table_lock.ExitWriteLock();
}
}
}
else
{
// New record must be added
hiscore_table_lock.EnterWriteLock();
try
{
hiscore_table.Add(_name, _score);
Console.WriteLine("{0} added {1}: {2}",
Thread.CurrentThread.Name,
_name,
_score);
}
finally
{
hiscore_table_lock.ExitWriteLock();
}
}
}
finally
{
// Release lock on resource
hiscore_table_lock.ExitUpgradeableReadLock();
}
}
// Delete a score from the table
public void Delete(string _name)
{
hiscore_table_lock.EnterUpgradeableReadLock();
try
{
if(hiscore_table.ContainsKey(_name))
{
hiscore_table_lock.EnterWriteLock();
try
{
hiscore_table.Remove(_name);
Console.WriteLine("{0} deleted {1}",
Thread.CurrentThread.Name,
_name);
}
finally
{
hiscore_table_lock.ExitWriteLock();
}
}
}
finally
{
hiscore_table_lock.ExitUpgradeableReadLock();
}
}
}
class Program
{
// Thread names
private static string[] names = {
"Tarquin",
"Mercutio",
"Falstaff",
"Bassanio",
"Lucrece",
"Collatine",
"Timon",
"Apemantus",
"Douglas",
"Edward"
};
// Demonstrates a basic multithreaded application
static void GeneralThreadingDemo()
{
Console.WriteLine("General thread demo with Fibonacci sequence");
// The amount of Fibonacci numbers to calculate
const int PROBLEM_SIZE = 16;
// Keep track of all workers calculating the sequence
var done_events = new ManualResetEvent[PROBLEM_SIZE];
var sequence = new FibonacciWorker[PROBLEM_SIZE];
Console.WriteLine("Running {0} tasks", PROBLEM_SIZE);
for(int i = 0; i < PROBLEM_SIZE; i++)
{
// Create new done event, set it to false
done_events[i] = new ManualResetEvent(false);
// Create a new worker for index i in sequence with this done event
sequence[i] = new FibonacciWorker(i, done_events[i]);
// Actually queue the new worker so that it may start when a thread becomes available
ThreadPool.QueueUserWorkItem(sequence[i].Callback, i);
}
// Wait for worker threads to finish
WaitHandle.WaitAll(done_events);
Console.WriteLine("Finished all operations!");
// Since all are finished, print the results
foreach(var worker in sequence)
{
Console.WriteLine("Fibonacci of {0} is {1}", worker.N, worker.Result);
}
Console.Write(Environment.NewLine);
}
// Demonstrates the use of an exclusive lock
static void ExclusiveLockDemo()
{
Console.WriteLine("Exclusive lock demo");
var random = new Random();
// Prepare threads
const int NUM_THREADS = 10;
var threads = new Thread[NUM_THREADS];
var hero = new Hero();
for(int i = 0; i < NUM_THREADS; i++)
{
threads[i] = new Thread(new ThreadStart(() => hero.Damage(10, random.Next(1000))));
threads[i].Name = names[i];
}
// Start threads
foreach(var thread in threads)
{
thread.Start();
}
// Block until all threads are finished
foreach(var thread in threads)
{
thread.Join();
}
Console.Write(Environment.NewLine);
}
// Demonstrates the use of a mutex
static void MutexDemo()
{
Console.WriteLine("Mutex demo");
// Create a few worker threads
const int NUM_THREADS = 3;
var threads = new Thread[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++)
{
threads[i] = new Thread(new ThreadStart(MutexThread.Work));
threads[i].Name = String.Format("Thread {0}", i);
}
// Start the worker threads
foreach(var thread in threads)
{
thread.Start();
}
// Block until all threads are finished
foreach(var thread in threads)
{
thread.Join();
}
Console.Write(Environment.NewLine);
}
// ReadWriterLockSlim demo methods
static void TeslaTest(HiscoreTable _table)
{
_table.Enter("Tesla", 10);
_table.Enter("Tesla", 10);
_table.Enter("Tesla", 100);
_table.Delete("Faraday");
}
static void EdisonTest(HiscoreTable _table)
{
_table.Enter("Edison", 1000);
_table.Delete("Edison");
_table.Delete("Tesla");
}
static void FaradayTest(HiscoreTable _table)
{
_table.Enter("Edison", 100);
_table.Enter("Faraday", 23);
_table.Enter("Faraday", 100);
_table.Enter("Edison", 100);
}
delegate void ThreadDelegate();
static void ReadWriterLockSlimDemo()
{
Console.WriteLine("ReadWriterLockSlim demo");
var random = new Random();
// The data the threads will attempt to manipulate
var hiscore_table = new HiscoreTable();
// Create a few worker threads
const int NUM_THREADS = 10;
var threads = new Thread[NUM_THREADS];
// Assign random tasks to the threads
for(int i = 0; i < NUM_THREADS; i++)
{
ThreadDelegate thread_delegate = () => {};
switch(random.Next(3))
{
case 0:
thread_delegate = () => TeslaTest(hiscore_table);
break;
case 1:
thread_delegate = () => EdisonTest(hiscore_table);
break;
case 2:
thread_delegate = () => FaradayTest(hiscore_table);
break;
}
threads[i] = new Thread(new ThreadStart(thread_delegate));
threads[i].Name = String.Format("Thread {0}", i);
}
// Start the threads
for(int i = 0; i < NUM_THREADS; i++)
{
threads[i].Start();
}
// Block until all threads are finished
for(int i = 0; i < NUM_THREADS; i++)
{
threads[i].Join();
}
Console.Write(Environment.NewLine);
}
// Semaphore demo methods
static void SemaphoreWork(Semaphore _semaphore, int _delay)
{
// Wait for the semaphore's signal
Console.WriteLine("{0} is waiting for the semaphore's signal",
Thread.CurrentThread.Name);
_semaphore.WaitOne();
// Simulate work by sleeping a random amount of time
Console.WriteLine("{0} enters the protected space",
Thread.CurrentThread.Name);
Thread.Sleep(_delay);
// Tell the semaphore we're done here
_semaphore.Release();
Console.WriteLine("{0} leaves the protected space",
Thread.CurrentThread.Name);
}
static void SemaphoreDemo()
{
Console.WriteLine("Semaphore demo");
var random = new Random();
// The semaphore regulates access to the protected space
var semaphore = new Semaphore(0, 3);
// Wait before granting access
Thread.Sleep(500);
semaphore.Release(3); // Open the space for 3 worker threads
// Create worker threads
const int NUM_THREADS = 10;
var threads = new Thread[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++)
{
threads[i] = new Thread(new ThreadStart(() => SemaphoreWork(semaphore, random.Next(1500))));
threads[i].Name = names[i];
}
// Start the threads
foreach(var thread in threads)
{
thread.Start();
}
// Block until threads are finished
foreach(var thread in threads)
{
thread.Join();
}
Console.Write(Environment.NewLine);
}
static void Main()
{
Console.WriteLine("Threading example - "
+ "Copyright 2017, Sjors van Gelderen"
+ Environment.NewLine);
GeneralThreadingDemo();
ExclusiveLockDemo();
MutexDemo();
ReadWriterLockSlimDemo();
SemaphoreDemo();
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int32Animation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Int32 property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class Int32Animation :
Int32AnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Int32[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for Int32Animation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static Int32Animation()
{
Type typeofProp = typeof(Int32?);
Type typeofThis = typeof(Int32Animation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Int32?)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Int32?)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Int32?)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new Int32Animation with all properties set to
/// their default values.
/// </summary>
public Int32Animation()
: base()
{
}
/// <summary>
/// Creates a new Int32Animation that will animate a
/// Int32 property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public Int32Animation(Int32 toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new Int32Animation that will animate a
/// Int32 property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public Int32Animation(Int32 toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new Int32Animation that will animate a
/// Int32 property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public Int32Animation(Int32 fromValue, Int32 toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new Int32Animation that will animate a
/// Int32 property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public Int32Animation(Int32 fromValue, Int32 toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this Int32Animation
/// </summary>
/// <returns>The copy</returns>
public new Int32Animation Clone()
{
return (Int32Animation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Int32Animation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Int32 GetCurrentValueCore(Int32 defaultOriginValue, Int32 defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Int32 from = new Int32();
Int32 to = new Int32();
Int32 accumulated = new Int32();
Int32 foundation = new Int32();
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddInt32(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueInt32(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueInt32(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Int32 accumulator = AnimatedTypeHelpers.SubtractInt32(to, from);
accumulated = AnimatedTypeHelpers.ScaleInt32(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddInt32(
foundation,
AnimatedTypeHelpers.AddInt32(
accumulated,
AnimatedTypeHelpers.InterpolateInt32(from, to, progress)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From.HasValue)
{
if (To.HasValue)
{
_animationType = AnimationType.FromTo;
_keyValues = new Int32[2];
_keyValues[0] = From.Value;
_keyValues[1] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.FromBy;
_keyValues = new Int32[2];
_keyValues[0] = From.Value;
_keyValues[1] = By.Value;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Int32[1];
_keyValues[0] = From.Value;
}
}
else if (To.HasValue)
{
_animationType = AnimationType.To;
_keyValues = new Int32[1];
_keyValues[0] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.By;
_keyValues = new Int32[1];
_keyValues[0] = By.Value;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Int32Animation a = (Int32Animation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Int32? typedValue = (Int32?)value;
if (typedValue.HasValue)
{
return AnimatedTypeHelpers.IsValidAnimationValueInt32(typedValue.Value);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Int32? From
{
get
{
return (Int32?)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Int32? To
{
get
{
return (Int32?)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Int32? By
{
get
{
return (Int32?)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using System.Collections;
using Leap.Unity.Attributes;
namespace Leap.Unity {
/**
* Detects when specified fingers are pointing in the specified manner.
*
* Directions can be specified relative to the global frame of reference, relative to
* the camera frame of reference, or using a combination of the two -- relative to the
* camera direction in the x-z plane, but not changing relative to the horizon.
*
* You can alternatively specify a target game object.
*
* If added to a IHandModel instance or one of its children, this detector checks the
* finger direction at the interval specified by the Period variable. You can also specify
* which hand model to observe explicitly by setting handModel in the Unity editor or
* in code.
*
* @since 4.1.2
*/
public class FingerDirectionDetector : Detector {
/**
* The interval at which to check finger state.
* @since 4.1.2
*/
[Units("seconds")]
[Tooltip("The interval in seconds at which to check this detector's conditions.")]
[MinValue(0)]
public float Period = .1f; //seconds
/**
* The IHandModel instance to observe.
* Set automatically if not explicitly set in the editor.
* @since 4.1.2
*/
[Tooltip("The hand model to watch. Set automatically if detector is on a hand.")]
public IHandModel HandModel = null;
/**
* The finger to compare to the specified direction.
* @since 4.1.2
*/
[Tooltip("The finger to observe.")]
public Finger.FingerType FingerName = Finger.FingerType.TYPE_INDEX;
/**
* Specifies how to interprete the direction specified by PointingDirection.
*
* - RelativeToCamera -- the target direction is defined relative to the camera's forward vector, i.e. (0, 0, 1) is the cmaera's
* local forward direction.
* - RelativeToHorizon -- the target direction is defined relative to the camera's forward vector,
* except that it does not change with pitch.
* - RelativeToWorld -- the target direction is defined as a global direction that does not change with camera movement. For example,
* (0, 1, 0) is always world up, no matter which way the camera is pointing.
* - AtTarget -- a target object is used as the pointing direction (The specified PointingDirection is ignored).
*
* In VR scenes, RelativeToHorizon with a direction of (0, 0, 1) for camera forward and RelativeToWorld with a direction
* of (0, 1, 0) for absolute up, are often the most useful settings.
* @since 4.1.2
*/
[Header("Direction Settings")]
[Tooltip("How to treat the target direction.")]
public PointingType PointingType = PointingType.RelativeToHorizon;
/**
* The target direction as interpreted by the PointingType setting.
* Ignored when Pointingtype is "AtTarget."
* @since 4.1.2
*/
[Tooltip("The target direction.")]
[DisableIf("PointingType", isEqualTo: PointingType.AtTarget)]
public Vector3 PointingDirection = Vector3.forward;
/**
* The object to point at when the PointingType is "AtTarget." Ignored otherwise.
*/
[Tooltip("A target object(optional). Use PointingType.AtTarget")]
[DisableIf("PointingType", isNotEqualTo: PointingType.AtTarget)]
public Transform TargetObject = null;
/**
* The turn-on angle. The detector activates when the specified finger points within this
* many degrees of the target direction.
* @since 4.1.2
*/
[Tooltip("The angle in degrees from the target direction at which to turn on.")]
[Range(0, 180)]
public float OnAngle = 15f; //degrees
/**
* The turn-off angle. The detector deactivates when the specified finger points more than this
* many degrees away from the target direction. The off angle must be larger than the on angle.
* @since 4.1.2
*/
[Tooltip("The angle in degrees from the target direction at which to turn off.")]
[Range(0, 180)]
public float OffAngle = 25f; //degrees
/** Whether to draw the detector's Gizmos for debugging. (Not every detector provides gizmos.)
* @since 4.1.2
*/
[Header("")]
[Tooltip("Draw this detector's Gizmos, if any. (Gizmos must be on in Unity edtor, too.)")]
public bool ShowGizmos = true;
private IEnumerator watcherCoroutine;
private void OnValidate(){
if( OffAngle < OnAngle){
OffAngle = OnAngle;
}
}
private void Awake () {
watcherCoroutine = fingerPointingWatcher();
}
private void OnEnable () {
StartCoroutine(watcherCoroutine);
}
private void OnDisable () {
StopCoroutine(watcherCoroutine);
Deactivate();
}
private IEnumerator fingerPointingWatcher() {
Hand hand;
Vector3 fingerDirection;
Vector3 targetDirection;
int selectedFinger = selectedFingerOrdinal();
while(true){
if(HandModel != null && HandModel.IsTracked){
hand = HandModel.GetLeapHand();
if(hand != null){
targetDirection = selectedDirection(hand.Fingers[selectedFinger].TipPosition.ToVector3());
fingerDirection = hand.Fingers[selectedFinger].Bone(Bone.BoneType.TYPE_DISTAL).Direction.ToVector3();
float angleTo = Vector3.Angle(fingerDirection, targetDirection);
if(HandModel.IsTracked && angleTo <= OnAngle){
Activate();
} else if (!HandModel.IsTracked || angleTo >= OffAngle) {
Deactivate();
}
}
}
yield return new WaitForSeconds(Period);
}
}
private Vector3 selectedDirection(Vector3 tipPosition){
switch(PointingType){
case PointingType.RelativeToHorizon:
Quaternion cameraRot = Camera.main.transform.rotation;
float cameraYaw = cameraRot.eulerAngles.y;
Quaternion rotator = Quaternion.AngleAxis(cameraYaw, Vector3.up);
return rotator * PointingDirection;
case PointingType.RelativeToCamera:
return Camera.main.transform.TransformDirection(PointingDirection);
case PointingType.RelativeToWorld:
return PointingDirection;
case PointingType.AtTarget:
return TargetObject.position - tipPosition;
default:
return PointingDirection;
}
}
private int selectedFingerOrdinal(){
switch(FingerName){
case Finger.FingerType.TYPE_INDEX:
return 1;
case Finger.FingerType.TYPE_MIDDLE:
return 2;
case Finger.FingerType.TYPE_PINKY:
return 4;
case Finger.FingerType.TYPE_RING:
return 3;
case Finger.FingerType.TYPE_THUMB:
return 0;
default:
return 1;
}
}
#if UNITY_EDITOR
private void OnDrawGizmos () {
if (ShowGizmos && HandModel != null && HandModel.IsTracked) {
Color innerColor;
if (IsActive) {
innerColor = OnColor;
} else {
innerColor = OffColor;
}
Finger finger = HandModel.GetLeapHand().Fingers[selectedFingerOrdinal()];
Vector3 fingerDirection = finger.Bone(Bone.BoneType.TYPE_DISTAL).Direction.ToVector3();
Utils.DrawCone(finger.TipPosition.ToVector3(), fingerDirection, OnAngle, finger.Length, innerColor);
Utils.DrawCone(finger.TipPosition.ToVector3(), fingerDirection, OffAngle, finger.Length, LimitColor);
Gizmos.color = DirectionColor;
Gizmos.DrawRay(finger.TipPosition.ToVector3(), selectedDirection(finger.TipPosition.ToVector3()));
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using E2ETests.Common;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
namespace E2ETests
{
// Uses ports ranging 5025 - 5039.
public class PublishAndRunTests_OnX64 : IDisposable
{
private readonly XunitLogger _logger;
public PublishAndRunTests_OnX64(ITestOutputHelper output)
{
_logger = new XunitLogger(output, LogLevel.Information);
}
[ConditionalTheory, Trait("E2Etests", "PublishAndRun")]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
//[InlineData(ServerType.WebListener, RuntimeFlavor.Clr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5025/", false)]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5026/", false)]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5027/", false)]
//[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5028/", false)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5029/", false)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5030/", false)]
public async Task WindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl,
bool noSource)
{
var testRunner = new PublishAndRunTests(_logger);
await testRunner.Publish_And_Run_Tests(
serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl, noSource);
}
[ConditionalTheory, Trait("E2Etests", "PublishAndRun")]
[OSSkipCondition(OperatingSystems.Windows)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5031/", false)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5032/", false)]
public async Task NonWindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl,
bool noSource)
{
var testRunner = new PublishAndRunTests(_logger);
await testRunner.Publish_And_Run_Tests(
serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl, noSource);
}
public void Dispose()
{
_logger.Dispose();
}
}
// TODO: temporarily disabling x86 tests as dotnet xunit test runner currently does not support 32-bit
// public
class PublishAndRunTests_OnX86 : IDisposable
{
private readonly XunitLogger _logger;
public PublishAndRunTests_OnX86(ITestOutputHelper output)
{
_logger = new XunitLogger(output, LogLevel.Information);
}
[ConditionalTheory, Trait("E2Etests", "PublishAndRun")]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(ServerType.WebListener, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5034/", false)]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5035/", false)]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Standalone, "http://localhost:5036/", false)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5037/", false)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5038/", false)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Standalone, "http://localhost:5039/", false)]
public async Task WindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl,
bool noSource)
{
var testRunner = new PublishAndRunTests(_logger);
await testRunner.Publish_And_Run_Tests(
serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl, noSource);
}
[ConditionalTheory, Trait("E2Etests", "PublishAndRun")]
[OSSkipCondition(OperatingSystems.Windows)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5040/", false)]
public async Task NonWindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl,
bool noSource)
{
var testRunner = new PublishAndRunTests(_logger);
await testRunner.Publish_And_Run_Tests(
serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl, noSource);
}
public void Dispose()
{
_logger.Dispose();
}
}
public class PublishAndRunTests
{
private ILogger _logger;
public PublishAndRunTests(ILogger logger)
{
_logger = logger;
}
public async Task Publish_And_Run_Tests(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl,
bool noSource)
{
using (_logger.BeginScope("Publish_And_Run_Tests"))
{
var musicStoreDbName = DbUtils.GetUniqueName();
var deploymentParameters = new DeploymentParameters(
Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
{
ApplicationBaseUriHint = applicationBaseUrl,
PublishApplicationBeforeDeployment = true,
PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
Configuration = Helpers.GetCurrentBuildConfiguration(),
ApplicationType = applicationType,
UserAdditionalCleanup = parameters =>
{
DbUtils.DropDatabase(musicStoreDbName, _logger);
}
};
// Override the connection strings using environment based configuration
deploymentParameters.EnvironmentVariables
.Add(new KeyValuePair<string, string>(
MusicStoreConfig.ConnectionStringKey,
DbUtils.CreateConnectionString(musicStoreDbName)));
using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, _logger))
{
var deploymentResult = deployer.Deploy();
var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true };
var httpClient = new HttpClient(httpClientHandler);
httpClient.BaseAddress = new Uri(deploymentResult.ApplicationBaseUri);
// Request to base address and check if various parts of the body are rendered &
// measure the cold startup time.
// Add retry logic since tests are flaky on mono due to connection issues
var response = await RetryHelper.RetryRequest(async () => await httpClient.GetAsync(string.Empty), logger: _logger, cancellationToken: deploymentResult.HostShutdownToken);
Assert.False(response == null, "Response object is null because the client could not " +
"connect to the server after multiple retries");
var validator = new Validator(httpClient, httpClientHandler, _logger, deploymentResult);
Console.WriteLine("Verifying home page");
await validator.VerifyHomePage(response);
Console.WriteLine("Verifying static files are served from static file middleware");
await validator.VerifyStaticContentServed();
if (serverType != ServerType.IISExpress)
{
if (Directory.GetFiles(
deploymentParameters.ApplicationPath, "*.cmd", SearchOption.TopDirectoryOnly).Length > 0)
{
throw new Exception("publishExclude parameter values are not honored.");
}
}
_logger.LogInformation("Variation completed successfully.");
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace EZOper.TechTester.OAuth2WebSI.Areas.ZApi
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Umbraco.Core.Logging;
namespace Umbraco.Core.ObjectResolution
{
/// <summary>
/// The base class for all lazy many-objects resolvers.
/// </summary>
/// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam>
/// <typeparam name="TResolved">The type of the resolved objects.</typeparam>
/// <remarks>
/// <para>This is a special case resolver for when types get lazily resolved in order to resolve the actual types. This is useful
/// for when there is some processing overhead (i.e. Type finding in assemblies) to return the Types used to instantiate the instances.
/// In some these cases we don't want to have to type-find during application startup, only when we need to resolve the instances.</para>
/// <para>Important notes about this resolver: it does not support Insert or Remove and therefore does not support any ordering unless
/// the types are marked with the WeightedPluginAttribute.</para>
/// </remarks>
public abstract class LazyManyObjectsResolverBase<TResolver, TResolved> : ManyObjectsResolverBase<TResolver, TResolved>
where TResolved : class
where TResolver : ResolverBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// and an optional lifetime scope.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="logger"></param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(serviceProvider, logger, scope)
{
Initialize();
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(scope)
{
Initialize();
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(HttpContextBase httpContext)
: base(httpContext)
{
Initialize();
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, IEnumerable<Lazy<Type>> lazyTypeList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(serviceProvider, logger, scope)
{
AddTypes(lazyTypeList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(IEnumerable<Lazy<Type>> lazyTypeList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, lazyTypeList, scope)
{
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, Func<IEnumerable<Type>> typeListProducerList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(serviceProvider, logger, scope)
{
_typeListProducerList.Add(typeListProducerList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(Func<IEnumerable<Type>> typeListProducerList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, typeListProducerList, scope)
{
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext, IEnumerable<Lazy<Type>> lazyTypeList)
: this(serviceProvider, logger, httpContext)
{
AddTypes(lazyTypeList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Lazy<Type>> lazyTypeList)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, httpContext, lazyTypeList)
{
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext, Func<IEnumerable<Type>> typeListProducerList)
: this(serviceProvider, logger, httpContext)
{
_typeListProducerList.Add(typeListProducerList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, Func<IEnumerable<Type>> typeListProducerList)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, httpContext, typeListProducerList)
{
}
#endregion
private readonly List<Lazy<Type>> _lazyTypeList = new List<Lazy<Type>>();
private readonly List<Func<IEnumerable<Type>>> _typeListProducerList = new List<Func<IEnumerable<Type>>>();
private readonly List<Type> _excludedTypesList = new List<Type>();
private Lazy<List<Type>> _resolvedTypes;
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="logger"></param>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext)
: base(serviceProvider, logger, httpContext)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of object types,
/// and an optional lifetime scope.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="logger"></param>
/// <param name="value">The list of object types.</param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(serviceProvider, logger, value, scope)
{
}
private void Initialize()
{
_resolvedTypes = new Lazy<List<Type>>(() =>
{
var resolvedTypes = new List<Type>();
// get the types by evaluating the lazy & producers
var types = new List<Type>();
types.AddRange(_lazyTypeList.Select(x => x.Value));
types.AddRange(_typeListProducerList.SelectMany(x => x()));
// we need to validate each resolved type now since we could
// not do it before evaluating the lazy & producers
foreach (var type in types.Where(x => _excludedTypesList.Contains(x) == false))
{
AddValidAndNoDuplicate(resolvedTypes, type);
}
return resolvedTypes;
});
}
/// <summary>
/// Gets a value indicating whether the resolver has resolved types to create instances from.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
public bool HasResolvedTypes
{
get { return _resolvedTypes.IsValueCreated; }
}
/// <summary>
/// Gets the list of types to create instances from.
/// </summary>
/// <remarks>When called, will get the types from the lazy list.</remarks>
protected override IEnumerable<Type> InstanceTypes
{
get { return _resolvedTypes.Value; }
}
/// <summary>
/// Ensures that type is valid and not a duplicate
/// then appends the type to the end of the list
/// </summary>
/// <param name="list"></param>
/// <param name="type"></param>
private void AddValidAndNoDuplicate(List<Type> list, Type type)
{
EnsureCorrectType(type);
if (list.Contains(type))
{
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", type.FullName));
}
list.Add(type);
}
#region Types collection manipulation
/// <summary>
/// Removes types from the list of types, once it has been lazily evaluated, and before actual objects are instanciated.
/// </summary>
/// <param name="value">The type to remove.</param>
public override void RemoveType(Type value)
{
EnsureSupportsRemove();
_excludedTypesList.Add(value);
}
/// <summary>
/// Lazily adds types from lazy types.
/// </summary>
/// <param name="types">The lazy types, to add.</param>
protected void AddTypes(IEnumerable<Lazy<Type>> types)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
foreach (var t in types)
{
_lazyTypeList.Add(t);
}
}
}
/// <summary>
/// Lazily adds types from a function producing types.
/// </summary>
/// <param name="typeListProducer">The functions producing types, to add.</param>
public void AddTypeListDelegate(Func<IEnumerable<Type>> typeListProducer)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_typeListProducerList.Add(typeListProducer);
}
}
/// <summary>
/// Lazily adds a type from a lazy type.
/// </summary>
/// <param name="value">The lazy type, to add.</param>
public void AddType(Lazy<Type> value)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Add(value);
}
}
/// <summary>
/// Lazily adds a type from an actual type.
/// </summary>
/// <param name="value">The actual type, to add.</param>
/// <remarks>The type is converted to a lazy type.</remarks>
public override void AddType(Type value)
{
AddType(new Lazy<Type>(() => value));
}
/// <summary>
/// Clears all lazy types
/// </summary>
public override void Clear()
{
EnsureSupportsClear();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Clear();
}
}
#endregion
#region Types collection manipulation support
/// <summary>
/// Gets a <c>false</c> value indicating that the resolver does NOT support inserting types.
/// </summary>
protected override bool SupportsInsert
{
get { return false; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
namespace Umbraco.Cms.Infrastructure.ModelsBuilder.Building
{
// NOTE
// The idea was to have different types of builder, because I wanted to experiment with
// building code with CodeDom. Turns out more complicated than I thought and maybe not
// worth it at the moment, to we're using TextBuilder and its Generate method is specific.
//
// Keeping the code as-is for the time being...
/// <summary>
/// Provides a base class for all builders.
/// </summary>
public abstract class Builder
{
protected Dictionary<string, string> ModelsMap { get; } = new Dictionary<string, string>();
// the list of assemblies that will be 'using' by default
protected IList<string> TypesUsing { get; } = new List<string>
{
"System",
"System.Linq.Expressions",
"Umbraco.Cms.Core.Models.PublishedContent",
"Umbraco.Cms.Core.PublishedCache",
"Umbraco.Cms.Infrastructure.ModelsBuilder",
"Umbraco.Cms.Core",
"Umbraco.Extensions"
};
/// <summary>
/// Gets or sets a value indicating the namespace to use for the models.
/// </summary>
/// <remarks>May be overriden by code attributes.</remarks>
public string ModelsNamespace { get; set; }
/// <summary>
/// Gets the list of assemblies to add to the set of 'using' assemblies in each model file.
/// </summary>
public IList<string> Using => TypesUsing;
/// <summary>
/// Gets the list of models to generate.
/// </summary>
/// <returns>The models to generate</returns>
public IEnumerable<TypeModel> GetModelsToGenerate() => TypeModels;
/// <summary>
/// Gets the list of all models.
/// </summary>
/// <remarks>Includes those that are ignored.</remarks>
public IList<TypeModel> TypeModels { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class with a list of models to generate,
/// the result of code parsing, and a models namespace.
/// </summary>
/// <param name="typeModels">The list of models to generate.</param>
/// <param name="modelsNamespace">The models namespace.</param>
protected Builder(ModelsBuilderSettings config, IList<TypeModel> typeModels)
{
TypeModels = typeModels ?? throw new ArgumentNullException(nameof(typeModels));
Config = config ?? throw new ArgumentNullException(nameof(config));
// can be null or empty, we'll manage
ModelsNamespace = Config.ModelsNamespace;
// but we want it to prepare
Prepare();
}
// for unit tests only
protected Builder()
{ }
protected ModelsBuilderSettings Config { get; }
/// <summary>
/// Prepares generation by processing the result of code parsing.
/// </summary>
private void Prepare()
{
TypeModel.MapModelTypes(TypeModels, ModelsNamespace);
var isInMemoryMode = Config.ModelsMode == ModelsMode.InMemoryAuto;
// for the first two of these two tests,
// always throw, even in InMemory mode: cannot happen unless ppl start fidling with attributes to rename
// things, and then they should pay attention to the generation error log - there's no magic here
// for the last one, don't throw in InMemory mode, see comment
// ensure we have no duplicates type names
foreach (var xx in TypeModels.GroupBy(x => x.ClrName).Where(x => x.Count() > 1))
throw new InvalidOperationException($"Type name \"{xx.Key}\" is used"
+ $" for types with alias {string.Join(", ", xx.Select(x => x.ItemType + ":\"" + x.Alias + "\""))}. Names have to be unique."
+ " Consider using an attribute to assign different names to conflicting types.");
// ensure we have no duplicates property names
foreach (var typeModel in TypeModels)
foreach (var xx in typeModel.Properties.GroupBy(x => x.ClrName).Where(x => x.Count() > 1))
throw new InvalidOperationException($"Property name \"{xx.Key}\" in type {typeModel.ItemType}:\"{typeModel.Alias}\""
+ $" is used for properties with alias {string.Join(", ", xx.Select(x => "\"" + x.Alias + "\""))}. Names have to be unique."
+ " Consider using an attribute to assign different names to conflicting properties.");
// ensure content & property type don't have identical name (csharp hates it)
foreach (var typeModel in TypeModels)
{
foreach (var xx in typeModel.Properties.Where(x => x.ClrName == typeModel.ClrName))
{
if (!isInMemoryMode)
throw new InvalidOperationException($"The model class for content type with alias \"{typeModel.Alias}\" is named \"{xx.ClrName}\"."
+ $" CSharp does not support using the same name for the property with alias \"{xx.Alias}\"."
+ " Consider using an attribute to assign a different name to the property.");
// in InMemory mode we generate commented out properties with an error message,
// instead of throwing, because then it kills the sites and ppl don't understand why
xx.AddError($"The class {typeModel.ClrName} cannot implement this property, because"
+ $" CSharp does not support naming the property with alias \"{xx.Alias}\" with the same name as content type with alias \"{typeModel.Alias}\"."
+ " Consider using an attribute to assign a different name to the property.");
// will not be implemented on interface nor class
// note: we will still create the static getter, and implement the property on other classes...
}
}
// ensure we have no collision between base types
// NO: we may want to define a base class in a partial, on a model that has a parent
// we are NOT checking that the defined base type does maintain the inheritance chain
//foreach (var xx in _typeModels.Where(x => !x.IsContentIgnored).Where(x => x.BaseType != null && x.HasBase))
// throw new InvalidOperationException(string.Format("Type alias \"{0}\" has more than one parent class.",
// xx.Alias));
// discover interfaces that need to be declared / implemented
foreach (var typeModel in TypeModels)
{
// collect all the (non-removed) types implemented at parent level
// ie the parent content types and the mixins content types, recursively
var parentImplems = new List<TypeModel>();
if (typeModel.BaseType != null)
TypeModel.CollectImplems(parentImplems, typeModel.BaseType);
// interfaces we must declare we implement (initially empty)
// ie this type's mixins, except those that have been removed,
// and except those that are already declared at the parent level
// in other words, DeclaringInterfaces is "local mixins"
var declaring = typeModel.MixinTypes
.Except(parentImplems);
typeModel.DeclaringInterfaces.AddRange(declaring);
// interfaces we must actually implement (initially empty)
// if we declare we implement a mixin interface, we must actually implement
// its properties, all recursively (ie if the mixin interface implements...)
// so, starting with local mixins, we collect all the (non-removed) types above them
var mixinImplems = new List<TypeModel>();
foreach (var i in typeModel.DeclaringInterfaces)
TypeModel.CollectImplems(mixinImplems, i);
// and then we remove from that list anything that is already declared at the parent level
typeModel.ImplementingInterfaces.AddRange(mixinImplems.Except(parentImplems));
}
// ensure elements don't inherit from non-elements
foreach (var typeModel in TypeModels.Where(x => x.IsElement))
{
if (typeModel.BaseType != null && !typeModel.BaseType.IsElement)
throw new InvalidOperationException($"Cannot generate model for type '{typeModel.Alias}' because it is an element type, but its parent type '{typeModel.BaseType.Alias}' is not.");
var errs = typeModel.MixinTypes.Where(x => !x.IsElement).ToList();
if (errs.Count > 0)
throw new InvalidOperationException($"Cannot generate model for type '{typeModel.Alias}' because it is an element type, but it is composed of {string.Join(", ", errs.Select(x => "'" + x.Alias + "'"))} which {(errs.Count == 1 ? "is" : "are")} not.");
}
}
// looking for a simple symbol eg 'Umbraco' or 'String'
// expecting to match eg 'Umbraco' or 'System.String'
// returns true if either
// - more than 1 symbol is found (explicitely ambiguous)
// - 1 symbol is found BUT not matching (implicitely ambiguous)
protected bool IsAmbiguousSymbol(string symbol, string match)
{
// cannot figure out is a symbol is ambiguous without Roslyn
// so... let's say everything is ambiguous - code won't be
// pretty but it'll work
// Essentially this means that a `global::` syntax will be output for the generated models
return true;
}
public string ModelsNamespaceForTests { get; set; }
public string GetModelsNamespace()
{
if (ModelsNamespaceForTests != null)
return ModelsNamespaceForTests;
// if builder was initialized with a namespace, use that one
if (!string.IsNullOrWhiteSpace(ModelsNamespace))
return ModelsNamespace;
// use configured else fallback to default
return string.IsNullOrWhiteSpace(Config.ModelsNamespace)
? Constants.ModelsBuilder.DefaultModelsNamespace
: Config.ModelsNamespace;
}
protected string GetModelsBaseClassName(TypeModel type)
{
// default
return type.IsElement ? "PublishedElementModel" : "PublishedContentModel";
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XsdValidator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Runtime.Versioning;
#pragma warning disable 618
internal sealed class XsdValidator : BaseValidator {
private int startIDConstraint = -1;
private const int STACK_INCREMENT = 10;
private HWStack validationStack; // validaton contexts
private Hashtable attPresence;
private XmlNamespaceManager nsManager;
private bool bManageNamespaces = false;
private Hashtable IDs;
private IdRefNode idRefListHead;
private Parser inlineSchemaParser = null;
private XmlSchemaContentProcessing processContents;
private static readonly XmlSchemaDatatype dtCDATA = XmlSchemaDatatype.FromXmlTokenizedType(XmlTokenizedType.CDATA);
private static readonly XmlSchemaDatatype dtQName = XmlSchemaDatatype.FromXmlTokenizedTypeXsd(XmlTokenizedType.QName);
private static readonly XmlSchemaDatatype dtStringArray = dtCDATA.DeriveByList(null);
//To avoid SchemaNames creation
private string NsXmlNs;
private string NsXs;
private string NsXsi;
private string XsiType;
private string XsiNil;
private string XsiSchemaLocation;
private string XsiNoNamespaceSchemaLocation;
private string XsdSchema;
internal XsdValidator(BaseValidator validator) : base(validator) {
Init();
}
internal XsdValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling) : base(reader, schemaCollection, eventHandling) {
Init();
}
private void Init() {
nsManager = reader.NamespaceManager;
if (nsManager == null) {
nsManager = new XmlNamespaceManager(NameTable);
bManageNamespaces = true;
}
validationStack = new HWStack(STACK_INCREMENT);
textValue = new StringBuilder();
attPresence = new Hashtable();
schemaInfo = new SchemaInfo ();
checkDatatype = false;
processContents = XmlSchemaContentProcessing.Strict;
Push (XmlQualifiedName.Empty);
//Add common strings to be compared to NameTable
NsXmlNs = NameTable.Add(XmlReservedNs.NsXmlNs);
NsXs = NameTable.Add(XmlReservedNs.NsXs);
NsXsi = NameTable.Add(XmlReservedNs.NsXsi);
XsiType = NameTable.Add("type");
XsiNil = NameTable.Add("nil");
XsiSchemaLocation = NameTable.Add("schemaLocation");
XsiNoNamespaceSchemaLocation = NameTable.Add("noNamespaceSchemaLocation");
XsdSchema = NameTable.Add("schema");
}
public override void Validate() {
if (IsInlineSchemaStarted) {
ProcessInlineSchema();
}
else {
switch (reader.NodeType) {
case XmlNodeType.Element:
ValidateElement();
if (reader.IsEmptyElement) {
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.Whitespace:
ValidateWhitespace();
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
case XmlNodeType.SignificantWhitespace:
ValidateText();
break;
case XmlNodeType.EndElement:
ValidateEndElement();
break;
}
}
}
public override void CompleteValidation() {
CheckForwardRefs();
}
//for frag validation
public ValidationState Context{
set { context = value; }
}
//share for frag validation
public static XmlSchemaDatatype DtQName {
get { return dtQName; }
}
private bool IsInlineSchemaStarted {
get { return inlineSchemaParser != null; }
}
private void ProcessInlineSchema() {
if (!inlineSchemaParser.ParseReaderNode()) { // Done
inlineSchemaParser.FinishParsing();
XmlSchema schema = inlineSchemaParser.XmlSchema;
string inlineNS = null;
if (schema != null && schema.ErrorCount == 0) {
try {
SchemaInfo inlineSchemaInfo = new SchemaInfo();
inlineSchemaInfo.SchemaType = SchemaType.XSD;
inlineNS = schema.TargetNamespace == null? string.Empty : schema.TargetNamespace;
if (!SchemaInfo.TargetNamespaces.ContainsKey(inlineNS)) {
if (SchemaCollection.Add(inlineNS, inlineSchemaInfo, schema, true) != null) { //If no errors on compile
//Add to validator's SchemaInfo
SchemaInfo.Add(inlineSchemaInfo, EventHandler);
}
}
}
catch(XmlSchemaException e) {
SendValidationEvent(Res.Sch_CannotLoadSchema, new string[] {BaseUri.AbsoluteUri, e.Message}, XmlSeverityType.Error);
}
}
inlineSchemaParser = null;
}
}
private void ValidateElement() {
elementName.Init(reader.LocalName, reader.NamespaceURI);
object particle = ValidateChildElement ();
if (IsXSDRoot(elementName.Name, elementName.Namespace) && reader.Depth > 0) {
inlineSchemaParser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler);
inlineSchemaParser.StartParsing(reader, null);
ProcessInlineSchema();
}
else {
ProcessElement(particle);
}
}
private object ValidateChildElement() {
object particle = null;
int errorCode = 0;
if (context.NeedValidateChildren) {
if (context.IsNill) {
SendValidationEvent(Res.Sch_ContentInNill, elementName.ToString());
return null;
}
particle = context.ElementDecl.ContentValidator.ValidateElement(elementName, context, out errorCode);
if (particle == null) {
processContents = context.ProcessContents = XmlSchemaContentProcessing.Skip;
if (errorCode == -2) { //ContentModel all group error
SendValidationEvent(Res.Sch_AllElement, elementName.ToString());
}
XmlSchemaValidator.ElementValidationError(elementName, context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
return particle;
}
private void ProcessElement(object particle) {
XmlQualifiedName xsiType;
string xsiNil;
SchemaElementDecl elementDecl = FastGetElementDecl (particle);
Push(elementName);
if (bManageNamespaces) {
nsManager.PushScope();
}
ProcessXsiAttributes(out xsiType, out xsiNil);
if (processContents != XmlSchemaContentProcessing.Skip) {
if (elementDecl == null || !xsiType.IsEmpty || xsiNil != null) {
elementDecl = ThoroughGetElementDecl(elementDecl, xsiType, xsiNil);
}
if (elementDecl == null) {
if (HasSchema && processContents == XmlSchemaContentProcessing.Strict) {
SendValidationEvent(Res.Sch_UndeclaredElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
else {
SendValidationEvent(Res.Sch_NoElementSchemaFound, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace), XmlSeverityType.Warning);
}
}
}
context.ElementDecl = elementDecl;
ValidateStartElementIdentityConstraints();
ValidateStartElement();
if (context.ElementDecl != null) {
ValidateEndStartElement();
context.NeedValidateChildren = processContents != XmlSchemaContentProcessing.Skip;
context.ElementDecl.ContentValidator.InitValidation(context);
}
}
// SxS: This method processes attributes read from source document and does not expose any resources.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
private void ProcessXsiAttributes(out XmlQualifiedName xsiType, out string xsiNil) {
string[] xsiSchemaLocation = null;
string xsiNoNamespaceSchemaLocation = null;
xsiType = XmlQualifiedName.Empty;
xsiNil = null;
if (reader.Depth == 0) {
//Load schema for empty namespace
LoadSchema(string.Empty, null);
//Should load schemas for namespaces already added to nsManager
foreach(string ns in nsManager.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml).Values) {
LoadSchema(ns, null);
}
}
if (reader.MoveToFirstAttribute()) {
do {
string objectNs = reader.NamespaceURI;
string objectName = reader.LocalName;
if (Ref.Equal(objectNs, NsXmlNs)) {
LoadSchema(reader.Value, null);
if (bManageNamespaces) {
nsManager.AddNamespace(reader.Prefix.Length == 0 ? string.Empty : reader.LocalName, reader.Value);
}
}
else if (Ref.Equal(objectNs, NsXsi)) {
if (Ref.Equal(objectName, XsiSchemaLocation)) {
xsiSchemaLocation = (string[])dtStringArray.ParseValue(reader.Value, NameTable, nsManager);
}
else if (Ref.Equal(objectName, XsiNoNamespaceSchemaLocation)) {
xsiNoNamespaceSchemaLocation = reader.Value;
}
else if (Ref.Equal(objectName, XsiType)) {
xsiType = (XmlQualifiedName)dtQName.ParseValue(reader.Value, NameTable, nsManager);
}
else if (Ref.Equal(objectName, XsiNil)) {
xsiNil = reader.Value;
}
}
} while(reader.MoveToNextAttribute());
reader.MoveToElement();
}
if (xsiNoNamespaceSchemaLocation != null) {
LoadSchema(string.Empty, xsiNoNamespaceSchemaLocation);
}
if (xsiSchemaLocation != null) {
for (int i = 0; i < xsiSchemaLocation.Length - 1; i += 2) {
LoadSchema((string)xsiSchemaLocation[i], (string)xsiSchemaLocation[i + 1]);
}
}
}
private void ValidateEndElement() {
if (bManageNamespaces) {
nsManager.PopScope();
}
if (context.ElementDecl != null) {
if (!context.IsNill) {
if (context.NeedValidateChildren) {
if(!context.ElementDecl.ContentValidator.CompleteValidation(context)) {
XmlSchemaValidator.CompleteValidationError(context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
if (checkDatatype && !context.IsNill) {
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
if(!(stringValue.Length == 0 && context.ElementDecl.DefaultValueTyped != null)) {
CheckValue(stringValue, null);
checkDatatype = false;
}
}
}
// for each level in the stack, endchildren and fill value from element
if (HasIdentityConstraints) {
EndElementIdentityConstraints();
}
}
Pop();
}
private SchemaElementDecl FastGetElementDecl(object particle) {
SchemaElementDecl elementDecl = null;
if (particle != null) {
XmlSchemaElement element = particle as XmlSchemaElement;
if (element != null) {
elementDecl = element.ElementDecl;
}
else {
XmlSchemaAny any = (XmlSchemaAny)particle;
processContents = any.ProcessContentsCorrect;
}
}
return elementDecl;
}
private SchemaElementDecl ThoroughGetElementDecl(SchemaElementDecl elementDecl, XmlQualifiedName xsiType, string xsiNil) {
if (elementDecl == null) {
elementDecl = schemaInfo.GetElementDecl(elementName);
}
if (elementDecl != null) {
if (xsiType.IsEmpty) {
if (elementDecl.IsAbstract) {
SendValidationEvent(Res.Sch_AbstractElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
elementDecl = null;
}
}
else if(xsiNil != null && xsiNil.Equals("true")) {
SendValidationEvent(Res.Sch_XsiNilAndType);
}
else {
SchemaElementDecl elementDeclXsi;
if (!schemaInfo.ElementDeclsByType.TryGetValue(xsiType, out elementDeclXsi) && xsiType.Namespace == NsXs) {
XmlSchemaSimpleType simpleType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName(xsiType.Name,NsXs));
if (simpleType != null) {
elementDeclXsi = simpleType.ElementDecl;
}
}
if (elementDeclXsi == null) {
SendValidationEvent(Res.Sch_XsiTypeNotFound, xsiType.ToString());
elementDecl = null;
}
else if (!XmlSchemaType.IsDerivedFrom(elementDeclXsi.SchemaType,elementDecl.SchemaType,elementDecl.Block)) {
SendValidationEvent(Res.Sch_XsiTypeBlockedEx, new string[] { xsiType.ToString(), XmlSchemaValidator.QNameString(context.LocalName, context.Namespace) });
elementDecl = null;
}
else {
elementDecl = elementDeclXsi;
}
}
if (elementDecl != null && elementDecl.IsNillable) {
if (xsiNil != null) {
context.IsNill = XmlConvert.ToBoolean(xsiNil);
if (context.IsNill && elementDecl.DefaultValueTyped != null) {
SendValidationEvent(Res.Sch_XsiNilAndFixed);
}
}
}
else if (xsiNil != null) {
SendValidationEvent(Res.Sch_InvalidXsiNill);
}
}
return elementDecl;
}
private void ValidateStartElement() {
if (context.ElementDecl != null) {
if (context.ElementDecl.IsAbstract) {
SendValidationEvent(Res.Sch_AbstractElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
reader.SchemaTypeObject = context.ElementDecl.SchemaType;
if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped != null) {
reader.TypedValueObject = UnWrapUnion(context.ElementDecl.DefaultValueTyped);
context.IsNill = true; // reusing IsNill
}
else {
reader.TypedValueObject = null; //Typed value cleanup
}
if (this.context.ElementDecl.HasRequiredAttribute || HasIdentityConstraints) {
attPresence.Clear();
}
}
if (reader.MoveToFirstAttribute()) {
do {
if ((object)reader.NamespaceURI == (object)NsXmlNs) {
continue;
}
if ((object)reader.NamespaceURI == (object)NsXsi) {
continue;
}
try {
reader.SchemaTypeObject = null;
XmlQualifiedName attQName = new XmlQualifiedName(reader.LocalName, reader.NamespaceURI);
bool skipContents = (processContents == XmlSchemaContentProcessing.Skip);
SchemaAttDef attnDef = schemaInfo.GetAttributeXsd(context.ElementDecl, attQName, ref skipContents);
if (attnDef != null) {
if (context.ElementDecl != null && (context.ElementDecl.HasRequiredAttribute || this.startIDConstraint != -1)) {
attPresence.Add(attnDef.Name, attnDef);
}
Debug.Assert(attnDef.SchemaType != null);
reader.SchemaTypeObject = attnDef.SchemaType;
if (attnDef.Datatype != null) {
// need to check the contents of this attribute to make sure
// it is valid according to the specified attribute type.
CheckValue(reader.Value, attnDef);
}
if (HasIdentityConstraints) {
AttributeIdentityConstraints(reader.LocalName, reader.NamespaceURI, reader.TypedValueObject, reader.Value, attnDef);
}
}
else if (!skipContents) {
if (context.ElementDecl == null
&& processContents == XmlSchemaContentProcessing.Strict
&& attQName.Namespace.Length != 0
&& schemaInfo.Contains(attQName.Namespace)
) {
SendValidationEvent(Res.Sch_UndeclaredAttribute, attQName.ToString());
}
else {
SendValidationEvent(Res.Sch_NoAttributeSchemaFound, attQName.ToString(), XmlSeverityType.Warning);
}
}
}
catch (XmlSchemaException e) {
e.SetSource(reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
} while(reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
private void ValidateEndStartElement() {
if (context.ElementDecl.HasDefaultAttribute) {
for (int i = 0; i < context.ElementDecl.DefaultAttDefs.Count; ++i) {
SchemaAttDef attdef = (SchemaAttDef)context.ElementDecl.DefaultAttDefs[i];
reader.AddDefaultAttribute(attdef);
// even default attribute i have to move to... but can't exist
if (HasIdentityConstraints && !attPresence.Contains(attdef.Name)) {
AttributeIdentityConstraints(attdef.Name.Name, attdef.Name.Namespace, UnWrapUnion(attdef.DefaultValueTyped), attdef.DefaultValueRaw, attdef);
}
}
}
if (context.ElementDecl.HasRequiredAttribute) {
try {
context.ElementDecl.CheckAttributes(attPresence, reader.StandAlone);
}
catch (XmlSchemaException e) {
e.SetSource(reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
}
if (context.ElementDecl.Datatype != null) {
checkDatatype = true;
hasSibling = false;
textString = string.Empty;
textValue.Length = 0;
}
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private void LoadSchemaFromLocation(string uri, string url) {
XmlReader reader = null;
SchemaInfo schemaInfo = null;
try {
Uri ruri = this.XmlResolver.ResolveUri(BaseUri, url);
Stream stm = (Stream)this.XmlResolver.GetEntity(ruri,null,null);
reader = new XmlTextReader(ruri.ToString(), stm, NameTable);
//XmlSchema schema = SchemaCollection.Add(uri, reader, this.XmlResolver);
Parser parser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler);
parser.XmlResolver = this.XmlResolver;
SchemaType schemaType = parser.Parse(reader, uri);
schemaInfo = new SchemaInfo();
schemaInfo.SchemaType = schemaType;
if (schemaType == SchemaType.XSD) {
if (SchemaCollection.EventHandler == null) {
SchemaCollection.EventHandler = this.EventHandler;
}
SchemaCollection.Add(uri, schemaInfo, parser.XmlSchema, true);
}
//Add to validator's SchemaInfo
SchemaInfo.Add(schemaInfo, EventHandler);
while(reader.Read());// wellformness check
}
catch(XmlSchemaException e) {
schemaInfo = null;
SendValidationEvent(Res.Sch_CannotLoadSchema, new string[] {uri, e.Message}, XmlSeverityType.Error);
}
catch(Exception e) {
schemaInfo = null;
SendValidationEvent(Res.Sch_CannotLoadSchema, new string[] {uri, e.Message}, XmlSeverityType.Warning);
}
finally {
if (reader != null) {
reader.Close();
}
}
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private void LoadSchema(string uri, string url) {
if (this.XmlResolver == null) {
return;
}
if (SchemaInfo.TargetNamespaces.ContainsKey(uri) && nsManager.LookupPrefix(uri) != null) {
return;
}
SchemaInfo schemaInfo = null;
if (SchemaCollection != null)
schemaInfo = SchemaCollection.GetSchemaInfo(uri);
if (schemaInfo != null) {
if(schemaInfo.SchemaType != SchemaType.XSD) {
throw new XmlException(Res.Xml_MultipleValidaitonTypes, string.Empty, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
SchemaInfo.Add(schemaInfo, EventHandler);
return;
}
if (url != null) {
LoadSchemaFromLocation(uri, url);
}
}
private bool HasSchema { get { return schemaInfo.SchemaType != SchemaType.None;}}
public override bool PreserveWhitespace {
get { return context.ElementDecl != null ? context.ElementDecl.ContentValidator.PreserveWhitespace : false; }
}
void ProcessTokenizedType(
XmlTokenizedType ttype,
string name
) {
switch(ttype) {
case XmlTokenizedType.ID:
if (FindId(name) != null) {
SendValidationEvent(Res.Sch_DupId, name);
}
else {
AddID(name, context.LocalName);
}
break;
case XmlTokenizedType.IDREF:
object p = FindId(name);
if (p == null) { // add it to linked list to check it later
idRefListHead = new IdRefNode(idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
break;
case XmlTokenizedType.ENTITY:
ProcessEntity(schemaInfo, name, this, EventHandler, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
break;
default:
break;
}
}
private void CheckValue(
string value,
SchemaAttDef attdef
) {
try {
reader.TypedValueObject = null;
bool isAttn = attdef != null;
XmlSchemaDatatype dtype = isAttn ? attdef.Datatype : context.ElementDecl.Datatype;
if (dtype == null) {
return; // no reason to check
}
object typedValue = dtype.ParseValue(value, NameTable, nsManager, true);
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY || ttype == XmlTokenizedType.ID || ttype == XmlTokenizedType.IDREF) {
if (dtype.Variety == XmlSchemaDatatypeVariety.List) {
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i) {
ProcessTokenizedType(dtype.TokenizedType, ss[i]);
}
}
else {
ProcessTokenizedType(dtype.TokenizedType, (string)typedValue);
}
}
SchemaDeclBase decl = isAttn ? (SchemaDeclBase)attdef : (SchemaDeclBase)context.ElementDecl;
if (!decl.CheckValue(typedValue)) {
if (isAttn) {
SendValidationEvent(Res.Sch_FixedAttributeValue, attdef.Name.ToString());
}
else {
SendValidationEvent(Res.Sch_FixedElementValue, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
if (dtype.Variety == XmlSchemaDatatypeVariety.Union) {
typedValue = UnWrapUnion(typedValue);
}
reader.TypedValueObject = typedValue;
}
catch (XmlSchemaException) {
if (attdef != null) {
SendValidationEvent(Res.Sch_AttributeValueDataType, attdef.Name.ToString());
}
else {
SendValidationEvent(Res.Sch_ElementValueDataType, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
internal void AddID(string name, object node) {
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
if (IDs == null) {
IDs = new Hashtable();
}
IDs.Add(name, node);
}
public override object FindId(string name) {
return IDs == null ? null : IDs[name];
}
public bool IsXSDRoot(string localName, string ns) {
return Ref.Equal(ns, NsXs) && Ref.Equal(localName, XsdSchema);
}
private void Push(XmlQualifiedName elementName) {
context = (ValidationState)validationStack.Push();
if (context == null) {
context = new ValidationState();
validationStack.AddToTop(context);
}
context.LocalName = elementName.Name;
context.Namespace = elementName.Namespace;
context.HasMatched = false;
context.IsNill = false;
context.ProcessContents = processContents;
context.NeedValidateChildren = false;
context.Constr = null; //resetting the constraints to be null incase context != null
// when pushing onto stack;
}
private void Pop() {
if (validationStack.Length > 1) {
validationStack.Pop();
if (startIDConstraint == validationStack.Length) {
startIDConstraint = -1;
}
context = (ValidationState)validationStack.Peek();
processContents = context.ProcessContents;
}
}
private void CheckForwardRefs() {
IdRefNode next = idRefListHead;
while (next != null) {
if(FindId(next.Id) == null) {
SendValidationEvent(new XmlSchemaException(Res.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos));
}
IdRefNode ptr = next.Next;
next.Next = null; // unhook each object so it is cleaned up by Garbage Collector
next = ptr;
}
// not needed any more.
idRefListHead = null;
}
private void ValidateStartElementIdentityConstraints() {
// added on June 15, set the context here, so the stack can have them
if (context.ElementDecl != null) {
if (context.ElementDecl.Constraints != null) {
AddIdentityConstraints();
}
//foreach constraint in stack (including the current one)
if (HasIdentityConstraints) {
ElementIdentityConstraints();
}
}
}
private bool HasIdentityConstraints {
get { return startIDConstraint != -1; }
}
private void AddIdentityConstraints() {
context.Constr = new ConstraintStruct[context.ElementDecl.Constraints.Length];
int id = 0;
for (int i = 0; i < context.ElementDecl.Constraints.Length; ++i) {
context.Constr[id++] = new ConstraintStruct (context.ElementDecl.Constraints[i]);
} // foreach constraint /constraintstruct
// added on June 19, make connections between new keyref tables with key/unique tables in stack
// i can't put it in the above loop, coz there will be key on the same level
for (int i = 0; i < context.Constr.Length; ++i) {
if ( context.Constr[i].constraint.Role == CompiledIdentityConstraint.ConstraintRole.Keyref ) {
bool find = false;
// go upwards checking or only in this level
for (int level = this.validationStack.Length - 1; level >= ((this.startIDConstraint >= 0) ? this.startIDConstraint : this.validationStack.Length - 1); level --) {
// no constraint for this level
if (((ValidationState)(this.validationStack[level])).Constr == null) {
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState) this.validationStack[level]).Constr;
for (int j = 0; j < constraints.Length; ++j) {
if (constraints[j].constraint.name == context.Constr[i].constraint.refer) {
find = true;
if (constraints[j].keyrefTable == null) {
constraints[j].keyrefTable = new Hashtable();
}
context.Constr[i].qualifiedTable = constraints[j].keyrefTable;
break;
}
}
if (find) {
break;
}
}
if (!find) {
// didn't find connections, throw exceptions
SendValidationEvent(Res.Sch_RefNotInScope, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
} // finished dealing with keyref
} // end foreach
// initial set
if (this.startIDConstraint == -1) {
this.startIDConstraint = this.validationStack.Length - 1;
}
}
private void ElementIdentityConstraints () {
for (int i = this.startIDConstraint; i < this.validationStack.Length; i ++) {
// no constraint for this level
if (((ValidationState)(this.validationStack[i])).Constr == null) {
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)this.validationStack[i]).Constr;
for (int j = 0; j < constraints.Length; ++j) {
// check selector from here
if (constraints[j].axisSelector.MoveToStartElement(reader.LocalName, reader.NamespaceURI)) {
// selector selects new node, activate a new set of fields
Debug.WriteLine("Selector Match!");
Debug.WriteLine("Name: " + reader.LocalName + "\t|\tURI: " + reader.NamespaceURI + "\n");
// in which axisFields got updated
constraints[j].axisSelector.PushKS(PositionInfo.LineNumber, PositionInfo.LinePosition);
}
// axisFields is not null, but may be empty
for (int k = 0; k < constraints[j].axisFields.Count; ++k) {
LocatedActiveAxis laxis = (LocatedActiveAxis)constraints[j].axisFields[k];
// check field from here
if (laxis.MoveToStartElement(reader.LocalName, reader.NamespaceURI)) {
Debug.WriteLine("Element Field Match!");
// checking simpleType / simpleContent
if (context.ElementDecl != null) { // nextElement can be null when xml/xsd are not valid
if (context.ElementDecl.Datatype == null) {
SendValidationEvent(Res.Sch_FieldSimpleTypeExpected, reader.LocalName);
}
else {
// can't fill value here, wait till later....
// fill type : xsdType
laxis.isMatched = true;
// since it's simpletyped element, the endchildren will come consequently... don't worry
}
}
}
}
}
}
}
// facilitate modifying
private void AttributeIdentityConstraints(string name, string ns, object obj, string sobj, SchemaAttDef attdef) {
for (int ci = this.startIDConstraint; ci < this.validationStack.Length; ci ++) {
// no constraint for this level
if (((ValidationState)(this.validationStack[ci])).Constr == null) {
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)this.validationStack[ci]).Constr;
for (int i = 0; i < constraints.Length; ++i) {
// axisFields is not null, but may be empty
for (int j = 0; j < constraints[i].axisFields.Count; ++j) {
LocatedActiveAxis laxis = (LocatedActiveAxis)constraints[i].axisFields[j];
// check field from here
if (laxis.MoveToAttribute(name, ns)) {
Debug.WriteLine("Attribute Field Match!");
//attribute is only simpletype, so needn't checking...
// can fill value here, yeah!!
Debug.WriteLine("Attribute Field Filling Value!");
Debug.WriteLine("Name: " + name + "\t|\tURI: " + ns + "\t|\tValue: " + obj + "\n");
if (laxis.Ks[laxis.Column] != null) {
// should be evaluated to either an empty node-set or a node-set with exactly one member
// two matches...
SendValidationEvent (Res.Sch_FieldSingleValueExpected, name);
}
else if ((attdef != null) && (attdef.Datatype != null)){
laxis.Ks[laxis.Column] = new TypedObject (obj, sobj, attdef.Datatype);
}
}
}
}
}
}
private object UnWrapUnion(object typedValue) {
XsdSimpleValue simpleValue = typedValue as XsdSimpleValue;
if (simpleValue != null) {
typedValue = simpleValue.TypedValue;
}
return typedValue;
}
private void EndElementIdentityConstraints() {
for (int ci = this.validationStack.Length - 1; ci >= this.startIDConstraint; ci --) {
// no constraint for this level
if (((ValidationState)(this.validationStack[ci])).Constr == null) {
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)this.validationStack[ci]).Constr;
for (int i = 0; i < constraints.Length; ++i) {
// EndChildren
// axisFields is not null, but may be empty
for (int j = 0; j < constraints[i].axisFields.Count; ++j) {
LocatedActiveAxis laxis = (LocatedActiveAxis)constraints[i].axisFields[j];
// check field from here
// isMatched is false when nextElement is null. so needn't change this part.
if (laxis.isMatched) {
Debug.WriteLine("Element Field Filling Value!");
Debug.WriteLine("Name: " + reader.LocalName + "\t|\tURI: " + reader.NamespaceURI + "\t|\tValue: " + reader.TypedValueObject + "\n");
// fill value
laxis.isMatched = false;
if (laxis.Ks[laxis.Column] != null) {
// [field...] should be evaluated to either an empty node-set or a node-set with exactly one member
// two matches... already existing field value in the table.
SendValidationEvent (Res.Sch_FieldSingleValueExpected, reader.LocalName);
}
else {
// for element, reader.Value = "";
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
if(reader.TypedValueObject != null && stringValue.Length != 0) {
laxis.Ks[laxis.Column] = new TypedObject(reader.TypedValueObject,stringValue,context.ElementDecl.Datatype);
}
}
}
// EndChildren
laxis.EndElement(reader.LocalName, reader.NamespaceURI);
}
if (constraints[i].axisSelector.EndElement(reader.LocalName, reader.NamespaceURI)) {
// insert key sequence into hash (+ located active axis tuple leave for later)
KeySequence ks = constraints[i].axisSelector.PopKS();
// unqualified keysequence are not allowed
switch (constraints[i].constraint.Role) {
case CompiledIdentityConstraint.ConstraintRole.Key:
if (! ks.IsQualified()) {
//Key's fields can't be null... if we can return context node's line info maybe it will be better
//only keymissing & keyduplicate reporting cases are necessary to be dealt with... 3 places...
SendValidationEvent(new XmlSchemaException(Res.Sch_MissingKey, constraints[i].constraint.name.ToString(), reader.BaseURI, ks.PosLine, ks.PosCol));
}
else if (constraints[i].qualifiedTable.Contains (ks)) {
// unique or key checking value confliction
// for redundant key, reporting both occurings
// doesn't work... how can i retrieve value out??
SendValidationEvent(new XmlSchemaException(Res.Sch_DuplicateKey,
new string[2] {ks.ToString(), constraints[i].constraint.name.ToString()},
reader.BaseURI, ks.PosLine, ks.PosCol));
}
else {
constraints[i].qualifiedTable.Add (ks, ks);
}
break;
case CompiledIdentityConstraint.ConstraintRole.Unique:
if (! ks.IsQualified()) {
continue;
}
if (constraints[i].qualifiedTable.Contains (ks)) {
// unique or key checking confliction
SendValidationEvent(new XmlSchemaException(Res.Sch_DuplicateKey,
new string[2] {ks.ToString(), constraints[i].constraint.name.ToString()},
reader.BaseURI, ks.PosLine, ks.PosCol));
}
else {
constraints[i].qualifiedTable.Add (ks, ks);
}
break;
case CompiledIdentityConstraint.ConstraintRole.Keyref:
// is there any possibility:
// 2 keyrefs: value is equal, type is not
// both put in the hashtable, 1 reference, 1 not
if (constraints[i].qualifiedTable != null) { //Will be null in cases when the keyref is outside the scope of the key, that is not allowed by our impl
if (! ks.IsQualified() || constraints[i].qualifiedTable.Contains (ks)) {
continue;
}
constraints[i].qualifiedTable.Add (ks, ks);
}
break;
}
}
}
}
// current level's constraint struct
ConstraintStruct[] vcs = ((ValidationState)(this.validationStack[this.validationStack.Length - 1])).Constr;
if ( vcs != null) {
// validating all referencing tables...
for (int i = 0; i < vcs.Length; ++i) {
if (( vcs[i].constraint.Role == CompiledIdentityConstraint.ConstraintRole.Keyref)
|| (vcs[i].keyrefTable == null)) {
continue;
}
foreach (KeySequence ks in vcs[i].keyrefTable.Keys) {
if (! vcs[i].qualifiedTable.Contains (ks)) {
SendValidationEvent(new XmlSchemaException(Res.Sch_UnresolvedKeyref, new string[2] { ks.ToString(), vcs[i].constraint.name.ToString() },
reader.BaseURI, ks.PosLine, ks.PosCol));
}
}
}
}
}
}
#pragma warning restore 618
}
| |
/*
* 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.Diagnostics;
using System.IO;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("generics")]
public class SerializationTests : ThinClientRegionSteps
{
private const int OTHER_TYPE1 = 1;
private const int OTHER_TYPE2 = 2;
private const int OTHER_TYPE22 = 3;
private const int OTHER_TYPE4 = 4;
private const int OTHER_TYPE42 = 5;
private const int OTHER_TYPE43 = 6;
private UnitProcess sender, receiver;
protected override ClientBase[] GetClients()
{
sender = new UnitProcess();
receiver = new UnitProcess();
return new ClientBase[] { sender, receiver };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
sender.Call(DestroyRegions);
receiver.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
private IGeodeSerializable CreateOtherType(int i, int otherType)
{
IGeodeSerializable ot;
switch (otherType)
{
case OTHER_TYPE1: ot = new OtherType(i, i + 20000); break;
case OTHER_TYPE2: ot = new OtherType2(i, i + 20000); break;
case OTHER_TYPE22: ot = new OtherType22(i, i + 20000); break;
case OTHER_TYPE4: ot = new OtherType4(i, i + 20000); break;
case OTHER_TYPE42: ot = new OtherType42(i, i + 20000); break;
case OTHER_TYPE43: ot = new OtherType43(i, i + 20000); break;
default: ot = new OtherType(i, i + 20000); break;
}
return ot;
}
#region Functions that are invoked by the tests
public void CreateRegionForOT(string locators)
{
CacheHelper.CreateTCRegion2<object, object>(RegionNames[0], true, false,
null, locators, false);
Serializable.RegisterTypeGeneric(OtherType.CreateDeserializable);
Serializable.RegisterTypeGeneric(OtherType2.CreateDeserializable);
Serializable.RegisterTypeGeneric(OtherType22.CreateDeserializable);
Serializable.RegisterTypeGeneric(OtherType4.CreateDeserializable);
Serializable.RegisterTypeGeneric(OtherType42.CreateDeserializable);
Serializable.RegisterTypeGeneric(OtherType43.CreateDeserializable);
}
public void DoNPuts(int n)
{
try
{
Serializable.RegisterTypeGeneric(OtherType.CreateDeserializable);
Assert.Fail("Expected exception in registering the type again.");
}
catch (IllegalStateException ex)
{
Util.Log("Got expected exception in RegisterType: {0}", ex);
}
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]);
for (int i = 0; i < n; i++)
{
//CacheableInt32 key = new CacheableInt32(i);
//region.Put(key, key);
int key = i;
region[key] = key;
}
}
public void DoValidates(int n)
{
try
{
Serializable.RegisterTypeGeneric(OtherType.CreateDeserializable);
Assert.Fail("Expected exception in registering the type again.");
}
catch (IllegalStateException ex)
{
Util.Log("Got expected exception in RegisterType: {0}", ex);
}
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]);
for (int i = 0; i < n; i++)
{
//CacheableInt32 val = region.Get(i) as CacheableInt32;
object val = region[i];
Assert.AreEqual(i, val, "Found unexpected value");
}
}
public void DoNPutsOtherType(int n, int otherType)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]);
for (int i = 0; i < n; i++)
{
IGeodeSerializable ot = CreateOtherType(i, otherType);
region[i + 10] = ot;
}
}
public void DoValidateNPutsOtherType(int n, int otherType)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(RegionNames[0]);
for (int i = 0; i < n; i++)
{
object val = region[i + 10];
IGeodeSerializable ot = CreateOtherType(i, otherType);
Assert.IsTrue(ot.Equals(val), "Found unexpected value");
}
}
#endregion
#region Tests
[Test]
public void CustomTypes()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator 1 started.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
sender.Call(CreateRegionForOT, CacheHelper.Locators);
Util.Log("StepOne complete.");
receiver.Call(CreateRegionForOT, CacheHelper.Locators);
Util.Log("StepTwo complete.");
sender.Call(DoNPuts, 10);
receiver.Call(DoValidates, 10);
Util.Log("StepThree complete.");
sender.Call(DoNPutsOtherType, 10, OTHER_TYPE1);
receiver.Call(DoValidateNPutsOtherType, 10, OTHER_TYPE1);
Util.Log("StepFour complete.");
sender.Call(DoNPutsOtherType, 10, OTHER_TYPE2);
receiver.Call(DoValidateNPutsOtherType, 10, OTHER_TYPE2);
Util.Log("StepFive complete.");
sender.Call(DoNPutsOtherType, 10, OTHER_TYPE22);
receiver.Call(DoValidateNPutsOtherType, 10, OTHER_TYPE22);
Util.Log("StepSix complete.");
sender.Call(DoNPutsOtherType, 10, OTHER_TYPE4);
receiver.Call(DoValidateNPutsOtherType, 10, OTHER_TYPE4);
Util.Log("StepSeven complete.");
sender.Call(DoNPutsOtherType, 10, OTHER_TYPE42);
receiver.Call(DoValidateNPutsOtherType, 10, OTHER_TYPE42);
Util.Log("StepEight complete.");
sender.Call(DoNPutsOtherType, 10, OTHER_TYPE43);
receiver.Call(DoValidateNPutsOtherType, 10, OTHER_TYPE43);
Util.Log("StepNine complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
}
#endregion
}
[Serializable]
public struct CData
{
#region Private members
private Int32 m_first;
private Int64 m_second;
#endregion
#region Public accessors
public Int32 First
{
get
{
return m_first;
}
set
{
m_first = value;
}
}
public Int64 Second
{
get
{
return m_second;
}
set
{
m_second = value;
}
}
#endregion
public CData(Int32 first, Int64 second)
{
m_first = first;
m_second = second;
}
public static bool operator ==(CData obj1, CData obj2)
{
return ((obj1.m_first == obj2.m_first) && (obj1.m_second == obj2.m_second));
}
public static bool operator !=(CData obj1, CData obj2)
{
return ((obj1.m_first != obj2.m_first) || (obj1.m_second != obj2.m_second));
}
public override bool Equals(object obj)
{
if (obj is CData)
{
CData otherObj = (CData)obj;
return ((m_first == otherObj.m_first) && (m_second == otherObj.m_second));
}
return false;
}
public override int GetHashCode()
{
return m_first.GetHashCode() ^ m_second.GetHashCode();
}
};
public class PdxCData : IPdxSerializable
{
#region Private members
private Int32 m_first;
private Int64 m_second;
#endregion
#region Public accessors
public Int32 First
{
get
{
return m_first;
}
set
{
m_first = value;
}
}
public Int64 Second
{
get
{
return m_second;
}
set
{
m_second = value;
}
}
#endregion
public PdxCData(Int32 first, Int64 second)
{
m_first = first;
m_second = second;
}
public PdxCData() { }
public static PdxCData CreateDeserializable()
{
return new PdxCData();
}
public static bool operator ==(PdxCData obj1, PdxCData obj2)
{
return ((obj1.m_first == obj2.m_first) && (obj1.m_second == obj2.m_second));
}
public static bool operator !=(PdxCData obj1, PdxCData obj2)
{
return ((obj1.m_first != obj2.m_first) || (obj1.m_second != obj2.m_second));
}
public override bool Equals(object obj)
{
if (obj is PdxCData)
{
PdxCData otherObj = (PdxCData)obj;
return ((m_first == otherObj.m_first) && (m_second == otherObj.m_second));
}
return false;
}
public override int GetHashCode()
{
return m_first.GetHashCode();
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_first = reader.ReadInt("m_first");
m_second = reader.ReadLong("m_second");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("m_first", m_first);
writer.MarkIdentityField("m_first");
writer.WriteLong("m_second", m_second);
}
#endregion
};
public class OtherType : IGeodeSerializable
{
private CData m_struct;
private ExceptionType m_exType;
public enum ExceptionType
{
None,
Geode,
System,
// below are with inner exceptions
GeodeGeode,
GeodeSystem,
SystemGeode,
SystemSystem
}
public OtherType()
{
m_exType = ExceptionType.None;
}
public OtherType(Int32 first, Int64 second)
: this(first, second, ExceptionType.None)
{
}
public OtherType(Int32 first, Int64 second, ExceptionType exType)
{
m_struct.First = first;
m_struct.Second = second;
m_exType = exType;
}
public CData Data
{
get
{
return m_struct;
}
}
public static IGeodeSerializable Duplicate(IGeodeSerializable orig)
{
DataOutput dout = new DataOutput();
orig.ToData(dout);
DataInput din = new DataInput(dout.GetBuffer());
IGeodeSerializable dup = (IGeodeSerializable)din.ReadObject();
return dup;
}
#region IGeodeSerializable Members
public IGeodeSerializable FromData(DataInput input)
{
m_struct.First = input.ReadInt32();
m_struct.Second = input.ReadInt64();
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_struct.First);
output.WriteInt64(m_struct.Second);
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
}
public UInt32 ObjectSize
{
get
{
return (UInt32)(sizeof(Int32) + sizeof(Int64));
}
}
public UInt32 ClassId
{
get
{
return 0x0;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new OtherType();
}
public override int GetHashCode()
{
return m_struct.First.GetHashCode() ^ m_struct.Second.GetHashCode();
}
public override bool Equals(object obj)
{
OtherType ot = obj as OtherType;
if (ot != null)
{
return (m_struct.Equals(ot.m_struct));
}
return false;
}
}
public class OtherType2 : IGeodeSerializable
{
private CData m_struct;
private ExceptionType m_exType;
public enum ExceptionType
{
None,
Geode,
System,
// below are with inner exceptions
GeodeGeode,
GeodeSystem,
SystemGeode,
SystemSystem
}
public OtherType2()
{
m_exType = ExceptionType.None;
}
public OtherType2(Int32 first, Int64 second)
: this(first, second, ExceptionType.None)
{
}
public OtherType2(Int32 first, Int64 second, ExceptionType exType)
{
m_struct.First = first;
m_struct.Second = second;
m_exType = exType;
}
public CData Data
{
get
{
return m_struct;
}
}
public static IGeodeSerializable Duplicate(IGeodeSerializable orig)
{
DataOutput dout = new DataOutput();
orig.ToData(dout);
DataInput din = new DataInput(dout.GetBuffer());
IGeodeSerializable dup = (IGeodeSerializable)din.ReadObject();
return dup;
}
#region IGeodeSerializable Members
public IGeodeSerializable FromData(DataInput input)
{
m_struct.First = input.ReadInt32();
m_struct.Second = input.ReadInt64();
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_struct.First);
output.WriteInt64(m_struct.Second);
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
}
public UInt32 ObjectSize
{
get
{
return (UInt32)(sizeof(Int32) + sizeof(Int64));
}
}
public UInt32 ClassId
{
get
{
return 0x8C;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new OtherType2();
}
public override int GetHashCode()
{
return m_struct.First.GetHashCode() ^ m_struct.Second.GetHashCode();
}
public override bool Equals(object obj)
{
OtherType2 ot = obj as OtherType2;
if (ot != null)
{
return (m_struct.Equals(ot.m_struct));
}
return false;
}
}
public class OtherType22 : IGeodeSerializable
{
private CData m_struct;
private ExceptionType m_exType;
public enum ExceptionType
{
None,
Geode,
System,
// below are with inner exceptions
GeodeGeode,
GeodeSystem,
SystemGeode,
SystemSystem
}
public OtherType22()
{
m_exType = ExceptionType.None;
}
public OtherType22(Int32 first, Int64 second)
: this(first, second, ExceptionType.None)
{
}
public OtherType22(Int32 first, Int64 second, ExceptionType exType)
{
m_struct.First = first;
m_struct.Second = second;
m_exType = exType;
}
public CData Data
{
get
{
return m_struct;
}
}
public static IGeodeSerializable Duplicate(IGeodeSerializable orig)
{
DataOutput dout = new DataOutput();
orig.ToData(dout);
DataInput din = new DataInput(dout.GetBuffer());
IGeodeSerializable dup = (IGeodeSerializable)din.ReadObject();
return dup;
}
#region IGeodeSerializable Members
public IGeodeSerializable FromData(DataInput input)
{
m_struct.First = input.ReadInt32();
m_struct.Second = input.ReadInt64();
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_struct.First);
output.WriteInt64(m_struct.Second);
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
}
public UInt32 ObjectSize
{
get
{
return (UInt32)(sizeof(Int32) + sizeof(Int64));
}
}
public UInt32 ClassId
{
get
{
return 0x8C0;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new OtherType22();
}
public override int GetHashCode()
{
return m_struct.First.GetHashCode() ^ m_struct.Second.GetHashCode();
}
public override bool Equals(object obj)
{
OtherType22 ot = obj as OtherType22;
if (ot != null)
{
return (m_struct.Equals(ot.m_struct));
}
return false;
}
}
public class OtherType4 : IGeodeSerializable
{
private CData m_struct;
private ExceptionType m_exType;
public enum ExceptionType
{
None,
Geode,
System,
// below are with inner exceptions
GeodeGeode,
GeodeSystem,
SystemGeode,
SystemSystem
}
public OtherType4()
{
m_exType = ExceptionType.None;
}
public OtherType4(Int32 first, Int64 second)
: this(first, second, ExceptionType.None)
{
}
public OtherType4(Int32 first, Int64 second, ExceptionType exType)
{
m_struct.First = first;
m_struct.Second = second;
m_exType = exType;
}
public CData Data
{
get
{
return m_struct;
}
}
public static IGeodeSerializable Duplicate(IGeodeSerializable orig)
{
DataOutput dout = new DataOutput();
orig.ToData(dout);
DataInput din = new DataInput(dout.GetBuffer());
IGeodeSerializable dup = (IGeodeSerializable)din.ReadObject();
return dup;
}
#region IGeodeSerializable Members
public IGeodeSerializable FromData(DataInput input)
{
m_struct.First = input.ReadInt32();
m_struct.Second = input.ReadInt64();
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_struct.First);
output.WriteInt64(m_struct.Second);
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
}
public UInt32 ObjectSize
{
get
{
return (UInt32)(sizeof(Int32) + sizeof(Int64));
}
}
public UInt32 ClassId
{
get
{
return 0x8FC0;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new OtherType4();
}
public override int GetHashCode()
{
return m_struct.First.GetHashCode() ^ m_struct.Second.GetHashCode();
}
public override bool Equals(object obj)
{
OtherType4 ot = obj as OtherType4;
if (ot != null)
{
return (m_struct.Equals(ot.m_struct));
}
return false;
}
}
public class OtherType42 : IGeodeSerializable
{
private CData m_struct;
private ExceptionType m_exType;
public enum ExceptionType
{
None,
Geode,
System,
// below are with inner exceptions
GeodeGeode,
GeodeSystem,
SystemGeode,
SystemSystem
}
public OtherType42()
{
m_exType = ExceptionType.None;
}
public OtherType42(Int32 first, Int64 second)
: this(first, second, ExceptionType.None)
{
}
public OtherType42(Int32 first, Int64 second, ExceptionType exType)
{
m_struct.First = first;
m_struct.Second = second;
m_exType = exType;
}
public CData Data
{
get
{
return m_struct;
}
}
public static IGeodeSerializable Duplicate(IGeodeSerializable orig)
{
DataOutput dout = new DataOutput();
orig.ToData(dout);
DataInput din = new DataInput(dout.GetBuffer());
IGeodeSerializable dup = (IGeodeSerializable)din.ReadObject();
return dup;
}
#region IGeodeSerializable Members
public IGeodeSerializable FromData(DataInput input)
{
m_struct.First = input.ReadInt32();
m_struct.Second = input.ReadInt64();
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_struct.First);
output.WriteInt64(m_struct.Second);
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
}
public UInt32 ObjectSize
{
get
{
return (UInt32)(sizeof(Int32) + sizeof(Int64));
}
}
public UInt32 ClassId
{
get
{
return 0x6F3F97;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new OtherType42();
}
public override int GetHashCode()
{
return m_struct.First.GetHashCode() ^ m_struct.Second.GetHashCode();
}
public override bool Equals(object obj)
{
OtherType42 ot = obj as OtherType42;
if (ot != null)
{
return (m_struct.Equals(ot.m_struct));
}
return false;
}
}
public class OtherType43 : IGeodeSerializable
{
private CData m_struct;
private ExceptionType m_exType;
public enum ExceptionType
{
None,
Geode,
System,
// below are with inner exceptions
GeodeGeode,
GeodeSystem,
SystemGeode,
SystemSystem
}
public OtherType43()
{
m_exType = ExceptionType.None;
}
public OtherType43(Int32 first, Int64 second)
: this(first, second, ExceptionType.None)
{
}
public OtherType43(Int32 first, Int64 second, ExceptionType exType)
{
m_struct.First = first;
m_struct.Second = second;
m_exType = exType;
}
public CData Data
{
get
{
return m_struct;
}
}
public static IGeodeSerializable Duplicate(IGeodeSerializable orig)
{
DataOutput dout = new DataOutput();
orig.ToData(dout);
DataInput din = new DataInput(dout.GetBuffer());
IGeodeSerializable dup = (IGeodeSerializable)din.ReadObject();
return dup;
}
#region IGeodeSerializable Members
public IGeodeSerializable FromData(DataInput input)
{
m_struct.First = input.ReadInt32();
m_struct.Second = input.ReadInt64();
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
return this;
}
public void ToData(DataOutput output)
{
output.WriteInt32(m_struct.First);
output.WriteInt64(m_struct.Second);
switch (m_exType)
{
case ExceptionType.None:
break;
case ExceptionType.Geode:
throw new GeodeIOException("Throwing an exception");
case ExceptionType.System:
throw new IOException("Throwing an exception");
case ExceptionType.GeodeGeode:
throw new GeodeIOException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.GeodeSystem:
throw new CacheServerException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
case ExceptionType.SystemGeode:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new CacheServerException("This is an inner exception"));
case ExceptionType.SystemSystem:
throw new ApplicationException("Throwing an exception with inner " +
"exception", new IOException("This is an inner exception"));
}
}
public UInt32 ObjectSize
{
get
{
return (UInt32)(sizeof(Int32) + sizeof(Int64));
}
}
public UInt32 ClassId
{
get
{
return 0x7FFFFFFF;
}
}
#endregion
public static IGeodeSerializable CreateDeserializable()
{
return new OtherType43();
}
public override int GetHashCode()
{
return m_struct.First.GetHashCode() ^ m_struct.Second.GetHashCode();
}
public override bool Equals(object obj)
{
OtherType43 ot = obj as OtherType43;
if (ot != null)
{
return (m_struct.Equals(ot.m_struct));
}
return false;
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace RootMotion.FinalIK {
/// <summary>
/// Using a spherical polygon to limit the range of rotation on universal and ball-and-socket joints. A reach cone is specified as a spherical polygon
/// on the surface of a a reach sphere that defines all positions the longitudinal segment axis beyond the joint can take.
///
/// This class is based on the "Fast and Easy Reach-Cone Joint Limits" paper by Jane Wilhelms and Allen Van Gelder.
/// Computer Science Dept., University of California, Santa Cruz, CA 95064. August 2, 2001
/// http://users.soe.ucsc.edu/~avg/Papers/jtl.pdf
///
/// </summary>
[AddComponentMenu("Scripts/RootMotion.FinalIK/Rotation Limits/Rotation Limit Polygonal")]
public class RotationLimitPolygonal : RotationLimit {
#region Main Interface
/// <summary>
/// Limit of twist rotation around the main axis.
/// </summary>
[Range(0f, 180f)] public float twistLimit = 180;
/// <summary>
/// The number of smoothing iterations applied to the polygon.
/// </summary>
[Range(0, 3)] public int smoothIterations = 0;
/// <summary>
/// Sets the limit points and recalculates the reach cones.
/// </summary>
/// <param name='_points'>
/// _points.
/// </param>
public void SetLimitPoints(LimitPoint[] points) {
if (points.Length < 3) {
LogWarning("The polygon must have at least 3 Limit Points.");
return;
}
this.points = points;
BuildReachCones();
}
#endregion Main Interface
/*
* Limits the rotation in the local space of this instance's Transform.
* */
protected override Quaternion LimitRotation(Quaternion rotation) {
if (reachCones.Length == 0) Start();
// Subtracting off-limits swing
Quaternion swing = LimitSwing(rotation);
// Apply twist limits
return LimitTwist(swing, axis, secondaryAxis, twistLimit);
}
/*
* Tetrahedron composed of 2 Limit points, the origin and an axis point.
* */
[System.Serializable]
public class ReachCone {
public Vector3[] tetrahedron;
public float volume;
public Vector3 S, B;
public Vector3 o { get { return tetrahedron[0]; }}
public Vector3 a { get { return tetrahedron[1]; }}
public Vector3 b { get { return tetrahedron[2]; }}
public Vector3 c { get { return tetrahedron[3]; }}
public ReachCone(Vector3 _o, Vector3 _a, Vector3 _b, Vector3 _c) {
this.tetrahedron = new Vector3[4];
this.tetrahedron[0] = _o; // Origin
this.tetrahedron[1] = _a; // Axis
this.tetrahedron[2] = _b; // Limit Point 1
this.tetrahedron[3] = _c; // Limit Point 2
this.volume = 0;
this.S = Vector3.zero;
this.B = Vector3.zero;
}
public bool isValid { get { return volume > 0; }}
public void Calculate() {
Vector3 crossAB = Vector3.Cross(a, b);
volume = Vector3.Dot(crossAB, c) / 6.0f;
S = Vector3.Cross(a, b).normalized;
B = Vector3.Cross(b, c).normalized;
}
}
/*
* The points defining the polygon
* */
[System.Serializable]
public class LimitPoint {
public Vector3 point;
public float tangentWeight;
public LimitPoint() {
this.point = Vector3.forward;
this.tangentWeight = 1;
}
}
[SerializeField][HideInInspector] public LimitPoint[] points;
[SerializeField][HideInInspector] public Vector3[] P;
[SerializeField][HideInInspector] public ReachCone[] reachCones = new ReachCone[0];
void Start() {
if (points.Length < 3) ResetToDefault();
// Check if Limit Points are valid
for (int i = 0; i < reachCones.Length; i++) {
if (!reachCones[i].isValid) {
if (smoothIterations <= 0) {
int nextPoint = 0;
if (i < reachCones.Length - 1) nextPoint = i + 1;
else nextPoint = 0;
LogWarning("Reach Cone {point " + i + ", point " + nextPoint + ", Origin} has negative volume. Make sure Axis vector is in the reachable area and the polygon is convex.");
} else LogWarning("One of the Reach Cones in the polygon has negative volume. Make sure Axis vector is in the reachable area and the polygon is convex.");
}
}
axis = axis.normalized;
}
#region Precalculations
/*
* Apply the default initial setup of 4 Limit Points
* */
public void ResetToDefault() {
points = new LimitPoint[4];
for (int i = 0; i < points.Length; i++) points[i] = new LimitPoint();
Quaternion swing1Rotation = Quaternion.AngleAxis(45, Vector3.right);
Quaternion swing2Rotation = Quaternion.AngleAxis(45, Vector3.up);
points[0].point = (swing1Rotation * swing2Rotation) * axis;
points[1].point = (Quaternion.Inverse(swing1Rotation) * swing2Rotation) * axis;
points[2].point = (Quaternion.Inverse(swing1Rotation) * Quaternion.Inverse(swing2Rotation)) * axis;
points[3].point = (swing1Rotation * Quaternion.Inverse(swing2Rotation)) * axis;
BuildReachCones();
}
/*
* Recalculate reach cones if the Limit Points have changed
* */
public void BuildReachCones() {
smoothIterations = Mathf.Clamp(smoothIterations, 0, 3);
// Make another array for the points so that they could be smoothed without changing the initial points
P = new Vector3[points.Length];
for (int i = 0; i < points.Length; i++) P[i] = points[i].point.normalized;
for (int i = 0; i < smoothIterations; i++) P = SmoothPoints();
// Calculating the reach cones
reachCones = new ReachCone[P.Length];
for (int i = 0; i < reachCones.Length - 1; i++) {
reachCones[i] = new ReachCone(Vector3.zero, axis.normalized, P[i], P[i + 1]);
}
reachCones[P.Length - 1] = new ReachCone(Vector3.zero, axis.normalized, P[P.Length - 1], P[0]);
for (int i = 0; i < reachCones.Length; i++) reachCones[i].Calculate();
}
/*
* Automatically adds virtual limit points to smooth the polygon
* */
private Vector3[] SmoothPoints() {
// Create the new point array with double length
Vector3[] Q = new Vector3[P.Length * 2];
float scalar = GetScalar(P.Length); // Get the constant used for interpolation
// Project all the existing points on a plane that is tangent to the unit sphere at the Axis point
for (int i = 0; i < Q.Length; i+= 2) Q[i] = PointToTangentPlane(P[i / 2], 1);
// Interpolate the new points
for (int i = 1; i < Q.Length; i+= 2) {
Vector3 minus2 = Vector3.zero;
Vector3 plus1 = Vector3.zero;
Vector3 plus2 = Vector3.zero;
if (i > 1 && i < Q.Length - 2) {
minus2 = Q[i - 2];
plus2 = Q[i + 1];
} else if (i == 1) {
minus2 = Q[Q.Length - 2];
plus2 = Q[i + 1];
} else if (i == Q.Length - 1) {
minus2 = Q[i - 2];
plus2 = Q[0];
}
if (i < Q.Length - 1) plus1 = Q[i + 1];
else plus1 = Q[0];
int t = Q.Length / points.Length;
// Interpolation
Q[i] = (0.5f * (Q[i - 1] + plus1)) + (scalar * points[i / t].tangentWeight * (plus1 - minus2)) + (scalar * points[i / t].tangentWeight * (Q[i - 1] - plus2));
}
// Project the points from tangent plane to the sphere
for (int i = 0; i < Q.Length; i++) Q[i] = TangentPointToSphere(Q[i], 1);
return Q;
}
/*
* Returns scalar values used for interpolating smooth positions between limit points
* */
private float GetScalar(int k) {
// Values k (number of points) == 3, 4 and 6 are calculated by analytical geometry, values 5 and 7 were estimated by interpolation
if (k <= 3) return .1667f;
if (k == 4) return .1036f;
if (k == 5) return .0850f;
if (k == 6) return .0773f;
if (k == 7) return .0700f;
return .0625f; // Cubic spline fit
}
/*
* Project a point on the sphere to a plane that is tangent to the unit sphere at the Axis point
* */
private Vector3 PointToTangentPlane(Vector3 p, float r) {
float d = Vector3.Dot(axis, p);
float u = (2 * r * r) / ((r * r) + d);
return (u * p) + ((1 - u) * -axis);
}
/*
* Project a point on the tangent plane to the sphere
* */
private Vector3 TangentPointToSphere(Vector3 q, float r) {
float d = Vector3.Dot(q - axis, q - axis);
float u = (4 * r * r) / ((4 * r * r) + d);
return (u * q) + ((1 - u) * -axis);
}
#endregion Precalculations
#region Runtime calculations
/*
* Applies Swing limit to the rotation
* */
private Quaternion LimitSwing(Quaternion rotation) {
if (rotation == Quaternion.identity) return rotation; // Assuming initial rotation is in the reachable area
Vector3 L = rotation * axis; // Test this vector against the reach cones
int r = GetReachCone(L); // Get the reach cone to test against (can be only 1)
// Just in case we are running our application with invalid reach cones
if (r == -1) {
if (!Warning.logged) LogWarning("RotationLimitPolygonal reach cones are invalid.");
return rotation;
}
// Dot product of cone normal and rotated axis
float v = Vector3.Dot(reachCones[r].B, L);
if (v > 0) return rotation; // Rotation is reachable
// Find normal for a plane defined by origin, axis, and rotated axis
Vector3 rotationNormal = Vector3.Cross(axis, L);
// Find the line where this plane intersects with the reach cone plane
L = Vector3.Cross(-reachCones[r].B, rotationNormal);
// Rotation from current(illegal) swing rotation to the limited(legal) swing rotation
Quaternion toLimits = Quaternion.FromToRotation(rotation * axis, L);
// Subtract the illegal rotation
return toLimits * rotation;
}
/*
* Finding the reach cone to test against
* */
private int GetReachCone(Vector3 L) {
float p = 0;
float p1 = Vector3.Dot(reachCones[0].S, L);
for (int i = 0; i < reachCones.Length; i++) {
p = p1;
if (i < reachCones.Length - 1) p1 = Vector3.Dot(reachCones[i + 1].S, L);
else p1 = Vector3.Dot(reachCones[0].S, L);
if (p >= 0 && p1 < 0) return i;
}
return -1;
}
#endregion Runtime calculations
// Open the User Manual URL
[ContextMenu("User Manual")]
private void OpenUserManual() {
Application.OpenURL("http://www.root-motion.com/finalikdox/html/page12.html");
}
// Open the Script Reference URL
[ContextMenu("Scrpt Reference")]
private void OpenScriptReference() {
Application.OpenURL("http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_final_i_k_1_1_rotation_limit_polygonal.html");
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using OpenNETCF.IO.Ports;
namespace OpenNETCF.IO.Ports.Streams
{
public class WinStream : Stream, ISerialStreamCtrl
{
internal OpenNETCF.IO.Serial.Port _port;
public class Consts
{
public const int Win32Err_ERROR_INSUFFICIENT_BUFFER = 122;
public const uint PortEnum_InitBufSize = 8 * 1024;
public const uint PortEnum_MaxBufSize = 100 * 1024;
}
#region Construction and Disposing
internal WinStream(
int baudRate,
int dataBits,
bool discardNull,
bool dtrEnable,
Handshake handshake,
Parity parity,
byte parityReplace,
string portName,
int readBufferSize,
int readTimeout,
int receivedBytesThreshold,
bool rtsEnable,
StopBits stopBits,
int writeBufferSize,
int writeTimeout )
{
_port = new OpenNETCF.IO.Serial.Port( portName, readBufferSize, writeBufferSize );
BaudRate = baudRate;
DataBits = dataBits;
DiscardNull = discardNull;
DtrEnable = dtrEnable;
Handshake = handshake;
Parity = parity;
ParityReplace = parityReplace;
// TODO: ReadTimeout = readTimeout;
ReceivedBytesThreshold = receivedBytesThreshold;
RtsEnable = rtsEnable;
StopBits = stopBits;
// TODO: WriteTimeout = writeTimeout;
_port.DataReceived += new OpenNETCF.IO.Serial.Port.CommEvent(_port_DataReceived);
_port.OnError += new OpenNETCF.IO.Serial.Port.CommErrorEvent(_port_OnError);
_port.RingChange += new OpenNETCF.IO.Serial.Port.CommChangeEvent(_port_RingChange);
_port.RLSDChange += new OpenNETCF.IO.Serial.Port.CommChangeEvent(_port_RLSDChange);
if( !_port.Open() )
throw new UnauthorizedAccessException();
}
protected void AssertOpenPort()
{
if( !_port.IsOpen )
throw new InvalidOperationException("Serial Port is not open");
}
protected bool GetCommStatusFlag( OpenNETCF.IO.Serial.CommModemStatusFlags statusFlag )
{
AssertOpenPort();
uint modemStatus = 0;
_port.m_CommAPI.GetCommModemStatus( _port.hPort, ref modemStatus );
return ( (uint)statusFlag & modemStatus ) != 0;
}
public void Dispose()
{
_port.Dispose();
}
#endregion
#region Stream Implementation
public override bool CanRead { get { return _port.IsOpen; }}
public override bool CanWrite { get { return _port.IsOpen; }}
public override bool CanSeek { get { return false; }}
public override long Length { get { throw new NotSupportedException(); }}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override void Close()
{
base.Close ();
Dispose();
}
public override void Flush()
{
AssertOpenPort();
if( _port.OutBufferCount > 0 )
{
int oldSThreshold = _port.SThreshold;
_port.SThreshold = -1; // force even empty buffer to be written out
_port.Output = new byte[0];
_port.SThreshold = oldSThreshold;
}
// Flush OS buffer
if( !_port.m_CommAPI.FlushFileBuffers(_port.hPort) )
throw new InvalidOperationException( string.Format( "Error flushing buffer: {0}", Marshal.GetLastWin32Error() ));
}
public override int Read( byte[] buffer, int offset, int count )
{
AssertOpenPort();
if( buffer == null )
throw new ArgumentException( "null", "buffer" );
if( offset < 0 )
throw new ArgumentException( "<0", "offset" );
if( count < 0 )
throw new ArgumentException( "<0", "count" );
else if( count == 0 )
return 0;
//
// modified from original Port.Input
//
// lock the rx FIFO while reading
_port.rxBufferBusy.WaitOne();
// how much data are we *actually* going to return from the call?
int dequeueLength = (count < _port.rxFIFO.Count) ? count : _port.rxFIFO.Count;
// dequeue the data
for(int p = offset ; p < offset + dequeueLength ; p++)
buffer[p] = (byte)_port.rxFIFO.Dequeue();
// release the mutex so the Rx thread can continue
_port.rxBufferBusy.ReleaseMutex();
return dequeueLength;
}
public override long Seek( long offset, SeekOrigin origin )
{
throw new NotSupportedException();
}
public override void SetLength( long value )
{
throw new NotSupportedException();
}
public override void Write( byte[] buffer, int offset, int count )
{
AssertOpenPort();
if( buffer == null )
throw new ArgumentException( "null", "buffer" );
if( offset < 0 )
throw new ArgumentException( "<0", "offset" );
if( count < 0 )
throw new ArgumentException( "<0", "count" );
else if( count == 0 )
return;
byte[] buf = new byte[ count ];
Buffer.BlockCopy( buffer, offset, buf, 0, count );
_port.Output = buf;
}
#endregion
#region ISerialStreamCtrl Members
public int BaudRate
{
get { return (int) _port.Settings.BaudRate; }
set { _port.Settings.BaudRate = (OpenNETCF.IO.Serial.BaudRates) value; }
}
public bool BreakState
{
get { return _port.Break; }
set { _port.Break = value; }
}
public int BytesToRead
{
get { return _port.InBufferCount; }
}
public int BytesToWrite
{
get { return _port.OutBufferCount; }
}
public bool CDHolding
{
get { return GetCommStatusFlag( OpenNETCF.IO.Serial.CommModemStatusFlags.MS_RLSD_ON ); }
}
public bool CtsHolding
{
get { return GetCommStatusFlag( OpenNETCF.IO.Serial.CommModemStatusFlags.MS_CTS_ON ); }
}
public int DataBits
{
get { return _port.Settings.ByteSize; }
set { _port.Settings.ByteSize = (byte)value; }
}
public bool DiscardNull
{
get { return _port.DetailedSettings.DiscardNulls; }
set { _port.DetailedSettings.DiscardNulls = value; }
}
public bool DsrHolding
{
get { return GetCommStatusFlag( OpenNETCF.IO.Serial.CommModemStatusFlags.MS_DSR_ON ); }
}
public bool DtrEnable
{
get { return _port.DTREnable; }
set { _port.DTREnable = value; }
}
public static string[] GetPortNames()
{
string buffer;
uint bufferSize = Consts.PortEnum_InitBufSize;
uint res;
int error;
ArrayList comPorts = new ArrayList();
do
{
buffer = new String( '\0', (int) bufferSize );
// TODO: two strange bugs (features?):
// GetLastError() does not reset once err# 122 occurs - fixed with SetLastError
// if initial buffer has enough space, err# 127 occurs.
SetLastError(0);
res = QueryDosDevice( null, buffer, (uint) buffer.Length );
error = Marshal.GetLastWin32Error();
if( res == 0 )
{
// QueryDosDevice failed
if( error == Consts.Win32Err_ERROR_INSUFFICIENT_BUFFER )
{
// no clue how much we need, double the buffer size
bufferSize *= 2;
}
else
throw new InvalidOperationException("QueryDosDevice error #" + error.ToString());
}
else if( res > bufferSize )
{
// TODO: specs are vague for Win2000 & WinNT - needs testing
// QueryDosDevice failed with non-zero res
if( error == Consts.Win32Err_ERROR_INSUFFICIENT_BUFFER )
{
// this platform knows what it needs
bufferSize = res;
}
else
throw new InvalidOperationException("QueryDosDevice error #" + error.ToString());
}
else if( error == 0 && res == 0 )
{
// sanity check
throw new InvalidOperationException("Internal error");
}
else
break;
} while( bufferSize <= Consts.PortEnum_MaxBufSize );
if( bufferSize > Consts.PortEnum_MaxBufSize )
throw new InvalidOperationException("Maximum buffer size exceeded");
buffer = buffer.Substring( 0, (int)res );
foreach( string device in buffer.Split( '\0' ))
{
// Assumptions: serial port must be a string that begins with "COM#",
// where # is a 1 to 3 digit number
if( device.Length >= 4 && device.Length <= 6 &&
device.StartsWith("COM") &&
Char.IsDigit( device, 3 ) &&
(device.Length < 5 || Char.IsDigit( device, 4 )) &&
(device.Length < 6 || Char.IsDigit( device, 5 )) )
{
comPorts.Add( string.Copy( device )); // avoid locking the original buffer string
}
}
return (string[]) comPorts.ToArray( typeof(string) );
}
public Handshake Handshake
{
get
{
if( _port.DetailedSettings is OpenNETCF.IO.Serial.HandshakeNone )
return Handshake.None;
else if( _port.DetailedSettings is OpenNETCF.IO.Serial.HandshakeCtsRts )
return Handshake.RequestToSend;
else if( _port.DetailedSettings is OpenNETCF.IO.Serial.HandshakeXonXoff )
return Handshake.XOnXOff;
else if( _port.DetailedSettings is OpenNETCF.IO.Serial.HandshakeDsrDtr )
return Handshake.RequestToSendXOnXOff;
else
throw new NotImplementedException();
}
set
{
// Creating a new Handshaking object resets BasicSettings parameters.
OpenNETCF.IO.Serial.BasicPortSettings tempPortSettings = _port.DetailedSettings.BasicSettings;
switch( value )
{
case OpenNETCF.IO.Ports.Handshake.None:
_port.DetailedSettings = new OpenNETCF.IO.Serial.HandshakeNone();
break;
case OpenNETCF.IO.Ports.Handshake.RequestToSend:
_port.DetailedSettings = new OpenNETCF.IO.Serial.HandshakeCtsRts();
break;
case OpenNETCF.IO.Ports.Handshake.XOnXOff:
_port.DetailedSettings = new OpenNETCF.IO.Serial.HandshakeXonXoff();
break;
case OpenNETCF.IO.Ports.Handshake.RequestToSendXOnXOff:
_port.DetailedSettings = new OpenNETCF.IO.Serial.HandshakeDsrDtr();
break;
default:
throw new NotImplementedException();
}
_port.DetailedSettings.BasicSettings = tempPortSettings;
}
}
public bool IsOpen
{
get { return _port.IsOpen; }
}
public Parity Parity
{
get { return (Parity) Convert.ToInt32(_port.Settings.Parity); }
set { _port.Settings.Parity = (OpenNETCF.IO.Serial.Parity) Convert.ToInt32(value); }
}
public byte ParityReplace
{
get
{
return _port.DetailedSettings.ReplaceErrorChar ? (byte)_port.DetailedSettings.ErrorChar : (byte)0;
}
set
{
if( value == 0 )
_port.DetailedSettings.ReplaceErrorChar = false;
else
{
_port.DetailedSettings.ErrorChar = (char) value;
_port.DetailedSettings.ReplaceErrorChar = true;
}
}
}
public int ReadBufferSize
{
get { return _port.rxBufferSize; }
set { throw new InvalidOperationException("Only available during port initialization"); }
}
public int ReadTimeout
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public int ReceivedBytesThreshold
{
get { return _port.RThreshold; }
set { _port.RThreshold = value; }
}
public bool RtsEnable
{
get { return _port.RTSEnable; }
set { _port.RTSEnable = value; }
}
public StopBits StopBits
{
get
{
switch( _port.Settings.StopBits )
{
default:
throw new InvalidOperationException();
case OpenNETCF.IO.Serial.StopBits.one:
return StopBits.One;
case OpenNETCF.IO.Serial.StopBits.onePointFive:
return StopBits.OnePointFive;
case OpenNETCF.IO.Serial.StopBits.two:
return StopBits.Two;
}
}
set
{
switch( value )
{
case StopBits.One:
_port.Settings.StopBits = OpenNETCF.IO.Serial.StopBits.one;
break;
case StopBits.OnePointFive:
_port.Settings.StopBits = OpenNETCF.IO.Serial.StopBits.onePointFive;
break;
case StopBits.Two:
_port.Settings.StopBits = OpenNETCF.IO.Serial.StopBits.two;
break;
}
}
}
public int WriteBufferSize
{
get { return _port.txBufferSize; }
set { throw new InvalidOperationException("Only available during port initialization"); }
}
public int WriteTimeout
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public event SerialErrorEventHandler ErrorEvent;
public event SerialReceivedEventHandler ReceivedEvent;
public event SerialPinChangedEventHandler PinChangedEvent;
public void DiscardInBuffer()
{
// lock the rx FIFO while reading
_port.rxBufferBusy.WaitOne();
// Empty buffer
_port.rxFIFO.Clear();
// release the mutex so the Rx thread can continue
_port.rxBufferBusy.ReleaseMutex();
}
public void DiscardOutBuffer()
{
_port.ptxBuffer = 0;
}
#endregion
#region Internal Events Forwarding
private void _port_DataReceived()
{
if( ReceivedEvent != null )
ReceivedEvent(this, new SerialReceivedEventArgs(SerialReceived.ReceivedChars));
}
private void _port_OnError(string Description)
{
if( ErrorEvent != null )
{
SerialErrors err = (SerialErrors) 0;
if( Description.IndexOf("Framing") >= 0 )
err |= SerialErrors.Frame;
if( Description.IndexOf("Overrun") >= 0 )
err |= SerialErrors.Overrun;
if( Description.IndexOf("Receive Overflow") >= 0 )
err |= SerialErrors.RxOver;
if( Description.IndexOf("Parity") >= 0 )
err |= SerialErrors.RxParity;
if( Description.IndexOf("Transmit Overflow") >= 0 )
err |= SerialErrors.TxFull;
ErrorEvent( this, new SerialErrorEventArgs(err) );
}
}
private void _port_RingChange(bool NewState)
{
if( PinChangedEvent != null )
PinChangedEvent(this, new SerialPinChangedEventArgs(SerialPinChanges.Ring));
}
private void _port_RLSDChange(bool NewState)
{
if( PinChangedEvent != null )
PinChangedEvent(this, new SerialPinChangedEventArgs(SerialPinChanges.CDChanged));
}
#endregion
#region Extern code declarations
[DllImport("kernel32.dll")]
static extern void SetLastError(uint dwErrCode);
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private extern static uint QueryDosDevice(
[MarshalAs(UnmanagedType.LPTStr)]
string lpDeviceName,
[MarshalAs(UnmanagedType.LPTStr)]
string lpTargetPath,
uint ucchMax);
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
// Soon to be dismissed
[Serializable]
public class ChildAgentDataUpdate
{
public Guid ActiveGroupID;
public Guid AgentID;
public bool alwaysrun;
public float AVHeight;
public Vector3 cameraPosition;
public float drawdistance;
public float godlevel;
public uint GroupAccess;
public Vector3 Position;
public ulong regionHandle;
public byte[] throttles;
public Vector3 Velocity;
public ChildAgentDataUpdate()
{
}
}
public interface IAgentData
{
UUID AgentID { get; set; }
OSDMap Pack();
void Unpack(OSDMap map, IScene scene);
}
/// <summary>
/// Replacement for ChildAgentDataUpdate. Used over RESTComms and LocalComms.
/// </summary>
public class AgentPosition : IAgentData
{
private UUID m_id;
public UUID AgentID
{
get { return m_id; }
set { m_id = value; }
}
public ulong RegionHandle;
public uint CircuitCode;
public UUID SessionID;
public float Far;
public Vector3 Position;
public Vector3 Velocity;
public Vector3 Center;
public Vector3 Size;
public Vector3 AtAxis;
public Vector3 LeftAxis;
public Vector3 UpAxis;
public bool ChangedGrid;
// This probably shouldn't be here
public byte[] Throttles;
public OSDMap Pack()
{
OSDMap args = new OSDMap();
args["message_type"] = OSD.FromString("AgentPosition");
args["region_handle"] = OSD.FromString(RegionHandle.ToString());
args["circuit_code"] = OSD.FromString(CircuitCode.ToString());
args["agent_uuid"] = OSD.FromUUID(AgentID);
args["session_uuid"] = OSD.FromUUID(SessionID);
args["position"] = OSD.FromString(Position.ToString());
args["velocity"] = OSD.FromString(Velocity.ToString());
args["center"] = OSD.FromString(Center.ToString());
args["size"] = OSD.FromString(Size.ToString());
args["at_axis"] = OSD.FromString(AtAxis.ToString());
args["left_axis"] = OSD.FromString(LeftAxis.ToString());
args["up_axis"] = OSD.FromString(UpAxis.ToString());
args["far"] = OSD.FromReal(Far);
args["changed_grid"] = OSD.FromBoolean(ChangedGrid);
if ((Throttles != null) && (Throttles.Length > 0))
args["throttles"] = OSD.FromBinary(Throttles);
return args;
}
public void Unpack(OSDMap args, IScene scene)
{
if (args.ContainsKey("region_handle"))
UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle);
if (args["circuit_code"] != null)
UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
if (args["agent_uuid"] != null)
AgentID = args["agent_uuid"].AsUUID();
if (args["session_uuid"] != null)
SessionID = args["session_uuid"].AsUUID();
if (args["position"] != null)
Vector3.TryParse(args["position"].AsString(), out Position);
if (args["velocity"] != null)
Vector3.TryParse(args["velocity"].AsString(), out Velocity);
if (args["center"] != null)
Vector3.TryParse(args["center"].AsString(), out Center);
if (args["size"] != null)
Vector3.TryParse(args["size"].AsString(), out Size);
if (args["at_axis"] != null)
Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
if (args["left_axis"] != null)
Vector3.TryParse(args["left_axis"].AsString(), out LeftAxis);
if (args["up_axis"] != null)
Vector3.TryParse(args["up_axis"].AsString(), out UpAxis);
if (args["changed_grid"] != null)
ChangedGrid = args["changed_grid"].AsBoolean();
if (args["far"] != null)
Far = (float)(args["far"].AsReal());
if (args["throttles"] != null)
Throttles = args["throttles"].AsBinary();
}
/// <summary>
/// Soon to be decommissioned
/// </summary>
/// <param name="cAgent"></param>
public void CopyFrom(ChildAgentDataUpdate cAgent, UUID sid)
{
AgentID = new UUID(cAgent.AgentID);
SessionID = sid;
// next: ???
Size = new Vector3();
Size.Z = cAgent.AVHeight;
Center = cAgent.cameraPosition;
Far = cAgent.drawdistance;
Position = cAgent.Position;
RegionHandle = cAgent.regionHandle;
Throttles = cAgent.throttles;
Velocity = cAgent.Velocity;
}
}
public class AgentGroupData
{
public UUID GroupID;
public ulong GroupPowers;
public bool AcceptNotices;
public AgentGroupData(UUID id, ulong powers, bool notices)
{
GroupID = id;
GroupPowers = powers;
AcceptNotices = notices;
}
public AgentGroupData(OSDMap args)
{
UnpackUpdateMessage(args);
}
public OSDMap PackUpdateMessage()
{
OSDMap groupdata = new OSDMap();
groupdata["group_id"] = OSD.FromUUID(GroupID);
groupdata["group_powers"] = OSD.FromString(GroupPowers.ToString());
groupdata["accept_notices"] = OSD.FromBoolean(AcceptNotices);
return groupdata;
}
public void UnpackUpdateMessage(OSDMap args)
{
if (args["group_id"] != null)
GroupID = args["group_id"].AsUUID();
if (args["group_powers"] != null)
UInt64.TryParse((string)args["group_powers"].AsString(), out GroupPowers);
if (args["accept_notices"] != null)
AcceptNotices = args["accept_notices"].AsBoolean();
}
}
public class ControllerData
{
public UUID ItemID;
public uint IgnoreControls;
public uint EventControls;
public ControllerData(UUID item, uint ignore, uint ev)
{
ItemID = item;
IgnoreControls = ignore;
EventControls = ev;
}
public ControllerData(OSDMap args)
{
UnpackUpdateMessage(args);
}
public OSDMap PackUpdateMessage()
{
OSDMap controldata = new OSDMap();
controldata["item"] = OSD.FromUUID(ItemID);
controldata["ignore"] = OSD.FromInteger(IgnoreControls);
controldata["event"] = OSD.FromInteger(EventControls);
return controldata;
}
public void UnpackUpdateMessage(OSDMap args)
{
if (args["item"] != null)
ItemID = args["item"].AsUUID();
if (args["ignore"] != null)
IgnoreControls = (uint)args["ignore"].AsInteger();
if (args["event"] != null)
EventControls = (uint)args["event"].AsInteger();
}
}
public class AgentData : IAgentData
{
private UUID m_id;
public UUID AgentID
{
get { return m_id; }
set { m_id = value; }
}
public UUID RegionID;
public uint CircuitCode;
public UUID SessionID;
public Vector3 Position;
public Vector3 Velocity;
public Vector3 Center;
public Vector3 Size;
public Vector3 AtAxis;
public Vector3 LeftAxis;
public Vector3 UpAxis;
/// <summary>
/// Signal on a V2 teleport that Scene.IncomingChildAgentDataUpdate(AgentData ad) should wait for the
/// scene presence to become root (triggered when the viewer sends a CompleteAgentMovement UDP packet after
/// establishing the connection triggered by it's receipt of a TeleportFinish EQ message).
/// </summary>
public bool SenderWantsToWaitForRoot;
public float Far;
public float Aspect;
//public int[] Throttles;
public byte[] Throttles;
public uint LocomotionState;
public Quaternion HeadRotation;
public Quaternion BodyRotation;
public uint ControlFlags;
public float EnergyLevel;
public Byte GodLevel;
public bool AlwaysRun;
public UUID PreyAgent;
public Byte AgentAccess;
public UUID ActiveGroupID;
public AgentGroupData[] Groups;
public Animation[] Anims;
public Animation DefaultAnim = null;
public Animation AnimState = null;
public UUID GranterID;
// Appearance
public AvatarAppearance Appearance;
// DEBUG ON
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// DEBUG OFF
/*
public byte[] AgentTextures;
public byte[] VisualParams;
public UUID[] Wearables;
public AvatarAttachment[] Attachments;
*/
// Scripted
public ControllerData[] Controllers;
public string CallbackURI;
// These two must have the same Count
public List<ISceneObject> AttachmentObjects;
public List<string> AttachmentObjectStates;
public virtual OSDMap Pack()
{
// m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Pack data");
OSDMap args = new OSDMap();
args["message_type"] = OSD.FromString("AgentData");
args["region_id"] = OSD.FromString(RegionID.ToString());
args["circuit_code"] = OSD.FromString(CircuitCode.ToString());
args["agent_uuid"] = OSD.FromUUID(AgentID);
args["session_uuid"] = OSD.FromUUID(SessionID);
args["position"] = OSD.FromString(Position.ToString());
args["velocity"] = OSD.FromString(Velocity.ToString());
args["center"] = OSD.FromString(Center.ToString());
args["size"] = OSD.FromString(Size.ToString());
args["at_axis"] = OSD.FromString(AtAxis.ToString());
args["left_axis"] = OSD.FromString(LeftAxis.ToString());
args["up_axis"] = OSD.FromString(UpAxis.ToString());
//backwards compatibility
args["changed_grid"] = OSD.FromBoolean(SenderWantsToWaitForRoot);
args["wait_for_root"] = OSD.FromBoolean(SenderWantsToWaitForRoot);
args["far"] = OSD.FromReal(Far);
args["aspect"] = OSD.FromReal(Aspect);
if ((Throttles != null) && (Throttles.Length > 0))
args["throttles"] = OSD.FromBinary(Throttles);
args["locomotion_state"] = OSD.FromString(LocomotionState.ToString());
args["head_rotation"] = OSD.FromString(HeadRotation.ToString());
args["body_rotation"] = OSD.FromString(BodyRotation.ToString());
args["control_flags"] = OSD.FromString(ControlFlags.ToString());
args["energy_level"] = OSD.FromReal(EnergyLevel);
args["god_level"] = OSD.FromString(GodLevel.ToString());
args["always_run"] = OSD.FromBoolean(AlwaysRun);
args["prey_agent"] = OSD.FromUUID(PreyAgent);
args["agent_access"] = OSD.FromString(AgentAccess.ToString());
args["active_group_id"] = OSD.FromUUID(ActiveGroupID);
if ((Groups != null) && (Groups.Length > 0))
{
OSDArray groups = new OSDArray(Groups.Length);
foreach (AgentGroupData agd in Groups)
groups.Add(agd.PackUpdateMessage());
args["groups"] = groups;
}
if ((Anims != null) && (Anims.Length > 0))
{
OSDArray anims = new OSDArray(Anims.Length);
foreach (Animation aanim in Anims)
anims.Add(aanim.PackUpdateMessage());
args["animations"] = anims;
}
if (DefaultAnim != null)
{
args["default_animation"] = DefaultAnim.PackUpdateMessage();
}
if (AnimState != null)
{
args["animation_state"] = AnimState.PackUpdateMessage();
}
if (Appearance != null)
args["packed_appearance"] = Appearance.Pack();
//if ((AgentTextures != null) && (AgentTextures.Length > 0))
//{
// OSDArray textures = new OSDArray(AgentTextures.Length);
// foreach (UUID uuid in AgentTextures)
// textures.Add(OSD.FromUUID(uuid));
// args["agent_textures"] = textures;
//}
// The code to pack textures, visuals, wearables and attachments
// should be removed; packed appearance contains the full appearance
// This is retained for backward compatibility only
if (Appearance.Texture != null)
{
byte[] rawtextures = Appearance.Texture.GetBytes();
args["texture_entry"] = OSD.FromBinary(rawtextures);
}
if ((Appearance.VisualParams != null) && (Appearance.VisualParams.Length > 0))
args["visual_params"] = OSD.FromBinary(Appearance.VisualParams);
// We might not pass this in all cases...
if ((Appearance.Wearables != null) && (Appearance.Wearables.Length > 0))
{
OSDArray wears = new OSDArray(Appearance.Wearables.Length);
foreach (AvatarWearable awear in Appearance.Wearables)
wears.Add(awear.Pack());
args["wearables"] = wears;
}
List<AvatarAttachment> attachments = Appearance.GetAttachments();
if ((attachments != null) && (attachments.Count > 0))
{
OSDArray attachs = new OSDArray(attachments.Count);
foreach (AvatarAttachment att in attachments)
attachs.Add(att.Pack());
args["attachments"] = attachs;
}
// End of code to remove
if ((Controllers != null) && (Controllers.Length > 0))
{
OSDArray controls = new OSDArray(Controllers.Length);
foreach (ControllerData ctl in Controllers)
controls.Add(ctl.PackUpdateMessage());
args["controllers"] = controls;
}
if ((CallbackURI != null) && (!CallbackURI.Equals("")))
args["callback_uri"] = OSD.FromString(CallbackURI);
// Attachment objects for fatpack messages
if (AttachmentObjects != null)
{
int i = 0;
OSDArray attObjs = new OSDArray(AttachmentObjects.Count);
foreach (ISceneObject so in AttachmentObjects)
{
OSDMap info = new OSDMap(4);
info["sog"] = OSD.FromString(so.ToXml2());
info["extra"] = OSD.FromString(so.ExtraToXmlString());
info["modified"] = OSD.FromBoolean(so.HasGroupChanged);
try
{
info["state"] = OSD.FromString(AttachmentObjectStates[i++]);
}
catch (IndexOutOfRangeException)
{
m_log.WarnFormat("[CHILD AGENT DATA]: scripts list is shorter than object list.");
}
attObjs.Add(info);
}
args["attach_objects"] = attObjs;
}
return args;
}
/// <summary>
/// Deserialization of agent data.
/// Avoiding reflection makes it painful to write, but that's the price!
/// </summary>
/// <param name="hash"></param>
public virtual void Unpack(OSDMap args, IScene scene)
{
//m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Unpack data");
if (args.ContainsKey("region_id"))
UUID.TryParse(args["region_id"].AsString(), out RegionID);
if (args["circuit_code"] != null)
UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
if (args["agent_uuid"] != null)
AgentID = args["agent_uuid"].AsUUID();
if (args["session_uuid"] != null)
SessionID = args["session_uuid"].AsUUID();
if (args["position"] != null)
Vector3.TryParse(args["position"].AsString(), out Position);
if (args["velocity"] != null)
Vector3.TryParse(args["velocity"].AsString(), out Velocity);
if (args["center"] != null)
Vector3.TryParse(args["center"].AsString(), out Center);
if (args["size"] != null)
Vector3.TryParse(args["size"].AsString(), out Size);
if (args["at_axis"] != null)
Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
if (args["left_axis"] != null)
Vector3.TryParse(args["left_axis"].AsString(), out AtAxis);
if (args["up_axis"] != null)
Vector3.TryParse(args["up_axis"].AsString(), out AtAxis);
if (args.ContainsKey("wait_for_root") && args["wait_for_root"] != null)
SenderWantsToWaitForRoot = args["wait_for_root"].AsBoolean();
if (args["far"] != null)
Far = (float)(args["far"].AsReal());
if (args["aspect"] != null)
Aspect = (float)args["aspect"].AsReal();
if (args["throttles"] != null)
Throttles = args["throttles"].AsBinary();
if (args["locomotion_state"] != null)
UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState);
if (args["head_rotation"] != null)
Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation);
if (args["body_rotation"] != null)
Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation);
if (args["control_flags"] != null)
UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags);
if (args["energy_level"] != null)
EnergyLevel = (float)(args["energy_level"].AsReal());
if (args["god_level"] != null)
Byte.TryParse(args["god_level"].AsString(), out GodLevel);
if (args["always_run"] != null)
AlwaysRun = args["always_run"].AsBoolean();
if (args["prey_agent"] != null)
PreyAgent = args["prey_agent"].AsUUID();
if (args["agent_access"] != null)
Byte.TryParse(args["agent_access"].AsString(), out AgentAccess);
if (args["active_group_id"] != null)
ActiveGroupID = args["active_group_id"].AsUUID();
if ((args["groups"] != null) && (args["groups"]).Type == OSDType.Array)
{
OSDArray groups = (OSDArray)(args["groups"]);
Groups = new AgentGroupData[groups.Count];
int i = 0;
foreach (OSD o in groups)
{
if (o.Type == OSDType.Map)
{
Groups[i++] = new AgentGroupData((OSDMap)o);
}
}
}
if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array)
{
OSDArray anims = (OSDArray)(args["animations"]);
Anims = new Animation[anims.Count];
int i = 0;
foreach (OSD o in anims)
{
if (o.Type == OSDType.Map)
{
Anims[i++] = new Animation((OSDMap)o);
}
}
}
if (args["default_animation"] != null)
{
try
{
DefaultAnim = new Animation((OSDMap)args["default_animation"]);
}
catch
{
DefaultAnim = null;
}
}
if (args["animation_state"] != null)
{
try
{
AnimState = new Animation((OSDMap)args["animation_state"]);
}
catch
{
AnimState = null;
}
}
//if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array)
//{
// OSDArray textures = (OSDArray)(args["agent_textures"]);
// AgentTextures = new UUID[textures.Count];
// int i = 0;
// foreach (OSD o in textures)
// AgentTextures[i++] = o.AsUUID();
//}
Appearance = new AvatarAppearance();
// The code to unpack textures, visuals, wearables and attachments
// should be removed; packed appearance contains the full appearance
// This is retained for backward compatibility only
if (args["texture_entry"] != null)
{
byte[] rawtextures = args["texture_entry"].AsBinary();
Primitive.TextureEntry textures = new Primitive.TextureEntry(rawtextures,0,rawtextures.Length);
Appearance.SetTextureEntries(textures);
}
if (args["visual_params"] != null)
Appearance.SetVisualParams(args["visual_params"].AsBinary());
if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array)
{
OSDArray wears = (OSDArray)(args["wearables"]);
for (int i = 0; i < wears.Count / 2; i++)
{
AvatarWearable awear = new AvatarWearable((OSDArray)wears[i]);
Appearance.SetWearable(i,awear);
}
}
if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array)
{
OSDArray attachs = (OSDArray)(args["attachments"]);
foreach (OSD o in attachs)
{
if (o.Type == OSDType.Map)
{
// We know all of these must end up as attachments so we
// append rather than replace to ensure multiple attachments
// per point continues to work
// m_log.DebugFormat("[CHILDAGENTDATAUPDATE]: Appending attachments for {0}", AgentID);
Appearance.AppendAttachment(new AvatarAttachment((OSDMap)o));
}
}
}
// end of code to remove
if (args.ContainsKey("packed_appearance") && (args["packed_appearance"]).Type == OSDType.Map)
Appearance = new AvatarAppearance((OSDMap)args["packed_appearance"]);
else
m_log.WarnFormat("[CHILDAGENTDATAUPDATE] No packed appearance");
if ((args["controllers"] != null) && (args["controllers"]).Type == OSDType.Array)
{
OSDArray controls = (OSDArray)(args["controllers"]);
Controllers = new ControllerData[controls.Count];
int i = 0;
foreach (OSD o in controls)
{
if (o.Type == OSDType.Map)
{
Controllers[i++] = new ControllerData((OSDMap)o);
}
}
}
if (args["callback_uri"] != null)
CallbackURI = args["callback_uri"].AsString();
// Attachment objects
if (args["attach_objects"] != null && args["attach_objects"].Type == OSDType.Array)
{
OSDArray attObjs = (OSDArray)(args["attach_objects"]);
AttachmentObjects = new List<ISceneObject>();
AttachmentObjectStates = new List<string>();
foreach (OSD o in attObjs)
{
if (o.Type == OSDType.Map)
{
OSDMap info = (OSDMap)o;
ISceneObject so = scene.DeserializeObject(info["sog"].AsString());
so.ExtraFromXmlString(info["extra"].AsString());
so.HasGroupChanged = info["modified"].AsBoolean();
AttachmentObjects.Add(so);
AttachmentObjectStates.Add(info["state"].AsString());
}
}
}
}
public AgentData()
{
}
public AgentData(Hashtable hash)
{
//UnpackUpdateMessage(hash);
}
public void Dump()
{
System.Console.WriteLine("------------ AgentData ------------");
System.Console.WriteLine("UUID: " + AgentID);
System.Console.WriteLine("Region: " + RegionID);
System.Console.WriteLine("Position: " + Position);
}
}
public class CompleteAgentData : AgentData
{
public override OSDMap Pack()
{
return base.Pack();
}
public override void Unpack(OSDMap map, IScene scene)
{
base.Unpack(map, scene);
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using com.adjust.sdk.test;
namespace com.adjust.sdk
{
public class Adjust : MonoBehaviour
{
private const string errorMsgEditor = "Adjust: SDK can not be used in Editor.";
private const string errorMsgStart = "Adjust: SDK not started. Start it manually using the 'start' method.";
private const string errorMsgPlatform = "Adjust: SDK can only be used in Android, iOS, Windows Phone 8.1, Windows Store or Universal Windows apps.";
public bool startManually = true;
public bool eventBuffering = false;
public bool sendInBackground = false;
public bool launchDeferredDeeplink = true;
public string appToken = "{Your App Token}";
public AdjustLogLevel logLevel = AdjustLogLevel.Info;
public AdjustEnvironment environment = AdjustEnvironment.Sandbox;
#if UNITY_IOS
// Delegate references for iOS callback triggering
private static Action<string> deferredDeeplinkDelegate = null;
private static Action<AdjustEventSuccess> eventSuccessDelegate = null;
private static Action<AdjustEventFailure> eventFailureDelegate = null;
private static Action<AdjustSessionSuccess> sessionSuccessDelegate = null;
private static Action<AdjustSessionFailure> sessionFailureDelegate = null;
private static Action<AdjustAttribution> attributionChangedDelegate = null;
#endif
void Awake()
{
if (IsEditor()) { return; }
DontDestroyOnLoad(transform.gameObject);
if (!this.startManually)
{
AdjustConfig adjustConfig = new AdjustConfig(this.appToken, this.environment, (this.logLevel == AdjustLogLevel.Suppress));
adjustConfig.setLogLevel(this.logLevel);
adjustConfig.setSendInBackground(this.sendInBackground);
adjustConfig.setEventBufferingEnabled(this.eventBuffering);
adjustConfig.setLaunchDeferredDeeplink(this.launchDeferredDeeplink);
Adjust.start(adjustConfig);
}
}
void OnApplicationPause(bool pauseStatus)
{
if (IsEditor()) { return; }
#if UNITY_IOS
// No action, iOS SDK is subscribed to iOS lifecycle notifications.
#elif UNITY_ANDROID
if (pauseStatus)
{
AdjustAndroid.OnPause();
}
else
{
AdjustAndroid.OnResume();
}
#elif (UNITY_WSA || UNITY_WP8)
if (pauseStatus)
{
AdjustWindows.OnPause();
}
else
{
AdjustWindows.OnResume();
}
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void start(AdjustConfig adjustConfig)
{
if (IsEditor()) { return; }
if (adjustConfig == null)
{
Debug.Log("Adjust: Missing config to start.");
return;
}
#if UNITY_IOS
Adjust.eventSuccessDelegate = adjustConfig.getEventSuccessDelegate();
Adjust.eventFailureDelegate = adjustConfig.getEventFailureDelegate();
Adjust.sessionSuccessDelegate = adjustConfig.getSessionSuccessDelegate();
Adjust.sessionFailureDelegate = adjustConfig.getSessionFailureDelegate();
Adjust.deferredDeeplinkDelegate = adjustConfig.getDeferredDeeplinkDelegate();
Adjust.attributionChangedDelegate = adjustConfig.getAttributionChangedDelegate();
AdjustiOS.Start(adjustConfig);
#elif UNITY_ANDROID
AdjustAndroid.Start(adjustConfig);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.Start(adjustConfig);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void trackEvent(AdjustEvent adjustEvent)
{
if (IsEditor()) { return; }
if (adjustEvent == null)
{
Debug.Log("Adjust: Missing event to track.");
return;
}
#if UNITY_IOS
AdjustiOS.TrackEvent(adjustEvent);
#elif UNITY_ANDROID
AdjustAndroid.TrackEvent(adjustEvent);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.TrackEvent(adjustEvent);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void setEnabled(bool enabled)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.SetEnabled(enabled);
#elif UNITY_ANDROID
AdjustAndroid.SetEnabled(enabled);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.SetEnabled(enabled);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static bool isEnabled()
{
if (IsEditor()) { return false; }
#if UNITY_IOS
return AdjustiOS.IsEnabled();
#elif UNITY_ANDROID
return AdjustAndroid.IsEnabled();
#elif (UNITY_WSA || UNITY_WP8)
return AdjustWindows.IsEnabled();
#else
Debug.Log(errorMsgPlatform);
return false;
#endif
}
public static void setOfflineMode(bool enabled)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.SetOfflineMode(enabled);
#elif UNITY_ANDROID
AdjustAndroid.SetOfflineMode(enabled);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.SetOfflineMode(enabled);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void setDeviceToken(string deviceToken)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.SetDeviceToken(deviceToken);
#elif UNITY_ANDROID
AdjustAndroid.SetDeviceToken(deviceToken);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.SetDeviceToken(deviceToken);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void gdprForgetMe()
{
#if UNITY_IOS
AdjustiOS.GdprForgetMe();
#elif UNITY_ANDROID
AdjustAndroid.GdprForgetMe();
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.GdprForgetMe();
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void appWillOpenUrl(string url)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.AppWillOpenUrl(url);
#elif UNITY_ANDROID
AdjustAndroid.AppWillOpenUrl(url);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.AppWillOpenUrl(url);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void sendFirstPackages()
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.SendFirstPackages();
#elif UNITY_ANDROID
AdjustAndroid.SendFirstPackages();
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.SendFirstPackages();
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void addSessionPartnerParameter(string key, string value)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.AddSessionPartnerParameter(key, value);
#elif UNITY_ANDROID
AdjustAndroid.AddSessionPartnerParameter(key, value);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.AddSessionPartnerParameter(key, value);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void addSessionCallbackParameter(string key, string value)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.AddSessionCallbackParameter(key, value);
#elif UNITY_ANDROID
AdjustAndroid.AddSessionCallbackParameter(key, value);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.AddSessionCallbackParameter(key, value);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void removeSessionPartnerParameter(string key)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.RemoveSessionPartnerParameter(key);
#elif UNITY_ANDROID
AdjustAndroid.RemoveSessionPartnerParameter(key);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.RemoveSessionPartnerParameter(key);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void removeSessionCallbackParameter(string key)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.RemoveSessionCallbackParameter(key);
#elif UNITY_ANDROID
AdjustAndroid.RemoveSessionCallbackParameter(key);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.RemoveSessionCallbackParameter(key);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void resetSessionPartnerParameters()
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.ResetSessionPartnerParameters();
#elif UNITY_ANDROID
AdjustAndroid.ResetSessionPartnerParameters();
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.ResetSessionPartnerParameters();
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void resetSessionCallbackParameters()
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.ResetSessionCallbackParameters();
#elif UNITY_ANDROID
AdjustAndroid.ResetSessionCallbackParameters();
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.ResetSessionCallbackParameters();
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static string getAdid()
{
if (IsEditor()) { return string.Empty; }
#if UNITY_IOS
return AdjustiOS.GetAdid();
#elif UNITY_ANDROID
return AdjustAndroid.GetAdid();
#elif (UNITY_WSA || UNITY_WP8)
return AdjustWindows.GetAdid();
#else
Debug.Log(errorMsgPlatform);
return string.Empty;
#endif
}
public static AdjustAttribution getAttribution()
{
if (IsEditor()) { return null; }
#if UNITY_IOS
return AdjustiOS.GetAttribution();
#elif UNITY_ANDROID
return AdjustAndroid.GetAttribution();
#elif (UNITY_WSA || UNITY_WP8)
return AdjustWindows.GetAttribution();
#else
Debug.Log(errorMsgPlatform);
return null;
#endif
}
public static string getWinAdid()
{
if (IsEditor()) { return string.Empty; }
#if UNITY_IOS
Debug.Log("Adjust: Error! Windows Advertising ID is not available on iOS platform.");
return string.Empty;
#elif UNITY_ANDROID
Debug.Log("Adjust: Error! Windows Advertising ID is not available on Android platform.");
return string.Empty;
#elif (UNITY_WSA || UNITY_WP8)
return AdjustWindows.GetWinAdId();
#else
Debug.Log(errorMsgPlatform);
return string.Empty;
#endif
}
public static string getIdfa()
{
if (IsEditor()) { return string.Empty; }
#if UNITY_IOS
return AdjustiOS.GetIdfa();
#elif UNITY_ANDROID
Debug.Log("Adjust: Error! IDFA is not available on Android platform.");
return string.Empty;
#elif (UNITY_WSA || UNITY_WP8)
Debug.Log("Adjust: Error! IDFA is not available on Windows platform.");
return string.Empty;
#else
Debug.Log(errorMsgPlatform);
return string.Empty;
#endif
}
[Obsolete("This method is intended for testing purposes only. Do not use it.")]
public static void setReferrer(string referrer)
{
if (IsEditor()) { return; }
#if UNITY_IOS
Debug.Log("Adjust: Install referrer is not available on iOS platform.");
#elif UNITY_ANDROID
AdjustAndroid.SetReferrer(referrer);
#elif (UNITY_WSA || UNITY_WP8)
Debug.Log("Adjust: Error! Install referrer is not available on Windows platform.");
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static void getGoogleAdId(Action<string> onDeviceIdsRead)
{
if (IsEditor()) { return; }
#if UNITY_IOS
Debug.Log("Adjust: Google Play Advertising ID is not available on iOS platform.");
onDeviceIdsRead(string.Empty);
#elif UNITY_ANDROID
AdjustAndroid.GetGoogleAdId(onDeviceIdsRead);
#elif (UNITY_WSA || UNITY_WP8)
Debug.Log("Adjust: Google Play Advertising ID is not available on Windows platform.");
onDeviceIdsRead(string.Empty);
#else
Debug.Log(errorMsgPlatform);
#endif
}
public static string getAmazonAdId()
{
if (IsEditor()) { return string.Empty; }
#if UNITY_IOS
Debug.Log("Adjust: Amazon Advertising ID is not available on iOS platform.");
return string.Empty;
#elif UNITY_ANDROID
return AdjustAndroid.GetAmazonAdId();
#elif (UNITY_WSA || UNITY_WP8)
Debug.Log("Adjust: Amazon Advertising ID not available on Windows platform.");
return string.Empty;
#else
Debug.Log(errorMsgPlatform);
return string.Empty;
#endif
}
#if UNITY_IOS
public void GetNativeAttribution(string attributionData)
{
if (IsEditor()) { return; }
if (Adjust.attributionChangedDelegate == null)
{
Debug.Log("Adjust: Attribution changed delegate was not set.");
return;
}
var attribution = new AdjustAttribution(attributionData);
Adjust.attributionChangedDelegate(attribution);
}
public void GetNativeEventSuccess(string eventSuccessData)
{
if (IsEditor()) { return; }
if (Adjust.eventSuccessDelegate == null)
{
Debug.Log("Adjust: Event success delegate was not set.");
return;
}
var eventSuccess = new AdjustEventSuccess(eventSuccessData);
Adjust.eventSuccessDelegate(eventSuccess);
}
public void GetNativeEventFailure(string eventFailureData)
{
if (IsEditor()) { return; }
if (Adjust.eventFailureDelegate == null)
{
Debug.Log("Adjust: Event failure delegate was not set.");
return;
}
var eventFailure = new AdjustEventFailure(eventFailureData);
Adjust.eventFailureDelegate(eventFailure);
}
public void GetNativeSessionSuccess(string sessionSuccessData)
{
if (IsEditor()) { return; }
if (Adjust.sessionSuccessDelegate == null)
{
Debug.Log("Adjust: Session success delegate was not set.");
return;
}
var sessionSuccess = new AdjustSessionSuccess(sessionSuccessData);
Adjust.sessionSuccessDelegate(sessionSuccess);
}
public void GetNativeSessionFailure(string sessionFailureData)
{
if (IsEditor()) { return; }
if (Adjust.sessionFailureDelegate == null)
{
Debug.Log("Adjust: Session failure delegate was not set.");
return;
}
var sessionFailure = new AdjustSessionFailure(sessionFailureData);
Adjust.sessionFailureDelegate(sessionFailure);
}
public void GetNativeDeferredDeeplink(string deeplinkURL)
{
if (IsEditor()) { return; }
if (Adjust.deferredDeeplinkDelegate == null)
{
Debug.Log("Adjust: Deferred deeplink delegate was not set.");
return;
}
Adjust.deferredDeeplinkDelegate(deeplinkURL);
}
#endif
private static bool IsEditor()
{
#if UNITY_EDITOR
Debug.Log(errorMsgEditor);
return true;
#else
return false;
#endif
}
public static void SetTestOptions(AdjustTestOptions testOptions)
{
if (IsEditor()) { return; }
#if UNITY_IOS
AdjustiOS.SetTestOptions(testOptions);
#elif UNITY_ANDROID
AdjustAndroid.SetTestOptions(testOptions);
#elif (UNITY_WSA || UNITY_WP8)
AdjustWindows.SetTestOptions(testOptions);
#else
Debug.Log("Cannot run integration tests. None of the supported platforms selected.");
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Runtime.Versioning;
using NuGet.Packages;
using NuGet.Resources;
namespace NuGet
{
public class ZipPackage : LocalPackage, IPackagePhysicalPathInfo
{
private const string CacheKeyFormat = "NUGET_ZIP_PACKAGE_{0}_{1}{2}";
private const string AssembliesCacheKey = "ASSEMBLIES";
private const string FilesCacheKey = "FILES";
private readonly bool _enableCaching;
private static readonly TimeSpan CacheTimeout = TimeSpan.FromSeconds(15);
// paths to exclude
private static readonly string[] ExcludePaths = new[] { "_rels", "package" };
// We don't store the stream itself, just a way to open the stream on demand
// so we don't have to hold on to that resource
private readonly Func<Stream> _streamFactory;
public ZipPackage(string filePath)
: this(filePath, enableCaching: false)
{
}
public ZipPackage(Func<Stream> packageStreamFactory, Func<Stream> manifestStreamFactory, string physicalPathInfo)
{
if (packageStreamFactory == null)
{
throw new ArgumentNullException("packageStreamFactory");
}
if (manifestStreamFactory == null)
{
throw new ArgumentNullException("manifestStreamFactory");
}
_enableCaching = false;
_streamFactory = packageStreamFactory;
PhysicalFilePath = physicalPathInfo;
EnsureManifest(manifestStreamFactory);
}
public ZipPackage(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
_enableCaching = false;
_streamFactory = stream.ToStreamFactory();
using (stream = _streamFactory())
{
EnsureManifest(() => GetManifestStreamFromPackage(stream));
}
}
private ZipPackage(string filePath, bool enableCaching)
{
if (String.IsNullOrEmpty(filePath))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "filePath");
}
_enableCaching = enableCaching;
_streamFactory = () => File.OpenRead(filePath);
using (var stream = _streamFactory())
{
EnsureManifest(() => GetManifestStreamFromPackage(stream));
}
}
internal ZipPackage(Func<Stream> streamFactory, bool enableCaching)
{
if (streamFactory == null)
{
throw new ArgumentNullException("streamFactory");
}
_enableCaching = enableCaching;
_streamFactory = streamFactory;
using (var stream = _streamFactory())
{
EnsureManifest(() => GetManifestStreamFromPackage(stream));
}
}
public override Stream GetStream()
{
return _streamFactory();
}
public override void ExtractContents(IFileSystem fileSystem, string extractPath)
{
using (Stream stream = _streamFactory())
{
var package = Package.Open(stream);
foreach (var part in package.GetParts()
.Where(p => IsPackageFile(p, package.PackageProperties.Identifier)))
{
var relativePath = UriUtility.GetPath(part.Uri);
var targetPath = Path.Combine(extractPath, relativePath);
using (var partStream = part.GetStream())
{
fileSystem.AddFile(targetPath, partStream);
}
}
}
}
public override IEnumerable<FrameworkName> GetSupportedFrameworks()
{
IEnumerable<FrameworkName> fileFrameworks;
IEnumerable<IPackageFile> cachedFiles;
if (_enableCaching && MemoryCache.Instance.TryGetValue(GetFilesCacheKey(), out cachedFiles))
{
fileFrameworks = cachedFiles.Select(c => c.TargetFramework);
}
else
{
using (Stream stream = _streamFactory())
{
var package = Package.Open(stream);
string effectivePath;
fileFrameworks = from part in package.GetParts()
where IsPackageFile(part, Id)
select VersionUtility.ParseFrameworkNameFromFilePath(UriUtility.GetPath(part.Uri), out effectivePath);
}
}
return base.GetSupportedFrameworks()
.Concat(fileFrameworks)
.Where(f => f != null)
.Distinct();
}
protected override IEnumerable<IPackageAssemblyReference> GetAssemblyReferencesCore()
{
if (_enableCaching)
{
return MemoryCache.Instance.GetOrAdd(GetAssembliesCacheKey(), GetAssembliesNoCache, CacheTimeout);
}
return GetAssembliesNoCache();
}
protected override IEnumerable<IPackageFile> GetFilesBase()
{
if (_enableCaching)
{
return MemoryCache.Instance.GetOrAdd(GetFilesCacheKey(), GetFilesNoCache, CacheTimeout);
}
return GetFilesNoCache();
}
private List<IPackageAssemblyReference> GetAssembliesNoCache()
{
return (from file in GetFiles()
where IsAssemblyReference(file.Path)
select (IPackageAssemblyReference)new ZipPackageAssemblyReference(file)).ToList();
}
private List<IPackageFile> GetFilesNoCache()
{
using (Stream stream = _streamFactory())
{
Package package = Package.Open(stream);
return (from part in package.GetParts()
where IsPackageFile(part, package.PackageProperties.Identifier)
select (IPackageFile)new ZipPackageFile(part)).ToList();
}
}
private void EnsureManifest(Func<Stream> manifestStreamFactory)
{
using (Stream manifestStream = manifestStreamFactory())
{
ReadManifest(manifestStream);
}
}
private static Stream GetManifestStreamFromPackage(Stream packageStream)
{
Package package = Package.Open(packageStream);
PackageRelationship relationshipType = package.GetRelationshipsByType(Constants.PackageRelationshipNamespace + PackageBuilder.ManifestRelationType).SingleOrDefault();
if (relationshipType == null)
{
throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest);
}
PackagePart manifestPart = package.GetPart(relationshipType.TargetUri);
if (manifestPart == null)
{
throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest);
}
return manifestPart.GetStream();
}
private string GetFilesCacheKey()
{
return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, FilesCacheKey, Id, Version);
}
private string GetAssembliesCacheKey()
{
return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, AssembliesCacheKey, Id, Version);
}
internal static bool IsPackageFile(PackagePart part, string packageId)
{
string path = UriUtility.GetPath(part.Uri);
string directory = Path.GetDirectoryName(path);
// We exclude any opc files and the auto-generated package manifest file ({packageId}.nuspec)
return !ExcludePaths.Any(p => directory.StartsWith(p, StringComparison.OrdinalIgnoreCase)) &&
!PackageHelper.IsPackageManifest(path, packageId);
}
internal static void ClearCache(IPackage package)
{
var zipPackage = package as ZipPackage;
// Remove the cache entries for files and assemblies
if (zipPackage != null)
{
MemoryCache.Instance.Remove(zipPackage.GetAssembliesCacheKey());
MemoryCache.Instance.Remove(zipPackage.GetFilesCacheKey());
}
}
public string PhysicalFilePath { get; private set; }
}
}
| |
// 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.
/*============================================================
**
** Purpose: Some single-precision floating-point math operations
**
===========================================================*/
//This class contains only static members and doesn't require serialization.
using System.Runtime;
using System.Runtime.CompilerServices;
namespace System
{
public static partial class MathF
{
public const float E = 2.71828183f;
public const float PI = 3.14159265f;
private const int maxRoundingDigits = 6;
// This table is required for the Round function which can specify the number of digits to round to
private static float[] roundPower10Single = new float[] {
1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f
};
private static float singleRoundLimit = 1e8f;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Abs(float x)
{
return Math.Abs(x);
}
public static float IEEERemainder(float x, float y)
{
if (float.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (float.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
var regularMod = x % y;
if (float.IsNaN(regularMod))
{
return float.NaN;
}
if ((regularMod == 0) && float.IsNegative(x))
{
return float.NegativeZero;
}
var alternativeResult = (regularMod - (Abs(y) * Sign(x)));
if (Abs(alternativeResult) == Abs(regularMod))
{
var divisionResult = x / y;
var roundedResult = Round(divisionResult);
if (Abs(roundedResult) > Abs(divisionResult))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
if (Abs(alternativeResult) < Abs(regularMod))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
public static float Log(float x, float y)
{
if (float.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (float.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
if (y == 1)
{
return float.NaN;
}
if ((x != 1) && ((y == 0) || float.IsPositiveInfinity(y)))
{
return float.NaN;
}
return Log(x) / Log(y);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Max(float x, float y)
{
return Math.Max(x, y);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Min(float x, float y)
{
return Math.Min(x, y);
}
[Intrinsic]
public static float Round(float x)
{
// ************************************************************************************
// IMPORTANT: Do not change this implementation without also updating Math.Round(double),
// FloatingPointUtils::round(double), and FloatingPointUtils::round(float)
// ************************************************************************************
// If the number has no fractional part do nothing
// This shortcut is necessary to workaround precision loss in borderline cases on some platforms
if (x == (float)((int)x))
{
return x;
}
// We had a number that was equally close to 2 integers.
// We need to return the even one.
float flrTempVal = Floor(x + 0.5f);
if ((x == (Floor(x) + 0.5f)) && (FMod(flrTempVal, 2.0f) != 0))
{
flrTempVal -= 1.0f;
}
return CopySign(flrTempVal, x);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Round(float x, int digits)
{
return Round(x, digits, MidpointRounding.ToEven);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Round(float x, MidpointRounding mode)
{
return Round(x, 0, mode);
}
public static unsafe float Round(float x, int digits, MidpointRounding mode)
{
if ((digits < 0) || (digits > maxRoundingDigits))
{
throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
}
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnum, mode, nameof(MidpointRounding)), nameof(mode));
}
if (Abs(x) < singleRoundLimit)
{
var power10 = roundPower10Single[digits];
x *= power10;
if (mode == MidpointRounding.AwayFromZero)
{
var fraction = ModF(x, &x);
if (Abs(fraction) >= 0.5f)
{
x += Sign(fraction);
}
}
else
{
x = Round(x);
}
x /= power10;
}
return x;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sign(float x)
{
return Math.Sign(x);
}
public static unsafe float Truncate(float x)
{
ModF(x, &x);
return x;
}
private static unsafe float CopySign(float x, float y)
{
var xbits = BitConverter.SingleToInt32Bits(x);
var ybits = BitConverter.SingleToInt32Bits(y);
// If the sign bits of x and y are not the same,
// flip the sign bit of x and return the new value;
// otherwise, just return x
if (((xbits ^ ybits) >> 31) != 0)
{
return BitConverter.Int32BitsToSingle(xbits ^ int.MinValue);
}
return x;
}
}
}
| |
// 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.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
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>
/// RecoverableDatabasesOperations operations.
/// </summary>
internal partial class RecoverableDatabasesOperations : IServiceOperations<SqlManagementClient>, IRecoverableDatabasesOperations
{
/// <summary>
/// Initializes a new instance of the RecoverableDatabasesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RecoverableDatabasesOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Gets a recoverable database, which is a resource representing a database's
/// geo backup
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecoverableDatabase>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
string apiVersion = "2014-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("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recoverableDatabases/{databaseName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecoverableDatabase>();
_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<RecoverableDatabase>(_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>
/// Gets a list of recoverable databases
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<RecoverableDatabase>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
string apiVersion = "2014-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("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByServer", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/recoverableDatabases").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<RecoverableDatabase>>();
_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<Page<RecoverableDatabase>>(_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 (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: TextWriter
**
** <OWNER>Microsoft</OWNER>
**
**
** Purpose: Abstract base class for Text-only Writers.
** Subclasses will include StreamWriter & StringWriter.
**
**
===========================================================*/
/*
* https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/textwriter.cs
*/
using System;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.IO
{
// This abstract base class represents a writer that can write a sequential
// stream of characters. A subclass must minimally implement the
// Write(char) method.
//
// This class is intended for character output, not bytes.
// There are methods on the Stream class for writing bytes.
public abstract class TextWriter : IDisposable
{
public static readonly TextWriter Null = new NullTextWriter();
// This should be initialized to Environment.NewLine, but
// to avoid loading Environment unnecessarily so I've duplicated
// the value here.
private const String InitialNewLine = "\r\n";
protected char[] CoreNewLine = new char[] { '\r', '\n' };
// Can be null - if so, ask for the Thread's CurrentCulture every time.
private IFormatProvider InternalFormatProvider;
protected TextWriter()
{
InternalFormatProvider = null; // Ask for CurrentCulture all the time.
}
protected TextWriter(IFormatProvider formatProvider)
{
InternalFormatProvider = formatProvider;
}
public virtual IFormatProvider FormatProvider
{
get
{
if (InternalFormatProvider == null)
return CultureInfo.CurrentCulture;
else
return InternalFormatProvider;
}
}
// Closes this TextWriter and releases any system resources associated with the
// TextWriter. Following a call to Close, any operations on the TextWriter
// may raise exceptions. This default method is empty, but descendant
// classes can override the method to provide the appropriate
// functionality.
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
}
public void Dispose()
{
Dispose(true);
}
// Clears all buffers for this TextWriter and causes any buffered data to be
// written to the underlying device. This default method is empty, but
// descendant classes can override the method to provide the appropriate
// functionality.
public virtual void Flush()
{
}
public abstract Encoding Encoding
{
get;
}
// Returns the line terminator string used by this TextWriter. The default line
// terminator string is a carriage return followed by a line feed ("\r\n").
//
// Sets the line terminator string for this TextWriter. The line terminator
// string is written to the text stream whenever one of the
// WriteLine methods are called. In order for text written by
// the TextWriter to be readable by a TextReader, only one of the following line
// terminator strings should be used: "\r", "\n", or "\r\n".
//
public virtual String NewLine
{
get
{
return new String(CoreNewLine);
}
set
{
if (value == null)
value = InitialNewLine;
CoreNewLine = value.ToCharArray();
}
}
[HostProtection(Synchronization = true)]
public static TextWriter Synchronized(TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
Contract.Ensures(Contract.Result<TextWriter>() != null);
Contract.EndContractBlock();
return writer;
}
// Writes a character to the text stream. This default method is empty,
// but descendant classes can override the method to provide the
// appropriate functionality.
//
public virtual void Write(char value)
{
}
// Writes a character array to the text stream. This default method calls
// Write(char) for each of the characters in the character array.
// If the character array is null, nothing is written.
//
public virtual void Write(char[] buffer)
{
if (buffer != null) Write(buffer, 0, buffer.Length);
}
// Writes a range of a character array to the text stream. This method will
// write count characters of data into this TextWriter from the
// buffer character array starting at position index.
//
public virtual void Write(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (buffer.Length - index < count)
throw new ArgumentException();
Contract.EndContractBlock();
for (int i = 0; i < count; i++) Write(buffer[index + i]);
}
// Writes the text representation of a boolean to the text stream. This
// method outputs either Boolean.TrueString or Boolean.FalseString.
//
public virtual void Write(bool value)
{
Write(value ? Boolean.TrueString : Boolean.FalseString);
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// Int32.ToString() method.
//
public virtual void Write(int value)
{
Write(value.ToString("G", FormatProvider));
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// UInt32.ToString() method.
//
[CLSCompliant(false)]
public virtual void Write(uint value)
{
Write(value.ToString("G", FormatProvider));
}
// Writes the text representation of a long to the text stream. The
// text representation of the given value is produced by calling the
// Int64.ToString() method.
//
public virtual void Write(long value)
{
Write(value.ToString("G", FormatProvider));
}
// Writes the text representation of an unsigned long to the text
// stream. The text representation of the given value is produced
// by calling the UInt64.ToString() method.
//
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
Write(value.ToString("G", FormatProvider));
}
// Writes the text representation of a float to the text stream. The
// text representation of the given value is produced by calling the
// Float.toString(float) method.
//
public virtual void Write(float value)
{
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a double to the text stream. The
// text representation of the given value is produced by calling the
// Double.toString(double) method.
//
public virtual void Write(double value)
{
Write(value.ToString(FormatProvider));
}
public virtual void Write(Decimal value)
{
Write(value.ToString(FormatProvider));
}
// Writes a string to the text stream. If the given string is null, nothing
// is written to the text stream.
//
public virtual void Write(String value)
{
if (value != null) Write(value.ToCharArray());
}
// Writes the text representation of an object to the text stream. If the
// given object is null, nothing is written to the text stream.
// Otherwise, the object's ToString method is called to produce the
// string representation, and the resulting string is then written to the
// output stream.
//
public virtual void Write(Object value)
{
if (value != null)
{
IFormattable f = value as IFormattable;
if (f != null)
Write(f.ToString(null, FormatProvider));
else
Write(value.ToString());
}
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0)
{
Write(String.Format(FormatProvider, format, arg0));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0, Object arg1)
{
Write(String.Format(FormatProvider, format, arg0, arg1));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0, Object arg1, Object arg2)
{
Write(String.Format(FormatProvider, format, arg0, arg1, arg2));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, params Object[] arg)
{
Write(String.Format(FormatProvider, format, arg));
}
// Writes a line terminator to the text stream. The default line terminator
// is a carriage return followed by a line feed ("\r\n"), but this value
// can be changed by setting the NewLine property.
//
public virtual void WriteLine()
{
Write(CoreNewLine);
}
// Writes a character followed by a line terminator to the text stream.
//
public virtual void WriteLine(char value)
{
Write(value);
WriteLine();
}
// Writes an array of characters followed by a line terminator to the text
// stream.
//
public virtual void WriteLine(char[] buffer)
{
Write(buffer);
WriteLine();
}
// Writes a range of a character array followed by a line terminator to the
// text stream.
//
public virtual void WriteLine(char[] buffer, int index, int count)
{
Write(buffer, index, count);
WriteLine();
}
// Writes the text representation of a boolean followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(bool value)
{
Write(value);
WriteLine();
}
// Writes the text representation of an integer followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(int value)
{
Write(value);
WriteLine();
}
// Writes the text representation of an unsigned integer followed by
// a line terminator to the text stream.
//
[CLSCompliant(false)]
public virtual void WriteLine(uint value)
{
Write(value);
WriteLine();
}
// Writes the text representation of a long followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(long value)
{
Write(value);
WriteLine();
}
// Writes the text representation of an unsigned long followed by
// a line terminator to the text stream.
//
[CLSCompliant(false)]
public virtual void WriteLine(ulong value)
{
Write(value);
WriteLine();
}
// Writes the text representation of a float followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(float value)
{
Write(value);
WriteLine();
}
// Writes the text representation of a double followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(double value)
{
Write(value);
WriteLine();
}
public virtual void WriteLine(decimal value)
{
Write(value);
WriteLine();
}
// Writes a string followed by a line terminator to the text stream.
//
public virtual void WriteLine(String value)
{
if (value == null)
{
WriteLine();
}
else
{
// We'd ideally like WriteLine to be atomic, in that one call
// to WriteLine equals one call to the OS (ie, so writing to
// console while simultaneously calling printf will guarantee we
// write out a string and new line chars, without any interference).
// Additionally, we need to call ToCharArray on Strings anyways,
// so allocating a char[] here isn't any worse than what we were
// doing anyways. We do reduce the number of calls to the
// backing store this way, potentially.
int vLen = value.Length;
int nlLen = CoreNewLine.Length;
char[] chars = new char[vLen + nlLen];
value.CopyTo(0, chars, 0, vLen);
// CoreNewLine will almost always be 2 chars, and possibly 1.
if (nlLen == 2)
{
chars[vLen] = CoreNewLine[0];
chars[vLen + 1] = CoreNewLine[1];
}
else if (nlLen == 1)
chars[vLen] = CoreNewLine[0];
else
Array.Copy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2);
Write(chars, 0, vLen + nlLen);
}
/*
Write(value); // We could call Write(String) on StreamWriter...
WriteLine();
*/
}
// Writes the text representation of an object followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(Object value)
{
if (value == null)
{
WriteLine();
}
else
{
// Call WriteLine(value.ToString), not Write(Object), WriteLine().
// This makes calls to WriteLine(Object) atomic.
IFormattable f = value as IFormattable;
if (f != null)
WriteLine(f.ToString(null, FormatProvider));
else
WriteLine(value.ToString());
}
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine(String format, Object arg0)
{
WriteLine(String.Format(FormatProvider, format, arg0));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine(String format, Object arg0, Object arg1)
{
WriteLine(String.Format(FormatProvider, format, arg0, arg1));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
WriteLine(String.Format(FormatProvider, format, arg0, arg1, arg2));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine(String format, params Object[] arg)
{
WriteLine(String.Format(FormatProvider, format, arg));
}
#if FEATURE_ASYNC_IO
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char value)
{
Tuple<TextWriter, char> tuple = new Tuple<TextWriter, char>(this, value);
return Task.Factory.StartNew(_WriteCharDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(String value)
{
Tuple<TextWriter, string> tuple = new Tuple<TextWriter, string>(this, value);
return Task.Factory.StartNew(_WriteStringDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(char[] buffer)
{
if (buffer == null) return Task.CompletedTask;
return WriteAsync(buffer, 0, buffer.Length);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char[] buffer, int index, int count)
{
Tuple<TextWriter, char[], int, int> tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
return Task.Factory.StartNew(_WriteCharArrayRangeDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char value)
{
Tuple<TextWriter, char> tuple = new Tuple<TextWriter, char>(this, value);
return Task.Factory.StartNew(_WriteLineCharDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(String value)
{
Tuple<TextWriter, string> tuple = new Tuple<TextWriter, string>(this, value);
return Task.Factory.StartNew(_WriteLineStringDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteLineAsync(char[] buffer)
{
if (buffer == null) return Task.CompletedTask;
return WriteLineAsync(buffer, 0, buffer.Length);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char[] buffer, int index, int count)
{
Tuple<TextWriter, char[], int, int> tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
return Task.Factory.StartNew(_WriteLineCharArrayRangeDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync()
{
return WriteAsync(CoreNewLine);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task FlushAsync()
{
return Task.Factory.StartNew(_FlushDelegate, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
#endregion
#endif //FEATURE_ASYNC_IO
[Serializable]
private sealed class NullTextWriter : TextWriter
{
internal NullTextWriter() : base(CultureInfo.InvariantCulture)
{
}
public override Encoding Encoding
{
get
{
return Encoding.Default;
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void Write(char[] buffer, int index, int count)
{
}
public override void Write(String value)
{
}
// Not strictly necessary, but for perf reasons
public override void WriteLine()
{
}
// Not strictly necessary, but for perf reasons
public override void WriteLine(String value)
{
}
public override void WriteLine(Object value)
{
}
}
}
}
| |
// ****************************************************************
// Copyright 2008, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace NUnit.UiKit
{
/// <summary>
/// Summary description for EditTabPagesDialog.
/// </summary>
public class EditTabPagesDialog : System.Windows.Forms.Form
{
private TextDisplayTabSettings tabSettings;
private int selectedIndex = -1;
private System.Windows.Forms.Button addButton;
private System.Windows.Forms.Button closeButton;
private System.Windows.Forms.Button removeButton;
private System.Windows.Forms.ListBox tabPageListBox;
private System.Windows.Forms.Button moveDownButton;
private System.Windows.Forms.Button moveUpButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public EditTabPagesDialog(TextDisplayTabSettings tabSettings)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
this.tabSettings = tabSettings;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form 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.addButton = new System.Windows.Forms.Button();
this.closeButton = new System.Windows.Forms.Button();
this.removeButton = new System.Windows.Forms.Button();
this.tabPageListBox = new System.Windows.Forms.ListBox();
this.moveUpButton = new System.Windows.Forms.Button();
this.moveDownButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// addButton
//
this.addButton.Location = new System.Drawing.Point(192, 48);
this.addButton.Name = "addButton";
this.addButton.Size = new System.Drawing.Size(96, 32);
this.addButton.TabIndex = 10;
this.addButton.Text = "&Add...";
this.addButton.Click += new System.EventHandler(this.addButton_Click);
//
// closeButton
//
this.closeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.closeButton.Location = new System.Drawing.Point(190, 218);
this.closeButton.Name = "closeButton";
this.closeButton.Size = new System.Drawing.Size(96, 32);
this.closeButton.TabIndex = 9;
this.closeButton.Text = "Close";
//
// removeButton
//
this.removeButton.Location = new System.Drawing.Point(190, 10);
this.removeButton.Name = "removeButton";
this.removeButton.Size = new System.Drawing.Size(96, 32);
this.removeButton.TabIndex = 7;
this.removeButton.Text = "&Remove";
this.removeButton.Click += new System.EventHandler(this.removeButton_Click);
//
// tabPageListBox
//
this.tabPageListBox.ItemHeight = 16;
this.tabPageListBox.Location = new System.Drawing.Point(6, 10);
this.tabPageListBox.Name = "tabPageListBox";
this.tabPageListBox.Size = new System.Drawing.Size(168, 212);
this.tabPageListBox.TabIndex = 6;
this.tabPageListBox.SelectedIndexChanged += new System.EventHandler(this.tabPageListBox_SelectedIndexChanged);
//
// moveUpButton
//
this.moveUpButton.Location = new System.Drawing.Point(192, 88);
this.moveUpButton.Name = "moveUpButton";
this.moveUpButton.Size = new System.Drawing.Size(96, 32);
this.moveUpButton.TabIndex = 11;
this.moveUpButton.Text = "Move Up";
this.moveUpButton.Click += new System.EventHandler(this.moveUpButton_Click);
//
// moveDownButton
//
this.moveDownButton.Location = new System.Drawing.Point(192, 128);
this.moveDownButton.Name = "moveDownButton";
this.moveDownButton.Size = new System.Drawing.Size(96, 32);
this.moveDownButton.TabIndex = 12;
this.moveDownButton.Text = "Move Down";
this.moveDownButton.Click += new System.EventHandler(this.moveDownButton_Click);
//
// EditTabPagesDialog
//
this.AcceptButton = this.closeButton;
this.CancelButton = this.closeButton;
this.ClientSize = new System.Drawing.Size(292, 260);
this.ControlBox = false;
this.Controls.Add(this.moveDownButton);
this.Controls.Add(this.moveUpButton);
this.Controls.Add(this.addButton);
this.Controls.Add(this.closeButton);
this.Controls.Add(this.removeButton);
this.Controls.Add(this.tabPageListBox);
this.Name = "EditTabPagesDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Edit Tab Pages";
this.Load += new System.EventHandler(this.EditTabPagesDialog_Load);
this.ResumeLayout(false);
}
#endregion
private void EditTabPagesDialog_Load(object sender, System.EventArgs e)
{
FillListBox();
if ( tabPageListBox.Items.Count > 0 )
tabPageListBox.SelectedIndex = selectedIndex = 0;
}
private void tabPageListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
selectedIndex = tabPageListBox.SelectedIndex;
removeButton.Enabled = selectedIndex >= 0;
moveUpButton.Enabled = selectedIndex > 0;
moveDownButton.Enabled = selectedIndex >= 0 && selectedIndex < tabPageListBox.Items.Count - 1;
}
private void addButton_Click(object sender, System.EventArgs e)
{
using( AddTabPageDialog dlg = new AddTabPageDialog(tabSettings) )
{
this.Site.Container.Add( dlg );
if ( dlg.ShowDialog() == DialogResult.OK )
FillListBox();
}
}
private void removeButton_Click(object sender, System.EventArgs e)
{
tabSettings.Tabs.RemoveAt(selectedIndex);
FillListBox();
}
private void renameButton_Click(object sender, System.EventArgs e)
{
tabSettings.Tabs[selectedIndex].Title = "";
}
#region Helper Methods
private void FillListBox()
{
tabPageListBox.Items.Clear();
foreach( TextDisplayTabSettings.TabInfo tab in tabSettings.Tabs )
tabPageListBox.Items.Add( tab.Title );
int count = tabPageListBox.Items.Count;
if ( count > 0 )
{
if ( selectedIndex >= count )
selectedIndex = count - 1;
tabPageListBox.SelectedIndex = selectedIndex;
}
else selectedIndex = -1;
}
#endregion
private void moveUpButton_Click(object sender, System.EventArgs e)
{
TextDisplayTabSettings.TabInfo tab = tabSettings.Tabs[selectedIndex];
tabSettings.Tabs.RemoveAt(selectedIndex--);
tabSettings.Tabs.Insert(selectedIndex, tab );
FillListBox();
}
private void moveDownButton_Click(object sender, System.EventArgs e)
{
TextDisplayTabSettings.TabInfo tab = tabSettings.Tabs[selectedIndex];
tabSettings.Tabs.RemoveAt(selectedIndex++);
tabSettings.Tabs.Insert(selectedIndex, tab );
FillListBox();
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Security.Principal;
using EventStore.Common.Utils;
using EventStore.Core.Bus;
using EventStore.Core.Data;
using EventStore.Core.Helpers;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Core.Services.UserManagement;
using EventStore.Projections.Core.Messages;
namespace EventStore.Projections.Core.Services.Processing
{
public class DefaultCheckpointManager : CoreProjectionCheckpointManager,
IHandle<CoreProjectionCheckpointWriterMessage.CheckpointWritten>,
IHandle<CoreProjectionCheckpointWriterMessage.RestartRequested>
{
private readonly IPrincipal _runAs;
private readonly CheckpointTag _zeroTag;
private int _readRequestsInProgress;
private readonly HashSet<Guid> _loadStateRequests = new HashSet<Guid>();
protected readonly ProjectionVersion _projectionVersion;
protected readonly IODispatcher _ioDispatcher;
private readonly PositionTagger _positionTagger;
private readonly CoreProjectionCheckpointWriter _coreProjectionCheckpointWriter;
private PartitionStateUpdateManager _partitionStateUpdateManager;
public DefaultCheckpointManager(
IPublisher publisher, Guid projectionCorrelationId, ProjectionVersion projectionVersion, IPrincipal runAs,
IODispatcher ioDispatcher, ProjectionConfig projectionConfig, string name, PositionTagger positionTagger,
ProjectionNamesBuilder namingBuilder, bool usePersistentCheckpoints, bool producesRunningResults, bool definesFold,
CoreProjectionCheckpointWriter coreProjectionCheckpointWriter)
: base(
publisher, projectionCorrelationId, projectionConfig, name, positionTagger, namingBuilder,
usePersistentCheckpoints, producesRunningResults)
{
if (ioDispatcher == null) throw new ArgumentNullException("ioDispatcher");
_projectionVersion = projectionVersion;
_runAs = runAs;
_ioDispatcher = ioDispatcher;
_positionTagger = positionTagger;
_coreProjectionCheckpointWriter = coreProjectionCheckpointWriter;
_zeroTag = positionTagger.MakeZeroCheckpointTag();
}
protected override void BeginWriteCheckpoint(
CheckpointTag requestedCheckpointPosition, string requestedCheckpointState)
{
_requestedCheckpointPosition = requestedCheckpointPosition;
_coreProjectionCheckpointWriter.BeginWriteCheckpoint(
new SendToThisEnvelope(this), requestedCheckpointPosition, requestedCheckpointState);
}
public override void RecordEventOrder(
ResolvedEvent resolvedEvent, CheckpointTag orderCheckpointTag, Action committed)
{
committed();
}
public override void PartitionCompleted(string partition)
{
_partitionStateUpdateManager.PartitionCompleted(partition);
}
public override void Initialize()
{
base.Initialize();
_partitionStateUpdateManager = null;
foreach (var requestId in _loadStateRequests)
_ioDispatcher.BackwardReader.Cancel(requestId);
_loadStateRequests.Clear();
_coreProjectionCheckpointWriter.Initialize();
_requestedCheckpointPosition = null;
_readRequestsInProgress = 0;
}
public override void GetStatistics(ProjectionStatistics info)
{
base.GetStatistics(info);
info.ReadsInProgress += _readRequestsInProgress;
_coreProjectionCheckpointWriter.GetStatistics(info);
}
public override void BeginLoadPartitionStateAt(
string statePartition, CheckpointTag requestedStateCheckpointTag, Action<PartitionState> loadCompleted)
{
var stateEventType = ProjectionNamesBuilder.EventType_PartitionCheckpoint;
var partitionCheckpointStreamName = _namingBuilder.MakePartitionCheckpointStreamName(statePartition);
_readRequestsInProgress++;
var requestId = _ioDispatcher.ReadBackward(
partitionCheckpointStreamName, -1, 1, false, SystemAccount.Principal,
m =>
OnLoadPartitionStateReadStreamEventsBackwardCompleted(
m, requestedStateCheckpointTag, loadCompleted, partitionCheckpointStreamName, stateEventType));
if (requestId != Guid.Empty)
_loadStateRequests.Add(requestId);
}
private void OnLoadPartitionStateReadStreamEventsBackwardCompleted(
ClientMessage.ReadStreamEventsBackwardCompleted message, CheckpointTag requestedStateCheckpointTag,
Action<PartitionState> loadCompleted, string partitionStreamName, string stateEventType)
{
//NOTE: the following remove may do nothing in tests as completed is raised before we return from publish.
_loadStateRequests.Remove(message.CorrelationId);
_readRequestsInProgress--;
if (message.Events.Length == 1)
{
EventRecord @event = message.Events[0].Event;
if (@event.EventType == stateEventType)
{
var parsed = @event.Metadata.ParseCheckpointTagVersionExtraJson(_projectionVersion);
if (parsed.Version.ProjectionId != _projectionVersion.ProjectionId
|| _projectionVersion.Epoch > parsed.Version.Version)
{
var state = new PartitionState("", null, _zeroTag);
loadCompleted(state);
return;
}
else
{
var loadedStateCheckpointTag = parsed.AdjustBy(_positionTagger, _projectionVersion);
// always recovery mode? skip until state before current event
//TODO: skip event processing in case we know i has been already processed
if (loadedStateCheckpointTag < requestedStateCheckpointTag)
{
var state = PartitionState.Deserialize(
Helper.UTF8NoBom.GetString(@event.Data), loadedStateCheckpointTag);
loadCompleted(state);
return;
}
}
}
}
if (message.NextEventNumber == -1)
{
var state = new PartitionState("", null, _zeroTag);
loadCompleted(state);
return;
}
_readRequestsInProgress++;
var requestId = _ioDispatcher.ReadBackward(
partitionStreamName, message.NextEventNumber, 1, false, SystemAccount.Principal,
m =>
OnLoadPartitionStateReadStreamEventsBackwardCompleted(
m, requestedStateCheckpointTag, loadCompleted, partitionStreamName, stateEventType));
if (requestId != Guid.Empty)
_loadStateRequests.Add(requestId);
}
protected override ProjectionCheckpoint CreateProjectionCheckpoint(CheckpointTag checkpointPosition)
{
return new ProjectionCheckpoint(
_ioDispatcher, _projectionVersion, _runAs, this, checkpointPosition, _positionTagger, _zeroTag,
_projectionConfig.MaxWriteBatchLength, _logger);
}
public void Handle(CoreProjectionCheckpointWriterMessage.CheckpointWritten message)
{
CheckpointWritten(message.Position);
}
public void Handle(CoreProjectionCheckpointWriterMessage.RestartRequested message)
{
RequestRestart(message.Reason);
}
protected override void CapturePartitionStateUpdated(string partition, PartitionState oldState, PartitionState newState)
{
if (_partitionStateUpdateManager == null)
_partitionStateUpdateManager = new PartitionStateUpdateManager(_namingBuilder);
_partitionStateUpdateManager.StateUpdated(partition, newState, oldState.CausedBy);
}
protected override void EmitPartitionCheckpoints()
{
if (_partitionStateUpdateManager != null)
{
_partitionStateUpdateManager.EmitEvents(_currentCheckpoint);
_partitionStateUpdateManager = null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Diagnostics;
using System.Globalization;
using System.IO.Pipelines;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
{
internal partial class Http1Connection : HttpProtocol, IRequestProcessor, IHttpOutputAborter
{
private const byte ByteAsterisk = (byte)'*';
private const byte ByteForwardSlash = (byte)'/';
private const string Asterisk = "*";
private const string ForwardSlash = "/";
private readonly HttpConnectionContext _context;
private readonly IHttpParser<Http1ParsingHandler> _parser;
private readonly Http1OutputProducer _http1Output;
protected readonly long _keepAliveTicks;
private readonly long _requestHeadersTimeoutTicks;
private volatile bool _requestTimedOut;
private uint _requestCount;
private HttpRequestTarget _requestTargetForm = HttpRequestTarget.Unknown;
private Uri? _absoluteRequestTarget;
// The _parsed fields cache the Path, QueryString, RawTarget, and/or _absoluteRequestTarget
// from the previous request when DisableStringReuse is false.
private string? _parsedPath;
private string? _parsedQueryString;
private string? _parsedRawTarget;
private Uri? _parsedAbsoluteRequestTarget;
private long _remainingRequestHeadersBytesAllowed;
public Http1Connection(HttpConnectionContext context)
{
Initialize(context);
_context = context;
_parser = ServiceContext.HttpParser;
_keepAliveTicks = ServerOptions.Limits.KeepAliveTimeout.Ticks;
_requestHeadersTimeoutTicks = ServerOptions.Limits.RequestHeadersTimeout.Ticks;
_http1Output = new Http1OutputProducer(
_context.Transport.Output,
_context.ConnectionId,
_context.ConnectionContext,
_context.MemoryPool,
_context.ServiceContext.Log,
_context.TimeoutControl,
minResponseDataRateFeature: this,
outputAborter: this);
Input = _context.Transport.Input;
Output = _http1Output;
MemoryPool = _context.MemoryPool;
}
public PipeReader Input { get; }
public bool RequestTimedOut => _requestTimedOut;
public MinDataRate? MinResponseDataRate { get; set; }
public MemoryPool<byte> MemoryPool { get; }
protected override void OnRequestProcessingEnded()
{
if (IsUpgraded)
{
KestrelEventSource.Log.RequestUpgradedStop(this);
ServiceContext.ConnectionManager.UpgradedConnectionCount.ReleaseOne();
}
TimeoutControl.StartDrainTimeout(MinResponseDataRate, ServerOptions.Limits.MaxResponseBufferSize);
// Prevent RequestAborted from firing. Free up unneeded feature references.
Reset();
_http1Output.Dispose();
}
public void OnInputOrOutputCompleted()
{
_http1Output.Abort(new ConnectionAbortedException(CoreStrings.ConnectionAbortedByClient));
CancelRequestAbortedToken();
}
/// <summary>
/// Immediately kill the connection and poison the request body stream with an error.
/// </summary>
public void Abort(ConnectionAbortedException abortReason)
{
_http1Output.Abort(abortReason);
CancelRequestAbortedToken();
PoisonBody(abortReason);
}
protected override void ApplicationAbort()
{
Log.ApplicationAbortedConnection(ConnectionId, TraceIdentifier);
Abort(new ConnectionAbortedException(CoreStrings.ConnectionAbortedByApplication));
}
/// <summary>
/// Stops the request processing loop between requests.
/// Called on all active connections when the server wants to initiate a shutdown
/// and after a keep-alive timeout.
/// </summary>
public void StopProcessingNextRequest()
{
_keepAlive = false;
Input.CancelPendingRead();
}
public void SendTimeoutResponse()
{
_requestTimedOut = true;
Input.CancelPendingRead();
}
public void HandleRequestHeadersTimeout()
=> SendTimeoutResponse();
public void HandleReadDataRateTimeout()
{
Debug.Assert(MinRequestBodyDataRate != null);
Log.RequestBodyMinimumDataRateNotSatisfied(ConnectionId, TraceIdentifier, MinRequestBodyDataRate.BytesPerSecond);
SendTimeoutResponse();
}
public bool ParseRequest(ref SequenceReader<byte> reader)
{
switch (_requestProcessingStatus)
{
case RequestProcessingStatus.RequestPending:
if (reader.End)
{
break;
}
TimeoutControl.ResetTimeout(_requestHeadersTimeoutTicks, TimeoutReason.RequestHeaders);
_requestProcessingStatus = RequestProcessingStatus.ParsingRequestLine;
goto case RequestProcessingStatus.ParsingRequestLine;
case RequestProcessingStatus.ParsingRequestLine:
if (TakeStartLine(ref reader))
{
_requestProcessingStatus = RequestProcessingStatus.ParsingHeaders;
goto case RequestProcessingStatus.ParsingHeaders;
}
else
{
break;
}
case RequestProcessingStatus.ParsingHeaders:
if (TakeMessageHeaders(ref reader, trailers: false))
{
_requestProcessingStatus = RequestProcessingStatus.AppStarted;
// Consumed preamble
return true;
}
break;
}
// Haven't completed consuming preamble
return false;
}
public bool TakeStartLine(ref SequenceReader<byte> reader)
{
// Make sure the buffer is limited
if (reader.Remaining >= ServerOptions.Limits.MaxRequestLineSize)
{
// Input oversize, cap amount checked
return TrimAndTakeStartLine(ref reader);
}
return _parser.ParseRequestLine(new Http1ParsingHandler(this), ref reader);
bool TrimAndTakeStartLine(ref SequenceReader<byte> reader)
{
var trimmedBuffer = reader.Sequence.Slice(reader.Position, ServerOptions.Limits.MaxRequestLineSize);
var trimmedReader = new SequenceReader<byte>(trimmedBuffer);
if (!_parser.ParseRequestLine(new Http1ParsingHandler(this), ref trimmedReader))
{
// We read the maximum allowed but didn't complete the start line.
KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestLineTooLong);
}
reader.Advance(trimmedReader.Consumed);
return true;
}
}
public bool TakeMessageHeaders(ref SequenceReader<byte> reader, bool trailers)
{
// Make sure the buffer is limited
if (reader.Remaining > _remainingRequestHeadersBytesAllowed)
{
// Input oversize, cap amount checked
return TrimAndTakeMessageHeaders(ref reader, trailers);
}
var alreadyConsumed = reader.Consumed;
try
{
var result = _parser.ParseHeaders(new Http1ParsingHandler(this, trailers), ref reader);
if (result)
{
TimeoutControl.CancelTimeout();
}
return result;
}
finally
{
_remainingRequestHeadersBytesAllowed -= reader.Consumed - alreadyConsumed;
}
bool TrimAndTakeMessageHeaders(ref SequenceReader<byte> reader, bool trailers)
{
var trimmedBuffer = reader.Sequence.Slice(reader.Position, _remainingRequestHeadersBytesAllowed);
var trimmedReader = new SequenceReader<byte>(trimmedBuffer);
try
{
if (!_parser.ParseHeaders(new Http1ParsingHandler(this, trailers), ref trimmedReader))
{
// We read the maximum allowed but didn't complete the headers.
KestrelBadHttpRequestException.Throw(RequestRejectionReason.HeadersExceedMaxTotalSize);
}
TimeoutControl.CancelTimeout();
reader.Advance(trimmedReader.Consumed);
return true;
}
finally
{
_remainingRequestHeadersBytesAllowed -= trimmedReader.Consumed;
}
}
}
public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
{
var targetStart = targetPath.Offset;
// Slice out target
var target = startLine[targetStart..];
Debug.Assert(target.Length != 0, "Request target must be non-zero length");
var method = versionAndMethod.Method;
var ch = target[0];
if (ch == ByteForwardSlash)
{
// origin-form.
// The most common form of request-target.
// https://tools.ietf.org/html/rfc7230#section-5.3.1
OnOriginFormTarget(targetPath, target);
}
else if (ch == ByteAsterisk && target.Length == 1)
{
OnAsteriskFormTarget(method);
}
else if (startLine[targetStart..].GetKnownHttpScheme(out _))
{
OnAbsoluteFormTarget(targetPath, target);
}
else
{
// Assume anything else is considered authority form.
// FYI: this should be an edge case. This should only happen when
// a client mistakenly thinks this server is a proxy server.
OnAuthorityFormTarget(method, target);
}
Method = method;
if (method == HttpMethod.Custom)
{
_methodText = startLine[..versionAndMethod.MethodEnd].GetAsciiStringNonNullCharacters();
}
_httpVersion = versionAndMethod.Version;
Debug.Assert(RawTarget != null, "RawTarget was not set");
Debug.Assert(((IHttpRequestFeature)this).Method != null, "Method was not set");
Debug.Assert(Path != null, "Path was not set");
Debug.Assert(QueryString != null, "QueryString was not set");
Debug.Assert(HttpVersion != null, "HttpVersion was not set");
}
// Compare with Http2Stream.TryValidatePseudoHeaders
private void OnOriginFormTarget(TargetOffsetPathLength targetPath, Span<byte> target)
{
Debug.Assert(target[0] == ByteForwardSlash, "Should only be called when path starts with /");
_requestTargetForm = HttpRequestTarget.OriginForm;
if (target.Length == 1)
{
// If target.Length == 1 it can only be a forward slash (e.g. home page)
// and we know RawTarget and Path are the same and QueryString is Empty
RawTarget = ForwardSlash;
Path = ForwardSlash;
QueryString = string.Empty;
// Clear parsedData as we won't check it if we come via this path again,
// an setting to null is fast as it doesn't need to use a GC write barrier.
_parsedRawTarget = _parsedPath = _parsedQueryString = null;
_parsedAbsoluteRequestTarget = null;
return;
}
// Read raw target before mutating memory.
var previousValue = _parsedRawTarget;
if (ServerOptions.DisableStringReuse ||
previousValue == null || previousValue.Length != target.Length ||
!StringUtilities.BytesOrdinalEqualsStringAndAscii(previousValue, target))
{
ParseTarget(targetPath, target);
}
else
{
// As RawTarget is the same we can reuse the previous parsed values.
RawTarget = previousValue;
Path = _parsedPath;
QueryString = _parsedQueryString;
}
// Clear parsedData for absolute target as we won't check it if we come via this path again,
// an setting to null is fast as it doesn't need to use a GC write barrier.
_parsedAbsoluteRequestTarget = null;
}
private void ParseTarget(TargetOffsetPathLength targetPath, Span<byte> target)
{
// URIs are always encoded/escaped to ASCII https://tools.ietf.org/html/rfc3986#page-11
// Multibyte Internationalized Resource Identifiers (IRIs) are first converted to utf8;
// then encoded/escaped to ASCII https://www.ietf.org/rfc/rfc3987.txt "Mapping of IRIs to URIs"
try
{
// The previous string does not match what the bytes would convert to,
// so we will need to generate a new string.
RawTarget = _parsedRawTarget = target.GetAsciiStringNonNullCharacters();
var queryLength = 0;
if (target.Length == targetPath.Length)
{
// No query string
if (ReferenceEquals(_parsedQueryString, string.Empty))
{
QueryString = _parsedQueryString;
}
else
{
QueryString = string.Empty;
_parsedQueryString = string.Empty;
}
}
else
{
queryLength = ParseQuery(targetPath, target);
}
var pathLength = targetPath.Length;
if (pathLength == 1)
{
// If path.Length == 1 it can only be a forward slash (e.g. home page)
Path = _parsedPath = ForwardSlash;
}
else
{
var path = target[..pathLength];
Path = _parsedPath = PathNormalizer.DecodePath(path, targetPath.IsEncoded, RawTarget, queryLength);
}
}
catch (InvalidOperationException)
{
ThrowRequestTargetRejected(target);
}
}
private int ParseQuery(TargetOffsetPathLength targetPath, Span<byte> target)
{
var previousValue = _parsedQueryString;
var query = target[targetPath.Length..];
var queryLength = query.Length;
if (ServerOptions.DisableStringReuse ||
previousValue == null || previousValue.Length != queryLength ||
!StringUtilities.BytesOrdinalEqualsStringAndAscii(previousValue, query))
{
// The previous string does not match what the bytes would convert to,
// so we will need to generate a new string.
QueryString = _parsedQueryString = query.GetAsciiStringNonNullCharacters();
}
else
{
// Same as previous
QueryString = _parsedQueryString;
}
return queryLength;
}
private void OnAuthorityFormTarget(HttpMethod method, Span<byte> target)
{
_requestTargetForm = HttpRequestTarget.AuthorityForm;
// This is not complete validation. It is just a quick scan for invalid characters
// but doesn't check that the target fully matches the URI spec.
if (HttpCharacters.ContainsInvalidAuthorityChar(target))
{
ThrowRequestTargetRejected(target);
}
// The authority-form of request-target is only used for CONNECT
// requests (https://tools.ietf.org/html/rfc7231#section-4.3.6).
if (method != HttpMethod.Connect)
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.ConnectMethodRequired);
}
// When making a CONNECT request to establish a tunnel through one or
// more proxies, a client MUST send only the target URI's authority
// component (excluding any userinfo and its "@" delimiter) as the
// request-target.For example,
//
// CONNECT www.example.com:80 HTTP/1.1
//
// Allowed characters in the 'host + port' section of authority.
// See https://tools.ietf.org/html/rfc3986#section-3.2
var previousValue = _parsedRawTarget;
if (ServerOptions.DisableStringReuse ||
previousValue == null || previousValue.Length != target.Length ||
!StringUtilities.BytesOrdinalEqualsStringAndAscii(previousValue, target))
{
// The previous string does not match what the bytes would convert to,
// so we will need to generate a new string.
RawTarget = _parsedRawTarget = target.GetAsciiStringNonNullCharacters();
}
else
{
// Reuse previous value
RawTarget = _parsedRawTarget;
}
Path = string.Empty;
QueryString = string.Empty;
// Clear parsedData for path, queryString and absolute target as we won't check it if we come via this path again,
// an setting to null is fast as it doesn't need to use a GC write barrier.
_parsedPath = _parsedQueryString = null;
_parsedAbsoluteRequestTarget = null;
}
private void OnAsteriskFormTarget(HttpMethod method)
{
_requestTargetForm = HttpRequestTarget.AsteriskForm;
// The asterisk-form of request-target is only used for a server-wide
// OPTIONS request (https://tools.ietf.org/html/rfc7231#section-4.3.7).
if (method != HttpMethod.Options)
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.OptionsMethodRequired);
}
RawTarget = Asterisk;
Path = string.Empty;
QueryString = string.Empty;
// Clear parsedData as we won't check it if we come via this path again,
// an setting to null is fast as it doesn't need to use a GC write barrier.
_parsedRawTarget = _parsedPath = _parsedQueryString = null;
_parsedAbsoluteRequestTarget = null;
}
private void OnAbsoluteFormTarget(TargetOffsetPathLength targetPath, Span<byte> target)
{
Span<byte> query = target[targetPath.Length..];
_requestTargetForm = HttpRequestTarget.AbsoluteForm;
// absolute-form
// https://tools.ietf.org/html/rfc7230#section-5.3.2
// This code should be the edge-case.
// From the spec:
// a server MUST accept the absolute-form in requests, even though
// HTTP/1.1 clients will only send them in requests to proxies.
var disableStringReuse = ServerOptions.DisableStringReuse;
var previousValue = _parsedRawTarget;
if (disableStringReuse ||
previousValue == null || previousValue.Length != target.Length ||
!StringUtilities.BytesOrdinalEqualsStringAndAscii(previousValue, target))
{
// The previous string does not match what the bytes would convert to,
// so we will need to generate a new string.
RawTarget = _parsedRawTarget = target.GetAsciiStringNonNullCharacters();
// Validation of absolute URIs is slow, but clients
// should not be sending this form anyways, so perf optimization
// not high priority
if (!Uri.TryCreate(RawTarget, UriKind.Absolute, out var uri))
{
ThrowRequestTargetRejected(target);
}
_absoluteRequestTarget = _parsedAbsoluteRequestTarget = uri;
Path = _parsedPath = uri.LocalPath;
// don't use uri.Query because we need the unescaped version
previousValue = _parsedQueryString;
if (disableStringReuse ||
previousValue == null || previousValue.Length != query.Length ||
!StringUtilities.BytesOrdinalEqualsStringAndAscii(previousValue, query))
{
// The previous string does not match what the bytes would convert to,
// so we will need to generate a new string.
QueryString = _parsedQueryString = query.GetAsciiStringNonNullCharacters();
}
else
{
QueryString = _parsedQueryString;
}
}
else
{
// As RawTarget is the same we can reuse the previous values.
RawTarget = _parsedRawTarget;
Path = _parsedPath;
QueryString = _parsedQueryString;
_absoluteRequestTarget = _parsedAbsoluteRequestTarget;
}
}
internal void EnsureHostHeaderExists()
{
// https://tools.ietf.org/html/rfc7230#section-5.4
// A server MUST respond with a 400 (Bad Request) status code to any
// HTTP/1.1 request message that lacks a Host header field and to any
// request message that contains more than one Host header field or a
// Host header field with an invalid field-value.
var hostCount = HttpRequestHeaders.HostCount;
var hostText = HttpRequestHeaders.HeaderHost.ToString();
if (hostCount <= 0)
{
if (_httpVersion == Http.HttpVersion.Http10)
{
return;
}
KestrelBadHttpRequestException.Throw(RequestRejectionReason.MissingHostHeader);
}
else if (hostCount > 1)
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.MultipleHostHeaders);
}
else if (_requestTargetForm != HttpRequestTarget.OriginForm)
{
// Tail call
ValidateNonOriginHostHeader(hostText);
}
else if (!HttpUtilities.IsHostHeaderValid(hostText))
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidHostHeader, hostText);
}
}
private void ValidateNonOriginHostHeader(string hostText)
{
if (_requestTargetForm == HttpRequestTarget.AuthorityForm)
{
if (hostText != RawTarget)
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidHostHeader, hostText);
}
}
else if (_requestTargetForm == HttpRequestTarget.AbsoluteForm)
{
// If the target URI includes an authority component, then a
// client MUST send a field - value for Host that is identical to that
// authority component, excluding any userinfo subcomponent and its "@"
// delimiter.
// System.Uri doesn't not tell us if the port was in the original string or not.
// When IsDefaultPort = true, we will allow Host: with or without the default port
if (hostText != _absoluteRequestTarget!.Authority)
{
if (!_absoluteRequestTarget.IsDefaultPort
|| hostText != _absoluteRequestTarget.Authority + ":" + _absoluteRequestTarget.Port.ToString(CultureInfo.InvariantCulture))
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidHostHeader, hostText);
}
}
}
if (!HttpUtilities.IsHostHeaderValid(hostText))
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidHostHeader, hostText);
}
}
protected override void OnReset()
{
_requestTimedOut = false;
_requestTargetForm = HttpRequestTarget.Unknown;
_absoluteRequestTarget = null;
_remainingRequestHeadersBytesAllowed = ServerOptions.Limits.MaxRequestHeadersTotalSize + 2;
_requestCount++;
MinResponseDataRate = ServerOptions.Limits.MinResponseDataRate;
// Reset Http1 Features
_currentIHttpMinRequestBodyDataRateFeature = this;
_currentIHttpMinResponseDataRateFeature = this;
_currentIPersistentStateFeature = this;
}
protected override void OnRequestProcessingEnding()
{
}
protected override string CreateRequestId()
=> StringUtilities.ConcatAsHexSuffix(ConnectionId, ':', _requestCount);
protected override MessageBody CreateMessageBody()
=> Http1MessageBody.For(_httpVersion, HttpRequestHeaders, this);
protected override void BeginRequestProcessing()
{
// Reset the features and timeout.
Reset();
TimeoutControl.SetTimeout(_keepAliveTicks, TimeoutReason.KeepAlive);
}
protected override bool BeginRead(out ValueTask<ReadResult> awaitable)
{
awaitable = Input.ReadAsync();
return true;
}
protected override bool TryParseRequest(ReadResult result, out bool endConnection)
{
var reader = new SequenceReader<byte>(result.Buffer);
var isConsumed = false;
try
{
isConsumed = ParseRequest(ref reader);
}
catch (InvalidOperationException)
{
if (_requestProcessingStatus == RequestProcessingStatus.ParsingHeaders)
{
KestrelBadHttpRequestException.Throw(RequestRejectionReason.MalformedRequestInvalidHeaders);
}
throw;
}
finally
{
Input.AdvanceTo(reader.Position, isConsumed ? reader.Position : result.Buffer.End);
}
if (result.IsCompleted)
{
switch (_requestProcessingStatus)
{
case RequestProcessingStatus.RequestPending:
endConnection = true;
return true;
case RequestProcessingStatus.ParsingRequestLine:
KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidRequestLine);
break;
case RequestProcessingStatus.ParsingHeaders:
KestrelBadHttpRequestException.Throw(RequestRejectionReason.MalformedRequestInvalidHeaders);
break;
}
}
else if (!_keepAlive && _requestProcessingStatus == RequestProcessingStatus.RequestPending)
{
// Stop the request processing loop if the server is shutting down or there was a keep-alive timeout
// and there is no ongoing request.
endConnection = true;
return true;
}
else if (RequestTimedOut)
{
// In this case, there is an ongoing request but the start line/header parsing has timed out, so send
// a 408 response.
KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestHeadersTimeout);
}
endConnection = false;
if (_requestProcessingStatus == RequestProcessingStatus.AppStarted)
{
EnsureHostHeaderExists();
return true;
}
else
{
return false;
}
}
void IRequestProcessor.Tick(DateTimeOffset now) { }
}
}
| |
// 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.Net.Mail;
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Net.Mime
{
internal static class MailBnfHelper
{
// characters allowed in atoms
internal static readonly bool[] Atext = CreateCharactersAllowedInAtoms();
// characters allowed in quoted strings (not including unicode)
internal static readonly bool[] Qtext = CreateCharactersAllowedInQuotedStrings();
// characters allowed in domain literals
internal static readonly bool[] Dtext = CreateCharactersAllowedInDomainLiterals();
// characters allowed in header names
internal static readonly bool[] Ftext = CreateCharactersAllowedInHeaderNames();
// characters allowed in tokens
internal static readonly bool[] Ttext = CreateCharactersAllowedInTokens();
// characters allowed inside of comments
internal static readonly bool[] Ctext = CreateCharactersAllowedInComments();
internal static readonly int Ascii7bitMaxValue = 127;
internal static readonly char Quote = '\"';
internal static readonly char Space = ' ';
internal static readonly char Tab = '\t';
internal static readonly char CR = '\r';
internal static readonly char LF = '\n';
internal static readonly char StartComment = '(';
internal static readonly char EndComment = ')';
internal static readonly char Backslash = '\\';
internal static readonly char At = '@';
internal static readonly char EndAngleBracket = '>';
internal static readonly char StartAngleBracket = '<';
internal static readonly char StartSquareBracket = '[';
internal static readonly char EndSquareBracket = ']';
internal static readonly char Comma = ',';
internal static readonly char Dot = '.';
internal static readonly IList<char> Whitespace = CreateAllowedWhitespace();
private static List<char> CreateAllowedWhitespace()
{
// all allowed whitespace characters
var whitespace = new List<char>(4);
whitespace.Add(Tab);
whitespace.Add(Space);
whitespace.Add(CR);
whitespace.Add(LF);
return whitespace;
}
// NOTE: See RFC 2822 for more detail. By default, every value in the array is false and only
// those values which are allowed in that particular set are then set to true. The numbers
// annotating each definition below are the range of ASCII values which are allowed in that definition.
private static bool[] CreateCharactersAllowedInAtoms()
{
// atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
var atext = new bool[128];
for (int i = '0'; i <= '9'; i++) { atext[i] = true; }
for (int i = 'A'; i <= 'Z'; i++) { atext[i] = true; }
for (int i = 'a'; i <= 'z'; i++) { atext[i] = true; }
atext['!'] = true;
atext['#'] = true;
atext['$'] = true;
atext['%'] = true;
atext['&'] = true;
atext['\''] = true;
atext['*'] = true;
atext['+'] = true;
atext['-'] = true;
atext['/'] = true;
atext['='] = true;
atext['?'] = true;
atext['^'] = true;
atext['_'] = true;
atext['`'] = true;
atext['{'] = true;
atext['|'] = true;
atext['}'] = true;
atext['~'] = true;
return atext;
}
private static bool[] CreateCharactersAllowedInQuotedStrings()
{
// fqtext = %d1-9 / %d11 / %d12 / %d14-33 / %d35-91 / %d93-127
var qtext = new bool[128];
for (int i = 1; i <= 9; i++) { qtext[i] = true; }
qtext[11] = true;
qtext[12] = true;
for (int i = 14; i <= 33; i++) { qtext[i] = true; }
for (int i = 35; i <= 91; i++) { qtext[i] = true; }
for (int i = 93; i <= 127; i++) { qtext[i] = true; }
return qtext;
}
private static bool[] CreateCharactersAllowedInDomainLiterals()
{
// fdtext = %d1-8 / %d11 / %d12 / %d14-31 / %d33-90 / %d94-127
var dtext = new bool[128];
for (int i = 1; i <= 8; i++) { dtext[i] = true; }
dtext[11] = true;
dtext[12] = true;
for (int i = 14; i <= 31; i++) { dtext[i] = true; }
for (int i = 33; i <= 90; i++) { dtext[i] = true; }
for (int i = 94; i <= 127; i++) { dtext[i] = true; }
return dtext;
}
private static bool[] CreateCharactersAllowedInHeaderNames()
{
// ftext = %d33-57 / %d59-126
var ftext = new bool[128];
for (int i = 33; i <= 57; i++) { ftext[i] = true; }
for (int i = 59; i <= 126; i++) { ftext[i] = true; }
return ftext;
}
private static bool[] CreateCharactersAllowedInTokens()
{
// ttext = %d33-126 except '()<>@,;:\"/[]?='
var ttext = new bool[128];
for (int i = 33; i <= 126; i++) { ttext[i] = true; }
ttext['('] = false;
ttext[')'] = false;
ttext['<'] = false;
ttext['>'] = false;
ttext['@'] = false;
ttext[','] = false;
ttext[';'] = false;
ttext[':'] = false;
ttext['\\'] = false;
ttext['"'] = false;
ttext['/'] = false;
ttext['['] = false;
ttext[']'] = false;
ttext['?'] = false;
ttext['='] = false;
return ttext;
}
private static bool[] CreateCharactersAllowedInComments()
{
// ctext- %d1-8 / %d11 / %d12 / %d14-31 / %33-39 / %42-91 / %93-127
var ctext = new bool[128];
for (int i = 1; i <= 8; i++) { ctext[i] = true; }
ctext[11] = true;
ctext[12] = true;
for (int i = 14; i <= 31; i++) { ctext[i] = true; }
for (int i = 33; i <= 39; i++) { ctext[i] = true; }
for (int i = 42; i <= 91; i++) { ctext[i] = true; }
for (int i = 93; i <= 127; i++) { ctext[i] = true; }
return ctext;
}
internal static bool SkipCFWS(string data, ref int offset)
{
int comments = 0;
for (; offset < data.Length; offset++)
{
if (data[offset] > 127)
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
else if (data[offset] == '\\' && comments > 0)
offset += 2;
else if (data[offset] == '(')
comments++;
else if (data[offset] == ')')
comments--;
else if (data[offset] != ' ' && data[offset] != '\t' && comments == 0)
return true;
if (comments < 0)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
}
//returns false if end of string
return false;
}
internal static void ValidateHeaderName(string data)
{
int offset = 0;
for (; offset < data.Length; offset++)
{
if (data[offset] > Ftext.Length || !Ftext[data[offset]])
throw new FormatException(SR.InvalidHeaderName);
}
if (offset == 0)
throw new FormatException(SR.InvalidHeaderName);
}
internal static string ReadQuotedString(string data, ref int offset, StringBuilder builder)
{
return ReadQuotedString(data, ref offset, builder, false, false);
}
internal static string ReadQuotedString(string data, ref int offset, StringBuilder builder, bool doesntRequireQuotes, bool permitUnicodeInDisplayName)
{
// assume first char is the opening quote
if (!doesntRequireQuotes)
{
++offset;
}
int start = offset;
StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
for (; offset < data.Length; offset++)
{
if (data[offset] == '\\')
{
localBuilder.Append(data, start, offset - start);
start = ++offset;
}
else if (data[offset] == '"')
{
localBuilder.Append(data, start, offset - start);
offset++;
return (builder != null ? null : localBuilder.ToString());
}
else if (data[offset] == '=' &&
data.Length > offset + 3 &&
data[offset + 1] == '\r' &&
data[offset + 2] == '\n' &&
(data[offset + 3] == ' ' || data[offset + 3] == '\t'))
{
//it's a soft crlf so it's ok
offset += 3;
}
else if (permitUnicodeInDisplayName)
{
//if data contains unicode and unicode is permitted, then
//it is valid in a quoted string in a header.
if (data[offset] <= Ascii7bitMaxValue && !Qtext[data[offset]])
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
//not permitting unicode, in which case unicode is a formatting error
else if (data[offset] > Ascii7bitMaxValue || !Qtext[data[offset]])
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
}
if (doesntRequireQuotes)
{
localBuilder.Append(data, start, offset - start);
return (builder != null ? null : localBuilder.ToString());
}
throw new FormatException(SR.MailHeaderFieldMalformedHeader);
}
internal static string ReadParameterAttribute(string data, ref int offset, StringBuilder builder)
{
if (!SkipCFWS(data, ref offset))
return null; //
return ReadToken(data, ref offset, null);
}
internal static string ReadToken(string data, ref int offset, StringBuilder builder)
{
int start = offset;
for (; offset < data.Length; offset++)
{
if (data[offset] > Ascii7bitMaxValue)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
else if (!Ttext[data[offset]])
{
break;
}
}
if (start == offset)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
return data.Substring(start, offset - start);
}
private static string[] s_months = new string[] { null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
internal static string GetDateTimeString(DateTime value, StringBuilder builder)
{
StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
localBuilder.Append(value.Day);
localBuilder.Append(' ');
localBuilder.Append(s_months[value.Month]);
localBuilder.Append(' ');
localBuilder.Append(value.Year);
localBuilder.Append(' ');
if (value.Hour <= 9)
{
localBuilder.Append('0');
}
localBuilder.Append(value.Hour);
localBuilder.Append(':');
if (value.Minute <= 9)
{
localBuilder.Append('0');
}
localBuilder.Append(value.Minute);
localBuilder.Append(':');
if (value.Second <= 9)
{
localBuilder.Append('0');
}
localBuilder.Append(value.Second);
string offset = TimeZoneInfo.Local.GetUtcOffset(value).ToString();
if (offset[0] != '-')
{
localBuilder.Append(" +");
}
else
{
localBuilder.Append(' ');
}
string[] offsetFields = offset.Split(':');
localBuilder.Append(offsetFields[0]);
localBuilder.Append(offsetFields[1]);
return (builder != null ? null : localBuilder.ToString());
}
internal static void GetTokenOrQuotedString(string data, StringBuilder builder, bool allowUnicode)
{
int offset = 0, start = 0;
for (; offset < data.Length; offset++)
{
if (CheckForUnicode(data[offset], allowUnicode))
{
continue;
}
if (!Ttext[data[offset]] || data[offset] == ' ')
{
builder.Append('"');
for (; offset < data.Length; offset++)
{
if (CheckForUnicode(data[offset], allowUnicode))
{
continue;
}
else if (IsFWSAt(data, offset)) // Allow FWS == "\r\n "
{
// No-op, skip these three chars
offset++;
offset++;
}
else if (!Qtext[data[offset]])
{
builder.Append(data, start, offset - start);
builder.Append('\\');
start = offset;
}
}
builder.Append(data, start, offset - start);
builder.Append('"');
return;
}
}
//always a quoted string if it was empty.
if (data.Length == 0)
{
builder.Append("\"\"");
}
// Token, no quotes needed
builder.Append(data);
}
private static bool CheckForUnicode(char ch, bool allowUnicode)
{
if (ch < Ascii7bitMaxValue)
{
return false;
}
if (!allowUnicode)
{
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, ch));
}
return true;
}
internal static bool HasCROrLF(string data)
{
for (int i = 0; i < data.Length; i++)
{
if (data[i] == '\r' || data[i] == '\n')
{
return true;
}
}
return false;
}
// Is there a FWS ("\r\n " or "\r\n\t") starting at the given index?
internal static bool IsFWSAt(string data, int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < data.Length);
return (data[index] == MailBnfHelper.CR
&& index + 2 < data.Length
&& data[index + 1] == MailBnfHelper.LF
&& (data[index + 2] == MailBnfHelper.Space
|| data[index + 2] == MailBnfHelper.Tab));
}
}
}
| |
// 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.
/*=============================================================================
**
**
** Purpose: A circular-array implementation of a generic queue.
**
**
=============================================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Collections.Generic
{
// A simple Queue of generic objects. Internally it is implemented as a
// circular buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Queue<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array;
private int _head; // The index from which to dequeue if the queue isn't empty.
private int _tail; // The index at which to enqueue if the queue isn't full.
private int _size; // Number of elements.
private int _version;
private Object _syncRoot;
private const int MinimumGrow = 4;
private const int GrowFactor = 200; // double each time
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue"]/*' />
public Queue()
{
_array = Array.Empty<T>();
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue1"]/*' />
public Queue(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue3"]/*' />
public Queue(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
_tail = (_size == _array.Length) ? 0 : _size;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Count"]/*' />
public int Count
{
get { return _size; }
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IsSynchronized"]/*' />
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
Object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Clear"]/*' />
public void Clear()
{
if (_size != 0)
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.CopyTo"]/*' />
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
int arrayLen = array.Length;
if (arrayLen - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, arrayIndex, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy);
}
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
int arrayLen = array.Length;
if (index < 0 || index > arrayLen)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (arrayLen - index < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
try
{
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Adds item to the tail of the queue.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Enqueue"]/*' />
public void Enqueue(T item)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100);
if (newcapacity < _array.Length + MinimumGrow)
{
newcapacity = _array.Length + MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = item;
MoveNext(ref _tail);
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.GetEnumerator"]/*' />
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IEnumerable.GetEnumerator"]/*' />
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Dequeue"]/*' />
public T Dequeue()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
T removed = _array[_head];
_array[_head] = default(T);
MoveNext(ref _head);
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Peek"]/*' />
public T Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
return _array[_head];
}
// Returns true if the queue contains at least one object equal to item.
// Equality is determined using item.Equals().
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Contains"]/*' />
public bool Contains(T item)
{
int index = _head;
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > 0)
{
if (c.Equals(_array[index], item))
{
return true;
}
MoveNext(ref index);
}
return false;
}
private T GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.ToArray"]/*' />
public T[] ToArray()
{
if (_size == 0)
{
return Array.Empty<T>();
}
T[] arr = new T[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
T[] newarray = new T[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
// Increments the index wrapping it if necessary.
private void MoveNext(ref int index)
{
// It is tempting to use the remainder operator here but it is actually much slower
// than a simple comparison and a rarely taken branch.
int tmp = index + 1;
index = (tmp == _array.Length) ? 0 : tmp;
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
SetCapacity(_size);
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator"]/*' />
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private Queue<T> _q;
private int _index; // -1 = not started, -2 = ended/disposed
private int _version;
private T _currentElement;
internal Enumerator(Queue<T> q)
{
_q = q;
_version = _q._version;
_index = -1;
_currentElement = default(T);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Dispose"]/*' />
public void Dispose()
{
_index = -2;
_currentElement = default(T);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.MoveNext"]/*' />
public bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
return false;
_index++;
if (_index == _q._size)
{
_index = -2;
_currentElement = default(T);
return false;
}
_currentElement = _q.GetElement(_index);
return true;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Current"]/*' />
public T Current
{
get
{
if (_index < 0)
{
if (_index == -1)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
else
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
return _currentElement;
}
}
Object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
_currentElement = default(T);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/reservations/reservation_summary_lite.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.Reservations {
/// <summary>Holder for reflection information generated from booking/reservations/reservation_summary_lite.proto</summary>
public static partial class ReservationSummaryLiteReflection {
#region Descriptor
/// <summary>File descriptor for booking/reservations/reservation_summary_lite.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationSummaryLiteReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjNib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9zdW1tYXJ5X2xp",
"dGUucHJvdG8SIGhvbG1zLnR5cGVzLmJvb2tpbmcucmVzZXJ2YXRpb25zGi5i",
"b29raW5nL2luZGljYXRvcnMvcmVzZXJ2YXRpb25faW5kaWNhdG9yLnByb3Rv",
"Gixib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9zdGF0ZS5wcm90",
"bxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8aH3ByaW1pdGl2ZS9t",
"b25ldGFyeV9hbW91bnQucHJvdG8aM2ZvbGlvL2d1YXJhbnRlZXMvcmVzZXJ2",
"YXRpb25fZ3VhcmFudGVlX3N0YXR1cy5wcm90byL7BQoWUmVzZXJ2YXRpb25T",
"dW1tYXJ5TGl0ZRJHCgllbnRpdHlfaWQYASABKAsyNC5ob2xtcy50eXBlcy5i",
"b29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3ISQQoFc3Rh",
"dGUYAiABKA4yMi5ob2xtcy50eXBlcy5ib29raW5nLnJlc2VydmF0aW9ucy5S",
"ZXNlcnZhdGlvblN0YXRlEhUKDUJvb2tpbmdOdW1iZXIYAyABKAMSFQoNQm9v",
"a2luZ1ByZWZpeBgEIAEoCRIhChlDdXJyZW50T2NjdXBpZWRSb29tTnVtYmVy",
"GAUgASgJEiIKGlRlcm1pbmFsT2NjdXBpZWRSb29tTnVtYmVyGAYgASgJEiQK",
"HEZpcnN0TmlnaHRBc3NpZ25lZFJvb21OdW1iZXIYByABKAkSHwoXVmVoaWNs",
"ZVBsYXRlSW5mb3JtYXRpb24YCCABKAkSNwoLQXJyaXZhbERhdGUYCSABKAsy",
"Ii5ob2xtcy50eXBlcy5wcmltaXRpdmUuUGJMb2NhbERhdGUSOQoNRGVwYXJ0",
"dXJlRGF0ZRgKIAEoCzIiLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5QYkxvY2Fs",
"RGF0ZRIUCgxSb29tVHlwZU5hbWUYCyABKAkSEQoJT1RBTnVtYmVyGAwgASgJ",
"EhEKCUd1ZXN0VGV4dBgNIAEoCRIXCg9NYXN0ZXJGb2xpb1RleHQYDiABKAkS",
"GQoRSXNHcm91cEFzc29jaWF0ZWQYDyABKAgSQgoTQ3VycmVudER1ZUZyb21H",
"dWVzdBgQIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5Nb25ldGFyeUFt",
"b3VudBJVCg9HdWFyYW50ZWVTdGF0dXMYESABKA4yPC5ob2xtcy50eXBlcy5i",
"b29raW5nLnJlc2VydmF0aW9ucy5SZXNlcnZhdGlvbkd1YXJhbnRlZVN0YXR1",
"cxIaChJyZXNlcnZhdGlvbl9zb3VyY2UYEiABKAlCOVoUYm9va2luZy9yZXNl",
"cnZhdGlvbnOqAiBIT0xNUy5UeXBlcy5Cb29raW5nLlJlc2VydmF0aW9uc2IG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationStateReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatusReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.ReservationSummaryLite), global::HOLMS.Types.Booking.Reservations.ReservationSummaryLite.Parser, new[]{ "EntityId", "State", "BookingNumber", "BookingPrefix", "CurrentOccupiedRoomNumber", "TerminalOccupiedRoomNumber", "FirstNightAssignedRoomNumber", "VehiclePlateInformation", "ArrivalDate", "DepartureDate", "RoomTypeName", "OTANumber", "GuestText", "MasterFolioText", "IsGroupAssociated", "CurrentDueFromGuest", "GuaranteeStatus", "ReservationSource" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationSummaryLite : pb::IMessage<ReservationSummaryLite> {
private static readonly pb::MessageParser<ReservationSummaryLite> _parser = new pb::MessageParser<ReservationSummaryLite>(() => new ReservationSummaryLite());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationSummaryLite> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Reservations.ReservationSummaryLiteReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationSummaryLite() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationSummaryLite(ReservationSummaryLite other) : this() {
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
state_ = other.state_;
bookingNumber_ = other.bookingNumber_;
bookingPrefix_ = other.bookingPrefix_;
currentOccupiedRoomNumber_ = other.currentOccupiedRoomNumber_;
terminalOccupiedRoomNumber_ = other.terminalOccupiedRoomNumber_;
firstNightAssignedRoomNumber_ = other.firstNightAssignedRoomNumber_;
vehiclePlateInformation_ = other.vehiclePlateInformation_;
ArrivalDate = other.arrivalDate_ != null ? other.ArrivalDate.Clone() : null;
DepartureDate = other.departureDate_ != null ? other.DepartureDate.Clone() : null;
roomTypeName_ = other.roomTypeName_;
oTANumber_ = other.oTANumber_;
guestText_ = other.guestText_;
masterFolioText_ = other.masterFolioText_;
isGroupAssociated_ = other.isGroupAssociated_;
CurrentDueFromGuest = other.currentDueFromGuest_ != null ? other.CurrentDueFromGuest.Clone() : null;
guaranteeStatus_ = other.guaranteeStatus_;
reservationSource_ = other.reservationSource_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationSummaryLite Clone() {
return new ReservationSummaryLite(this);
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "state" field.</summary>
public const int StateFieldNumber = 2;
private global::HOLMS.Types.Booking.Reservations.ReservationState state_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Reservations.ReservationState State {
get { return state_; }
set {
state_ = value;
}
}
/// <summary>Field number for the "BookingNumber" field.</summary>
public const int BookingNumberFieldNumber = 3;
private long bookingNumber_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long BookingNumber {
get { return bookingNumber_; }
set {
bookingNumber_ = value;
}
}
/// <summary>Field number for the "BookingPrefix" field.</summary>
public const int BookingPrefixFieldNumber = 4;
private string bookingPrefix_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string BookingPrefix {
get { return bookingPrefix_; }
set {
bookingPrefix_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "CurrentOccupiedRoomNumber" field.</summary>
public const int CurrentOccupiedRoomNumberFieldNumber = 5;
private string currentOccupiedRoomNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CurrentOccupiedRoomNumber {
get { return currentOccupiedRoomNumber_; }
set {
currentOccupiedRoomNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "TerminalOccupiedRoomNumber" field.</summary>
public const int TerminalOccupiedRoomNumberFieldNumber = 6;
private string terminalOccupiedRoomNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TerminalOccupiedRoomNumber {
get { return terminalOccupiedRoomNumber_; }
set {
terminalOccupiedRoomNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "FirstNightAssignedRoomNumber" field.</summary>
public const int FirstNightAssignedRoomNumberFieldNumber = 7;
private string firstNightAssignedRoomNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FirstNightAssignedRoomNumber {
get { return firstNightAssignedRoomNumber_; }
set {
firstNightAssignedRoomNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "VehiclePlateInformation" field.</summary>
public const int VehiclePlateInformationFieldNumber = 8;
private string vehiclePlateInformation_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string VehiclePlateInformation {
get { return vehiclePlateInformation_; }
set {
vehiclePlateInformation_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ArrivalDate" field.</summary>
public const int ArrivalDateFieldNumber = 9;
private global::HOLMS.Types.Primitive.PbLocalDate arrivalDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate ArrivalDate {
get { return arrivalDate_; }
set {
arrivalDate_ = value;
}
}
/// <summary>Field number for the "DepartureDate" field.</summary>
public const int DepartureDateFieldNumber = 10;
private global::HOLMS.Types.Primitive.PbLocalDate departureDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate DepartureDate {
get { return departureDate_; }
set {
departureDate_ = value;
}
}
/// <summary>Field number for the "RoomTypeName" field.</summary>
public const int RoomTypeNameFieldNumber = 11;
private string roomTypeName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string RoomTypeName {
get { return roomTypeName_; }
set {
roomTypeName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "OTANumber" field.</summary>
public const int OTANumberFieldNumber = 12;
private string oTANumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OTANumber {
get { return oTANumber_; }
set {
oTANumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "GuestText" field.</summary>
public const int GuestTextFieldNumber = 13;
private string guestText_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GuestText {
get { return guestText_; }
set {
guestText_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "MasterFolioText" field.</summary>
public const int MasterFolioTextFieldNumber = 14;
private string masterFolioText_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MasterFolioText {
get { return masterFolioText_; }
set {
masterFolioText_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "IsGroupAssociated" field.</summary>
public const int IsGroupAssociatedFieldNumber = 15;
private bool isGroupAssociated_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsGroupAssociated {
get { return isGroupAssociated_; }
set {
isGroupAssociated_ = value;
}
}
/// <summary>Field number for the "CurrentDueFromGuest" field.</summary>
public const int CurrentDueFromGuestFieldNumber = 16;
private global::HOLMS.Types.Primitive.MonetaryAmount currentDueFromGuest_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount CurrentDueFromGuest {
get { return currentDueFromGuest_; }
set {
currentDueFromGuest_ = value;
}
}
/// <summary>Field number for the "GuaranteeStatus" field.</summary>
public const int GuaranteeStatusFieldNumber = 17;
private global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatus guaranteeStatus_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatus GuaranteeStatus {
get { return guaranteeStatus_; }
set {
guaranteeStatus_ = value;
}
}
/// <summary>Field number for the "reservation_source" field.</summary>
public const int ReservationSourceFieldNumber = 18;
private string reservationSource_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ReservationSource {
get { return reservationSource_; }
set {
reservationSource_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationSummaryLite);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationSummaryLite other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EntityId, other.EntityId)) return false;
if (State != other.State) return false;
if (BookingNumber != other.BookingNumber) return false;
if (BookingPrefix != other.BookingPrefix) return false;
if (CurrentOccupiedRoomNumber != other.CurrentOccupiedRoomNumber) return false;
if (TerminalOccupiedRoomNumber != other.TerminalOccupiedRoomNumber) return false;
if (FirstNightAssignedRoomNumber != other.FirstNightAssignedRoomNumber) return false;
if (VehiclePlateInformation != other.VehiclePlateInformation) return false;
if (!object.Equals(ArrivalDate, other.ArrivalDate)) return false;
if (!object.Equals(DepartureDate, other.DepartureDate)) return false;
if (RoomTypeName != other.RoomTypeName) return false;
if (OTANumber != other.OTANumber) return false;
if (GuestText != other.GuestText) return false;
if (MasterFolioText != other.MasterFolioText) return false;
if (IsGroupAssociated != other.IsGroupAssociated) return false;
if (!object.Equals(CurrentDueFromGuest, other.CurrentDueFromGuest)) return false;
if (GuaranteeStatus != other.GuaranteeStatus) return false;
if (ReservationSource != other.ReservationSource) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (State != 0) hash ^= State.GetHashCode();
if (BookingNumber != 0L) hash ^= BookingNumber.GetHashCode();
if (BookingPrefix.Length != 0) hash ^= BookingPrefix.GetHashCode();
if (CurrentOccupiedRoomNumber.Length != 0) hash ^= CurrentOccupiedRoomNumber.GetHashCode();
if (TerminalOccupiedRoomNumber.Length != 0) hash ^= TerminalOccupiedRoomNumber.GetHashCode();
if (FirstNightAssignedRoomNumber.Length != 0) hash ^= FirstNightAssignedRoomNumber.GetHashCode();
if (VehiclePlateInformation.Length != 0) hash ^= VehiclePlateInformation.GetHashCode();
if (arrivalDate_ != null) hash ^= ArrivalDate.GetHashCode();
if (departureDate_ != null) hash ^= DepartureDate.GetHashCode();
if (RoomTypeName.Length != 0) hash ^= RoomTypeName.GetHashCode();
if (OTANumber.Length != 0) hash ^= OTANumber.GetHashCode();
if (GuestText.Length != 0) hash ^= GuestText.GetHashCode();
if (MasterFolioText.Length != 0) hash ^= MasterFolioText.GetHashCode();
if (IsGroupAssociated != false) hash ^= IsGroupAssociated.GetHashCode();
if (currentDueFromGuest_ != null) hash ^= CurrentDueFromGuest.GetHashCode();
if (GuaranteeStatus != 0) hash ^= GuaranteeStatus.GetHashCode();
if (ReservationSource.Length != 0) hash ^= ReservationSource.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (entityId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EntityId);
}
if (State != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) State);
}
if (BookingNumber != 0L) {
output.WriteRawTag(24);
output.WriteInt64(BookingNumber);
}
if (BookingPrefix.Length != 0) {
output.WriteRawTag(34);
output.WriteString(BookingPrefix);
}
if (CurrentOccupiedRoomNumber.Length != 0) {
output.WriteRawTag(42);
output.WriteString(CurrentOccupiedRoomNumber);
}
if (TerminalOccupiedRoomNumber.Length != 0) {
output.WriteRawTag(50);
output.WriteString(TerminalOccupiedRoomNumber);
}
if (FirstNightAssignedRoomNumber.Length != 0) {
output.WriteRawTag(58);
output.WriteString(FirstNightAssignedRoomNumber);
}
if (VehiclePlateInformation.Length != 0) {
output.WriteRawTag(66);
output.WriteString(VehiclePlateInformation);
}
if (arrivalDate_ != null) {
output.WriteRawTag(74);
output.WriteMessage(ArrivalDate);
}
if (departureDate_ != null) {
output.WriteRawTag(82);
output.WriteMessage(DepartureDate);
}
if (RoomTypeName.Length != 0) {
output.WriteRawTag(90);
output.WriteString(RoomTypeName);
}
if (OTANumber.Length != 0) {
output.WriteRawTag(98);
output.WriteString(OTANumber);
}
if (GuestText.Length != 0) {
output.WriteRawTag(106);
output.WriteString(GuestText);
}
if (MasterFolioText.Length != 0) {
output.WriteRawTag(114);
output.WriteString(MasterFolioText);
}
if (IsGroupAssociated != false) {
output.WriteRawTag(120);
output.WriteBool(IsGroupAssociated);
}
if (currentDueFromGuest_ != null) {
output.WriteRawTag(130, 1);
output.WriteMessage(CurrentDueFromGuest);
}
if (GuaranteeStatus != 0) {
output.WriteRawTag(136, 1);
output.WriteEnum((int) GuaranteeStatus);
}
if (ReservationSource.Length != 0) {
output.WriteRawTag(146, 1);
output.WriteString(ReservationSource);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (State != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State);
}
if (BookingNumber != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(BookingNumber);
}
if (BookingPrefix.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(BookingPrefix);
}
if (CurrentOccupiedRoomNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CurrentOccupiedRoomNumber);
}
if (TerminalOccupiedRoomNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TerminalOccupiedRoomNumber);
}
if (FirstNightAssignedRoomNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FirstNightAssignedRoomNumber);
}
if (VehiclePlateInformation.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(VehiclePlateInformation);
}
if (arrivalDate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrivalDate);
}
if (departureDate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DepartureDate);
}
if (RoomTypeName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(RoomTypeName);
}
if (OTANumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OTANumber);
}
if (GuestText.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GuestText);
}
if (MasterFolioText.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MasterFolioText);
}
if (IsGroupAssociated != false) {
size += 1 + 1;
}
if (currentDueFromGuest_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(CurrentDueFromGuest);
}
if (GuaranteeStatus != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) GuaranteeStatus);
}
if (ReservationSource.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(ReservationSource);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationSummaryLite other) {
if (other == null) {
return;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.State != 0) {
State = other.State;
}
if (other.BookingNumber != 0L) {
BookingNumber = other.BookingNumber;
}
if (other.BookingPrefix.Length != 0) {
BookingPrefix = other.BookingPrefix;
}
if (other.CurrentOccupiedRoomNumber.Length != 0) {
CurrentOccupiedRoomNumber = other.CurrentOccupiedRoomNumber;
}
if (other.TerminalOccupiedRoomNumber.Length != 0) {
TerminalOccupiedRoomNumber = other.TerminalOccupiedRoomNumber;
}
if (other.FirstNightAssignedRoomNumber.Length != 0) {
FirstNightAssignedRoomNumber = other.FirstNightAssignedRoomNumber;
}
if (other.VehiclePlateInformation.Length != 0) {
VehiclePlateInformation = other.VehiclePlateInformation;
}
if (other.arrivalDate_ != null) {
if (arrivalDate_ == null) {
arrivalDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
ArrivalDate.MergeFrom(other.ArrivalDate);
}
if (other.departureDate_ != null) {
if (departureDate_ == null) {
departureDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
DepartureDate.MergeFrom(other.DepartureDate);
}
if (other.RoomTypeName.Length != 0) {
RoomTypeName = other.RoomTypeName;
}
if (other.OTANumber.Length != 0) {
OTANumber = other.OTANumber;
}
if (other.GuestText.Length != 0) {
GuestText = other.GuestText;
}
if (other.MasterFolioText.Length != 0) {
MasterFolioText = other.MasterFolioText;
}
if (other.IsGroupAssociated != false) {
IsGroupAssociated = other.IsGroupAssociated;
}
if (other.currentDueFromGuest_ != null) {
if (currentDueFromGuest_ == null) {
currentDueFromGuest_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
CurrentDueFromGuest.MergeFrom(other.CurrentDueFromGuest);
}
if (other.GuaranteeStatus != 0) {
GuaranteeStatus = other.GuaranteeStatus;
}
if (other.ReservationSource.Length != 0) {
ReservationSource = other.ReservationSource;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(entityId_);
break;
}
case 16: {
state_ = (global::HOLMS.Types.Booking.Reservations.ReservationState) input.ReadEnum();
break;
}
case 24: {
BookingNumber = input.ReadInt64();
break;
}
case 34: {
BookingPrefix = input.ReadString();
break;
}
case 42: {
CurrentOccupiedRoomNumber = input.ReadString();
break;
}
case 50: {
TerminalOccupiedRoomNumber = input.ReadString();
break;
}
case 58: {
FirstNightAssignedRoomNumber = input.ReadString();
break;
}
case 66: {
VehiclePlateInformation = input.ReadString();
break;
}
case 74: {
if (arrivalDate_ == null) {
arrivalDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(arrivalDate_);
break;
}
case 82: {
if (departureDate_ == null) {
departureDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(departureDate_);
break;
}
case 90: {
RoomTypeName = input.ReadString();
break;
}
case 98: {
OTANumber = input.ReadString();
break;
}
case 106: {
GuestText = input.ReadString();
break;
}
case 114: {
MasterFolioText = input.ReadString();
break;
}
case 120: {
IsGroupAssociated = input.ReadBool();
break;
}
case 130: {
if (currentDueFromGuest_ == null) {
currentDueFromGuest_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(currentDueFromGuest_);
break;
}
case 136: {
guaranteeStatus_ = (global::HOLMS.Types.Folio.Guarantees.ReservationGuaranteeStatus) input.ReadEnum();
break;
}
case 146: {
ReservationSource = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//-----------------------------------------------------------------------
// <copyright file="NSwagDocument.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NSwag.AssemblyLoader.Utilities;
using NSwag.Commands.SwaggerGeneration;
using NSwag.Commands.SwaggerGeneration.AspNetCore;
using NSwag.Commands.SwaggerGeneration.WebApi;
namespace NSwag.Commands
{
/// <summary>The NSwagDocument implementation.</summary>
/// <seealso cref="NSwagDocumentBase" />
public class NSwagDocument : NSwagDocumentBase
{
#if NET461
/// <summary>Gets or sets the root binary directory where the command line executables loaded from.</summary>
public static string RootBinaryDirectory { get; set; } =
System.IO.Path.GetDirectoryName(typeof(NSwagDocument).GetTypeInfo().Assembly.Location);
#endif
/// <summary>Initializes a new instance of the <see cref="NSwagDocument"/> class.</summary>
public NSwagDocument()
{
SwaggerGenerators.AspNetCoreToSwaggerCommand = new AspNetCoreToSwaggerCommand();
SwaggerGenerators.WebApiToSwaggerCommand = new WebApiToSwaggerCommand();
SwaggerGenerators.TypesToSwaggerCommand = new TypesToSwaggerCommand();
}
/// <summary>Creates a new NSwagDocument.</summary>
/// <returns>The document.</returns>
public static NSwagDocument Create()
{
return Create<NSwagDocument>();
}
/// <summary>Loads an existing NSwagDocument.</summary>
/// <param name="filePath">The file path.</param>
/// <returns>The document.</returns>
public static async Task<NSwagDocument> LoadAsync(string filePath)
{
return await LoadAsync<NSwagDocument>(filePath, null, false, new Dictionary<Type, Type>
{
{ typeof(AspNetCoreToSwaggerCommand), typeof(AspNetCoreToSwaggerCommand) },
{ typeof(WebApiToSwaggerCommand), typeof(WebApiToSwaggerCommand) },
{ typeof(TypesToSwaggerCommand), typeof(TypesToSwaggerCommand) }
});
}
/// <summary>Loads an existing NSwagDocument with environment variable expansions and variables.</summary>
/// <param name="filePath">The file path.</param>
/// <param name="variables">The variables.</param>
/// <returns>The document.</returns>
public static async Task<NSwagDocument> LoadWithTransformationsAsync(string filePath, string variables)
{
return await LoadAsync<NSwagDocument>(filePath, variables, true, new Dictionary<Type, Type>
{
{ typeof(AspNetCoreToSwaggerCommand), typeof(AspNetCoreToSwaggerCommand) },
{ typeof(WebApiToSwaggerCommand), typeof(WebApiToSwaggerCommand) },
{ typeof(TypesToSwaggerCommand), typeof(TypesToSwaggerCommand) }
});
}
/// <summary>Executes the document.</summary>
/// <returns>The task.</returns>
public override async Task<SwaggerDocumentExecutionResult> ExecuteAsync()
{
var document = await GenerateSwaggerDocumentAsync();
foreach (var codeGenerator in CodeGenerators.Items.Where(c => !string.IsNullOrEmpty(c.OutputFilePath)))
{
codeGenerator.Input = document;
await codeGenerator.RunAsync(null, null);
codeGenerator.Input = null;
}
return new SwaggerDocumentExecutionResult(null, null, true);
}
/// <summary>Executes the document via command line.</summary>
/// <param name="redirectOutput">Indicates whether to redirect the outputs.</param>
/// <returns>The result.</returns>
public async Task<SwaggerDocumentExecutionResult> ExecuteCommandLineAsync(bool redirectOutput)
{
return await Task.Run(async () =>
{
if (Runtime == Runtime.Debug)
return await ExecuteAsync();
var baseFilename = System.IO.Path.GetTempPath() + "nswag_document_" + Guid.NewGuid();
var swaggerFilename = baseFilename + "_swagger.json";
var filenames = new List<string>();
var clone = FromJson<NSwagDocument>(null, ToJson());
if (redirectOutput || string.IsNullOrEmpty(clone.SelectedSwaggerGenerator.OutputFilePath))
clone.SelectedSwaggerGenerator.OutputFilePath = swaggerFilename;
foreach (var command in clone.CodeGenerators.Items.Where(c => c != null))
{
if (redirectOutput || string.IsNullOrEmpty(command.OutputFilePath))
{
var codeFilePath = baseFilename + "_" + command.GetType().Name + ".temp";
command.OutputFilePath = codeFilePath;
filenames.Add(codeFilePath);
}
}
var configFilename = baseFilename + "_config.json";
File.WriteAllText(configFilename, clone.ToJson());
try
{
var command = "run \"" + configFilename + "\"";
var output = await StartCommandLineProcessAsync(command);
return clone.ProcessExecutionResult(output, baseFilename, redirectOutput);
}
finally
{
DeleteFileIfExists(configFilename);
DeleteFileIfExists(swaggerFilename);
foreach (var filename in filenames)
DeleteFileIfExists(filename);
}
});
}
/// <summary>Gets the available controller types by calling the command line.</summary>
/// <returns>The controller names.</returns>
public async Task<string[]> GetControllersFromCommandLineAsync()
{
return await Task.Run(async () =>
{
if (!(SelectedSwaggerGenerator is WebApiToSwaggerCommand))
return new string[0];
var baseFilename = System.IO.Path.GetTempPath() + "nswag_document_" + Guid.NewGuid();
var configFilename = baseFilename + "_config.json";
File.WriteAllText(configFilename, ToJson());
try
{
var command = "list-controllers /file:\"" + configFilename + "\"";
return GetListFromCommandLineOutput(await StartCommandLineProcessAsync(command));
}
finally
{
DeleteFileIfExists(configFilename);
}
});
}
/// <summary>Gets the available controller types by calling the command line.</summary>
/// <returns>The controller names.</returns>
public async Task<string[]> GetTypesFromCommandLineAsync()
{
return await Task.Run(async () =>
{
if (!(SelectedSwaggerGenerator is TypesToSwaggerCommand))
return new string[0];
var baseFilename = System.IO.Path.GetTempPath() + "nswag_document_" + Guid.NewGuid();
var configFilename = baseFilename + "_config.json";
File.WriteAllText(configFilename, ToJson());
try
{
var command = "list-types /file:\"" + configFilename + "\"";
return GetListFromCommandLineOutput(await StartCommandLineProcessAsync(command));
}
finally
{
DeleteFileIfExists(configFilename);
}
});
}
/// <summary>Converts to absolute path.</summary>
/// <param name="pathToConvert">The path to convert.</param>
/// <returns>The absolute path.</returns>
protected override string ConvertToAbsolutePath(string pathToConvert)
{
if (!string.IsNullOrEmpty(pathToConvert) && !System.IO.Path.IsPathRooted(pathToConvert) && !pathToConvert.Contains("%"))
return PathUtilities.MakeAbsolutePath(pathToConvert, GetDocumentDirectory());
return pathToConvert;
}
/// <summary>Converts a path to an relative path.</summary>
/// <param name="pathToConvert">The path to convert.</param>
/// <returns>The relative path.</returns>
protected override string ConvertToRelativePath(string pathToConvert)
{
if (!string.IsNullOrEmpty(pathToConvert) && !pathToConvert.Contains("C:\\Program Files\\") && !pathToConvert.Contains("%"))
return PathUtilities.MakeRelativePath(pathToConvert, GetDocumentDirectory())?.Replace("\\", "/");
return pathToConvert?.Replace("\\", "/");
}
private string[] GetListFromCommandLineOutput(string output)
{
return output.Replace("\r\n", "\n")
.Split(new string[] { "\n\n" }, StringSplitOptions.None)[1]
.Split('\n')
.Where(t => !string.IsNullOrEmpty(t))
.ToArray();
}
private SwaggerDocumentExecutionResult ProcessExecutionResult(string output, string baseFilename, bool redirectOutput)
{
var swaggerOutput = ReadFileIfExists(SelectedSwaggerGenerator.OutputFilePath);
var result = new SwaggerDocumentExecutionResult(output, swaggerOutput, redirectOutput);
foreach (var command in CodeGenerators.Items.Where(c => c != null))
{
if (redirectOutput || string.IsNullOrEmpty(command.OutputFilePath))
{
var codeFilepath = baseFilename + "_" + command.GetType().Name + ".temp";
result.AddGeneratorOutput(command.GetType(), ReadFileIfExists(codeFilepath));
}
else
result.AddGeneratorOutput(command.GetType(), ReadFileIfExists(command.OutputFilePath));
}
return result;
}
private async Task<string> StartCommandLineProcessAsync(string command)
{
var processStart = new ProcessStartInfo(GetProgramName(), GetArgumentsPrefix() + command);
processStart.RedirectStandardOutput = true;
processStart.RedirectStandardError = true;
processStart.UseShellExecute = false;
processStart.CreateNoWindow = true;
var process = Process.Start(processStart);
var output = await process.StandardOutput.ReadToEndAsync() +
"\n\n" + await process.StandardError.ReadToEndAsync();
if (process.ExitCode != 0)
{
var errorStart = output.IndexOf("...");
if (errorStart < 0)
errorStart = Regex.Match(output, "\n[^\n\r]*?Exception: .*", RegexOptions.Singleline)?.Index ?? -1;
var error = errorStart > 0 ? output.Substring(errorStart + 4) : output;
var stackTraceStart = error.IndexOf("Server stack trace: ");
if (stackTraceStart < 0)
stackTraceStart = error.IndexOf(" at ");
var message = stackTraceStart > 0 ? error.Substring(0, stackTraceStart) : error;
var stackTrace = stackTraceStart > 0 ? error.Substring(stackTraceStart) : "";
if (message.Contains("Could not load type"))
message = message + "Try running the document in another runtime, e.g. /runtime:NetCore20";
if (message.Contains("The system cannot find the file specified"))
message = message + "Check if .NET Core is installed and 'dotnet' is globally available.";
throw new CommandLineException(message, "Runtime: " + Runtime + "\n" + stackTrace);
}
return output;
}
private string GetDocumentDirectory()
{
var absoluteDocumentPath = PathUtilities.MakeAbsolutePath(Path, System.IO.Directory.GetCurrentDirectory());
return System.IO.Path.GetDirectoryName(absoluteDocumentPath);
}
private string GetArgumentsPrefix()
{
#if NET461
var runtime = Runtime != Runtime.Default ? Runtime : RuntimeUtilities.CurrentRuntime;
if (runtime == Runtime.NetCore10)
return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "NetCore10/dotnet-nswag.dll") + "\" ";
else if (runtime == Runtime.NetCore11)
return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "NetCore11/dotnet-nswag.dll") + "\" ";
else if (runtime == Runtime.NetCore20)
return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "NetCore20/dotnet-nswag.dll") + "\" ";
else if (runtime == Runtime.NetCore21)
return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "NetCore21/dotnet-nswag.dll") + "\" ";
else if (runtime == Runtime.NetCore22)
return "\"" + System.IO.Path.Combine(RootBinaryDirectory, "NetCore22/dotnet-nswag.dll") + "\" ";
else
#endif
return "";
}
private string GetProgramName()
{
#if NET461
var runtime = Runtime != Runtime.Default ? Runtime : RuntimeUtilities.CurrentRuntime;
if (runtime == Runtime.WinX64 || runtime == Runtime.Debug)
return System.IO.Path.Combine(RootBinaryDirectory, "Win/nswag.exe");
else if (runtime == Runtime.WinX86)
return System.IO.Path.Combine(RootBinaryDirectory, "Win/nswag.x86.exe");
else
#endif
return "dotnet";
}
private string ReadFileIfExists(string filename)
{
if (filename != null && File.Exists(filename))
return File.ReadAllText(filename);
return null;
}
private void DeleteFileIfExists(string filename)
{
if (File.Exists(filename))
File.Delete(filename);
}
internal class CommandLineException : Exception
{
public CommandLineException(string message, string stackTrace)
: base(message)
{
StackTrace = stackTrace;
}
public override string StackTrace { get; }
public override string ToString()
{
return Message + "\n" + StackTrace;
}
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Text;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto
{
/**
* super class for all Password Based Encyrption (Pbe) parameter generator classes.
*/
public abstract class PbeParametersGenerator
{
protected byte[] mPassword;
protected byte[] mSalt;
protected int mIterationCount;
/**
* base constructor.
*/
protected PbeParametersGenerator()
{
}
/**
* initialise the Pbe generator.
*
* @param password the password converted into bytes (see below).
* @param salt the salt to be mixed with the password.
* @param iterationCount the number of iterations the "mixing" function
* is to be applied for.
*/
public virtual void Init(
byte[] password,
byte[] salt,
int iterationCount)
{
if (password == null)
throw new ArgumentNullException("password");
if (salt == null)
throw new ArgumentNullException("salt");
this.mPassword = Arrays.Clone(password);
this.mSalt = Arrays.Clone(salt);
this.mIterationCount = iterationCount;
}
public virtual byte[] Password
{
get { return Arrays.Clone(mPassword); }
}
/**
* return the password byte array.
*
* @return the password byte array.
*/
[Obsolete("Use 'Password' property")]
public byte[] GetPassword()
{
return Password;
}
public virtual byte[] Salt
{
get { return Arrays.Clone(mSalt); }
}
/**
* return the salt byte array.
*
* @return the salt byte array.
*/
[Obsolete("Use 'Salt' property")]
public byte[] GetSalt()
{
return Salt;
}
/**
* return the iteration count.
*
* @return the iteration count.
*/
public virtual int IterationCount
{
get { return mIterationCount; }
}
/**
* Generate derived parameters for a key of length keySize.
*
* @param keySize the length, in bits, of the key required.
* @return a parameters object representing a key.
*/
[Obsolete("Use version with 'algorithm' parameter")]
public abstract ICipherParameters GenerateDerivedParameters(int keySize);
public abstract ICipherParameters GenerateDerivedParameters(string algorithm, int keySize);
/**
* Generate derived parameters for a key of length keySize, and
* an initialisation vector (IV) of length ivSize.
*
* @param keySize the length, in bits, of the key required.
* @param ivSize the length, in bits, of the iv required.
* @return a parameters object representing a key and an IV.
*/
[Obsolete("Use version with 'algorithm' parameter")]
public abstract ICipherParameters GenerateDerivedParameters(int keySize, int ivSize);
public abstract ICipherParameters GenerateDerivedParameters(string algorithm, int keySize, int ivSize);
/**
* Generate derived parameters for a key of length keySize, specifically
* for use with a MAC.
*
* @param keySize the length, in bits, of the key required.
* @return a parameters object representing a key.
*/
public abstract ICipherParameters GenerateDerivedMacParameters(int keySize);
/**
* converts a password to a byte array according to the scheme in
* Pkcs5 (ascii, no padding)
*
* @param password a character array representing the password.
* @return a byte array representing the password.
*/
public static byte[] Pkcs5PasswordToBytes(
char[] password)
{
if (password == null)
return new byte[0];
return Strings.ToAsciiByteArray(password);
}
[Obsolete("Use version taking 'char[]' instead")]
public static byte[] Pkcs5PasswordToBytes(
string password)
{
if (password == null)
return new byte[0];
return Strings.ToAsciiByteArray(password);
}
/**
* converts a password to a byte array according to the scheme in
* PKCS5 (UTF-8, no padding)
*
* @param password a character array representing the password.
* @return a byte array representing the password.
*/
public static byte[] Pkcs5PasswordToUtf8Bytes(
char[] password)
{
if (password == null)
return new byte[0];
return Encoding.UTF8.GetBytes(password);
}
[Obsolete("Use version taking 'char[]' instead")]
public static byte[] Pkcs5PasswordToUtf8Bytes(
string password)
{
if (password == null)
return new byte[0];
return Encoding.UTF8.GetBytes(password);
}
/**
* converts a password to a byte array according to the scheme in
* Pkcs12 (unicode, big endian, 2 zero pad bytes at the end).
*
* @param password a character array representing the password.
* @return a byte array representing the password.
*/
public static byte[] Pkcs12PasswordToBytes(
char[] password)
{
return Pkcs12PasswordToBytes(password, false);
}
public static byte[] Pkcs12PasswordToBytes(
char[] password,
bool wrongPkcs12Zero)
{
if (password == null || password.Length < 1)
{
return new byte[wrongPkcs12Zero ? 2 : 0];
}
// +1 for extra 2 pad bytes.
byte[] bytes = new byte[(password.Length + 1) * 2];
Encoding.BigEndianUnicode.GetBytes(password, 0, password.Length, bytes, 0);
return bytes;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;
using NUnit.Framework;
using ServiceStack.Common;
using ServiceStack.Text;
namespace RazorRockstars.Web
{
[TestFixture]
public class RazorRockstars_WebTests
{
Stopwatch startedAt;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
startedAt = Stopwatch.StartNew();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
"Time Taken {0}ms".Fmt(startedAt.ElapsedMilliseconds).Print();
}
[Ignore("Debug Run")][Test]
public void RunFor10Mins()
{
Thread.Sleep(TimeSpan.FromMinutes(10));
}
public void AssertStatus(string url, HttpStatusCode statusCode)
{
url.Print();
try
{
var text = url.GetStringFromUrl(AcceptContentType, responseFilter: r => {
if (r.StatusCode != statusCode)
Assert.Fail("'{0}' returned {1} expected {2}".Fmt(url, r.StatusCode, statusCode));
});
}
catch (WebException webEx)
{
if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError)
{
var errorResponse = ((HttpWebResponse) webEx.Response);
if (errorResponse.StatusCode != statusCode)
Assert.Fail("'{0}' returned {1} expected {2}".Fmt(url, errorResponse.StatusCode, statusCode));
return;
}
throw;
}
}
public static string AcceptContentType = "*/*";
public void Assert200(string url, params string[] containsItems)
{
try
{
Debug.WriteLine(url);
var text = url.GetStringFromUrl(AcceptContentType, responseFilter: r => {
if (r.StatusCode != HttpStatusCode.OK)
Assert.Fail(url + " did not return 200 OK");
});
foreach (var item in containsItems)
{
if (!text.Contains(item))
{
Assert.Fail(item + " was not found in " + url);
}
}
}
catch (WebException webEx)
{
var errorResponse = ((HttpWebResponse)webEx.Response);
var bytes = errorResponse.GetResponseStream().ReadFully();
var text = bytes.FromUtf8Bytes();
text.Print();
throw;
}
}
public void Assert200UrlContentType(string url, string contentType)
{
url.Print();
url.GetStringFromUrl(AcceptContentType, responseFilter: r => {
if (r.StatusCode != HttpStatusCode.OK)
Assert.Fail(url + " did not return 200 OK: " + r.StatusCode);
if (!r.ContentType.StartsWith(contentType))
Assert.Fail(url + " did not return contentType " + contentType);
});
}
public static string Host = "http://localhost:1339";
static string ViewRockstars = "<!--view:Rockstars.cshtml-->";
static string ViewRockstars2 = "<!--view:Rockstars2.cshtml-->";
static string ViewRockstars3 = "<!--view:Rockstars3.cshtml-->";
static string ViewRockstarsMark = "<!--view:RockstarsMark.md-->";
static string ViewNoModelNoController = "<!--view:NoModelNoController.cshtml-->";
static string ViewTypedModelNoController = "<!--view:TypedModelNoController.cshtml-->";
static string ViewPage1 = "<!--view:Page1.cshtml-->";
static string ViewPage2 = "<!--view:Page2.cshtml-->";
static string ViewPage3 = "<!--view:Page3.cshtml-->";
static string ViewPage4 = "<!--view:Page4.cshtml-->";
static string ViewMarkdownRootPage = "<!--view:MRootPage.md-->";
static string ViewMPage1 = "<!--view:MPage1.md-->";
static string ViewMPage2 = "<!--view:MPage2.md-->";
static string ViewMPage3 = "<!--view:MPage3.md-->";
static string ViewMPage4 = "<!--view:MPage4.md-->";
static string ViewRazorPartial = "<!--view:RazorPartial.cshtml-->";
static string ViewMarkdownPartial = "<!--view:MarkdownPartial.md-->";
static string ViewRazorPartialModel = "<!--view:RazorPartialModel.cshtml-->";
static string View_Default = "<!--view:default.cshtml-->";
static string View_Pages_Default = "<!--view:Pages/default.cshtml-->";
static string View_Pages_Dir_Default = "<!--view:Pages/Dir/default.cshtml-->";
static string ViewM_Pages_Dir2_Default = "<!--view:Pages/Dir2/default.md-->";
static string Template_Layout = "<!--template:_Layout.cshtml-->";
static string Template_Pages_Layout = "<!--template:Pages/_Layout.cshtml-->";
static string Template_Pages_Dir_Layout = "<!--template:Pages/Dir/_Layout.cshtml-->";
static string Template_SimpleLayout = "<!--template:SimpleLayout.cshtml-->";
static string Template_SimpleLayout2 = "<!--template:SimpleLayout2.cshtml-->";
static string Template_HtmlReport = "<!--template:HtmlReport.cshtml-->";
static string TemplateM_Layout = "<!--template:_Layout.shtml-->";
static string TemplateM_Pages_Layout = "<!--template:Pages/_Layout.shtml-->";
static string TemplateM_Pages_Dir_Layout = "<!--template:Pages/Dir/_Layout.shtml-->";
static string TemplateM_HtmlReport = "<!--template:HtmlReport.shtml-->";
[Test]
public void Can_get_page_with_default_view_and_template()
{
Assert200(Host + "/rockstars", ViewRockstars, Template_HtmlReport);
}
[Test]
public void Can_get_page_with_alt_view_and_default_template()
{
Assert200(Host + "/rockstars?View=Rockstars2", ViewRockstars2, Template_Layout);
}
[Test]
public void Can_get_page_with_alt_viewengine_view_and_default_template()
{
Assert200(Host + "/rockstars?View=RockstarsMark", ViewRockstarsMark, TemplateM_HtmlReport);
}
[Test]
public void Can_get_page_with_default_view_and_alt_template()
{
Assert200(Host + "/rockstars?Template=SimpleLayout", ViewRockstars, Template_SimpleLayout);
}
[Test]
public void Can_get_page_with_alt_viewengine_view_and_alt_razor_template()
{
Assert200(Host + "/rockstars?View=Rockstars2&Template=SimpleLayout2", ViewRockstars2, Template_SimpleLayout2);
}
[Test]
public void Can_get_razor_content_pages()
{
Assert200(Host + "/TypedModelNoController",
ViewTypedModelNoController, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
Assert200(Host + "/nomodelnocontroller",
ViewNoModelNoController, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial);
Assert200(Host + "/pages/page1",
ViewPage1, Template_Pages_Layout, ViewRazorPartialModel, ViewMarkdownPartial);
Assert200(Host + "/pages/dir/Page2",
ViewPage2, Template_Pages_Dir_Layout, ViewRazorPartial, ViewMarkdownPartial);
Assert200(Host + "/pages/dir2/Page3",
ViewPage3, Template_Pages_Layout, ViewRazorPartial, ViewMarkdownPartial);
Assert200(Host + "/pages/dir2/Page4",
ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial);
}
[Test]
public void Can_get_razor_content_pages_with_partials()
{
Assert200(Host + "/pages/dir2/Page4",
ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial, ViewMPage3);
}
[Test]
public void Can_get_markdown_content_pages()
{
Assert200(Host + "/MRootPage",
ViewMarkdownRootPage, TemplateM_Layout);
Assert200(Host + "/pages/mpage1",
ViewMPage1, TemplateM_Pages_Layout);
Assert200(Host + "/pages/dir/mPage2",
ViewMPage2, TemplateM_Pages_Dir_Layout);
}
[Test]
public void Redirects_when_trying_to_get_razor_page_with_extension()
{
Assert200(Host + "/pages/dir2/Page4.cshtml",
ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial, ViewMPage3);
}
[Test]
public void Redirects_when_trying_to_get_markdown_page_with_extension()
{
Assert200(Host + "/pages/mpage1.md",
ViewMPage1, TemplateM_Pages_Layout);
}
[Test]
public void Can_get_default_razor_pages()
{
Assert200(Host + "/",
View_Default, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
Assert200(Host + "/Pages/",
View_Pages_Default, Template_Pages_Layout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
Assert200(Host + "/Pages/Dir/",
View_Pages_Dir_Default, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
}
[Test]
public void Can_get_default_markdown_pages()
{
Assert200(Host + "/Pages/Dir2/",
ViewM_Pages_Dir2_Default, TemplateM_Pages_Layout);
}
[Test] //Good for testing adhoc compilation
public void Can_get_last_view_template_compiled()
{
Assert200(Host + "/rockstars?View=Rockstars3", ViewRockstars3, Template_SimpleLayout2);
}
[Test]
public void Does_return_custom_user_defined_error_pages()
{
Assert200(Host + "/throw/417/CustomErrorMessage",
"<!--view:ExpectationFailed.cshtml-->",
"ErrorCode: NotImplementedException",
"Message: CustomErrorMessage");
}
[Test]
public void Does_not_return_custom_user_defined_error_page_for_json()
{
AssertStatus(Host + "/throw/417/CustomErrorMessage?format=json", HttpStatusCode.ExpectationFailed);
}
[Test]
public void Does_not_return_custom_user_defined_error_page_for_unregistered_statuses()
{
AssertStatus(Host + "/throw/404/CustomErrorMessage", HttpStatusCode.NotFound);
}
[Test]
public void Does_allow_matching_fallback_route()
{
Assert200(Host + "/fallback", "\"Path\":\"fallback\"");
}
[Test]
public void Does_not_handle_non_matching_fallback_route()
{
AssertStatus(Host + "/fallback/extrapath", HttpStatusCode.NotFound);
}
[Test]
public void Test_multithread_errors()
{
var times = 1000;
var count = 0;
var errors = new List<Exception>();
times.Times(i =>
ThreadPool.QueueUserWorkItem(x => {
Interlocked.Increment(ref count);
try {
Assert200(Host + "/rockstars?View=Json", "[{\"");
}
catch (Exception ex) {
errors.Add(ex);
Assert.Fail("#" + count + " - " + ex.Message + ":: " + ex.GetResponseBody());
}
}));
while (count < times)
Thread.Sleep(100);
var errMsgs = errors.ConvertAll(x => x.Message);
errMsgs.PrintDump();
Assert.That(errors.Count, Is.EqualTo(0));
}
}
}
| |
using AutoMapper;
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using ReMi.Common.Constants.ReleaseCalendar;
using ReMi.Common.Constants.ReleaseExecution;
using ReMi.Common.Utils;
using ReMi.Common.Utils.Repository;
using ReMi.TestUtils.UnitTests;
using ReMi.Contracts.Plugins.Data;
using ReMi.DataAccess.BusinessEntityGateways.ReleaseCalendar;
using ReMi.DataAccess.Exceptions;
using ReMi.DataAccess.Exceptions.Configuration;
using ReMi.DataEntities.Metrics;
using ReMi.DataEntities.Plugins;
using ReMi.DataEntities.Products;
using ReMi.DataEntities.ReleaseCalendar;
using System;
using System.Collections.Generic;
using System.Linq;
using ReMi.DataEntities.Auth;
using BusinessReleaseWindow = ReMi.BusinessEntities.ReleaseCalendar.ReleaseWindow;
namespace ReMi.DataAccess.Tests.ReleaseCalendar
{
public class ReleaseWindowGatewayTests : TestClassFor<ReleaseWindowGateway>
{
private Mock<IRepository<ReleaseWindow>> _releaseWindowRepositoryMock;
private Mock<IRepository<Product>> _productRepositoryMock;
private Mock<IRepository<Metric>> _metricsRepositoryMock;
private Mock<IRepository<Account>> _accountRepositoryMock;
private Mock<IMappingEngine> _mappingEngineMock;
private Mock<IReleaseProductGateway> _releaseProductGatewayMock;
protected override ReleaseWindowGateway ConstructSystemUnderTest()
{
return new ReleaseWindowGateway
{
ReleaseWindowRepository = _releaseWindowRepositoryMock.Object,
ProductRepository = _productRepositoryMock.Object,
MetricRepository = _metricsRepositoryMock.Object,
MappingEngine = _mappingEngineMock.Object,
AccountRepository = _accountRepositoryMock.Object,
ReleaseProductGatewayFactory = () => _releaseProductGatewayMock.Object
};
}
protected override void TestInitialize()
{
_releaseWindowRepositoryMock = new Mock<IRepository<ReleaseWindow>>();
_productRepositoryMock = new Mock<IRepository<Product>>();
_metricsRepositoryMock = new Mock<IRepository<Metric>>();
_mappingEngineMock = new Mock<IMappingEngine>();
_releaseProductGatewayMock = new Mock<IReleaseProductGateway>();
_accountRepositoryMock = new Mock<IRepository<Account>>();
base.TestInitialize();
}
protected override void TestCleanup()
{
SystemTime.Reset();
base.TestCleanup();
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void GetAllStartingInTimeRange_ShouldThrowException_WhenDateRangeIsInvalid()
{
Sut.GetAllStartingInTimeRange(new DateTime(2014, 1, 2), new DateTime(2014, 1, 1));
}
[Test]
public void GetAllStartingInTimeRange_ShouldLookInReleaseWindowRepository_WhenDateRangeIsValid()
{
Sut.GetAllStartingInTimeRange(new DateTime(2014, 1, 2), new DateTime(2014, 1, 3));
_releaseWindowRepositoryMock.VerifyGet(r => r.Entities);
}
[Test]
public void GetAllStartingInTimeRange_ShouldNotLookInProductRepository_WhenDateRangeIsValid()
{
Sut.GetAllStartingInTimeRange(new DateTime(2014, 1, 2), new DateTime(2014, 1, 3));
_productRepositoryMock.VerifyGet(r => r.Entities, Times.Never());
}
[Test]
public void GetAllStartingInTimeRange_ShouldReturnOnlyWindowReleasesInRangeFromRepository_WhenDateRangeIsValid()
{
var rangeDays = RandomData.RandomInt(5, 10);
var startDate = new DateTime(2014, 1, 2);
//create twice as much (excess will be out of the range)
SetupRelaseWindowsWithProduct(rangeDays * 2, startDate);
Sut.GetAllStartingInTimeRange(startDate, startDate.AddDays(rangeDays));
_mappingEngineMock.Verify(
me => me.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindowView>>(
It.Is<IEnumerable<ReleaseWindow>>(
list => list.Count() == rangeDays + 1)));
}
[Test]
public void FindFirstOverlappedRelease_ShouldNotReturnReleases_WhenFinishTimeOfSpecifiedPeriodEqualsToExistingReleaseStartTime()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
SetupRelaseWindowsWithProduct(1, startDate, product);
Sut.FindFirstOverlappedRelease(product, startDate.AddHours(-5), startDate);
_mappingEngineMock.Verify(o =>
o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(null));
}
[Test]
public void FindFirstOverlappedRelease_ShouldReturnReleases_WhenFinishTimeOfSpecifiedPeriodGraterThenExistingReleaseStartTimeOneMinute()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
var releases = SetupRelaseWindowsWithProduct(1, startDate, product);
Sut.FindFirstOverlappedRelease(product, startDate.AddHours(-2), startDate.AddMinutes(1));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(
It.Is<ReleaseWindow>(x => x.ExternalId == releases.First().ExternalId)));
}
[Test]
public void FindFirstOverlappedRelease_ShouldReturnReleases_WhenEndTimeOfRequestedPeriodGraterThenReleaseStartTime()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
var releases = SetupRelaseWindowsWithProduct(1, startDate, product).ToList();
Sut.FindFirstOverlappedRelease(product, startDate.AddDays(-2).AddMinutes(1), startDate.AddDays(releases.Count()).AddHours(2));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(
It.Is<ReleaseWindow>(x => x.ExternalId == releases.First().ExternalId)), Times.Exactly(releases.Count));
}
[Test]
public void FindFirstOverlappedRelease_ShouldReturnReleases_WhenStartTimeOfRequestedPeriodLessThenReleaseEndTime()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
var releases = SetupRelaseWindowsWithProduct(1, startDate, product).ToList();
Sut.FindFirstOverlappedRelease(product, startDate.AddHours(1), startDate.AddHours(4));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(
It.Is<ReleaseWindow>(x => x.ExternalId == releases.First().ExternalId)), Times.Exactly(releases.Count));
}
[Test]
public void FindFirstOverlappedRelease_ShouldReturnReleases_WhenRequestedPeriodGraterThenReleasePeriod()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
var releases = SetupRelaseWindowsWithProduct(1, startDate, product).ToList();
Sut.FindFirstOverlappedRelease(product, startDate.AddHours(-4), startDate.AddHours(4));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(
It.Is<ReleaseWindow>(x => x.ExternalId == releases.First().ExternalId)), Times.Exactly(releases.Count));
}
[Test]
public void FindFirstOverlappedRelease_ShouldNotConsiderExistingReleases_WhenProductIsDifferent()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
SetupRelaseWindowsWithProduct(1, startDate, RandomData.RandomString(1, 10));
Sut.FindFirstOverlappedRelease(product, startDate, startDate.AddHours(2));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(null));
}
[Test]
public void FindFirstOverlappedRelease_ShouldNotConsiderClosedExistingReleases_WhenInvoked()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
SetupRelaseWindowsWithProduct(1, startDate, product,
r =>
{
r.Metrics = new List<Metric>
{
new Metric { ExecutedOn = RandomData.RandomDateTime(), MetricType = MetricType.Close }
};
return r;
});
Sut.FindFirstOverlappedRelease(product, startDate, startDate.AddHours(2));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(null));
}
[Test]
public void FindFirstOverlappedRelease_ShouldNotConsiderReleasesForAutomatedProducts_WhenInvoked()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
SetupRelaseWindowsWithProduct(1, startDate, product,
r =>
{
r.ReleaseProducts.First().Product.ReleaseTrack = ReleaseTrack.Automated;
return r;
});
Sut.FindFirstOverlappedRelease(product, startDate, startDate.AddHours(2));
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(null));
}
[Test]
public void FindFirstOverlappedRelease_ShouldNotConsiderMaintenanceReleases_WhenInvoked()
{
var product = RandomData.RandomString(1, 10);
var startDate = RandomData.RandomDateTime(DateTimeKind.Utc);
SetupRelaseWindowsWithProduct(1, startDate, product,
r =>
{
r.ReleaseType = ReleaseType.SystemMaintenance;
return r;
});
var result = Sut.FindFirstOverlappedRelease(product, startDate, startDate.AddHours(2));
Assert.IsNull(result);
_mappingEngineMock.Verify(o => o.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(null));
}
[Test]
[ExpectedException(typeof(ProductNotFoundException))]
public void GetNearReleases_ShouldRaiseProductNotFoundException_WhenProductInvalid()
{
Sut.GetNearReleases(string.Empty);
}
[Test]
public void GetNearReleases_ShouldReturnTwoClosedReleases_WhenInvoked()
{
var product = RandomData.RandomString(5);
var rows = Builder<ReleaseWindow>.CreateListOfSize(RandomData.RandomInt(5, 10))
.All()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.ReleaseProducts, new[] { SetupReleaseProduct(product) })
.With(o => o.Metrics, new List<Metric>
{
new Metric { ExecutedOn = RandomData.RandomDateTime(), MetricType = MetricType.Close }
})
.Build();
var requiredRows = rows.OrderByDescending(o => o.StartTime).Take(2).ToList();
_releaseWindowRepositoryMock.SetupEntities(rows);
Sut.GetNearReleases(product);
_mappingEngineMock.Verify(
me => me.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(
It.Is<IEnumerable<ReleaseWindow>>(
list => list.Count() == requiredRows.Count
&& list.Select(o => o.ExternalId).ToArray().All(x => requiredRows.Any(y => y.ExternalId == x)))));
}
[Test]
public void GetNearReleases_ShouldReturnThreeOpenReleases_WhenInvoked()
{
var product = RandomData.RandomString(5);
var rows = Builder<ReleaseWindow>.CreateListOfSize(RandomData.RandomInt(5, 10))
.All()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.ReleaseProducts, new[] { SetupReleaseProduct(product) })
.With(o => o.Metrics, new List<Metric>())
.Build();
var requiredRows = rows.OrderBy(o => o.StartTime).Take(3).ToList();
_releaseWindowRepositoryMock.SetupEntities(rows);
Sut.GetNearReleases(product);
_mappingEngineMock.Verify(
me => me.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(
It.Is<IEnumerable<ReleaseWindow>>(
list => list.Count() == requiredRows.Count
&& list.Select(o => o.ExternalId).ToArray().All(x => requiredRows.Any(y => y.ExternalId == x)))));
}
[Test]
public void GetNearReleases_ShouldReturnMixedReleases_WhenInvoked()
{
var product = RandomData.RandomString(5);
var rows = Builder<ReleaseWindow>.CreateListOfSize(20)
.All()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.ReleaseProducts, new[] { SetupReleaseProduct(product) })
.TheFirst(10)
.With(o => o.Metrics, new List<Metric>())
.TheLast(10)
.With(o => o.Metrics, new List<Metric>
{
new Metric { ExecutedOn = RandomData.RandomDateTime(), MetricType = MetricType.Close }
})
.Build();
_releaseWindowRepositoryMock.SetupEntities(rows);
Sut.GetNearReleases(product);
_mappingEngineMock.Verify(
me => me.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(
It.Is<IEnumerable<ReleaseWindow>>(
list => list.Count() == 5
&& list.Count(o => !o.Metrics.Any(m => m.MetricType == MetricType.Close && m.ExecutedOn.HasValue)) == 3
&& list.Count(o => o.Metrics.Any(m => m.MetricType == MetricType.Close && m.ExecutedOn.HasValue)) == 2)));
}
[Test]
public void GetCurrentRelease_ShouldReturnRelease_WhenReleaseWillStartInFifteenMinutes()
{
var startTime = new DateTime(2015, 1, 1, 20, 0, 0, DateTimeKind.Utc);
var endTime = new DateTime(2015, 1, 1, 22, 0, 0, DateTimeKind.Utc);
var nowTime = new DateTime(2015, 1, 1, 19, 45, 0, DateTimeKind.Utc);
var product = new Product { Description = RandomData.RandomString(10) };
var release = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ExternalId, Guid.NewGuid())
.With(x => x.ReleaseProducts, new[] { new ReleaseProduct { Product = product } })
.With(x => x.Metrics, new[]
{
new Metric { MetricType = MetricType.StartTime, ExecutedOn = startTime },
new Metric { MetricType = MetricType.EndTime, ExecutedOn = endTime }
}).Build();
SystemTime.Mock(nowTime);
_releaseWindowRepositoryMock.SetupEntities(new[] { release });
Sut.GetCurrentRelease(product.Description);
_mappingEngineMock.Verify(x => x.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(release), Times.Once);
}
[Test]
public void GetCurrentRelease_ShouldReturnRelease_WhenReleaseWhenNowIsOnStartTime()
{
var startTime = new DateTime(2015, 1, 1, 20, 0, 0, DateTimeKind.Utc);
var endTime = new DateTime(2015, 1, 1, 22, 0, 0, DateTimeKind.Utc);
var nowTime = startTime;
var product = new Product { Description = RandomData.RandomString(10) };
var release = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ExternalId, Guid.NewGuid())
.With(x => x.ReleaseProducts, new[] { new ReleaseProduct { Product = product } })
.With(x => x.Metrics, new[]
{
new Metric { MetricType = MetricType.StartTime, ExecutedOn = startTime },
new Metric { MetricType = MetricType.EndTime, ExecutedOn = endTime }
}).Build();
SystemTime.Mock(nowTime);
_releaseWindowRepositoryMock.SetupEntities(new[] { release });
Sut.GetCurrentRelease(product.Description);
_mappingEngineMock.Verify(x => x.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(release), Times.Once);
}
[Test]
public void GetCurrentRelease_ShouldReturnRelease_WhenReleaseWhenNowIsOnEndTime()
{
var startTime = new DateTime(2015, 1, 1, 20, 0, 0, DateTimeKind.Utc);
var endTime = new DateTime(2015, 1, 1, 22, 0, 0, DateTimeKind.Utc);
var nowTime = startTime;
var product = new Product { Description = RandomData.RandomString(10) };
var release = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ExternalId, Guid.NewGuid())
.With(x => x.ReleaseProducts, new[] { new ReleaseProduct { Product = product } })
.With(x => x.Metrics, new[]
{
new Metric { MetricType = MetricType.StartTime, ExecutedOn = startTime },
new Metric { MetricType = MetricType.EndTime, ExecutedOn = endTime }
}).Build();
SystemTime.Mock(nowTime);
_releaseWindowRepositoryMock.SetupEntities(new[] { release });
Sut.GetCurrentRelease(product.Description);
_mappingEngineMock.Verify(x => x.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(release), Times.Once);
}
[Test]
public void GetCurrentRelease_ShouldNotReturnRelease_WhenReleaseWillStartInSixteenMinutes()
{
var startTime = new DateTime(2015, 1, 1, 20, 0, 0, DateTimeKind.Utc);
var endTime = new DateTime(2015, 1, 1, 22, 0, 0, DateTimeKind.Utc);
var nowTime = new DateTime(2015, 1, 1, 19, 44, 0, DateTimeKind.Utc);
var product = new Product { Description = RandomData.RandomString(10) };
var release = Builder<ReleaseWindow>.CreateNew()
.With(x => x.ExternalId, Guid.NewGuid())
.With(x => x.ReleaseProducts, new[] { new ReleaseProduct { Product = product } })
.With(x => x.Metrics, new[]
{
new Metric { MetricType = MetricType.StartTime, ExecutedOn = startTime },
new Metric { MetricType = MetricType.EndTime, ExecutedOn = endTime }
}).Build();
SystemTime.Mock(nowTime);
_releaseWindowRepositoryMock.SetupEntities(new[] { release });
Sut.GetCurrentRelease(product.Description);
_mappingEngineMock.Verify(x => x.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(null), Times.Once);
}
[Test]
public void CloseRelease_ShouldFillOutClosedOnAndReleaseNotesAndInserMetric_WhenUpdatingReleaseWindowAndMetricNotExists()
{
var rows = Builder<ReleaseWindow>.CreateListOfSize(20)
.All()
.Do(o => o.ExternalId = Guid.NewGuid())
.Do(o => o.Metrics = new List<Metric>())
.Do(o => o.ReleaseWindowId = RandomData.RandomInt(int.MaxValue))
.Build();
_releaseWindowRepositoryMock.SetupEntities(rows);
_metricsRepositoryMock.Setup(x => x.Insert(It.Is<Metric>(m => m.ReleaseWindowId == rows[5].ReleaseWindowId)))
.Callback((Metric m) => rows[5].Metrics.Add(m));
var releaseNotes = RandomData.RandomString(10);
var now = DateTime.UtcNow;
SystemTime.Mock(now);
Sut.CloseRelease(releaseNotes, rows[5].ExternalId);
Assert.AreEqual(releaseNotes, rows[5].ReleaseNotes.ReleaseNotes);
Assert.AreEqual(now, rows[5].Metrics.First(m => m.MetricType == MetricType.Close).ExecutedOn);
_releaseWindowRepositoryMock.Verify(x => x.Update(rows[5]));
_metricsRepositoryMock.Verify(x => x.Insert(It.IsAny<Metric>()), Times.Once);
_metricsRepositoryMock.Verify(x => x.Update(It.IsAny<Metric>()), Times.Never);
}
[Test]
public void CloseRelease_ShouldFillOutClosedOnAndReleaseNotesAndUpdateMetric_WhenUpdatingReleaseWindowAndMetricExists()
{
var rows = Builder<ReleaseWindow>.CreateListOfSize(20)
.All()
.Do(o => o.ExternalId = Guid.NewGuid())
.Do(o => o.Metrics = new List<Metric>())
.Do(o => o.ReleaseWindowId = RandomData.RandomInt(int.MaxValue))
.Build();
var metric = new Metric
{
ExternalId = Guid.NewGuid(),
MetricType = MetricType.Close,
ReleaseWindowId = rows[5].ReleaseWindowId
};
_releaseWindowRepositoryMock.SetupEntities(rows);
_metricsRepositoryMock.SetupEntities(new[] { metric });
rows[5].Metrics.Add(metric);
var releaseNotes = RandomData.RandomString(10);
var now = DateTime.UtcNow;
SystemTime.Mock(now);
Sut.CloseRelease(releaseNotes, rows[5].ExternalId);
Assert.AreEqual(releaseNotes, rows[5].ReleaseNotes.ReleaseNotes);
Assert.AreEqual(now, rows[5].Metrics.First(m => m.MetricType == MetricType.Close).ExecutedOn);
_releaseWindowRepositoryMock.Verify(x => x.Update(rows[5]));
_metricsRepositoryMock.Verify(x => x.Insert(It.IsAny<Metric>()), Times.Never);
_metricsRepositoryMock.Verify(x => x.Update(It.IsAny<Metric>()), Times.Once);
}
[Test]
[ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void CloseRelease_ShouldThrowException_WhenReleaseWindowNotFound()
{
_releaseWindowRepositoryMock.SetupEntities(new ReleaseWindow[] { });
Sut.CloseRelease(string.Empty, Guid.NewGuid());
}
[Test]
[ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void GetByExternalId_ShouldRaiseExceptionNonExistingId_WhenCheckForExistanceForce()
{
Sut.GetByExternalId(Guid.Empty, true);
}
[Test]
public void GetByExternalId_ShouldReturnNullForNonExistingId_WhenCheckForExistanceNotForced()
{
var result = Sut.GetByExternalId(Guid.Empty);
Assert.IsNull(result);
}
[Test]
public void GetByExternalId_ShouldReturnReleaseWindowWithReleaseNotesAndPlugins_WhenReleaseExists()
{
var releaseWindow = new ReleaseWindow
{
ExternalId = Guid.NewGuid(),
ReleaseNotes = new ReleaseNote { ReleaseNotes = RandomData.RandomString(10), Issues = RandomData.RandomString(10) },
ReleaseProducts = new List<ReleaseProduct>
{
new ReleaseProduct { Product = new Product { PluginPackageConfiguration = new List<PluginPackageConfiguration>
{
new PluginPackageConfiguration
{
PluginId = RandomData.RandomInt(int.MaxValue),
Plugin = new DataEntities.Plugins.Plugin { ExternalId = Guid.NewGuid(), Key = RandomData.RandomString(10), PluginType = RandomData.RandomEnum<PluginType>() }
}
}}}
}
};
_releaseWindowRepositoryMock.SetupEntities(new[] { releaseWindow });
_mappingEngineMock.Setup(x => x.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(releaseWindow))
.Returns((ReleaseWindow r) => new BusinessEntities.ReleaseCalendar.ReleaseWindow { ExternalId = releaseWindow.ExternalId });
var result = Sut.GetByExternalId(releaseWindow.ExternalId, true, true);
Assert.AreEqual(releaseWindow.ExternalId, result.ExternalId);
Assert.AreEqual(releaseWindow.ReleaseNotes.ReleaseNotes, result.ReleaseNotes);
Assert.AreEqual(releaseWindow.ReleaseNotes.Issues, result.Issues);
Assert.AreEqual(releaseWindow.ReleaseProducts.First().Product.PluginPackageConfiguration.First().Plugin.ExternalId, result.Plugins.First().PluginId);
Assert.AreEqual(releaseWindow.ReleaseProducts.First().Product.PluginPackageConfiguration.First().Plugin.Key, result.Plugins.First().PluginKey);
Assert.AreEqual(releaseWindow.ReleaseProducts.First().Product.PluginPackageConfiguration.First().Plugin.PluginType, result.Plugins.First().PluginType);
}
[Test]
[ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void SaveIssues_ShouldRaiseExceptionNonExistingId_WhenCheckForExistanceForce()
{
Sut.SaveIssues(new BusinessEntities.ReleaseCalendar.ReleaseWindow { ExternalId = Guid.NewGuid() });
}
[Test]
public void SaveIssues_ShouldCreateReleaseNotes_WhenTheyDoesNotExist()
{
var releaseWindow = new ReleaseWindow { ExternalId = Guid.NewGuid() };
var issues = RandomData.RandomString(44, 66);
_releaseWindowRepositoryMock.SetupEntities(new List<ReleaseWindow> { releaseWindow });
Sut.SaveIssues(new BusinessEntities.ReleaseCalendar.ReleaseWindow { ExternalId = releaseWindow.ExternalId, Issues = issues });
_releaseWindowRepositoryMock.Verify(
x =>
x.Update(
It.Is<ReleaseWindow>(
w =>
w.ExternalId == releaseWindow.ExternalId && w.ReleaseNotes != null &&
w.ReleaseNotes.Issues == issues)));
}
[Test]
public void SaveIssues_ShouldJustSaveIssues_WhenReleaseNotesExist()
{
var releaseWindow = new ReleaseWindow
{
ExternalId = Guid.NewGuid(),
ReleaseNotes = new ReleaseNote { Issues = RandomData.RandomString(33, 55) }
};
var issues = RandomData.RandomString(44, 66);
_releaseWindowRepositoryMock.SetupEntities(new List<ReleaseWindow> { releaseWindow });
Sut.SaveIssues(new BusinessEntities.ReleaseCalendar.ReleaseWindow { ExternalId = releaseWindow.ExternalId, Issues = issues });
_releaseWindowRepositoryMock.Verify(
x =>
x.Update(
It.Is<ReleaseWindow>(
w =>
w.ExternalId == releaseWindow.ExternalId && w.ReleaseNotes != null &&
w.ReleaseNotes.Issues == issues)));
}
[Test]
public void UpdateReleaseDecision_ShouldUpdateReleaseDecisionField_WhenInvoked()
{
var rows = Builder<ReleaseWindow>.CreateListOfSize(20)
.All()
.Do(o => o.ExternalId = Guid.NewGuid())
.Build();
_releaseWindowRepositoryMock.SetupEntities(rows);
var releaseDecision = RandomData.RandomEnum<ReleaseDecision>();
Sut.UpdateReleaseDecision(rows[5].ExternalId, releaseDecision);
Assert.AreEqual(releaseDecision, rows[5].ReleaseDecision);
_releaseWindowRepositoryMock.Verify(x => x.Update(rows[5]));
}
[Test]
[ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void UpdateReleaseDecision_ShouldThrowException_WhenReleaseWindowNotFound()
{
_releaseWindowRepositoryMock.SetupEntities(new ReleaseWindow[] { });
Sut.UpdateReleaseDecision(Guid.NewGuid(), ReleaseDecision.Undetermined);
}
[Test]
public void ApproveRelease_ShouldInserMetric_WhenMetricNotExists()
{
var rows = Builder<ReleaseWindow>.CreateListOfSize(20)
.All()
.Do(o => o.ExternalId = Guid.NewGuid())
.Do(o => o.Metrics = new List<Metric>())
.Do(o => o.ReleaseWindowId = RandomData.RandomInt(int.MaxValue))
.Build();
_releaseWindowRepositoryMock.SetupEntities(rows);
_metricsRepositoryMock.Setup(x => x.Insert(It.Is<Metric>(m => m.ReleaseWindowId == rows[5].ReleaseWindowId)))
.Callback((Metric m) => rows[5].Metrics.Add(m));
var now = DateTime.UtcNow;
SystemTime.Mock(now);
Sut.ApproveRelease(rows[5].ExternalId);
Assert.AreEqual(now, rows[5].Metrics.First(m => m.MetricType == MetricType.Approve).ExecutedOn);
_metricsRepositoryMock.Verify(x => x.Insert(It.IsAny<Metric>()), Times.Once);
_metricsRepositoryMock.Verify(x => x.Update(It.IsAny<Metric>()), Times.Never);
}
[Test]
public void ApproveRelease_ShouldUpdateMetric_WhenMetricExists()
{
var rows = Builder<ReleaseWindow>.CreateListOfSize(20)
.All()
.Do(o => o.ExternalId = Guid.NewGuid())
.Do(o => o.Metrics = new List<Metric>())
.Do(o => o.ReleaseWindowId = RandomData.RandomInt(int.MaxValue))
.Build();
var metric = new Metric
{
ExternalId = Guid.NewGuid(),
MetricType = MetricType.Approve,
ReleaseWindowId = rows[5].ReleaseWindowId
};
_releaseWindowRepositoryMock.SetupEntities(rows);
_metricsRepositoryMock.SetupEntities(new[] { metric });
rows[5].Metrics.Add(metric);
var now = DateTime.UtcNow;
SystemTime.Mock(now);
Sut.ApproveRelease(rows[5].ExternalId);
Assert.AreEqual(now, rows[5].Metrics.First(m => m.MetricType == MetricType.Approve).ExecutedOn);
_metricsRepositoryMock.Verify(x => x.Insert(It.IsAny<Metric>()), Times.Never);
_metricsRepositoryMock.Verify(x => x.Update(It.IsAny<Metric>()), Times.Once);
}
[Test]
[ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void ApproveRelease_ShouldThrowException_WhenReleaseWindowNotFound()
{
_releaseWindowRepositoryMock.SetupEntities(new ReleaseWindow[] { });
Sut.ApproveRelease(Guid.NewGuid());
}
[Test]
public void GetExpiredReleases_ShouldReturnTwoClosedReleases_WhenInvoked()
{
var product = RandomData.RandomString(5);
var rows = new[]
{
Builder<ReleaseWindow>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.ReleaseProducts, new[] {SetupReleaseProduct(product)})
.With(o => o.Metrics, new List<Metric>
{
new Metric { ExecutedOn = RandomData.RandomDateTime(), MetricType = MetricType.Close }
})
.Build(),
Builder<ReleaseWindow>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.ReleaseProducts, new[] {SetupReleaseProduct(product)})
.With(o => o.Metrics, new List<Metric>
{
new Metric { ExecutedOn = RandomData.RandomDateTime(), MetricType = MetricType.Close },
new Metric { ExecutedOn = DateTime.UtcNow.AddHours(-1), MetricType = MetricType.EndTime }
})
.Build(),
Builder<ReleaseWindow>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.ReleaseProducts, new[] {SetupReleaseProduct(product)})
.With(o => o.Metrics, new List<Metric>
{
new Metric { ExecutedOn = null, MetricType = MetricType.Close },
new Metric { ExecutedOn = DateTime.UtcNow.AddHours(-1), MetricType = MetricType.EndTime }
})
.Build()
};
var requiredRow = rows[2];
_releaseWindowRepositoryMock.SetupEntities(rows);
Sut.GetExpiredReleases();
_mappingEngineMock.Verify(
x => x.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(
It.Is<IEnumerable<ReleaseWindow>>(
list => list.Count() == 1
&& list.First().ExternalId == requiredRow.ExternalId)));
}
[Test]
[ExpectedException(typeof(AccountNotFoundException))]
public void Create_ShouldThrowException_WhenAccountNotFound()
{
_accountRepositoryMock.SetupEntities(new[] { new Account() });
Sut.Create(new BusinessReleaseWindow(), Guid.NewGuid());
}
[Test]
[ExpectedException(typeof(ProductNotFoundException))]
public void Create_ShouldThrowException_WhenInvalidProductUsed()
{
var product = SetupProduct("P1");
var account = new Account { ExternalId = Guid.NewGuid() };
var release = Builder<BusinessReleaseWindow>.CreateNew()
.With(x => x.ExternalId)
.With(x => x.Products = new[] { "PX" })
.Build();
var dataRelease = BuildReleaseWindows(product, 1, DateTime.UtcNow.AddDays(1)).First();
_mappingEngineMock.Setup(x => x.Map<BusinessReleaseWindow, ReleaseWindow>(release))
.Returns(dataRelease);
_accountRepositoryMock.SetupEntities(new[] { account });
Sut.Create(release, account.ExternalId);
}
[Test]
[ExpectedException(typeof(ProductNotFoundException))]
public void Create_ShouldThrowException_WhenNotAllProductNamesResolved()
{
var products = SetupProducts(new[] { "P1", "P2" });
var account = new Account { ExternalId = Guid.NewGuid() };
var release = Builder<BusinessReleaseWindow>.CreateNew()
.With(x => x.ExternalId)
.With(x => x.Products = new[] { "P1", "PX" })
.Build();
var dataRelease = BuildReleaseWindows(products.First(), 1, DateTime.UtcNow.AddDays(1)).First();
_mappingEngineMock.Setup(x => x.Map<BusinessReleaseWindow, ReleaseWindow>(release))
.Returns(dataRelease);
_accountRepositoryMock.SetupEntities(new[] { account });
Sut.Create(release, account.ExternalId);
}
[Test]
public void Create_ShouldAssignReleaseWithProduct_WhenInvoked()
{
var product = SetupProduct("P1");
var account = new Account { ExternalId = Guid.NewGuid() };
var release = Builder<BusinessReleaseWindow>.CreateNew()
.With(x => x.ExternalId)
.With(x => x.Products = new[] { product.Description })
.Build();
var dataRelease = BuildReleaseWindows(product, 1, DateTime.UtcNow.AddDays(1)).First();
_mappingEngineMock.Setup(x => x.Map<BusinessReleaseWindow, ReleaseWindow>(release))
.Returns(dataRelease);
_accountRepositoryMock.SetupEntities(new[] { account });
Sut.Create(release, account.ExternalId);
_releaseProductGatewayMock.Verify(x => x.AssignProductsToRelease(release.ExternalId, It.Is<IEnumerable<string>>(p => p.Count() == 1 && p.First() == "P1")));
}
[Test]
[ExpectedException(typeof(ReleaseWindowNotFoundException))]
public void CloseFailedRelease_ShouldThrowException_WhenReleaseNotFound()
{
var product = SetupProduct("P1");
var release = Builder<BusinessReleaseWindow>.CreateNew()
.With(x => x.ExternalId)
.With(x => x.Products = new[] { product.Description })
.Build();
Sut.CloseFailedRelease(release.ExternalId, "issues");
}
[Test]
public void CloseFailedRelease_ShouldCreateReleaseNotes_WhenReleaseNotesNotCreated()
{
var releases = SetupRelaseWindowsWithProduct(1, DateTime.UtcNow, "P1").ToList();
Sut.CloseFailedRelease(releases.First().ExternalId, "issues");
_releaseWindowRepositoryMock.Verify(x =>
x.Update(It.Is<ReleaseWindow>(r =>
r.ReleaseNotes != null
&& r.ReleaseNotes.Issues == "issues"
)));
}
[Test]
public void CloseFailedRelease_ShouldUpdateIssues_WhenReleaseNotesAlreadyExists()
{
var releases = SetupRelaseWindowsWithProduct(1, DateTime.UtcNow, "P1", r =>
{
r.ReleaseNotes = new ReleaseNote { Issues = "old issues" };
return r;
}).ToList();
Sut.CloseFailedRelease(releases.First().ExternalId, "issues");
_releaseWindowRepositoryMock.Verify(x =>
x.Update(It.Is<ReleaseWindow>(r =>
r.ReleaseNotes != null
&& r.ReleaseNotes.Issues == "old issues" + Environment.NewLine + Environment.NewLine + "issues"
)));
}
[Test]
public void CloseFailedRelease_ShouldMarkReleaseAsFailed_WhenInvoked()
{
var releases = SetupRelaseWindowsWithProduct(1, DateTime.UtcNow, "P1").ToList();
Sut.CloseFailedRelease(releases.First().ExternalId, "issues");
_releaseWindowRepositoryMock.Verify(x =>
x.Update(It.Is<ReleaseWindow>(r => r.IsFailed)));
}
[Test]
public void CloseFailedRelease_ShouldMarkMetricsAsCompleted_WhenInvoked()
{
var releases = SetupRelaseWindowsWithProduct(1, DateTime.UtcNow, "P1").ToList();
_metricsRepositoryMock.SetupEntities(new[]
{
new Metric{ExecutedOn = DateTime.UtcNow, MetricId = 1, MetricType = MetricType.StartRun, ReleaseWindow = releases.First()},
new Metric{ExecutedOn = DateTime.UtcNow, MetricId = 2, MetricType = MetricType.SiteDown, ReleaseWindow = releases.First()},
new Metric{ExecutedOn = DateTime.UtcNow, MetricId = 3, MetricType = MetricType.SiteUp, ReleaseWindow = releases.First()},
new Metric{ExecutedOn = null, MetricId = 4, MetricType = MetricType.SignOff, ReleaseWindow = releases.First()},
new Metric{ExecutedOn = null, MetricId = 5, MetricType = MetricType.FinishRun, ReleaseWindow = releases.First()}
});
Sut.CloseFailedRelease(releases.First().ExternalId, "issues");
_metricsRepositoryMock.Verify(x =>
x.Update(It.IsAny<Metric>()), Times.Exactly(2));
_metricsRepositoryMock.Verify(x =>
x.Update(It.Is<Metric>(m => m.ExecutedOn.HasValue && m.MetricId == 4)));
_metricsRepositoryMock.Verify(x =>
x.Update(It.Is<Metric>(m => m.ExecutedOn.HasValue && m.MetricId == 5)));
}
private Product SetupProduct(string name = null, int? id = null)
{
var product = Builder<Product>.CreateNew()
.With(o => o.ProductId, id ?? RandomData.RandomInt(int.MaxValue))
.With(o => o.Description, name ?? RandomData.RandomString(50))
.With(o => o.ReleaseTrack, ReleaseTrack.Manual)
.Build();
_productRepositoryMock.SetupEntities(new[] { product });
return product;
}
private IEnumerable<Product> SetupProducts(IEnumerable<string> names = null)
{
var products = names.Select(x => Builder<Product>.CreateNew()
.With(o => o.ProductId, RandomData.RandomInt(int.MaxValue))
.With(o => o.Description, x ?? RandomData.RandomString(50))
.With(o => o.ReleaseTrack, ReleaseTrack.Manual)
.Build()).ToList();
_productRepositoryMock.SetupEntities(products);
return products;
}
private ReleaseProduct SetupReleaseProduct(string name = null, int? id = null)
{
var product = SetupProduct(name, id);
return new ReleaseProduct { Product = product };
}
private IEnumerable<ReleaseWindow> SetupRelaseWindowsWithProduct(int releaseWindowCount, DateTime startDate, string product = null, Func<ReleaseWindow, ReleaseWindow> testDataCustomiser = null)
{
var dbProduct = SetupProduct(product);
IEnumerable<ReleaseWindow> releaseWindows = BuildReleaseWindows(dbProduct, releaseWindowCount, startDate).ToList();
if (testDataCustomiser != null)
releaseWindows = releaseWindows.Select(testDataCustomiser).ToList();
_releaseWindowRepositoryMock.SetupEntities(releaseWindows);
return releaseWindows;
}
private static IEnumerable<ReleaseWindow> BuildReleaseWindows(Product product, int releaseWindowCount, DateTime startDate)
{
//generator is used to increment daily the release window
var dayGenerator = new SequentialGenerator<int> { Direction = GeneratorDirection.Ascending, Increment = 1 };
dayGenerator.StartingWith(0);
IList<ReleaseWindow> releaseWindows = Builder<ReleaseWindow>
.CreateListOfSize(releaseWindowCount)
.All()
.With(rw => rw.ReleaseProducts = new[] { new ReleaseProduct { Product = product } })
.And(rw => rw.StartTime = startDate.AddDays(dayGenerator.Generate()))
.And(rw => rw.ExternalId = Guid.NewGuid())
.Build();
foreach (var releaseWindow in releaseWindows)
{
releaseWindow.Metrics = new List<Metric>
{
new Metric
{
ExecutedOn = releaseWindow.StartTime,
MetricType = MetricType.StartTime,
ExternalId = Guid.NewGuid()
},
new Metric
{
ExecutedOn = releaseWindow.StartTime.AddHours(2),
MetricType = MetricType.EndTime,
ExternalId = Guid.NewGuid()
},
};
}
return releaseWindows;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Specifies the envelope recipients.
/// </summary>
[DataContract]
public partial class Recipients : IEquatable<Recipients>, IValidatableObject
{
public Recipients()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="Recipients" /> class.
/// </summary>
/// <param name="Agents">A complex type defining the management and access rights of a recipient assigned assigned as an agent on the document..</param>
/// <param name="CarbonCopies">A complex type containing information about recipients who should receive a copy of the envelope, but does not need to sign it..</param>
/// <param name="CertifiedDeliveries">A complex type containing information on a recipient the must receive the completed documents for the envelope to be completed, but the recipient does not need to sign, initial, date, or add information to any of the documents..</param>
/// <param name="CurrentRoutingOrder">.</param>
/// <param name="Editors">A complex type defining the management and access rights of a recipient assigned assigned as an editor on the document..</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="InPersonSigners">Specifies a signer that is in the same physical location as a DocuSign user who will act as a Signing Host for the transaction. The recipient added is the Signing Host and new separate Signer Name field appears after Sign in person is selected..</param>
/// <param name="Intermediaries">Identifies a recipient that can, but is not required to, add name and email information for recipients at the same or subsequent level in the routing order (until subsequent Agents, Editors or Intermediaries recipient types are added)..</param>
/// <param name="RecipientCount">.</param>
/// <param name="Seals">.</param>
/// <param name="Signers">A complex type containing information about the Signer recipient..</param>
public Recipients(List<Agent> Agents = default(List<Agent>), List<CarbonCopy> CarbonCopies = default(List<CarbonCopy>), List<CertifiedDelivery> CertifiedDeliveries = default(List<CertifiedDelivery>), string CurrentRoutingOrder = default(string), List<Editor> Editors = default(List<Editor>), ErrorDetails ErrorDetails = default(ErrorDetails), List<InPersonSigner> InPersonSigners = default(List<InPersonSigner>), List<Intermediary> Intermediaries = default(List<Intermediary>), string RecipientCount = default(string), List<SealSign> Seals = default(List<SealSign>), List<Signer> Signers = default(List<Signer>))
{
this.Agents = Agents;
this.CarbonCopies = CarbonCopies;
this.CertifiedDeliveries = CertifiedDeliveries;
this.CurrentRoutingOrder = CurrentRoutingOrder;
this.Editors = Editors;
this.ErrorDetails = ErrorDetails;
this.InPersonSigners = InPersonSigners;
this.Intermediaries = Intermediaries;
this.RecipientCount = RecipientCount;
this.Seals = Seals;
this.Signers = Signers;
}
/// <summary>
/// A complex type defining the management and access rights of a recipient assigned assigned as an agent on the document.
/// </summary>
/// <value>A complex type defining the management and access rights of a recipient assigned assigned as an agent on the document.</value>
[DataMember(Name="agents", EmitDefaultValue=false)]
public List<Agent> Agents { get; set; }
/// <summary>
/// A complex type containing information about recipients who should receive a copy of the envelope, but does not need to sign it.
/// </summary>
/// <value>A complex type containing information about recipients who should receive a copy of the envelope, but does not need to sign it.</value>
[DataMember(Name="carbonCopies", EmitDefaultValue=false)]
public List<CarbonCopy> CarbonCopies { get; set; }
/// <summary>
/// A complex type containing information on a recipient the must receive the completed documents for the envelope to be completed, but the recipient does not need to sign, initial, date, or add information to any of the documents.
/// </summary>
/// <value>A complex type containing information on a recipient the must receive the completed documents for the envelope to be completed, but the recipient does not need to sign, initial, date, or add information to any of the documents.</value>
[DataMember(Name="certifiedDeliveries", EmitDefaultValue=false)]
public List<CertifiedDelivery> CertifiedDeliveries { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="currentRoutingOrder", EmitDefaultValue=false)]
public string CurrentRoutingOrder { get; set; }
/// <summary>
/// A complex type defining the management and access rights of a recipient assigned assigned as an editor on the document.
/// </summary>
/// <value>A complex type defining the management and access rights of a recipient assigned assigned as an editor on the document.</value>
[DataMember(Name="editors", EmitDefaultValue=false)]
public List<Editor> Editors { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// Specifies a signer that is in the same physical location as a DocuSign user who will act as a Signing Host for the transaction. The recipient added is the Signing Host and new separate Signer Name field appears after Sign in person is selected.
/// </summary>
/// <value>Specifies a signer that is in the same physical location as a DocuSign user who will act as a Signing Host for the transaction. The recipient added is the Signing Host and new separate Signer Name field appears after Sign in person is selected.</value>
[DataMember(Name="inPersonSigners", EmitDefaultValue=false)]
public List<InPersonSigner> InPersonSigners { get; set; }
/// <summary>
/// Identifies a recipient that can, but is not required to, add name and email information for recipients at the same or subsequent level in the routing order (until subsequent Agents, Editors or Intermediaries recipient types are added).
/// </summary>
/// <value>Identifies a recipient that can, but is not required to, add name and email information for recipients at the same or subsequent level in the routing order (until subsequent Agents, Editors or Intermediaries recipient types are added).</value>
[DataMember(Name="intermediaries", EmitDefaultValue=false)]
public List<Intermediary> Intermediaries { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="recipientCount", EmitDefaultValue=false)]
public string RecipientCount { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="seals", EmitDefaultValue=false)]
public List<SealSign> Seals { get; set; }
/// <summary>
/// A complex type containing information about the Signer recipient.
/// </summary>
/// <value>A complex type containing information about the Signer recipient.</value>
[DataMember(Name="signers", EmitDefaultValue=false)]
public List<Signer> Signers { 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 Recipients {\n");
sb.Append(" Agents: ").Append(Agents).Append("\n");
sb.Append(" CarbonCopies: ").Append(CarbonCopies).Append("\n");
sb.Append(" CertifiedDeliveries: ").Append(CertifiedDeliveries).Append("\n");
sb.Append(" CurrentRoutingOrder: ").Append(CurrentRoutingOrder).Append("\n");
sb.Append(" Editors: ").Append(Editors).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" InPersonSigners: ").Append(InPersonSigners).Append("\n");
sb.Append(" Intermediaries: ").Append(Intermediaries).Append("\n");
sb.Append(" RecipientCount: ").Append(RecipientCount).Append("\n");
sb.Append(" Seals: ").Append(Seals).Append("\n");
sb.Append(" Signers: ").Append(Signers).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 Recipients);
}
/// <summary>
/// Returns true if Recipients instances are equal
/// </summary>
/// <param name="other">Instance of Recipients to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Recipients other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Agents == other.Agents ||
this.Agents != null &&
this.Agents.SequenceEqual(other.Agents)
) &&
(
this.CarbonCopies == other.CarbonCopies ||
this.CarbonCopies != null &&
this.CarbonCopies.SequenceEqual(other.CarbonCopies)
) &&
(
this.CertifiedDeliveries == other.CertifiedDeliveries ||
this.CertifiedDeliveries != null &&
this.CertifiedDeliveries.SequenceEqual(other.CertifiedDeliveries)
) &&
(
this.CurrentRoutingOrder == other.CurrentRoutingOrder ||
this.CurrentRoutingOrder != null &&
this.CurrentRoutingOrder.Equals(other.CurrentRoutingOrder)
) &&
(
this.Editors == other.Editors ||
this.Editors != null &&
this.Editors.SequenceEqual(other.Editors)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.InPersonSigners == other.InPersonSigners ||
this.InPersonSigners != null &&
this.InPersonSigners.SequenceEqual(other.InPersonSigners)
) &&
(
this.Intermediaries == other.Intermediaries ||
this.Intermediaries != null &&
this.Intermediaries.SequenceEqual(other.Intermediaries)
) &&
(
this.RecipientCount == other.RecipientCount ||
this.RecipientCount != null &&
this.RecipientCount.Equals(other.RecipientCount)
) &&
(
this.Seals == other.Seals ||
this.Seals != null &&
this.Seals.SequenceEqual(other.Seals)
) &&
(
this.Signers == other.Signers ||
this.Signers != null &&
this.Signers.SequenceEqual(other.Signers)
);
}
/// <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.Agents != null)
hash = hash * 59 + this.Agents.GetHashCode();
if (this.CarbonCopies != null)
hash = hash * 59 + this.CarbonCopies.GetHashCode();
if (this.CertifiedDeliveries != null)
hash = hash * 59 + this.CertifiedDeliveries.GetHashCode();
if (this.CurrentRoutingOrder != null)
hash = hash * 59 + this.CurrentRoutingOrder.GetHashCode();
if (this.Editors != null)
hash = hash * 59 + this.Editors.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.InPersonSigners != null)
hash = hash * 59 + this.InPersonSigners.GetHashCode();
if (this.Intermediaries != null)
hash = hash * 59 + this.Intermediaries.GetHashCode();
if (this.RecipientCount != null)
hash = hash * 59 + this.RecipientCount.GetHashCode();
if (this.Seals != null)
hash = hash * 59 + this.Seals.GetHashCode();
if (this.Signers != null)
hash = hash * 59 + this.Signers.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.Setup;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Orders;
using QuantConnect.Packets;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Handle the results of the backtest: where should we send the profit, portfolio updates:
/// Backtester or the Live trading platform:
/// </summary>
[InheritedExport(typeof(IResultHandler))]
public interface IResultHandler
{
/// <summary>
/// Put messages to process into the queue so they are processed by this thread.
/// </summary>
ConcurrentQueue<Packet> Messages
{
get;
set;
}
/// <summary>
/// Charts collection for storing the master copy of user charting data.
/// </summary>
ConcurrentDictionary<string, Chart> Charts
{
get;
set;
}
/// <summary>
/// Sampling period for timespans between resamples of the charting equity.
/// </summary>
/// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks>
TimeSpan ResamplePeriod
{
get;
}
/// <summary>
/// How frequently the backtests push messages to the browser.
/// </summary>
/// <remarks>Update frequency of notification packets</remarks>
TimeSpan NotificationPeriod
{
get;
}
/// <summary>
/// Boolean flag indicating the result hander thread is busy.
/// False means it has completely finished and ready to dispose.
/// </summary>
bool IsActive
{
get;
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="job">Algorithm job packet for this result handler</param>
/// <param name="messagingHandler"></param>
/// <param name="api"></param>
/// <param name="dataFeed"></param>
/// <param name="setupHandler"></param>
/// <param name="transactionHandler"></param>
void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler);
/// <summary>
/// Primary result thread entry point to process the result message queue and send it to whatever endpoint is set.
/// </summary>
void Run();
/// <summary>
/// Process debug messages with the preconfigured settings.
/// </summary>
/// <param name="message">String debug message</param>
void DebugMessage(string message);
/// <summary>
/// Send a list of security types to the browser
/// </summary>
/// <param name="types">Security types list inside algorithm</param>
void SecurityType(List<SecurityType> types);
/// <summary>
/// Send a logging message to the log list for storage.
/// </summary>
/// <param name="message">Message we'd in the log.</param>
void LogMessage(string message);
/// <summary>
/// Send an error message back to the browser highlighted in red with a stacktrace.
/// </summary>
/// <param name="error">Error message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace information string</param>
void ErrorMessage(string error, string stacktrace = "");
/// <summary>
/// Send a runtime error message back to the browser highlighted with in red
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="stacktrace">Stacktrace information string</param>
void RuntimeError(string message, string stacktrace = "");
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="chartType">Type of chart we should create if it doesn't already exist.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="time">Time for the sample</param>
/// <param name="value">Value for the chart sample.</param>
/// <param name="unit">Unit for the sample chart</param>
/// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks>
void Sample(string chartName, ChartType chartType, string seriesName, SeriesType seriesType, DateTime time, decimal value, string unit = "$");
/// <summary>
/// Wrapper methond on sample to create the equity chart.
/// </summary>
/// <param name="time">Time of the sample.</param>
/// <param name="value">Equity value at this moment in time.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleEquity(DateTime time, decimal value);
/// <summary>
/// Sample the current daily performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current daily performance value.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SamplePerformance(DateTime time, decimal value);
/// <summary>
/// Sample the asset prices to generate plots.
/// </summary>
/// <param name="symbol">Symbol we're sampling.</param>
/// <param name="time">Time of sample</param>
/// <param name="value">Value of the asset price</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleAssetPrices(string symbol, DateTime time, decimal value);
/// <summary>
/// Add a range of samples from the users algorithms to the end of our current list.
/// </summary>
/// <param name="samples">Chart updates since the last request.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleRange(List<Chart> samples);
/// <summary>
/// Set the algorithm of the result handler after its been initialized.
/// </summary>
/// <param name="algorithm">Algorithm object matching IAlgorithm interface</param>
void SetAlgorithm(IAlgorithm algorithm);
/// <summary>
/// Save the snapshot of the total results to storage.
/// </summary>
/// <param name="packet">Packet to store.</param>
/// <param name="async">Store the packet asyncronously to speed up the thread.</param>
/// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks>
void StoreResult(Packet packet, bool async = false);
/// <summary>
/// Post the final result back to the controller worker if backtesting, or to console if local.
/// </summary>
void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, Dictionary<string, string> statistics, Dictionary<string, string> banner);
/// <summary>
/// Send a algorithm status update to the user of the algorithms running state.
/// </summary>
/// <param name="algorithmId">String Id of the algorithm.</param>
/// <param name="status">Status enum of the algorithm.</param>
/// <param name="message">Optional string message describing reason for status change.</param>
void SendStatusUpdate(string algorithmId, AlgorithmStatus status, string message = "");
/// <summary>
/// Set the chart name:
/// </summary>
/// <param name="symbol">Symbol of the chart we want.</param>
void SetChartSubscription(string symbol);
/// <summary>
/// Set a dynamic runtime statistic to show in the (live) algorithm header
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
void RuntimeStatistic(string key, string value);
/// <summary>
/// Send a new order event.
/// </summary>
/// <param name="newEvent">Update, processing or cancellation of an order, update the IDE in live mode or ignore in backtesting.</param>
void OrderEvent(OrderEvent newEvent);
/// <summary>
/// Terminate the result thread and apply any required exit proceedures.
/// </summary>
void Exit();
/// <summary>
/// Purge/clear any outstanding messages in message queue.
/// </summary>
void PurgeQueue();
/// <summary>
/// Process any synchronous events in here that are primarily triggered from the algorithm loop
/// </summary>
void ProcessSynchronousEvents(bool forceProcess = false);
}
}
| |
using System;
namespace Versioning
{
public class InvoiceData : Sage_Container, IData, IFindFirstNext
{
/* Autogenerated by sage_wrapper_generator.pl */
SageDataObject110.InvoiceData nd11;
SageDataObject120.InvoiceData nd12;
SageDataObject130.InvoiceData nd13;
SageDataObject140.InvoiceData nd14;
SageDataObject150.InvoiceData nd15;
SageDataObject160.InvoiceData nd16;
SageDataObject170.InvoiceData nd17;
public InvoiceData(object inner, int version)
: base(version) {
switch (m_version) {
case 11: {
nd11 = (SageDataObject110.InvoiceData)inner;
m_fields = new Fields(nd11.Fields,m_version);
return;
}
case 12: {
nd12 = (SageDataObject120.InvoiceData)inner;
m_fields = new Fields(nd12.Fields,m_version);
return;
}
case 13: {
nd13 = (SageDataObject130.InvoiceData)inner;
m_fields = new Fields(nd13.Fields,m_version);
return;
}
case 14: {
nd14 = (SageDataObject140.InvoiceData)inner;
m_fields = new Fields(nd14.Fields,m_version);
return;
}
case 15: {
nd15 = (SageDataObject150.InvoiceData)inner;
m_fields = new Fields(nd15.Fields,m_version);
return;
}
case 16: {
nd16 = (SageDataObject160.InvoiceData)inner;
m_fields = new Fields(nd16.Fields,m_version);
return;
}
case 17: {
nd17 = (SageDataObject170.InvoiceData)inner;
m_fields = new Fields(nd17.Fields,m_version);
return;
}
default: throw new InvalidOperationException("ver");
}
}
/* Autogenerated with data_generator.pl */
const string ACCOUNT_REF = "ACCOUNT_REF";
const string NOMINALDATA = "InvoiceData";
public bool Open(OpenMode mode) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Open((SageDataObject110.OpenMode)mode);
break;
}
case 12: {
ret = nd12.Open((SageDataObject120.OpenMode)mode);
break;
}
case 13: {
ret = nd13.Open((SageDataObject130.OpenMode)mode);
break;
}
case 14: {
ret = nd14.Open((SageDataObject140.OpenMode)mode);
break;
}
case 15: {
ret = nd15.Open((SageDataObject150.OpenMode)mode);
break;
}
case 16: {
ret = nd16.Open((SageDataObject160.OpenMode)mode);
break;
}
case 17: {
ret = nd17.Open((SageDataObject170.OpenMode)mode);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public void Close() {
switch (m_version) {
case 11: {
nd11.Close();
break;
}
case 12: {
nd12.Close();
break;
}
case 13: {
nd13.Close();
break;
}
case 14: {
nd14.Close();
break;
}
case 15: {
nd15.Close();
break;
}
case 16: {
nd16.Close();
break;
}
case 17: {
nd17.Close();
break;
}
default: throw new InvalidOperationException("ver");
}
}
public bool Read(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Read(IRecNo);
break;
}
case 12: {
ret = nd12.Read(IRecNo);
break;
}
case 13: {
ret = nd13.Read(IRecNo);
break;
}
case 14: {
ret = nd14.Read(IRecNo);
break;
}
case 15: {
ret = nd15.Read(IRecNo);
break;
}
case 16: {
ret = nd16.Read(IRecNo);
break;
}
case 17: {
ret = nd17.Read(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Write(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Write(IRecNo);
break;
}
case 12: {
ret = nd12.Write(IRecNo);
break;
}
case 13: {
ret = nd13.Write(IRecNo);
break;
}
case 14: {
ret = nd14.Write(IRecNo);
break;
}
case 15: {
ret = nd15.Write(IRecNo);
break;
}
case 16: {
ret = nd16.Write(IRecNo);
break;
}
case 17: {
ret = nd17.Write(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Seek(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Seek(IRecNo);
break;
}
case 12: {
ret = nd12.Seek(IRecNo);
break;
}
case 13: {
ret = nd13.Seek(IRecNo);
break;
}
case 14: {
ret = nd14.Seek(IRecNo);
break;
}
case 15: {
ret = nd15.Seek(IRecNo);
break;
}
case 16: {
ret = nd16.Seek(IRecNo);
break;
}
case 17: {
ret = nd17.Seek(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Lock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Lock(IRecNo);
break;
}
case 12: {
ret = nd12.Lock(IRecNo);
break;
}
case 13: {
ret = nd13.Lock(IRecNo);
break;
}
case 14: {
ret = nd14.Lock(IRecNo);
break;
}
case 15: {
ret = nd15.Lock(IRecNo);
break;
}
case 16: {
ret = nd16.Lock(IRecNo);
break;
}
case 17: {
ret = nd17.Lock(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Unlock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Unlock(IRecNo);
break;
}
case 12: {
ret = nd12.Unlock(IRecNo);
break;
}
case 13: {
ret = nd13.Unlock(IRecNo);
break;
}
case 14: {
ret = nd14.Unlock(IRecNo);
break;
}
case 15: {
ret = nd15.Unlock(IRecNo);
break;
}
case 16: {
ret = nd16.Unlock(IRecNo);
break;
}
case 17: {
ret = nd17.Unlock(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool FindFirst(object varField, object varSearch) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.FindFirst(varField, varSearch);
break;
}
case 12: {
ret = nd12.FindFirst(varField, varSearch);
break;
}
case 13: {
ret = nd13.FindFirst(varField, varSearch);
break;
}
case 14: {
ret = nd14.FindFirst(varField, varSearch);
break;
}
case 15: {
ret = nd15.FindFirst(varField, varSearch);
break;
}
case 16: {
ret = nd16.FindFirst(varField, varSearch);
break;
}
case 17: {
ret = nd17.FindFirst(varField, varSearch);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool FindNext(object varField, object varSearch) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.FindNext(varField, varSearch);
break;
}
case 12: {
ret = nd12.FindNext(varField, varSearch);
break;
}
case 13: {
ret = nd13.FindNext(varField, varSearch);
break;
}
case 14: {
ret = nd14.FindNext(varField, varSearch);
break;
}
case 15: {
ret = nd15.FindNext(varField, varSearch);
break;
}
case 16: {
ret = nd16.FindNext(varField, varSearch);
break;
}
case 17: {
ret = nd17.FindNext(varField, varSearch);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public int Count {
get {
int ret;
switch (m_version) {
case 11: {
ret = nd11.Count();
break;
}
case 12: {
ret = nd12.Count();
break;
}
case 13: {
ret = nd13.Count();
break;
}
case 14: {
ret = nd14.Count();
break;
}
case 15: {
ret = nd15.Count();
break;
}
case 16: {
ret = nd16.Count();
break;
}
case 17: {
ret = nd17.Count();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LythumOSL.Core;
using LythumOSL.Core.Metadata;
using LythumOSL.Core.Net.Http;
using LythumOSL.Security;
using LythumOSL.Security.Encryptions;
namespace LythumOSL.Net.Lslw
{
/// <summary>
/// Low, raw level LSLW webservice client implementation
/// </summary>
public class LslwRawConnection : IMessenger
{
#region Const
const string LslwOperationName = "op";
#endregion
#region Attributes
bool _Connected;
Guid _SessionId;
LslwSettings _Settings;
Rsa _Rsa;
Aes _Aes;
HttpAccess _Access;
// UI stuff
IMessenger _Messenger;
#endregion
#region Properties
protected Rsa Rsa
{
get { return _Rsa; }
}
protected Aes Aes
{
get { return _Aes; }
}
/// <summary>
/// Shows connection state
/// </summary>
public bool Connected
{
get { return _Connected; }
}
static Dictionary<LslwRawOperation, string> _sLslwCommands = null;
public static Dictionary<LslwRawOperation, string> sLslwCommands
{
get
{
if (_sLslwCommands == null)
{
_sLslwCommands = new Dictionary<LslwRawOperation, string> ();
_sLslwCommands.Add (LslwRawOperation.RsaGetPublicKey, LslwRawCommands.RsaGetPublicKey);
_sLslwCommands.Add (LslwRawOperation.AesReceiveKey, LslwRawCommands.AesReceiveKey);
_sLslwCommands.Add (LslwRawOperation.AesData, LslwRawCommands.AesData);
_sLslwCommands.Add (LslwRawOperation.Disconnect, LslwRawCommands.Disconnect);
}
return _sLslwCommands;
}
}
/// <summary>
/// Overridable server encoding. Used to process data from and to server.
/// </summary>
protected virtual Encoding ServerEncoding
{
get
{
return Encoding.UTF8;
}
}
#endregion
#region Ctor
protected LslwRawConnection ()
{
_Connected = false;
_SessionId = Guid.NewGuid ();
_Rsa = new Rsa ();
_Aes = new Aes (ServerEncoding);
_Access = new HttpAccess ();
_Messenger = null;
}
public LslwRawConnection (LslwSettings settings)
: this()
{
Validation.RequireValid (settings, "settings");
_Settings = settings;
}
public LslwRawConnection (LslwSettings settings, IMessenger messenger)
: this (settings)
{
_Messenger = messenger;
}
#endregion
#region Methods
/// <summary>
/// Low level request method
/// </summary>
/// <param name="operation"></param>
/// <param name="postData"></param>
/// <returns></returns>
protected LslwResult RawRequest (LslwRawOperation operation, HttpAttributes postData)
{
string result = _Access.Request (
_Settings.WebserviceUrl + "?" + LslwOperationName + "=" + sLslwCommands[operation],
postData);
if (postData != null)
{
Debug.Print (postData["data"]);
}
return new LslwResult (operation, _Aes, result);
}
/// <summary>
/// This method must be called before any encrypting and etc...
/// Eslewhere data will be encrypted with random keys which is just for initialization of objects
/// And later replaced with good keys
/// </summary>
/// <returns></returns>
public bool Connect ()
{
// checking if already connected
if (_Connected)
{
return _Connected;
}
string errorStage = string.Empty;
//try
//{
errorStage = "requesting RSA public key"; // RSA
LslwResult result = RawRequest( LslwRawOperation.RsaGetPublicKey, null);
if (result.HasErrors)
{
return false;
}
errorStage = "loading RSA public key"; // RSA
_Rsa.LoadCertificateFromString (result.Result);
errorStage = "generating AES keys"; // AES
//DumpKeys ("Keys before generate");
_Aes.GenerateRandomKeys ();
//DumpKeys ("Keys after generate");
HttpAttributes postData = PreparePostData ();
postData["key"] = Base64.Encode( _Rsa.Encrypt (_Aes.Key), true);
postData["iv"] = Base64.Encode (_Rsa.Encrypt (_Aes.IV), true);
errorStage = "sending AES keys"; // AES
result = RawRequest (LslwRawOperation.AesReceiveKey, postData);
errorStage = "parsing AES result";
if (!result.HasErrors)
{
string[] nodes = result.DecryptedResult.Split (' ');
_Connected = nodes[0].Equals("000");
}
//}
//catch (Exception ex)
//{
// Error ("Error " + errorStage + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
//}
return _Connected;
}
public void Disconnect ()
{
if (Connected)
{
LslwResult result = RawRequest (LslwRawOperation.Disconnect, null);
Debug.Assert (!result.HasErrors);
}
}
#endregion
#region Helpers
HttpAttributes PreparePostData ()
{
HttpAttributes attributes = new HttpAttributes ();
attributes["guid"] = _SessionId.ToString ();
return attributes;
}
void DumpKeys (string text)
{
Debug.Print (text + ": Key=" + _Aes.KeyString + ", IV=" + _Aes.IVString);
}
#endregion
#region IMessenger Members
public void Warning (string msg)
{
if (_Messenger != null)
{
_Messenger.Warning (msg);
}
}
public void Error (string msg)
{
if (_Messenger != null)
{
_Messenger.Error (msg);
}
}
public bool Question (string msg)
{
if (_Messenger != null)
{
return _Messenger.Question (msg);
}
return false;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class BulkEnvelopeStatus : IEquatable<BulkEnvelopeStatus>
{
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="batchSize", EmitDefaultValue=false)]
public string BatchSize { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="batchId", EmitDefaultValue=false)]
public string BatchId { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="bulkEnvelopesBatchUri", EmitDefaultValue=false)]
public string BulkEnvelopesBatchUri { get; set; }
/// <summary>
/// Entries with a failed status.
/// </summary>
/// <value>Entries with a failed status.</value>
[DataMember(Name="failed", EmitDefaultValue=false)]
public string Failed { get; set; }
/// <summary>
/// Retrieves entries with a status of queued.
/// </summary>
/// <value>Retrieves entries with a status of queued.</value>
[DataMember(Name="queued", EmitDefaultValue=false)]
public string Queued { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="sent", EmitDefaultValue=false)]
public string Sent { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="submittedDate", EmitDefaultValue=false)]
public string SubmittedDate { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response.</value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set.</value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.</value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="bulkEnvelopes", EmitDefaultValue=false)]
public List<BulkEnvelope> BulkEnvelopes { 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 BulkEnvelopeStatus {\n");
sb.Append(" BatchSize: ").Append(BatchSize).Append("\n");
sb.Append(" BatchId: ").Append(BatchId).Append("\n");
sb.Append(" BulkEnvelopesBatchUri: ").Append(BulkEnvelopesBatchUri).Append("\n");
sb.Append(" Failed: ").Append(Failed).Append("\n");
sb.Append(" Queued: ").Append(Queued).Append("\n");
sb.Append(" Sent: ").Append(Sent).Append("\n");
sb.Append(" SubmittedDate: ").Append(SubmittedDate).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" BulkEnvelopes: ").Append(BulkEnvelopes).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 BulkEnvelopeStatus);
}
/// <summary>
/// Returns true if BulkEnvelopeStatus instances are equal
/// </summary>
/// <param name="other">Instance of BulkEnvelopeStatus to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkEnvelopeStatus other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BatchSize == other.BatchSize ||
this.BatchSize != null &&
this.BatchSize.Equals(other.BatchSize)
) &&
(
this.BatchId == other.BatchId ||
this.BatchId != null &&
this.BatchId.Equals(other.BatchId)
) &&
(
this.BulkEnvelopesBatchUri == other.BulkEnvelopesBatchUri ||
this.BulkEnvelopesBatchUri != null &&
this.BulkEnvelopesBatchUri.Equals(other.BulkEnvelopesBatchUri)
) &&
(
this.Failed == other.Failed ||
this.Failed != null &&
this.Failed.Equals(other.Failed)
) &&
(
this.Queued == other.Queued ||
this.Queued != null &&
this.Queued.Equals(other.Queued)
) &&
(
this.Sent == other.Sent ||
this.Sent != null &&
this.Sent.Equals(other.Sent)
) &&
(
this.SubmittedDate == other.SubmittedDate ||
this.SubmittedDate != null &&
this.SubmittedDate.Equals(other.SubmittedDate)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.BulkEnvelopes == other.BulkEnvelopes ||
this.BulkEnvelopes != null &&
this.BulkEnvelopes.SequenceEqual(other.BulkEnvelopes)
);
}
/// <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.BatchSize != null)
hash = hash * 57 + this.BatchSize.GetHashCode();
if (this.BatchId != null)
hash = hash * 57 + this.BatchId.GetHashCode();
if (this.BulkEnvelopesBatchUri != null)
hash = hash * 57 + this.BulkEnvelopesBatchUri.GetHashCode();
if (this.Failed != null)
hash = hash * 57 + this.Failed.GetHashCode();
if (this.Queued != null)
hash = hash * 57 + this.Queued.GetHashCode();
if (this.Sent != null)
hash = hash * 57 + this.Sent.GetHashCode();
if (this.SubmittedDate != null)
hash = hash * 57 + this.SubmittedDate.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 57 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 57 + this.StartPosition.GetHashCode();
if (this.EndPosition != null)
hash = hash * 57 + this.EndPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 57 + this.TotalSetSize.GetHashCode();
if (this.NextUri != null)
hash = hash * 57 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 57 + this.PreviousUri.GetHashCode();
if (this.BulkEnvelopes != null)
hash = hash * 57 + this.BulkEnvelopes.GetHashCode();
return hash;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_BeginRead_Generic : PortsTest
{
// Set bounds fore random timeout values.
// If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
// If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
// If the percentage difference between the expected timeout and the actual timeout
// found through Stopwatch is greater then 10% then the timeout value was not correctly
// to the read method and the testcase fails.
public const double maxPercentageDifference = .15;
// The number of random bytes to receive for parity testing
private const int numRndBytesPairty = 8;
// The number of characters to read at a time for parity testing
private const int numBytesReadPairty = 2;
// The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
// When we test Read and do not care about actually reading anything we must still
// create an byte array to pass into the method the following is the size of the
// byte array used in this situation
private const int defaultByteArraySize = 1;
private const int NUM_TRYS = 5;
private const int MAX_WAIT_THREAD = 1000;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
Stream serialStream = com.BaseStream;
com.Close();
VerifyReadException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterSerialStreamClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to BaseStream.Close()");
com.Open();
Stream serialStream = com.BaseStream;
com.BaseStream.Close();
VerifyReadException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
var rndGen = new Random(-55);
int readTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", readTimeout);
VerifyTimeout(readTimeout);
}
private void WriteToCom1()
{
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
// Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
if (com2.IsOpen)
com2.Close();
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesPairty - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
var rndGen = new Random(-55);
// if(!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), new System.Text.UTF7Encoding())){
VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), Encoding.Unicode);
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
var rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new UTF8Encoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(15);
var bytesToWrite = new byte[numRndBytesPairty];
var expectedBytes = new byte[numRndBytesPairty];
var actualBytes = new byte[numRndBytesPairty + 1];
IAsyncResult readAsyncResult;
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
// Generate random characters without an parity error
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedBytes[i] = randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
// Create a parity error on the last byte
expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace;
// Set the last expected byte to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
readAsyncResult = com2.BaseStream.BeginWrite(bytesToWrite, 0, bytesToWrite.Length, null, null);
readAsyncResult.AsyncWaitHandle.WaitOne();
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
com1.Read(actualBytes, 0, actualBytes.Length);
// Compare the chars that were written with the ones we expected to read
for (var i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != actualBytes[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i],
(int)actualBytes[i]);
}
}
if (1 < com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
// Clear the parity error on the last byte
expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
var rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
// if(!VerifyBytesToRead(1, new System.Text.UTF7Encoding())){
VerifyBytesToRead(1, Encoding.UTF32);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
var rndGen = new Random(-55);
VerifyBytesToRead(numRndBytesToRead, new UTF8Encoding());
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(int readTimeout)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
IAsyncResult readAsyncResult;
var asyncRead = new AsyncRead(com1);
var asyncEndRead = new Task(asyncRead.EndRead);
var asyncCallbackCalled = false;
com1.Open();
com2.Open();
com1.ReadTimeout = readTimeout;
readAsyncResult = com1.BaseStream.BeginRead(new byte[8], 0, 8,
delegate (IAsyncResult ar) { asyncCallbackCalled = true; }, null);
asyncRead.ReadAsyncResult = readAsyncResult;
Thread.Sleep(100 > com1.ReadTimeout ? 2 * com1.ReadTimeout : 200);
// Sleep for 200ms or 2 times the ReadTimeout
if (readAsyncResult.IsCompleted)
{
// Verify the IAsyncResult has not completed
Fail("Err_565088aueiud!!!: Expected read to not have completed");
}
asyncEndRead.Start();
TCSupport.WaitForTaskToStart(asyncEndRead);
Thread.Sleep(100 < com1.ReadTimeout ? 2 * com1.ReadTimeout : 200);
// Sleep for 200ms or 2 times the ReadTimeout
if (!asyncEndRead.IsCompleted)
{
// Verify EndRead is blocking and is still alive
Fail("Err_4085858aiehe!!!: Expected read to not have completed");
}
if (asyncCallbackCalled)
{
Fail("Err_750551aiuehd!!!: Expected AsyncCallback not to be called");
}
com2.Write(new byte[8], 0, 8);
TCSupport.WaitForTaskCompletion(asyncEndRead);
var waitTime = 0;
while (!asyncCallbackCalled && waitTime < 5000)
{
Thread.Sleep(50);
waitTime += 50;
}
Assert.True(asyncCallbackCalled, "Err_21208aheide!!!: Expected AsyncCallback to be called after some data was written to the port");
}
}
private void VerifyReadException(Stream serialStream, Type expectedException)
{
Assert.Throws(expectedException, () =>
{
IAsyncResult readAsyncResult = serialStream.BeginRead(new byte[defaultByteArraySize], 0, defaultByteArraySize,
null, null);
readAsyncResult.AsyncWaitHandle.WaitOne();
});
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
VerifyParityReplaceByte(parityReplace, parityErrorIndex, new ASCIIEncoding());
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, Encoding encoding)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var bytesToWrite = new byte[numRndBytesPairty];
var expectedBytes = new byte[numRndBytesPairty];
byte expectedByte;
// Generate random characters without an parity error
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedBytes[i] = randByte;
}
if (-1 == parityReplace)
{
// If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
// If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
// Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
// Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedBytes[parityErrorIndex] = (byte)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Encoding = encoding;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedBytes, numBytesReadPairty);
}
}
public void VerifyBytesToRead(int numBytesRead)
{
VerifyBytesToRead(numBytesRead, new ASCIIEncoding());
}
public void VerifyBytesToRead(int numBytesRead, Encoding encoding)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var bytesToWrite = new byte[numRndBytesToRead];
// Generate random characters
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Encoding = encoding;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, bytesToWrite, numBytesRead);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize)
{
var rcvBuffer = new byte[rcvBufferSize];
var buffer = new byte[bytesToWrite.Length];
int totalBytesRead;
int bytesToRead;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
bytesToRead = com1.BytesToRead;
while (0 != com1.BytesToRead)
{
int bytesRead = com1.BaseStream.EndRead(com1.BaseStream.BeginRead(rcvBuffer, 0, rcvBufferSize, null, null));
// While their are more characters to be read
if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
// If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (bytesToWrite.Length < totalBytesRead + bytesRead)
{
// If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
break;
}
Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead);
totalBytesRead += bytesRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}
// Compare the bytes that were written with the ones we expected to read
for (var i = 0; i < bytesToWrite.Length; i++)
{
if (expectedBytes[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", expectedBytes[i], buffer[i]);
}
}
}
private class AsyncRead
{
private readonly SerialPort _com;
private IAsyncResult _readAsyncResult;
public AsyncRead(SerialPort com)
{
_com = com;
}
public void BeginRead()
{
_readAsyncResult = _com.BaseStream.BeginRead(new byte[8], 0, 8, null, null);
}
public IAsyncResult ReadAsyncResult
{
get
{
return _readAsyncResult;
}
set
{
_readAsyncResult = value;
}
}
public void EndRead()
{
_com.BaseStream.EndRead(_readAsyncResult);
}
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using OpenHome.Net.Core;
using OpenHome.Net.ControlPoint;
namespace OpenHome.Net.ControlPoint.Proxies
{
public interface ICpProxyAvOpenhomeOrgInfo1 : ICpProxy, IDisposable
{
void SyncCounters(out uint aTrackCount, out uint aDetailsCount, out uint aMetatextCount);
void BeginCounters(CpProxy.CallbackAsyncComplete aCallback);
void EndCounters(IntPtr aAsyncHandle, out uint aTrackCount, out uint aDetailsCount, out uint aMetatextCount);
void SyncTrack(out String aUri, out String aMetadata);
void BeginTrack(CpProxy.CallbackAsyncComplete aCallback);
void EndTrack(IntPtr aAsyncHandle, out String aUri, out String aMetadata);
void SyncDetails(out uint aDuration, out uint aBitRate, out uint aBitDepth, out uint aSampleRate, out bool aLossless, out String aCodecName);
void BeginDetails(CpProxy.CallbackAsyncComplete aCallback);
void EndDetails(IntPtr aAsyncHandle, out uint aDuration, out uint aBitRate, out uint aBitDepth, out uint aSampleRate, out bool aLossless, out String aCodecName);
void SyncMetatext(out String aValue);
void BeginMetatext(CpProxy.CallbackAsyncComplete aCallback);
void EndMetatext(IntPtr aAsyncHandle, out String aValue);
void SetPropertyTrackCountChanged(System.Action aTrackCountChanged);
uint PropertyTrackCount();
void SetPropertyDetailsCountChanged(System.Action aDetailsCountChanged);
uint PropertyDetailsCount();
void SetPropertyMetatextCountChanged(System.Action aMetatextCountChanged);
uint PropertyMetatextCount();
void SetPropertyUriChanged(System.Action aUriChanged);
String PropertyUri();
void SetPropertyMetadataChanged(System.Action aMetadataChanged);
String PropertyMetadata();
void SetPropertyDurationChanged(System.Action aDurationChanged);
uint PropertyDuration();
void SetPropertyBitRateChanged(System.Action aBitRateChanged);
uint PropertyBitRate();
void SetPropertyBitDepthChanged(System.Action aBitDepthChanged);
uint PropertyBitDepth();
void SetPropertySampleRateChanged(System.Action aSampleRateChanged);
uint PropertySampleRate();
void SetPropertyLosslessChanged(System.Action aLosslessChanged);
bool PropertyLossless();
void SetPropertyCodecNameChanged(System.Action aCodecNameChanged);
String PropertyCodecName();
void SetPropertyMetatextChanged(System.Action aMetatextChanged);
String PropertyMetatext();
}
internal class SyncCountersAvOpenhomeOrgInfo1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgInfo1 iService;
private uint iTrackCount;
private uint iDetailsCount;
private uint iMetatextCount;
public SyncCountersAvOpenhomeOrgInfo1(CpProxyAvOpenhomeOrgInfo1 aProxy)
{
iService = aProxy;
}
public uint TrackCount()
{
return iTrackCount;
}
public uint DetailsCount()
{
return iDetailsCount;
}
public uint MetatextCount()
{
return iMetatextCount;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndCounters(aAsyncHandle, out iTrackCount, out iDetailsCount, out iMetatextCount);
}
};
internal class SyncTrackAvOpenhomeOrgInfo1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgInfo1 iService;
private String iUri;
private String iMetadata;
public SyncTrackAvOpenhomeOrgInfo1(CpProxyAvOpenhomeOrgInfo1 aProxy)
{
iService = aProxy;
}
public String Uri()
{
return iUri;
}
public String Metadata()
{
return iMetadata;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndTrack(aAsyncHandle, out iUri, out iMetadata);
}
};
internal class SyncDetailsAvOpenhomeOrgInfo1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgInfo1 iService;
private uint iDuration;
private uint iBitRate;
private uint iBitDepth;
private uint iSampleRate;
private bool iLossless;
private String iCodecName;
public SyncDetailsAvOpenhomeOrgInfo1(CpProxyAvOpenhomeOrgInfo1 aProxy)
{
iService = aProxy;
}
public uint Duration()
{
return iDuration;
}
public uint BitRate()
{
return iBitRate;
}
public uint BitDepth()
{
return iBitDepth;
}
public uint SampleRate()
{
return iSampleRate;
}
public bool Lossless()
{
return iLossless;
}
public String CodecName()
{
return iCodecName;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndDetails(aAsyncHandle, out iDuration, out iBitRate, out iBitDepth, out iSampleRate, out iLossless, out iCodecName);
}
};
internal class SyncMetatextAvOpenhomeOrgInfo1 : SyncProxyAction
{
private CpProxyAvOpenhomeOrgInfo1 iService;
private String iValue;
public SyncMetatextAvOpenhomeOrgInfo1(CpProxyAvOpenhomeOrgInfo1 aProxy)
{
iService = aProxy;
}
public String Value()
{
return iValue;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndMetatext(aAsyncHandle, out iValue);
}
};
/// <summary>
/// Proxy for the av.openhome.org:Info:1 UPnP service
/// </summary>
public class CpProxyAvOpenhomeOrgInfo1 : CpProxy, IDisposable, ICpProxyAvOpenhomeOrgInfo1
{
private OpenHome.Net.Core.Action iActionCounters;
private OpenHome.Net.Core.Action iActionTrack;
private OpenHome.Net.Core.Action iActionDetails;
private OpenHome.Net.Core.Action iActionMetatext;
private PropertyUint iTrackCount;
private PropertyUint iDetailsCount;
private PropertyUint iMetatextCount;
private PropertyString iUri;
private PropertyString iMetadata;
private PropertyUint iDuration;
private PropertyUint iBitRate;
private PropertyUint iBitDepth;
private PropertyUint iSampleRate;
private PropertyBool iLossless;
private PropertyString iCodecName;
private PropertyString iMetatext;
private System.Action iTrackCountChanged;
private System.Action iDetailsCountChanged;
private System.Action iMetatextCountChanged;
private System.Action iUriChanged;
private System.Action iMetadataChanged;
private System.Action iDurationChanged;
private System.Action iBitRateChanged;
private System.Action iBitDepthChanged;
private System.Action iSampleRateChanged;
private System.Action iLosslessChanged;
private System.Action iCodecNameChanged;
private System.Action iMetatextChanged;
private Mutex iPropertyLock;
/// <summary>
/// Constructor
/// </summary>
/// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks>
/// <param name="aDevice">The device to use</param>
public CpProxyAvOpenhomeOrgInfo1(ICpDevice aDevice)
: base("av-openhome-org", "Info", 1, aDevice)
{
OpenHome.Net.Core.Parameter param;
List<String> allowedValues = new List<String>();
iActionCounters = new OpenHome.Net.Core.Action("Counters");
param = new ParameterUint("TrackCount");
iActionCounters.AddOutputParameter(param);
param = new ParameterUint("DetailsCount");
iActionCounters.AddOutputParameter(param);
param = new ParameterUint("MetatextCount");
iActionCounters.AddOutputParameter(param);
iActionTrack = new OpenHome.Net.Core.Action("Track");
param = new ParameterString("Uri", allowedValues);
iActionTrack.AddOutputParameter(param);
param = new ParameterString("Metadata", allowedValues);
iActionTrack.AddOutputParameter(param);
iActionDetails = new OpenHome.Net.Core.Action("Details");
param = new ParameterUint("Duration");
iActionDetails.AddOutputParameter(param);
param = new ParameterUint("BitRate");
iActionDetails.AddOutputParameter(param);
param = new ParameterUint("BitDepth");
iActionDetails.AddOutputParameter(param);
param = new ParameterUint("SampleRate");
iActionDetails.AddOutputParameter(param);
param = new ParameterBool("Lossless");
iActionDetails.AddOutputParameter(param);
param = new ParameterString("CodecName", allowedValues);
iActionDetails.AddOutputParameter(param);
iActionMetatext = new OpenHome.Net.Core.Action("Metatext");
param = new ParameterString("Value", allowedValues);
iActionMetatext.AddOutputParameter(param);
iTrackCount = new PropertyUint("TrackCount", TrackCountPropertyChanged);
AddProperty(iTrackCount);
iDetailsCount = new PropertyUint("DetailsCount", DetailsCountPropertyChanged);
AddProperty(iDetailsCount);
iMetatextCount = new PropertyUint("MetatextCount", MetatextCountPropertyChanged);
AddProperty(iMetatextCount);
iUri = new PropertyString("Uri", UriPropertyChanged);
AddProperty(iUri);
iMetadata = new PropertyString("Metadata", MetadataPropertyChanged);
AddProperty(iMetadata);
iDuration = new PropertyUint("Duration", DurationPropertyChanged);
AddProperty(iDuration);
iBitRate = new PropertyUint("BitRate", BitRatePropertyChanged);
AddProperty(iBitRate);
iBitDepth = new PropertyUint("BitDepth", BitDepthPropertyChanged);
AddProperty(iBitDepth);
iSampleRate = new PropertyUint("SampleRate", SampleRatePropertyChanged);
AddProperty(iSampleRate);
iLossless = new PropertyBool("Lossless", LosslessPropertyChanged);
AddProperty(iLossless);
iCodecName = new PropertyString("CodecName", CodecNamePropertyChanged);
AddProperty(iCodecName);
iMetatext = new PropertyString("Metatext", MetatextPropertyChanged);
AddProperty(iMetatext);
iPropertyLock = new Mutex();
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aTrackCount"></param>
/// <param name="aDetailsCount"></param>
/// <param name="aMetatextCount"></param>
public void SyncCounters(out uint aTrackCount, out uint aDetailsCount, out uint aMetatextCount)
{
SyncCountersAvOpenhomeOrgInfo1 sync = new SyncCountersAvOpenhomeOrgInfo1(this);
BeginCounters(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aTrackCount = sync.TrackCount();
aDetailsCount = sync.DetailsCount();
aMetatextCount = sync.MetatextCount();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndCounters().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginCounters(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionCounters, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionCounters.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionCounters.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionCounters.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aTrackCount"></param>
/// <param name="aDetailsCount"></param>
/// <param name="aMetatextCount"></param>
public void EndCounters(IntPtr aAsyncHandle, out uint aTrackCount, out uint aDetailsCount, out uint aMetatextCount)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aTrackCount = Invocation.OutputUint(aAsyncHandle, index++);
aDetailsCount = Invocation.OutputUint(aAsyncHandle, index++);
aMetatextCount = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aUri"></param>
/// <param name="aMetadata"></param>
public void SyncTrack(out String aUri, out String aMetadata)
{
SyncTrackAvOpenhomeOrgInfo1 sync = new SyncTrackAvOpenhomeOrgInfo1(this);
BeginTrack(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aUri = sync.Uri();
aMetadata = sync.Metadata();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndTrack().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginTrack(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionTrack, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionTrack.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentString((ParameterString)iActionTrack.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aUri"></param>
/// <param name="aMetadata"></param>
public void EndTrack(IntPtr aAsyncHandle, out String aUri, out String aMetadata)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aUri = Invocation.OutputString(aAsyncHandle, index++);
aMetadata = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aDuration"></param>
/// <param name="aBitRate"></param>
/// <param name="aBitDepth"></param>
/// <param name="aSampleRate"></param>
/// <param name="aLossless"></param>
/// <param name="aCodecName"></param>
public void SyncDetails(out uint aDuration, out uint aBitRate, out uint aBitDepth, out uint aSampleRate, out bool aLossless, out String aCodecName)
{
SyncDetailsAvOpenhomeOrgInfo1 sync = new SyncDetailsAvOpenhomeOrgInfo1(this);
BeginDetails(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aDuration = sync.Duration();
aBitRate = sync.BitRate();
aBitDepth = sync.BitDepth();
aSampleRate = sync.SampleRate();
aLossless = sync.Lossless();
aCodecName = sync.CodecName();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndDetails().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginDetails(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionDetails, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionDetails.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionDetails.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionDetails.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionDetails.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentBool((ParameterBool)iActionDetails.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentString((ParameterString)iActionDetails.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aDuration"></param>
/// <param name="aBitRate"></param>
/// <param name="aBitDepth"></param>
/// <param name="aSampleRate"></param>
/// <param name="aLossless"></param>
/// <param name="aCodecName"></param>
public void EndDetails(IntPtr aAsyncHandle, out uint aDuration, out uint aBitRate, out uint aBitDepth, out uint aSampleRate, out bool aLossless, out String aCodecName)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aDuration = Invocation.OutputUint(aAsyncHandle, index++);
aBitRate = Invocation.OutputUint(aAsyncHandle, index++);
aBitDepth = Invocation.OutputUint(aAsyncHandle, index++);
aSampleRate = Invocation.OutputUint(aAsyncHandle, index++);
aLossless = Invocation.OutputBool(aAsyncHandle, index++);
aCodecName = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aValue"></param>
public void SyncMetatext(out String aValue)
{
SyncMetatextAvOpenhomeOrgInfo1 sync = new SyncMetatextAvOpenhomeOrgInfo1(this);
BeginMetatext(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aValue = sync.Value();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndMetatext().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginMetatext(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionMetatext, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentString((ParameterString)iActionMetatext.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aValue"></param>
public void EndMetatext(IntPtr aAsyncHandle, out String aValue)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aValue = Invocation.OutputString(aAsyncHandle, index++);
}
/// <summary>
/// Set a delegate to be run when the TrackCount state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aTrackCountChanged">The delegate to run when the state variable changes</param>
public void SetPropertyTrackCountChanged(System.Action aTrackCountChanged)
{
lock (iPropertyLock)
{
iTrackCountChanged = aTrackCountChanged;
}
}
private void TrackCountPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iTrackCountChanged);
}
}
/// <summary>
/// Set a delegate to be run when the DetailsCount state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aDetailsCountChanged">The delegate to run when the state variable changes</param>
public void SetPropertyDetailsCountChanged(System.Action aDetailsCountChanged)
{
lock (iPropertyLock)
{
iDetailsCountChanged = aDetailsCountChanged;
}
}
private void DetailsCountPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iDetailsCountChanged);
}
}
/// <summary>
/// Set a delegate to be run when the MetatextCount state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aMetatextCountChanged">The delegate to run when the state variable changes</param>
public void SetPropertyMetatextCountChanged(System.Action aMetatextCountChanged)
{
lock (iPropertyLock)
{
iMetatextCountChanged = aMetatextCountChanged;
}
}
private void MetatextCountPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iMetatextCountChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Uri state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aUriChanged">The delegate to run when the state variable changes</param>
public void SetPropertyUriChanged(System.Action aUriChanged)
{
lock (iPropertyLock)
{
iUriChanged = aUriChanged;
}
}
private void UriPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iUriChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Metadata state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aMetadataChanged">The delegate to run when the state variable changes</param>
public void SetPropertyMetadataChanged(System.Action aMetadataChanged)
{
lock (iPropertyLock)
{
iMetadataChanged = aMetadataChanged;
}
}
private void MetadataPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iMetadataChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Duration state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aDurationChanged">The delegate to run when the state variable changes</param>
public void SetPropertyDurationChanged(System.Action aDurationChanged)
{
lock (iPropertyLock)
{
iDurationChanged = aDurationChanged;
}
}
private void DurationPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iDurationChanged);
}
}
/// <summary>
/// Set a delegate to be run when the BitRate state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aBitRateChanged">The delegate to run when the state variable changes</param>
public void SetPropertyBitRateChanged(System.Action aBitRateChanged)
{
lock (iPropertyLock)
{
iBitRateChanged = aBitRateChanged;
}
}
private void BitRatePropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iBitRateChanged);
}
}
/// <summary>
/// Set a delegate to be run when the BitDepth state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aBitDepthChanged">The delegate to run when the state variable changes</param>
public void SetPropertyBitDepthChanged(System.Action aBitDepthChanged)
{
lock (iPropertyLock)
{
iBitDepthChanged = aBitDepthChanged;
}
}
private void BitDepthPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iBitDepthChanged);
}
}
/// <summary>
/// Set a delegate to be run when the SampleRate state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aSampleRateChanged">The delegate to run when the state variable changes</param>
public void SetPropertySampleRateChanged(System.Action aSampleRateChanged)
{
lock (iPropertyLock)
{
iSampleRateChanged = aSampleRateChanged;
}
}
private void SampleRatePropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iSampleRateChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Lossless state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aLosslessChanged">The delegate to run when the state variable changes</param>
public void SetPropertyLosslessChanged(System.Action aLosslessChanged)
{
lock (iPropertyLock)
{
iLosslessChanged = aLosslessChanged;
}
}
private void LosslessPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iLosslessChanged);
}
}
/// <summary>
/// Set a delegate to be run when the CodecName state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aCodecNameChanged">The delegate to run when the state variable changes</param>
public void SetPropertyCodecNameChanged(System.Action aCodecNameChanged)
{
lock (iPropertyLock)
{
iCodecNameChanged = aCodecNameChanged;
}
}
private void CodecNamePropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iCodecNameChanged);
}
}
/// <summary>
/// Set a delegate to be run when the Metatext state variable changes.
/// </summary>
/// <remarks>Callbacks may be run in different threads but callbacks for a
/// CpProxyAvOpenhomeOrgInfo1 instance will not overlap.</remarks>
/// <param name="aMetatextChanged">The delegate to run when the state variable changes</param>
public void SetPropertyMetatextChanged(System.Action aMetatextChanged)
{
lock (iPropertyLock)
{
iMetatextChanged = aMetatextChanged;
}
}
private void MetatextPropertyChanged()
{
lock (iPropertyLock)
{
ReportEvent(iMetatextChanged);
}
}
/// <summary>
/// Query the value of the TrackCount property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the TrackCount property</returns>
public uint PropertyTrackCount()
{
PropertyReadLock();
uint val;
try
{
val = iTrackCount.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the DetailsCount property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the DetailsCount property</returns>
public uint PropertyDetailsCount()
{
PropertyReadLock();
uint val;
try
{
val = iDetailsCount.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the MetatextCount property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the MetatextCount property</returns>
public uint PropertyMetatextCount()
{
PropertyReadLock();
uint val;
try
{
val = iMetatextCount.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Uri property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Uri property</returns>
public String PropertyUri()
{
PropertyReadLock();
String val;
try
{
val = iUri.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Metadata property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Metadata property</returns>
public String PropertyMetadata()
{
PropertyReadLock();
String val;
try
{
val = iMetadata.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Duration property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Duration property</returns>
public uint PropertyDuration()
{
PropertyReadLock();
uint val;
try
{
val = iDuration.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the BitRate property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the BitRate property</returns>
public uint PropertyBitRate()
{
PropertyReadLock();
uint val;
try
{
val = iBitRate.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the BitDepth property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the BitDepth property</returns>
public uint PropertyBitDepth()
{
PropertyReadLock();
uint val;
try
{
val = iBitDepth.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the SampleRate property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the SampleRate property</returns>
public uint PropertySampleRate()
{
PropertyReadLock();
uint val;
try
{
val = iSampleRate.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Lossless property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Lossless property</returns>
public bool PropertyLossless()
{
PropertyReadLock();
bool val;
try
{
val = iLossless.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the CodecName property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the CodecName property</returns>
public String PropertyCodecName()
{
PropertyReadLock();
String val;
try
{
val = iCodecName.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Query the value of the Metatext property.
/// </summary>
/// <remarks>This function is threadsafe and can only be called if Subscribe() has been
/// called and a first eventing callback received more recently than any call
/// to Unsubscribe().</remarks>
/// <returns>Value of the Metatext property</returns>
public String PropertyMetatext()
{
PropertyReadLock();
String val;
try
{
val = iMetatext.Value();
}
finally
{
PropertyReadUnlock();
}
return val;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public void Dispose()
{
lock (this)
{
if (iHandle == IntPtr.Zero)
return;
DisposeProxy();
iHandle = IntPtr.Zero;
}
iActionCounters.Dispose();
iActionTrack.Dispose();
iActionDetails.Dispose();
iActionMetatext.Dispose();
iTrackCount.Dispose();
iDetailsCount.Dispose();
iMetatextCount.Dispose();
iUri.Dispose();
iMetadata.Dispose();
iDuration.Dispose();
iBitRate.Dispose();
iBitDepth.Dispose();
iSampleRate.Dispose();
iLossless.Dispose();
iCodecName.Dispose();
iMetatext.Dispose();
}
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace FastDbNet
{
//-------------------------------------------------------------------------
public class FastDbConnection: IDisposable {
public static readonly int DefaultInitDatabaseSize = 4*1024*1024; // Default initial db size (number of objects)
public static readonly int DefaultInitIndexSize = 512*1024; // Default initial index size (number of objects)
public static readonly int DefaultExtensionQuantum = 4*1024*1024; // Quantum of extension of allocated memory
public static readonly int MaxParallelSearchThreads = 64; // Maximal number of threads which can be spawned to perform parallel sequentila search
public static readonly int DefaultDatabasePort = 6010;
public static readonly int DefReconnectTimeoutSec = 120; // Reconnect timeout seconds
/// <summary>
/// Create a FastDb connection (without opening a database).
/// </summary>
/// <param name="DatabaseName">Database name</param>
public FastDbConnection(string DatabaseName) {
this.dbName = DatabaseName;
this.dbPath = DatabaseName + ".fdb";
}
/// <summary>
/// Destroy FastDb connection, close the database, and free session resources.
/// </summary>
~FastDbConnection() { Dispose(false); }
/// <summary>
/// Create table given its structure.
/// </summary>
/// <param name="TableName">Table name</param>
/// <param name="fields">Table fields</param>
/// <returns>Return code (int)CLI.ErrorCode</returns>
public int CreateTable(string TableName, FastDbFields fields) {
CLI.CliFieldDescriptor[] flds = (CLI.CliFieldDescriptor[])Array.CreateInstance(typeof(CLI.CliFieldDescriptor), fields.Count);
//(CLI.CliFieldDescriptor[])aFlds.ToArray(typeof(CLI.CliFieldDescriptor));
for(int i=0; i<fields.Count; i++) {
flds[i].type = fields[i].Type;
flds[i].flags = fields[i].Flags;
flds[i].name = Marshal.StringToHGlobalAnsi(fields[i].Name);
flds[i].refTableName = Marshal.StringToHGlobalAnsi(fields[i].RefTable);
flds[i].inverseRefFieldName = Marshal.StringToHGlobalAnsi(fields[i].InvRefField);
}
int rc = CLI.cli_create_table(session, TableName, fields.Count, flds);
for(int i=0; i < fields.Count; i++) {
Marshal.FreeCoTaskMem(flds[i].name);
Marshal.FreeCoTaskMem(flds[i].refTableName);
Marshal.FreeCoTaskMem(flds[i].inverseRefFieldName);
}
if (rc < 0 && rc != (int)CLI.ErrorCode.cli_table_already_exists) CLI.CliCheck(rc);
return rc;
}
/// <summary>
/// Name of the database
/// </summary>
public string DatabaseName { get { return dbName; } set { CheckConnection(false); dbName = value; } }
/// <summary>
/// Path to the database file.
/// </summary>
public string DatabasePath { get { return dbPath; } set { CheckConnection(false); dbPath = value; } }
/// <summary>
/// Initial database size.
/// </summary>
public int InitDbSize { get { return initDbSize; } set { CheckConnection(false); initDbSize = value; } }
/// <summary>
/// Initial database index size.
/// </summary>
public int InitIdxSize { get { return initIdxSize; } set { CheckConnection(false); initIdxSize = value; } }
/// <summary>
/// Memory extention quantum size
/// </summary>
public int ExtensionQuantum { get { return extQuantum; } set { CheckConnection(false); extQuantum = value; } }
/// <summary>
/// Maximum allowed size of the database file. 0 = unlimited.
/// </summary>
public int FileSizeLimit { get { return fileSizeLimit; } set { CheckConnection(false); fileSizeLimit = value; } }
/// <summary>
/// Number of attempts to establish connection
/// </summary>
public int MaxConnectRetries { get { return maxConnectRetries; } set { CheckConnection(false); maxConnectRetries = value; } }
/// <summary>
/// Timeout in seconds between connection attempts
/// </summary>
public int ReconnectTimeout { get { return reconnectTimeout; } set { CheckConnection(false); reconnectTimeout = value; } }
/// <summary>
/// If true, Open() creates a replicated node. Defaults to false.
/// </summary>
public bool EnableReplication { get { return enableReplication; } set { CheckConnection(false); enableReplication = value; } }
/// <summary>
/// Trasnaction commit delay (specify 0 to disable).
/// </summary>
public uint TransCommitDelay { get { return transCommitDelay; } set { CheckConnection(false); transCommitDelay = value; } }
/// <summary>
/// Node identifier: 0 ... NodeNames.Length (only relevant for a replicated database).
/// </summary>
public int NodeID { get { return nodeID; } set { CheckConnection(false); nodeID = value; } }
/// <summary>
/// Names of the replicated nodes (only relevant for a replicated database).
/// </summary>
public string[] NodeNames { get { return nodeNames; } set { CheckConnection(false); nodeNames = value; } }
/// <summary>
/// Internal session handle
/// </summary>
public int Session { get { return session; } }
/// <summary>
/// Controls automated calls to Attach()/Detach() methods. Disabled by default.
/// </summary>
public bool Threaded { get { return threaded; } set { threaded = value; } }
/// <summary>
/// Attributes used to open database. <seealso cref="CLI.CliOpenAttribute"/>
/// </summary>
public CLI.CliOpenAttribute OpenAttributes {
get { return openAttributes; }
set { CheckConnection(false); openAttributes = value; }
}
/// <summary>
/// Open local database.
/// </summary>
public void Open() { this.Open(true, "", 0); }
public void Open(string Host, int Port) { this.Open(false, Host, Port); }
/// <summary>
/// Commit transaction and write changed data to disk.
/// </summary>
public void Commit() { CLI.CliCheck(CLI.cli_commit(session)); }
/// <summary>
/// Commit transaction without writing changed data to disk.
/// </summary>
public void PreCommit() { CLI.CliCheck(CLI.cli_precommit(session)); }
/// <summary>
/// Roolback current transaction.
/// </summary>
public void Rollback() { CLI.CliCheck(CLI.cli_abort(session)); }
/// <summary>
/// Close database connection.
/// </summary>
public void Close()
{
for(int i=commands.Count-1; i >= 0; --i)
((FastDbCommand)commands[i]).Free();
CLI.CliCheck(CLI.cli_close(session));
session = -1;
}
/// <summary>
/// List tables in the database.
/// </summary>
/// <returns>A string array of table names</returns>
public unsafe string[] ListTables() {
bool dummy = false;
return ListTables("", ref dummy);
}
/// <summary>
/// Checks if a table exists in the database.
/// </summary>
/// <param name="TableName">Name of the table to check for existence</param>
/// <returns>true - table exists.</returns>
public bool TableExists(string TableName) {
bool exists = false;
ListTables(TableName, ref exists);
return exists;
}
public FastDbFields DescribeTable(string TableName) {
return this.DescribeTable(TableName, true); }
/// <summary>
/// Describes a table given its name.
/// </summary>
/// <param name="TableName">Name of the table to describe</param>
/// <param name="RaiseError">If true, an error check will be performed (default: true).</param>
/// <returns>A collection of fields fetched from the database's table.</returns>
public unsafe FastDbFields DescribeTable(string TableName, bool RaiseError) {
FastDbFields fields = new FastDbFields();
void* p = null;
int rc = CLI.cli_describe(session, TableName, ref p);
if (RaiseError) CLI.CliCheck(rc);
if (rc > 0) {
try {
CLI.CliFieldDescriptor* fld = (CLI.CliFieldDescriptor*)p;
for(int i=0; i<rc; i++, fld++) {
Debug.Assert(fld->name != IntPtr.Zero, "Field name is a null pointer!");
string s = Marshal.PtrToStringAnsi(fld->name);
string sr = (fld->refTableName == IntPtr.Zero) ? null : Marshal.PtrToStringAnsi(fld->refTableName);
string si = (fld->inverseRefFieldName == IntPtr.Zero) ? null : Marshal.PtrToStringAnsi(fld->inverseRefFieldName);
fields.Add(s, fld->type, fld->flags, sr, si);
}
}
finally {
CLI.cli_free_memory(session, p);
}
}
return fields;
}
/// <summary>
/// Drop a table from the database
/// </summary>
/// <param name="TableName">Name of the table</param>
public void DropTable(string TableName) {
CLI.CliCheck(CLI.cli_drop_table(session, TableName));
}
/// <summary>
/// Alter index on a field
/// </summary>
/// <param name="TableName">Name of the table</param>
/// <param name="FieldName">Name of the field</param>
/// <param name="NewFlags">New index types.</param>
public void AlterIndex(string TableName, string FieldName, CLI.FieldFlags NewFlags) {
CLI.CliCheck(CLI.cli_alter_index(session, TableName, FieldName, NewFlags));
}
/// <summary>
/// Create a new SQL command in this connection. <seealso cref="CLI.FastDbCommand"/>
/// </summary>
/// <param name="sql">SQL text representing a command</param>
/// <returns>FastDbCommand object to be used for executing the SQL command</returns>
public FastDbCommand CreateCommand(string sql) {
lock(typeof(FastDbConnection)) {
int n = commands.Add(new FastDbCommand(this, sql));
return (FastDbCommand)commands[n];
}
}
internal void RemoveCommand(FastDbCommand command) {
lock(typeof(FastDbConnection)) {
commands.Remove(command);
}
}
/// <summary>
/// Attach current thread to the database. Each thread except one opened the database
/// should first attach to the database before any access to the database,
/// and detach after end of the work with database.
/// </summary>
public void Attach() {
CLI.CliCheck(CLI.cli_attach(session));
}
public void Detach() {
Detach(CLI.CliDetachMode.cli_commit_on_detach | CLI.CliDetachMode.cli_destroy_context_on_detach);
}
/// <summary>
/// Detach current thread from the database. Each thread except one opened the database
/// should perform attach to the database before any access to the database,
/// and detach after end of the work with database
/// <seealso cref="CLI.CliDetachMode"/>
/// </summary>
/// <param name="mode">Optional parameter indicating the detach action.</param>
public void Detach(CLI.CliDetachMode mode) {
CLI.CliCheck(CLI.cli_detach(session, mode));
}
/// <summary>
/// Set exclusive database lock
/// </summary>
public void Lock() {
CLI.CliCheck(CLI.cli_lock(session));
}
/// <summary>
/// Perform database backup
/// </summary>
/// <param name="filePath">backup file path</param>
/// <param name="compactify">if true then databae will be compactified during backup -
/// i.e. all used objects will be placed together without holes; if false then
/// backup is performed by just writting memory mapped object to the backup file.</param>
public void Backup(string filePath, bool compactify) {
CLI.CliCheck(CLI.cli_backup(session, filePath, compactify ? 1 : 0));
}
/// <summary>
/// Schedule database backup
/// </summary>
/// <param name="filePath">path to backup file. If name ends with '?', then
/// each backup willbe placed in seprate file with '?' replaced with current timestamp</param>
/// <param name=" period">period of performing backups in seconds</param>
public void ScheduleBackup(string filePath, int period) {
CLI.CliCheck(CLI.cli_schedule_backup(session, filePath, period));
}
/// <summary>
/// Extract a DDL of a table
/// </summary>
/// <param name="TableName">Name of a table</param>
/// <returns>A string representing the table's DDL.</returns>
public string ExtractTableDDL(string TableName) {
FastDbFields flds = DescribeTable(TableName);
StringBuilder result = new StringBuilder("create table "+TableName+" (\n");
int nLen = 0;
for(int i=0; i<flds.Count; i++) nLen = (nLen > flds[i].Name.Length) ? nLen : flds[i].Name.Length;
for(int i=0; i<flds.Count; i++) {
result.AppendFormat("\t{0} {1}{2}", flds[i].Name.PadRight(nLen, ' '), CLI.CliTypeToStr(flds[i].Type, true),
(flds[i].RefTable == null) ? "" : " to "+flds[i].RefTable);
result.Append((i==(flds.Count-1)) ? "" : ",\n");
}
result.Append(");\n");
string IDX_STR = "create {0} on {1}.{2};\n";
for(int i=0; i<flds.Count; i++) {
if (Enum.IsDefined(flds[i].Flags.GetType(), CLI.FieldFlags.cli_hashed))
result.AppendFormat(IDX_STR, "hash", TableName, flds[i].Name);
if (Enum.IsDefined(flds[i].Flags.GetType(), CLI.FieldFlags.cli_indexed))
result.AppendFormat(IDX_STR, "index", TableName, flds[i].Name);
}
return result.ToString();
}
/// <summary>
/// Extracts the metadata of the entire FastDB database, and stores it to a file
/// </summary>
/// <param name="FileName">FileName where the DDL is to be saved.</param>
public void SaveDDLtoFile(string FileName) {
System.IO.StreamWriter writer = System.IO.File.CreateText(FileName);
try {
string[] tables = ListTables();
writer.WriteLine("open '{0}';", dbName);
foreach (string table in tables)
writer.Write(ExtractTableDDL(table));
writer.WriteLine("commit;");
writer.WriteLine("exit;");
}
finally {
writer.Close();
}
}
/// <summary>
/// This method implements IDisposable. It takes this object off
/// the Finalization queue to prevent finalization code for this
/// object from executing a second time.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// This method executes by a user's call, or by the runtime.
/// </summary>
/// <param name="disposing">If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed. If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.</param>
protected virtual void Dispose(bool disposing) {
if(this.session != -1) { // Check to see if Dispose has already been called.
if(disposing) {} // Dispose managed resources here.
Close(); // Release unmanaged resources.
}
}
protected void CheckConnection(bool IsConnected) {
if ((IsConnected) ? session == -1 : session != -1)
throw new CliError("The session is " + ((IsConnected) ? "connected" : "not connected"));
}
private static void SessionErrorHandler(int error,
[MarshalAs(UnmanagedType.LPStr)] string msg, int msgarg, IntPtr UserData) {
//Debug.Assert(UserData != IntPtr.Zero, "UserData must be assigned FastDbSession value!");
//int handle; Marshal.Copy(UserData, handle, 0, 1);
// This procedure must raise an error to unwind the stack
throw new CliError(error-100, msg+String.Format(" ({0})", msgarg));
}
private unsafe string[] ListTables(string TableName, ref bool tableExists) {
IntPtr p = new IntPtr(0);
int rc = CLI.CliCheck(CLI.cli_show_tables(session, ref p));
ArrayList tables = new ArrayList(rc);
if (rc > 0) {
try {
CLI.CliTableDescriptor* table = (CLI.CliTableDescriptor*)p.ToPointer();
tableExists = false;
for(int i=0; i < rc; i++, table++) {
string s = Marshal.PtrToStringAnsi(table->name);
if (String.Compare(s, TableName, true) == 0) tableExists = true;
tables.Add(s);
}
}
finally {
CLI.cli_free_memory(session, p.ToPointer());
}
}
return (string[])tables.ToArray(typeof(string));
}
private void Open(bool isLocal, string Host, int Port) {
CheckConnection(false);
if (!isLocal)
session = CLI.cli_open(String.Format("{0}:{1}", Host, Port), maxConnectRetries, reconnectTimeout);
else
session = (int)CLI.ErrorCode.cli_bad_address;
if (session != (int)CLI.ErrorCode.cli_bad_address)
throw new CliError(session, "cli_open failed");
else {
if (enableReplication)
session =
CLI.CliCheck(CLI.cli_create_replication_node(
nodeID,
nodeNames.Length,
nodeNames,
dbName,
dbPath,
(int)openAttributes,
initDbSize,
extQuantum,
initIdxSize,
fileSizeLimit), "cli_create_replication_node failed");
else
session =
CLI.CliCheck(CLI.cli_create(dbName,
dbPath,
transCommitDelay,
(int)openAttributes,
initDbSize,
extQuantum,
initIdxSize,
fileSizeLimit), "cli_create failed");
}
sessionThreadID = System.Threading.Thread.CurrentThread.GetHashCode();
IntPtr dummy = IntPtr.Zero;
CLI.cli_set_error_handler(session, new CLI.CliErrorHandler(SessionErrorHandler), dummy);
}
private string dbName;
private string dbPath;
private int session = -1;
private int initDbSize = DefaultInitDatabaseSize;
private int initIdxSize = DefaultInitIndexSize;
private int extQuantum = DefaultExtensionQuantum;
private int fileSizeLimit = 0;
private uint transCommitDelay = 0;
private CLI.CliOpenAttribute openAttributes = CLI.CliOpenAttribute.oaReadWrite;
private int sessionThreadID = -1;
private int maxConnectRetries = 0;
private int reconnectTimeout = DefReconnectTimeoutSec;
private bool enableReplication = false;
private int nodeID = 0;
private string[] nodeNames = new string[] {};
private bool threaded = false;
private ArrayList commands = new ArrayList();
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared.Instance
{
public class ScriptInstance : MarshalByRefObject, IScriptInstance
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IScriptEngine m_Engine;
private IScriptWorkItem m_CurrentResult = null;
private Queue m_EventQueue = new Queue(32);
private bool m_RunEvents = false;
private UUID m_ItemID;
private uint m_LocalID;
private UUID m_ObjectID;
private UUID m_AssetID;
private IScript m_Script;
private UUID m_AppDomain;
private DetectParams[] m_DetectParams;
private bool m_TimerQueued;
private DateTime m_EventStart;
private bool m_InEvent;
private string m_PrimName;
private string m_ScriptName;
private string m_Assembly;
private int m_StartParam;
private string m_CurrentEvent = String.Empty;
private bool m_InSelfDelete;
private int m_MaxScriptQueue;
private bool m_SaveState = true;
private bool m_ShuttingDown;
private int m_ControlEventsInQueue;
private int m_LastControlLevel;
private bool m_CollisionInQueue;
private TaskInventoryItem m_thisScriptTask;
// The following is for setting a minimum delay between events
private double m_minEventDelay;
private long m_eventDelayTicks;
private long m_nextEventTimeTicks;
private bool m_startOnInit = true;
private UUID m_AttachedAvatar;
private StateSource m_stateSource;
private bool m_postOnRez;
private bool m_startedFromSavedState;
private UUID m_CurrentStateHash;
private UUID m_RegionID;
private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
m_LineMap;
public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
LineMap
{
get { return m_LineMap; }
set { m_LineMap = value; }
}
private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
// Script state
private string m_State="default";
public Object[] PluginData = new Object[0];
/// <summary>
/// Used by llMinEventDelay to suppress events happening any faster than this speed.
/// This currently restricts all events in one go. Not sure if each event type has
/// its own check so take the simple route first.
/// </summary>
public double MinEventDelay
{
get { return m_minEventDelay; }
set
{
if (value > 0.001)
m_minEventDelay = value;
else
m_minEventDelay = 0.0;
m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
m_nextEventTimeTicks = DateTime.Now.Ticks;
}
}
public bool Running
{
get { return m_RunEvents; }
set { m_RunEvents = value; }
}
public bool ShuttingDown
{
get { return m_ShuttingDown; }
set { m_ShuttingDown = value; }
}
public string State
{
get { return m_State; }
set { m_State = value; }
}
public IScriptEngine Engine
{
get { return m_Engine; }
}
public UUID AppDomain
{
get { return m_AppDomain; }
set { m_AppDomain = value; }
}
public string PrimName
{
get { return m_PrimName; }
}
public string ScriptName
{
get { return m_ScriptName; }
}
public UUID ItemID
{
get { return m_ItemID; }
}
public UUID ObjectID
{
get { return m_ObjectID; }
}
public uint LocalID
{
get { return m_LocalID; }
}
public UUID AssetID
{
get { return m_AssetID; }
}
public Queue EventQueue
{
get { return m_EventQueue; }
}
public void ClearQueue()
{
m_TimerQueued = false;
m_EventQueue.Clear();
}
public int StartParam
{
get { return m_StartParam; }
set { m_StartParam = value; }
}
public TaskInventoryItem ScriptTask
{
get { return m_thisScriptTask; }
}
public ScriptInstance(IScriptEngine engine, SceneObjectPart part,
UUID itemID, UUID assetID, string assembly,
AppDomain dom, string primName, string scriptName,
int startParam, bool postOnRez, StateSource stateSource,
int maxScriptQueue)
{
m_Engine = engine;
m_LocalID = part.LocalId;
m_ObjectID = part.UUID;
m_ItemID = itemID;
m_AssetID = assetID;
m_PrimName = primName;
m_ScriptName = scriptName;
m_Assembly = assembly;
m_StartParam = startParam;
m_MaxScriptQueue = maxScriptQueue;
m_stateSource = stateSource;
m_postOnRez = postOnRez;
m_AttachedAvatar = part.AttachedAvatar;
m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID;
if (part != null)
{
lock (part.TaskInventory)
{
if (part.TaskInventory.ContainsKey(m_ItemID))
{
m_thisScriptTask = part.TaskInventory[m_ItemID];
}
}
}
ApiManager am = new ApiManager();
foreach (string api in am.GetApis())
{
m_Apis[api] = am.CreateApi(api);
m_Apis[api].Initialize(engine, part, m_LocalID, itemID);
}
try
{
if (dom != System.AppDomain.CurrentDomain)
m_Script = (IScript)dom.CreateInstanceAndUnwrap(
Path.GetFileNameWithoutExtension(assembly),
"SecondLife.Script");
else
m_Script = (IScript)Assembly.Load(
Path.GetFileNameWithoutExtension(assembly)).CreateInstance(
"SecondLife.Script");
//ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
//RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
// lease.Register(this);
}
catch (Exception)
{
// m_log.ErrorFormat("[Script] Error loading assembly {0}\n"+e.ToString(), assembly);
}
try
{
foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
{
m_Script.InitApi(kv.Key, kv.Value);
}
// // m_log.Debug("[Script] Script instance created");
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
}
catch (Exception)
{
// m_log.Error("[Script] Error loading script instance\n"+e.ToString());
return;
}
m_SaveState = true;
string savedState = Path.Combine(Path.GetDirectoryName(assembly),
m_ItemID.ToString() + ".state");
if (File.Exists(savedState))
{
string xml = String.Empty;
try
{
FileInfo fi = new FileInfo(savedState);
int size = (int)fi.Length;
if (size < 512000)
{
using (FileStream fs = File.Open(savedState,
FileMode.Open, FileAccess.Read, FileShare.None))
{
System.Text.UTF8Encoding enc =
new System.Text.UTF8Encoding();
Byte[] data = new Byte[size];
fs.Read(data, 0, size);
xml = enc.GetString(data);
ScriptSerializer.Deserialize(xml, this);
AsyncCommandManager.CreateFromData(m_Engine,
m_LocalID, m_ItemID, m_ObjectID,
PluginData);
// m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
if (m_RunEvents && (!m_ShuttingDown))
{
m_RunEvents = false;
}
else
{
m_RunEvents = false;
m_startOnInit = false;
}
// we get new rez events on sim restart, too
// but if there is state, then we fire the change
// event
// We loaded state, don't force a re-save
m_SaveState = false;
m_startedFromSavedState = true;
}
}
else
{
// m_log.Error("[Script] Unable to load script state: Memory limit exceeded");
}
}
catch (Exception)
{
// m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n"+e.ToString(), xml);
}
}
// else
// {
// ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID);
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
// }
}
public void Init()
{
if (!m_startOnInit) return;
if (m_startedFromSavedState)
{
Start();
if (m_postOnRez)
{
PostEvent(new EventParams("on_rez",
new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
}
if (m_stateSource == StateSource.AttachedRez)
{
PostEvent(new EventParams("attach",
new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
}
else if (m_stateSource == StateSource.NewRez)
{
// m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
PostEvent(new EventParams("changed",
new Object[] {new LSL_Types.LSLInteger(256)}, new DetectParams[0]));
}
else if (m_stateSource == StateSource.PrimCrossing)
{
// CHANGED_REGION
PostEvent(new EventParams("changed",
new Object[] {new LSL_Types.LSLInteger(512)}, new DetectParams[0]));
}
}
else
{
Start();
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
if (m_postOnRez)
{
PostEvent(new EventParams("on_rez",
new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
}
if (m_stateSource == StateSource.AttachedRez)
{
PostEvent(new EventParams("attach",
new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
}
}
}
private void ReleaseControls()
{
SceneObjectPart part = m_Engine.World.GetSceneObjectPart(m_LocalID);
if (part != null)
{
int permsMask;
UUID permsGranter;
lock (part.TaskInventory)
{
if (!part.TaskInventory.ContainsKey(m_ItemID))
return;
permsGranter = part.TaskInventory[m_ItemID].PermsGranter;
permsMask = part.TaskInventory[m_ItemID].PermsMask;
}
if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
{
ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter);
if (presence != null)
presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID);
}
}
}
public void DestroyScriptInstance()
{
ReleaseControls();
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
}
public void RemoveState()
{
string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
m_ItemID.ToString() + ".state");
try
{
File.Delete(savedState);
}
catch(Exception)
{
}
}
public void VarDump(Dictionary<string, object> vars)
{
// m_log.Info("Variable dump for script "+ m_ItemID.ToString());
// foreach (KeyValuePair<string, object> v in vars)
// {
// m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
// }
}
public void Start()
{
lock (m_EventQueue)
{
if (Running)
return;
m_RunEvents = true;
if (m_EventQueue.Count > 0)
{
if (m_CurrentResult == null)
m_CurrentResult = m_Engine.QueueEventHandler(this);
// else
// m_log.Error("[Script] Tried to start a script that was already queued");
}
}
}
public bool Stop(int timeout)
{
IScriptWorkItem result;
lock (m_EventQueue)
{
if (!Running)
return true;
if (m_CurrentResult == null)
{
m_RunEvents = false;
return true;
}
if (m_CurrentResult.Cancel())
{
m_CurrentResult = null;
m_RunEvents = false;
return true;
}
result = m_CurrentResult;
m_RunEvents = false;
}
if (result.Wait(new TimeSpan((long)timeout * 100000)))
{
return true;
}
lock (m_EventQueue)
{
result = m_CurrentResult;
}
if (result == null)
return true;
if (!m_InSelfDelete)
result.Abort();
lock (m_EventQueue)
{
m_CurrentResult = null;
}
return false;
}
public void SetState(string state)
{
if (state == State)
return;
PostEvent(new EventParams("state_exit", new Object[0],
new DetectParams[0]));
PostEvent(new EventParams("state", new Object[] { state },
new DetectParams[0]));
PostEvent(new EventParams("state_entry", new Object[0],
new DetectParams[0]));
throw new EventAbortException();
}
public void PostEvent(EventParams data)
{
// m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
// m_PrimName, m_ScriptName, data.EventName, m_State);
if (!Running)
return;
// If min event delay is set then ignore any events untill the time has expired
// This currently only allows 1 event of any type in the given time period.
// This may need extending to allow for a time for each individual event type.
if (m_eventDelayTicks != 0)
{
if (DateTime.Now.Ticks < m_nextEventTimeTicks)
return;
m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
}
lock (m_EventQueue)
{
if (m_EventQueue.Count >= m_MaxScriptQueue)
return;
if (data.EventName == "timer")
{
if (m_TimerQueued)
return;
m_TimerQueued = true;
}
if (data.EventName == "control")
{
int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
// int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
// If the last message was a 0 (nothing held)
// and this one is also nothing held, drop it
//
if (m_LastControlLevel == held && held == 0)
return;
// If there is one or more queued, then queue
// only changed ones, else queue unconditionally
//
if (m_ControlEventsInQueue > 0)
{
if (m_LastControlLevel == held)
return;
}
m_LastControlLevel = held;
m_ControlEventsInQueue++;
}
if (data.EventName == "collision")
{
if (m_CollisionInQueue)
return;
if (data.DetectParams == null)
return;
m_CollisionInQueue = true;
}
m_EventQueue.Enqueue(data);
if (m_CurrentResult == null)
{
m_CurrentResult = m_Engine.QueueEventHandler(this);
}
}
}
/// <summary>
/// Process the next event queued for this script
/// </summary>
/// <returns></returns>
public object EventProcessor()
{
lock (m_Script)
{
EventParams data = null;
lock (m_EventQueue)
{
data = (EventParams) m_EventQueue.Dequeue();
if (data == null) // Shouldn't happen
{
if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
{
m_CurrentResult = m_Engine.QueueEventHandler(this);
}
else
{
m_CurrentResult = null;
}
return 0;
}
if (data.EventName == "timer")
m_TimerQueued = false;
if (data.EventName == "control")
{
if (m_ControlEventsInQueue > 0)
m_ControlEventsInQueue--;
}
if (data.EventName == "collision")
m_CollisionInQueue = false;
}
//m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
m_DetectParams = data.DetectParams;
if (data.EventName == "state") // Hardcoded state change
{
// m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
// m_PrimName, m_ScriptName, data.Params[0].ToString());
m_State=data.Params[0].ToString();
AsyncCommandManager.RemoveScript(m_Engine,
m_LocalID, m_ItemID);
SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
m_LocalID);
if (part != null)
{
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
}
}
else
{
if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
data.EventName == "control") // Don't freeze avies!
{
SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
m_LocalID);
// m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
// m_PrimName, m_ScriptName, data.EventName, m_State);
try
{
m_CurrentEvent = data.EventName;
m_EventStart = DateTime.Now;
m_InEvent = true;
m_Script.ExecuteEvent(State, data.EventName, data.Params);
m_InEvent = false;
m_CurrentEvent = String.Empty;
if (m_SaveState)
{
// This will be the very first event we deliver
// (state_entry) in default state
//
SaveState(m_Assembly);
m_SaveState = false;
}
}
catch (Exception e)
{
// m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message);
m_InEvent = false;
m_CurrentEvent = String.Empty;
if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException))
{
try
{
// DISPLAY ERROR INWORLD
string text = FormatException(e);
if (text.Length > 1000)
text = text.Substring(0, 1000);
m_Engine.World.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
part.AbsolutePosition,
part.Name, part.UUID, false);
}
catch (Exception)
{
}
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[SCRIPT]: "+
// "Error displaying error in-world: " +
// e2.ToString());
// m_log.Error("[SCRIPT]: " +
// "Errormessage: Error compiling script:\r\n" +
// e.ToString());
// }
}
else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
{
m_InSelfDelete = true;
if (part != null && part.ParentGroup != null)
m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
}
else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
{
m_InSelfDelete = true;
if (part != null && part.ParentGroup != null)
part.Inventory.RemoveInventoryItem(m_ItemID);
}
}
}
}
lock (m_EventQueue)
{
if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
{
m_CurrentResult = m_Engine.QueueEventHandler(this);
}
else
{
m_CurrentResult = null;
}
}
m_DetectParams = null;
return 0;
}
}
public int EventTime()
{
if (!m_InEvent)
return 0;
return (DateTime.Now - m_EventStart).Seconds;
}
public void ResetScript()
{
if (m_Script == null)
return;
bool running = Running;
RemoveState();
ReleaseControls();
Stop(0);
SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
m_EventQueue.Clear();
m_Script.ResetVars();
m_State = "default";
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
if (running)
Start();
m_SaveState = true;
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
}
public void ApiResetScript()
{
// bool running = Running;
RemoveState();
ReleaseControls();
m_Script.ResetVars();
SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
m_EventQueue.Clear();
m_Script.ResetVars();
m_State = "default";
part.SetScriptEvents(m_ItemID,
(int)m_Script.GetStateEventFlags(State));
if (m_CurrentEvent != "state_entry")
{
m_SaveState = true;
PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0]));
throw new EventAbortException();
}
}
public Dictionary<string, object> GetVars()
{
return m_Script.GetVars();
}
public void SetVars(Dictionary<string, object> vars)
{
m_Script.SetVars(vars);
}
public DetectParams GetDetectParams(int idx)
{
if (m_DetectParams == null)
return null;
if (idx < 0 || idx >= m_DetectParams.Length)
return null;
return m_DetectParams[idx];
}
public UUID GetDetectID(int idx)
{
if (m_DetectParams == null)
return UUID.Zero;
if (idx < 0 || idx >= m_DetectParams.Length)
return UUID.Zero;
return m_DetectParams[idx].Key;
}
public void SaveState(string assembly)
{
// If we're currently in an event, just tell it to save upon return
//
if (m_InEvent)
{
m_SaveState = true;
return;
}
PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
string xml = ScriptSerializer.Serialize(this);
// Compare hash of the state we just just created with the state last written to disk
// If the state is different, update the disk file.
UUID hash = UUID.Parse(Utils.MD5String(xml));
if (hash != m_CurrentStateHash)
{
try
{
FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
Byte[] buf = enc.GetBytes(xml);
fs.Write(buf, 0, buf.Length);
fs.Close();
}
catch(Exception)
{
// m_log.Error("Unable to save xml\n"+e.ToString());
}
//if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
//{
// throw new Exception("Completed persistence save, but no file was created");
//}
m_CurrentStateHash = hash;
}
}
public IScriptApi GetApi(string name)
{
if (m_Apis.ContainsKey(name))
return m_Apis[name];
return null;
}
public override string ToString()
{
return String.Format("{0} {1} on {2}", m_ScriptName, m_ItemID, m_PrimName);
}
string FormatException(Exception e)
{
if (e.InnerException == null) // Not a normal runtime error
return e.ToString();
string message = "Runtime error:\n" + e.InnerException.StackTrace;
string[] lines = message.Split(new char[] {'\n'});
foreach (string line in lines)
{
if (line.Contains("SecondLife.Script"))
{
int idx = line.IndexOf(':');
if (idx != -1)
{
string val = line.Substring(idx+1);
int lineNum = 0;
if (int.TryParse(val, out lineNum))
{
KeyValuePair<int, int> pos =
Compiler.FindErrorPosition(
lineNum, 0, LineMap);
int scriptLine = pos.Key;
int col = pos.Value;
if (scriptLine == 0)
scriptLine++;
if (col == 0)
col++;
message = string.Format("Runtime error:\n" +
"({0}): {1}", scriptLine - 1,
e.InnerException.Message);
System.Console.WriteLine(e.ToString()+"\n");
return message;
}
}
}
}
// m_log.ErrorFormat("Scripting exception:");
// m_log.ErrorFormat(e.ToString());
return e.ToString();
}
public string GetAssemblyName()
{
return m_Assembly;
}
public string GetXMLState()
{
bool run = Running;
bool stopped = Stop(100);
Running = run;
// We should not be doing this, but since we are about to
// dispose this, it really doesn't make a difference
// This is meant to work around a Windows only race
//
m_InEvent = false;
// Force an update of the in-memory plugin data
//
if (!stopped)
return String.Empty;
PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
return ScriptSerializer.Serialize(this);
}
public UUID RegionID
{
get { return m_RegionID; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml
{
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable
{
// Write methods
// Writes out the XML declaration with the version "1.0".
public virtual Task WriteStartDocumentAsync()
{
throw NotImplemented.ByDesign;
}
//Writes out the XML declaration with the version "1.0" and the speficied standalone attribute.
public virtual Task WriteStartDocumentAsync(bool standalone)
{
throw NotImplemented.ByDesign;
}
//Closes any open elements or attributes and puts the writer back in the Start state.
public virtual Task WriteEndDocumentAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public virtual Task WriteStartElementAsync(string prefix, string localName, string ns)
{
throw NotImplemented.ByDesign;
}
// Closes one element and pops the corresponding namespace scope.
public virtual Task WriteEndElementAsync()
{
throw NotImplemented.ByDesign;
}
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public virtual Task WriteFullEndElementAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value)
{
Task task = WriteStartAttributeAsync(prefix, localName, ns);
if (task.IsSuccess())
{
return WriteStringAsync(value).CallTaskFuncWhenFinishAsync(thisRef => thisRef.WriteEndAttributeAsync(), this);
}
else
{
return WriteAttributeStringAsyncHelper(task, value);
}
}
private async Task WriteAttributeStringAsyncHelper(Task task, string value)
{
await task.ConfigureAwait(false);
await WriteStringAsync(value).ConfigureAwait(false);
await WriteEndAttributeAsync().ConfigureAwait(false);
}
// Writes the start of an attribute.
protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns)
{
throw NotImplemented.ByDesign;
}
// Closes the attribute opened by WriteStartAttribute call.
protected internal virtual Task WriteEndAttributeAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out a <![CDATA[...]]>; block containing the specified text.
public virtual Task WriteCDataAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Writes out a comment <!--...-->; containing the specified text.
public virtual Task WriteCommentAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public virtual Task WriteProcessingInstructionAsync(string name, string text)
{
throw NotImplemented.ByDesign;
}
// Writes out an entity reference as follows: "&"+name+";".
public virtual Task WriteEntityRefAsync(string name)
{
throw NotImplemented.ByDesign;
}
// Forces the generation of a character entity for the specified Unicode character value.
public virtual Task WriteCharEntityAsync(char ch)
{
throw NotImplemented.ByDesign;
}
// Writes out the given whitespace.
public virtual Task WriteWhitespaceAsync(string ws)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified text content.
public virtual Task WriteStringAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Write out the given surrogate pair as an entity reference.
public virtual Task WriteSurrogateCharEntityAsync(char lowChar, char highChar)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified text content.
public virtual Task WriteCharsAsync(char[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Writes raw markup from the given character buffer.
public virtual Task WriteRawAsync(char[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Writes raw markup from the given string.
public virtual Task WriteRawAsync(string data)
{
throw NotImplemented.ByDesign;
}
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public virtual Task WriteBase64Async(byte[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public virtual Task WriteBinHexAsync(byte[] buffer, int index, int count)
{
return BinHexEncoder.EncodeAsync(buffer, index, count, this);
}
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public virtual Task FlushAsync()
{
throw NotImplemented.ByDesign;
}
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual Task WriteNmTokenAsync(string name)
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual Task WriteNameAsync(string name)
{
return WriteStringAsync(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual async Task WriteQualifiedNameAsync(string localName, string ns)
{
if (ns != null && ns.Length > 0)
{
string prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
await WriteStringAsync(prefix).ConfigureAwait(false);
await WriteStringAsync(":").ConfigureAwait(false);
}
await WriteStringAsync(localName).ConfigureAwait(false);
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException("reader");
}
if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration)
{
if (reader.MoveToFirstAttribute())
{
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute)
{
throw new XmlException(SR.Xml_InvalidPosition, string.Empty);
}
else
{
do
{
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal)
{
await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
}
else
{
await WriteStringAsync(reader.Value).ConfigureAwait(false);
}
}
await WriteEndAttributeAsync().ConfigureAwait(false);
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual Task WriteNodeAsync(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException("reader");
}
if (reader.Settings != null && reader.Settings.Async)
{
return WriteNodeAsync_CallAsyncReader(reader, defattr);
}
else
{
return WriteNodeAsync_CallSyncReader(reader, defattr);
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
//use sync methods on the reader
internal async Task WriteNodeAsync_CallSyncReader(XmlReader reader, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
if (reader.IsEmptyElement)
{
await WriteEndElementAsync().ConfigureAwait(false);
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false);
}
}
else
{
await WriteStringAsync(reader.Value).ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
await WriteWhitespaceAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.CDATA:
await WriteCDataAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EntityReference:
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.DocumentType:
await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.Comment:
await WriteCommentAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EndElement:
await WriteFullEndElementAsync().ConfigureAwait(false);
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
//use async methods on the reader
internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
if (reader.IsEmptyElement)
{
await WriteEndElementAsync().ConfigureAwait(false);
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = await reader.ReadValueChunkAsync(_writeNodeBuffer, 0, WriteNodeBufferSize).ConfigureAwait(false)) > 0)
{
await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false);
}
}
else
{
//reader.Value may block on Text or WhiteSpace node, use GetValueAsync
await WriteStringAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
await WriteWhitespaceAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false);
break;
case XmlNodeType.CDATA:
await WriteCDataAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EntityReference:
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.DocumentType:
await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.Comment:
await WriteCommentAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EndElement:
await WriteFullEndElementAsync().ConfigureAwait(false);
break;
}
} while (await reader.ReadAsync().ConfigureAwait(false) && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Element Helper Methods
// Writes out an attribute with the specified name, namespace URI, and string value.
public async Task WriteElementStringAsync(string prefix, String localName, String ns, String value)
{
await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false);
if (null != value && 0 != value.Length)
{
await WriteStringAsync(value).ConfigureAwait(false);
}
await WriteEndElementAsync().ConfigureAwait(false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Cosmos.Debug.Common;
using Dapper;
using SQLinq.Dapper;
using SQLinq;
namespace Cosmos.Debug.VSDebugEngine
{
// An implementation of IDebugProperty2
// This interface represents a stack frame property, a program document property, or some other property.
// The property is usually the result of an expression evaluation.
//
// The sample engine only supports locals and parameters for functions that have symbols loaded.
class AD7Property : IDebugProperty2
{
private DebugLocalInfo m_variableInformation;
private AD7Process mProcess;
private AD7StackFrame mStackFrame;
private LOCAL_ARGUMENT_INFO mDebugInfo;
const uint mArrayLengthOffset = 8;
const uint mArrayFirstElementOffset = 16;
private const string NULL = "null";
protected Int32 OFFSET
{
get
{
return mDebugInfo.OFFSET;
}
}
public AD7Property(DebugLocalInfo localInfo, AD7Process process, AD7StackFrame stackFrame)
{
m_variableInformation = localInfo;
mProcess = process;
mStackFrame = stackFrame;
if (localInfo.IsLocal)
{
mDebugInfo = mStackFrame.mLocalInfos[m_variableInformation.Index];
}
else if (localInfo.IsReference)
{
mDebugInfo = new LOCAL_ARGUMENT_INFO()
{
TYPENAME = localInfo.Type,
NAME = localInfo.Name,
OFFSET = localInfo.Offset
};
}
else
{
mDebugInfo = mStackFrame.mArgumentInfos[m_variableInformation.Index];
}
}
public void ReadData<T>(ref DEBUG_PROPERTY_INFO propertyInfo, Func<byte[], int, T> ByteToTypeAction)
{
byte[] xData;
if (m_variableInformation.IsReference)
{
xData = mProcess.mDbgConnector.GetMemoryData(m_variableInformation.Pointer, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)));
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
return;
}
var xTypedIntValue = ByteToTypeAction(xData, 0);
propertyInfo.bstrValue = String.Format("{0}", xTypedIntValue);
}
else
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)));
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
return;
}
var xTypedIntValue = ByteToTypeAction(xData, 0);
propertyInfo.bstrValue = String.Format("{0}", xTypedIntValue);
}
}
public void ReadDataArray<T>(ref DEBUG_PROPERTY_INFO propertyInfo, string typeAsString)
{
byte[] xData;
// Get handle
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
// Get actual pointer
xData = mProcess.mDbgConnector.GetMemoryData(BitConverter.ToUInt32(xData, 0), 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xPointer = BitConverter.ToUInt32(xData, 0);
if (xPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xPointer + mArrayLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xDataLength = BitConverter.ToUInt32(xData, 0);
bool xIsTooLong = xDataLength > 512;
if (xIsTooLong)
{
xDataLength = 512;
}
if (xDataLength > 0)
{
if (this.m_variableInformation.Children.Count == 0)
{
for (int i = 0; i < xDataLength; i++)
{
DebugLocalInfo inf = new DebugLocalInfo();
inf.IsReference = true;
inf.Type = typeof(T).AssemblyQualifiedName;
inf.Offset = (int)(mArrayFirstElementOffset + (System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) * i));
inf.Pointer = (uint)(xPointer + mArrayFirstElementOffset + (System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)) * i));
inf.Name = "[" + i.ToString() + "]";
this.m_variableInformation.Children.Add(new AD7Property(inf, this.mProcess, this.mStackFrame));
}
}
}
propertyInfo.bstrValue = String.Format(typeAsString + "[{0}] at 0x{1} ", xDataLength, xPointer.ToString("X"));
}
}
}
}
// Construct a DEBUG_PROPERTY_INFO representing this local or parameter.
public DEBUG_PROPERTY_INFO ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields)
{
DEBUG_PROPERTY_INFO propertyInfo = new DEBUG_PROPERTY_INFO();
try
{
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME))
{
propertyInfo.bstrFullName = m_variableInformation.Name;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME))
{
propertyInfo.bstrName = m_variableInformation.Name;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE))
{
propertyInfo.bstrType = mDebugInfo.TYPENAME;
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE))
{
byte[] xData;
#region string
if (mDebugInfo.TYPENAME == typeof(string).AssemblyQualifiedName)
{
const uint xStringLengthOffset = 12;
const uint xStringFirstCharOffset = 16;
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xStrPointer = BitConverter.ToUInt32(xData, 0);
if (xStrPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xStrPointer + xStringLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xStringLength = BitConverter.ToUInt32(xData, 0);
propertyInfo.bstrValue = "String of length: " + xStringLength;
if (xStringLength > 100)
{
propertyInfo.bstrValue = "For now, strings larger than 100 chars are not supported..";
}
else if (xStringLength == 0)
{
propertyInfo.bstrValue = "\"\"";
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xStrPointer + xStringFirstCharOffset, xStringLength * 2, 2);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
propertyInfo.bstrValue = "\"" + Encoding.Unicode.GetString(xData) + "\"";
}
}
}
}
}
}
#endregion
#warning TODO: String[]
#region byte
// Byte
else if (mDebugInfo.TYPENAME == typeof(byte).AssemblyQualifiedName)
{
ReadData<byte>(ref propertyInfo, new Func<byte[], int, byte>(delegate(byte[] barr, int ind) { return barr[ind]; }));
}
else if (mDebugInfo.TYPENAME == typeof(byte[]).AssemblyQualifiedName)
{
ReadDataArray<byte>(ref propertyInfo, "byte");
}
#endregion
#region sbyte
// SByte
else if (mDebugInfo.TYPENAME == typeof(sbyte).AssemblyQualifiedName)
{
ReadData<sbyte>(ref propertyInfo, new Func<byte[], int, sbyte>(delegate(byte[] barr, int ind) { return unchecked((sbyte)barr[ind]); }));
}
else if (mDebugInfo.TYPENAME == typeof(sbyte[]).AssemblyQualifiedName)
{
ReadDataArray<sbyte>(ref propertyInfo, "sbyte");
}
#endregion
#region char
else if (mDebugInfo.TYPENAME == typeof(char).AssemblyQualifiedName)
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 2);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
var xTypedCharValue = BitConverter.ToChar(xData, 0);
propertyInfo.bstrValue = String.Format("{0} '{1}'", (ushort)xTypedCharValue, xTypedCharValue);
}
}
else if (mDebugInfo.TYPENAME == typeof(char[]).AssemblyQualifiedName)
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
uint xArrayPointer = BitConverter.ToUInt32(xData, 0);
if (xArrayPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + mArrayLengthOffset, 4, 4);
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Memory data received was null!");
}
else
{
uint xDataLength = BitConverter.ToUInt32(xData, 0);
bool xIsTooLong = xDataLength > 512;
var xSB = new StringBuilder();
xSB.AppendFormat("Char[{0}] at 0x{1} {{ ", xDataLength, xArrayPointer.ToString("X"));
if (xIsTooLong)
{
xDataLength = 512;
}
if (xDataLength > 0)
{
xData = mProcess.mDbgConnector.GetMemoryData(xArrayPointer + mArrayFirstElementOffset, xDataLength * 2);
if (xData == null)
{
xSB.Append(String.Format("Error! Memory data received was null!"));
}
else
{
bool first = true;
for (int i = 0; (i / 2) < xDataLength; i += 2)
{
if (!first)
xSB.Append(", ");
char c = BitConverter.ToChar(xData, i);
xSB.Append('\'');
if (c == '\0')
{
xSB.Append("\\0");
}
else
{
xSB.Append(c);
}
xSB.Append('\'');
first = false;
}
}
}
if (xIsTooLong)
{
xSB.Append(", ..");
}
xSB.Append(" }");
propertyInfo.bstrValue = xSB.ToString();
}
}
}
}
#endregion
#region short
// Short
else if (mDebugInfo.TYPENAME == typeof(short).AssemblyQualifiedName)
{
ReadData<short>(ref propertyInfo, new Func<byte[], int, short>(BitConverter.ToInt16));
}
else if (mDebugInfo.TYPENAME == typeof(short[]).AssemblyQualifiedName)
{
ReadDataArray<short>(ref propertyInfo, "short");
}
#endregion
#region ushort
// UShort
else if (mDebugInfo.TYPENAME == typeof(ushort).AssemblyQualifiedName)
{
ReadData<ushort>(ref propertyInfo, new Func<byte[], int, ushort>(BitConverter.ToUInt16));
}
else if (mDebugInfo.TYPENAME == typeof(ushort[]).AssemblyQualifiedName)
{
ReadDataArray<ushort>(ref propertyInfo, "ushort");
}
#endregion
#region int
// Int32
else if (mDebugInfo.TYPENAME == typeof(int).AssemblyQualifiedName)
{
ReadData<int>(ref propertyInfo, new Func<byte[], int, int>(BitConverter.ToInt32));
}
else if (mDebugInfo.TYPENAME == typeof(int[]).AssemblyQualifiedName)
{
ReadDataArray<int>(ref propertyInfo, "int");
}
#endregion
#region uint
// UInt32
else if (mDebugInfo.TYPENAME == typeof(uint).AssemblyQualifiedName)
{
ReadData<uint>(ref propertyInfo, new Func<byte[], int, uint>(BitConverter.ToUInt32));
}
else if (mDebugInfo.TYPENAME == typeof(uint[]).AssemblyQualifiedName)
{
ReadDataArray<uint>(ref propertyInfo, "uint");
}
#endregion
#region long
// Long
else if (mDebugInfo.TYPENAME == typeof(long).AssemblyQualifiedName)
{
ReadData<long>(ref propertyInfo, new Func<byte[], int, long>(BitConverter.ToInt64));
}
else if (mDebugInfo.TYPENAME == typeof(long[]).AssemblyQualifiedName)
{
ReadDataArray<long>(ref propertyInfo, "long");
}
#endregion
#region ulong
// ULong
else if (mDebugInfo.TYPENAME == typeof(ulong).AssemblyQualifiedName)
{
ReadData<ulong>(ref propertyInfo, new Func<byte[], int, ulong>(BitConverter.ToUInt64));
}
else if (mDebugInfo.TYPENAME == typeof(ulong[]).AssemblyQualifiedName)
{
ReadDataArray<ulong>(ref propertyInfo, "ulong");
}
#endregion
#region float
// Float
else if (mDebugInfo.TYPENAME == typeof(float).AssemblyQualifiedName)
{
ReadData<float>(ref propertyInfo, new Func<byte[], int, float>(BitConverter.ToSingle));
}
else if (mDebugInfo.TYPENAME == typeof(float[]).AssemblyQualifiedName)
{
ReadDataArray<float>(ref propertyInfo, "float");
}
#endregion
#region double
// Double
else if (mDebugInfo.TYPENAME == typeof(double).AssemblyQualifiedName)
{
ReadData<double>(ref propertyInfo, new Func<byte[], int, double>(BitConverter.ToDouble));
}
else if (mDebugInfo.TYPENAME == typeof(double[]).AssemblyQualifiedName)
{
ReadDataArray<double>(ref propertyInfo, "double");
}
#endregion
#region bool
// Bool
else if (mDebugInfo.TYPENAME == typeof(bool).AssemblyQualifiedName)
{
ReadData<bool>(ref propertyInfo, new Func<byte[], int, bool>(BitConverter.ToBoolean));
}
else if (mDebugInfo.TYPENAME == typeof(bool[]).AssemblyQualifiedName)
{
ReadDataArray<bool>(ref propertyInfo, "bool");
}
#endregion
else
{
if (m_variableInformation.IsReference)
{
xData = mProcess.mDbgConnector.GetMemoryData(m_variableInformation.Pointer, 4, 4);
}
else
{
xData = mProcess.mDbgConnector.GetStackData(OFFSET, 4);
}
if (xData == null)
{
propertyInfo.bstrValue = String.Format("Error! Stack data received was null!");
}
else
{
var xPointer = BitConverter.ToUInt32(xData, 0);
if (xPointer == 0)
{
propertyInfo.bstrValue = NULL;
}
else
{
try
{
var mp = mProcess.mDebugInfoDb.GetFieldMap(mDebugInfo.TYPENAME);
foreach (string str in mp.FieldNames)
{
Cosmos.Debug.Common.FIELD_INFO xFieldInfo;
xFieldInfo = mProcess.mDebugInfoDb.GetFieldInfoByName(str);
var inf = new DebugLocalInfo();
inf.IsReference = true;
inf.Type = xFieldInfo.TYPE;
inf.Offset = xFieldInfo.OFFSET;
inf.Pointer = (uint)(xPointer + xFieldInfo.OFFSET + 12);
inf.Name = GetFieldName(xFieldInfo);
this.m_variableInformation.Children.Add(new AD7Property(inf, this.mProcess, this.mStackFrame));
}
propertyInfo.bstrValue = String.Format("{0} (0x{1})", xPointer, xPointer.ToString("X").ToUpper());
}
catch (Exception ex)
{
if (ex.GetType().Name == "SQLiteException")
{
//Ignore but warn user
propertyInfo.bstrValue = "SQLiteException. Could not get type information for " + mDebugInfo.TYPENAME;
}
else
{
throw new Exception("Unexpected error in AD7Property.cs:459", ex);
}
}
}
}
}
propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE;
}
if (dwFields.HasFlag(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ATTRIB))
{
// The sample does not support writing of values displayed in the debugger, so mark them all as read-only.
propertyInfo.dwAttrib = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_READONLY;
if (this.m_variableInformation.Children.Count > 0)
{
propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_OBJ_IS_EXPANDABLE;
}
}
propertyInfo.pProperty = (IDebugProperty2)this;
propertyInfo.dwFields |= (enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP);
// If the debugger has asked for the property, or the property has children (meaning it is a pointer in the sample)
// then set the pProperty field so the debugger can call back when the children are enumerated.
//if (((dwFields & (uint)enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP) != 0)
//|| (this.m_variableInformation.child != null))
//{
// propertyInfo.pProperty = (IDebugProperty2)this;
// propertyInfo.dwFields |= (enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP);
//}
}
catch
{
}
return propertyInfo;
}
private static string GetFieldName(Cosmos.Debug.Common.FIELD_INFO fInf)
{
string s = fInf.NAME;
int i = s.LastIndexOf('.');
if (i > 0)
{
s = s.Substring(i + 1, s.Length - i - 1);
return s;
}
return s;
}
#region IDebugProperty2 Members
// Enumerates the children of a property. This provides support for dereferencing pointers, displaying members of an array, or fields of a class or struct.
// The sample debugger only supports pointer dereferencing as children. This means there is only ever one child.
public int EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref System.Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum)
{
ppEnum = null;
if (this.m_variableInformation.Children.Count > 0)
{
List<DEBUG_PROPERTY_INFO> infs = new List<DEBUG_PROPERTY_INFO>();
foreach (AD7Property dp in m_variableInformation.Children)
{
infs.Add(dp.ConstructDebugPropertyInfo(dwFields));
}
ppEnum = new AD7PropertyEnum(infs.ToArray());
return VSConstants.S_OK;
}
//if (this.m_variableInformation.child != null)
//{
// DEBUG_PROPERTY_INFO[] properties = new DEBUG_PROPERTY_INFO[1];
// properties[0] = (new AD7Property(this.m_variableInformation.child)).ConstructDebugPropertyInfo(dwFields);
// ppEnum = new AD7PropertyEnum(properties);
// return VSConstants.S_OK;
//}
return VSConstants.S_FALSE;
}
// Returns the property that describes the most-derived property of a property
// This is called to support object oriented languages. It allows the debug engine to return an IDebugProperty2 for the most-derived
// object in a hierarchy. This engine does not support this.
public int GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost)
{
throw new Exception("The method or operation is not implemented.");
}
// This method exists for the purpose of retrieving information that does not lend itself to being retrieved by calling the IDebugProperty2::GetPropertyInfo
// method. This includes information about custom viewers, managed type slots and other information.
// The sample engine does not support this.
public int GetExtendedInfo(ref System.Guid guidExtendedInfo, out object pExtendedInfo)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the memory bytes for a property value.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the memory context for a property value.
public int GetMemoryContext(out IDebugMemoryContext2 ppMemory)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the parent of a property.
// The sample engine does not support obtaining the parent of properties.
public int GetParent(out IDebugProperty2 ppParent)
{
throw new Exception("The method or operation is not implemented.");
}
// Fills in a DEBUG_PROPERTY_INFO structure that describes a property.
public int GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo)
{
pPropertyInfo[0] = new DEBUG_PROPERTY_INFO();
rgpArgs = null;
pPropertyInfo[0] = ConstructDebugPropertyInfo(dwFields);
return VSConstants.S_OK;
}
// Return an IDebugReference2 for this property. An IDebugReference2 can be thought of as a type and an address.
public int GetReference(out IDebugReference2 ppReference)
{
throw new Exception("The method or operation is not implemented.");
}
// Returns the size, in bytes, of the property value.
public int GetSize(out uint pdwSize)
{
throw new Exception("The method or operation is not implemented.");
}
// The debugger will call this when the user tries to edit the property's values
// the sample has set the read-only flag on its properties, so this should not be called.
public int SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout)
{
throw new Exception("The method or operation is not implemented.");
}
// The debugger will call this when the user tries to edit the property's values in one of the debugger windows.
// the sample has set the read-only flag on its properties, so this should not be called.
public int SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
// Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean
// operations like union and intersection to combine 3D solids. This library
// implements CSG operations on meshes elegantly and concisely using BSP trees,
// and is meant to serve as an easily understandable implementation of the
// algorithm. All edge cases involving overlapping coplanar polygons in both
// solids are correctly handled.
//
// Example usage:
//
// var cube = CSG.cube();
// var sphere = CSG.sphere({ radius: 1.3 });
// var polygons = cube.subtract(sphere).toPolygons();
//
// ## Implementation Details
//
// All CSG operations are implemented in terms of two functions, `clipTo()` and
// `invert()`, which remove parts of a BSP tree inside another BSP tree and swap
// solid and empty space, respectively. To find the union of `a` and `b`, we
// want to remove everything in `a` inside `b` and everything in `b` inside `a`,
// then combine polygons from `a` and `b` into one solid:
//
// a.clipTo(b);
// b.clipTo(a);
// a.build(b.allPolygons());
//
// The only tricky part is handling overlapping coplanar polygons in both trees.
// The code above keeps both copies, but we need to keep them in one tree and
// remove them in the other tree. To remove them from `b` we can clip the
// inverse of `b` against `a`. The code for union now looks like this:
//
// a.clipTo(b);
// b.clipTo(a);
// b.invert();
// b.clipTo(a);
// b.invert();
// a.build(b.allPolygons());
//
// Subtraction and intersection naturally follow from set operations. If
// union is `A | B`, subtraction is `A - B = ~(~A | B)` and intersection is
// `A & B = ~(~A | ~B)` where `~` is the complement operator.
//
// ## License
//
// Copyright (c) 2011 Evan Wallace (http://madebyevan.com/), under the MIT license.
// Parts Copyright (c) 2012 Joost Nieuwenhuijse ([email protected]) under the MIT license.
// # class CSG
// Holds a binary space partition tree representing a 3D solid. Two solids can
// be combined using the `union()`, `subtract()`, and `intersect()` methods.
public class CSG
{
private List<CSGPolygon> polygons = new List<CSGPolygon>();
// Construct a CSG solid from a list of `CSG.Polygon` instances.
static public CSG fromPolygons(List<CSGPolygon> polygons)
{
CSG csg = new CSG();
csg.polygons = polygons;
return csg;
}
public CSG clone()
{
CSG csg = new CSG();
foreach(CSGPolygon polygon in this.polygons)
csg.polygons.Add(polygon.clone());
return csg;
}
public List<CSGPolygon> toPolygons()
{
return this.polygons;
}
// Return a new CSG solid representing space in either this solid or in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.union(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +----+
// +----+--+ | +----+ |
// | B | | |
// | | | |
// +-------+ +-------+
//
public CSG union(CSG csg)
{
CSGNode a = new CSGNode(this.clone().polygons);
CSGNode b = new CSGNode(csg.clone().polygons);
a.clipTo(b);
b.clipTo(a);
b.invert();
b.clipTo(a);
b.invert();
List<CSGPolygon> result = a.allPolygons();
result.AddRange(b.allPolygons());
return CSG.fromPolygons(result);
}
// Return a new CSG solid representing space in this solid but not in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.subtract(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +--+
// +----+--+ | +----+
// | B |
// | |
// +-------+
//
public CSG subtract(CSG csg)
{
CSGNode a = new CSGNode(this.clone().polygons);
CSGNode b = new CSGNode(csg.clone().polygons);
a.invert();
a.clipTo(b);
b.clipTo(a);
b.invert();
b.clipTo(a);
b.invert();
a.addPolygons(b.allPolygons());
a.invert();
return CSG.fromPolygons(a.allPolygons());
}
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.intersect(B)
//
// +-------+
// | |
// | A |
// | +--+----+ = +--+
// +----+--+ | +--+
// | B |
// | |
// +-------+
//
public CSG intersect(CSG csg)
{
CSGNode a = new CSGNode(this.clone().polygons);
CSGNode b = new CSGNode(csg.clone().polygons);
a.invert();
b.clipTo(a);
b.invert();
a.clipTo(b);
b.clipTo(a);
a.addPolygons(b.allPolygons());
a.invert();
return CSG.fromPolygons(a.allPolygons());
}
// Return a new CSG solid with solid and empty space switched. This solid is
// not modified.
public CSG inverse()
{
CSG csg = this.clone();
foreach(CSGPolygon p in csg.polygons)
p.flip();
return csg;
}
// Affine transformation of CSG object. Returns a new CSG object
public CSG transform(CSGMatrix4x4 matrix4x4)
{
List<CSGPolygon> newpolygons = new List<CSGPolygon>();
foreach(CSGPolygon p in this.polygons)
newpolygons.Add(p.transform(matrix4x4));
return CSG.fromPolygons(newpolygons);
}
public CSG translate(CSGVector3 v)
{
return this.transform(CSGMatrix4x4.translation(v));
}
public CSG scale(CSGVector3 v)
{
return this.transform(CSGMatrix4x4.scaling(v));
}
public CSG rotateX(float deg)
{
return this.transform(CSGMatrix4x4.rotationX(deg));
}
public CSG rotateY(float deg)
{
return this.transform(CSGMatrix4x4.rotationY(deg));
}
public CSG rotateZ(float deg)
{
return this.transform(CSGMatrix4x4.rotationZ(deg));
}
// Construct an axis-aligned solid cuboid. Optional parameters are `center` and
// `radius`, which default to `[0, 0, 0]` and `[1, 1, 1]`. The radius can be
// specified using a single number or a list of three numbers, one for each axis.
static public CSG cube(CSGVector3 center, CSGVector3 halfSize, CSGShared shared)
{
int[][][] data = new int[][][] {
new int[][] {new int[] { 0, 4, 6, 2}, new int[] {-1, 0, 0}},
new int[][] {new int[] { 1, 3, 7, 5}, new int[] {+1, 0, 0}},
new int[][] {new int[] { 0, 1, 5, 4}, new int[] {0, -1, 0}},
new int[][] {new int[] { 2, 6, 7, 3}, new int[] {0, +1, 0}},
new int[][] {new int[] { 0, 2, 3, 1}, new int[] {0, 0, -1}},
new int[][] {new int[] { 4, 5, 7, 6}, new int[] {0, 0, +1}}
};
List<CSGPolygon> polygons = new List<CSGPolygon>();
foreach(int[][] info in data)
{
List<CSGVertex> vertices = new List<CSGVertex>();
foreach(int i in info[0])
{
CSGVector3 pos = new CSGVector3(
center.x + halfSize.x * (2 * ((i & 1) != 0 ? 1 : 0) - 1),
center.y + halfSize.y * (2 * ((i & 2) != 0 ? 1 : 0) - 1),
center.z + halfSize.z * (2 * ((i & 4) != 0 ? 1 : 0) - 1)
);
vertices.Add(new CSGVertex(pos, new CSGVector3(info[1][0], info[1][1], info[1][2])));
}
polygons.Add(new CSGPolygon(vertices, shared));
}
return CSG.fromPolygons(polygons);
}
// Construct a solid sphere. Optional parameters are `center`, `radius`,
// `slices`, and `stacks`, which default to `[0, 0, 0]`, `1`, `16`, and `8`.
// The `slices` and `stacks` parameters control the tessellation along the
// longitude and latitude directions.
//
// Example usage:
//
// var sphere = CSG.sphere({
// center: [0, 0, 0],
// radius: 1,
// slices: 16,
// stacks: 8
// });
static public CSG sphere(CSGVector3 center, float radius, int slices, int stacks, CSGShared shared)
{
List<CSGPolygon> polygons = new List<CSGPolygon>();
for (float i = 0; i < slices; i++)
{
for (float j = 0; j < stacks; j++)
{
List<CSGVertex> vertices = new List<CSGVertex>();
sphereVertex(center, radius, i / slices, j / stacks, vertices);
if (j > 0)
sphereVertex(center, radius, (i + 1) / slices, j / stacks, vertices);
if (j < stacks - 1)
sphereVertex(center, radius, (i + 1) / slices, (j + 1) / stacks, vertices);
sphereVertex(center, radius, i / slices, (j + 1) / stacks, vertices);
polygons.Add(new CSGPolygon(vertices, shared));
}
}
return CSG.fromPolygons(polygons);
}
static private void sphereVertex(CSGVector3 center, float radius, float theta, float phi, List<CSGVertex> vertices)
{
theta *= ((float) Math.PI) * 2;
phi *= ((float) Math.PI);
CSGVector3 dir = new CSGVector3(
(float) Math.Cos(theta) * (float) Math.Sin(phi),
(float) Math.Cos(phi),
(float) Math.Sin(theta) * (float) Math.Sin(phi)
);
vertices.Add(new CSGVertex(center.plus(dir.times(radius)), dir));
}
// Construct a solid cylinder. Optional parameters are `start`, `end`,
// `radius`, and `slices`, which default to `[0, -1, 0]`, `[0, 1, 0]`, `1`, and
// `16`. The `slices` parameter controls the tessellation.
//
// Example usage:
//
// var cylinder = CSG.cylinder({
// start: [0, -1, 0],
// end: [0, 1, 0],
// radius: 1,
// slices: 16
// });
static public CSG cylinder(CSGVector3 s, CSGVector3 e, float radius, int slices, CSGShared shared)
{
CSGVector3 ray = e.minus(s);
CSGVector3 axisZ = ray.unit();
bool isY = (Math.Abs(axisZ.y) > 0.5f);
CSGVector3 axisX = new CSGVector3(isY ? 1 : 0, !isY ? 1 : 0, 0).cross(axisZ).unit();
CSGVector3 axisY = axisX.cross(axisZ).unit();
CSGVertex start = new CSGVertex(s, axisZ.negated());
CSGVertex end = new CSGVertex(e, axisZ.unit());
List<CSGPolygon> polygons = new List<CSGPolygon>();
for (float i = 0; i < slices; i++)
{
float t0 = i / slices;
float t1 = (i + 1) / slices;
//cylinderPoint(s, ray, radius, axisX, axisY, axisZ,
polygons.Add(
new CSGPolygon(
new CSGVertex[] {
start,
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 0, t0, -1),
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 0, t1, -1)}, shared));
polygons.Add(
new CSGPolygon(
new CSGVertex[] {
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 0, t1, 0),
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 0, t0, 0),
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 1, t0, 0),
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 1, t1, 0)}, shared));
polygons.Add(
new CSGPolygon(
new CSGVertex[] {
end,
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 1, t1, 1),
cylinderPoint(s, ray, radius, axisX, axisY, axisZ, 1, t0, 1)}, shared));
}
return CSG.fromPolygons(polygons);
}
static private CSGVertex cylinderPoint(CSGVector3 s, CSGVector3 ray, float r, CSGVector3 axisX, CSGVector3 axisY, CSGVector3 axisZ, float stack, float slice, float normalBlend)
{
float angle = slice * ((float) Math.PI) * 2;
CSGVector3 outv = axisX.times((float) Math.Cos(angle)).plus(axisY.times((float) Math.Sin(angle)));
CSGVector3 pos = s.plus(ray.times(stack)).plus(outv.times(r));
CSGVector3 normal = outv.times(1 - Math.Abs(normalBlend)).plus(axisZ.times(normalBlend));
return new CSGVertex(pos, normal);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using NUnit.Framework;
using Newtonsoft.Json;
using GlmSharp;
// ReSharper disable InconsistentNaming
namespace GlmSharpTest.Generated.Vec2
{
[TestFixture]
public class UintVec2Test
{
[Test]
public void Constructors()
{
{
var v = new uvec2(1u);
Assert.AreEqual(1u, v.x);
Assert.AreEqual(1u, v.y);
}
{
var v = new uvec2(5u, 2u);
Assert.AreEqual(5u, v.x);
Assert.AreEqual(2u, v.y);
}
{
var v = new uvec2(new uvec2(3u, 3u));
Assert.AreEqual(3u, v.x);
Assert.AreEqual(3u, v.y);
}
{
var v = new uvec2(new uvec3(9u, 6u, 6u));
Assert.AreEqual(9u, v.x);
Assert.AreEqual(6u, v.y);
}
{
var v = new uvec2(new uvec4(2u, 3u, 8u, 7u));
Assert.AreEqual(2u, v.x);
Assert.AreEqual(3u, v.y);
}
}
[Test]
public void Indexer()
{
var v = new uvec2(2u, 9u);
Assert.AreEqual(2u, v[0]);
Assert.AreEqual(9u, v[1]);
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-2147483648]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-2147483648] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-1]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-1] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[2] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2147483647]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[2147483647] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[5]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[5] = 0u; } );
v[1] = 0u;
Assert.AreEqual(0u, v[1]);
v[1] = 1u;
Assert.AreEqual(1u, v[1]);
v[0] = 2u;
Assert.AreEqual(2u, v[0]);
v[1] = 3u;
Assert.AreEqual(3u, v[1]);
v[0] = 4u;
Assert.AreEqual(4u, v[0]);
v[1] = 5u;
Assert.AreEqual(5u, v[1]);
v[1] = 6u;
Assert.AreEqual(6u, v[1]);
v[0] = 7u;
Assert.AreEqual(7u, v[0]);
v[0] = 8u;
Assert.AreEqual(8u, v[0]);
v[0] = 9u;
Assert.AreEqual(9u, v[0]);
}
[Test]
public void PropertyValues()
{
var v = new uvec2(8u, 0u);
var vals = v.Values;
Assert.AreEqual(8u, vals[0]);
Assert.AreEqual(0u, vals[1]);
Assert.That(vals.SequenceEqual(v.ToArray()));
}
[Test]
public void StaticProperties()
{
Assert.AreEqual(0u, uvec2.Zero.x);
Assert.AreEqual(0u, uvec2.Zero.y);
Assert.AreEqual(1u, uvec2.Ones.x);
Assert.AreEqual(1u, uvec2.Ones.y);
Assert.AreEqual(1u, uvec2.UnitX.x);
Assert.AreEqual(0u, uvec2.UnitX.y);
Assert.AreEqual(0u, uvec2.UnitY.x);
Assert.AreEqual(1u, uvec2.UnitY.y);
Assert.AreEqual(uint.MaxValue, uvec2.MaxValue.x);
Assert.AreEqual(uint.MaxValue, uvec2.MaxValue.y);
Assert.AreEqual(uint.MinValue, uvec2.MinValue.x);
Assert.AreEqual(uint.MinValue, uvec2.MinValue.y);
}
[Test]
public void Operators()
{
var v1 = new uvec2(0u, 7u);
var v2 = new uvec2(0u, 7u);
var v3 = new uvec2(7u, 0u);
Assert.That(v1 == new uvec2(v1));
Assert.That(v2 == new uvec2(v2));
Assert.That(v3 == new uvec2(v3));
Assert.That(v1 == v2);
Assert.That(v1 != v3);
Assert.That(v2 != v3);
}
[Test]
public void StringInterop()
{
var v = new uvec2(7u, 0u);
var s0 = v.ToString();
var s1 = v.ToString("#");
var v0 = uvec2.Parse(s0);
var v1 = uvec2.Parse(s1, "#");
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
var b0 = uvec2.TryParse(s0, out v0);
var b1 = uvec2.TryParse(s1, "#", out v1);
Assert.That(b0);
Assert.That(b1);
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
b0 = uvec2.TryParse(null, out v0);
Assert.False(b0);
b0 = uvec2.TryParse("", out v0);
Assert.False(b0);
b0 = uvec2.TryParse(s0 + ", 0", out v0);
Assert.False(b0);
Assert.Throws<NullReferenceException>(() => { uvec2.Parse(null); });
Assert.Throws<FormatException>(() => { uvec2.Parse(""); });
Assert.Throws<FormatException>(() => { uvec2.Parse(s0 + ", 0"); });
var s2 = v.ToString(";", CultureInfo.InvariantCulture);
Assert.That(s2.Length > 0);
var s3 = v.ToString("; ", "G");
var s4 = v.ToString("; ", "G", CultureInfo.InvariantCulture);
var v3 = uvec2.Parse(s3, "; ", NumberStyles.Number);
var v4 = uvec2.Parse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture);
Assert.AreEqual(v, v3);
Assert.AreEqual(v, v4);
var b4 = uvec2.TryParse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture, out v4);
Assert.That(b4);
Assert.AreEqual(v, v4);
}
[Test]
public void SerializationJson()
{
var v0 = new uvec2(8u, 2u);
var s0 = JsonConvert.SerializeObject(v0);
var v1 = JsonConvert.DeserializeObject<uvec2>(s0);
var s1 = JsonConvert.SerializeObject(v1);
Assert.AreEqual(v0, v1);
Assert.AreEqual(s0, s1);
}
[Test]
public void InvariantId()
{
{
var v0 = new uvec2(6u, 3u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(0u, 5u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(4u, 0u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(1u, 1u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(5u, 5u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(5u, 1u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(5u, 8u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(0u, 3u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(3u, 8u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec2(1u, 7u);
Assert.AreEqual(v0, +v0);
}
}
[Test]
public void InvariantDouble()
{
{
var v0 = new uvec2(1u, 3u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(9u, 0u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(0u, 8u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(1u, 9u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(7u, 3u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(3u, 7u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(1u, 4u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(4u, 4u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(3u, 6u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec2(2u, 2u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
}
[Test]
public void InvariantTriple()
{
{
var v0 = new uvec2(5u, 4u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(5u, 4u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(6u, 8u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(3u, 4u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(0u, 8u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(2u, 6u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(4u, 8u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(4u, 6u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(4u, 5u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec2(2u, 9u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
}
[Test]
public void InvariantCommutative()
{
{
var v0 = new uvec2(3u, 7u);
var v1 = new uvec2(3u, 9u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(9u, 4u);
var v1 = new uvec2(4u, 1u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(4u, 2u);
var v1 = new uvec2(0u, 5u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(1u, 8u);
var v1 = new uvec2(6u, 1u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(1u, 5u);
var v1 = new uvec2(6u, 6u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(1u, 3u);
var v1 = new uvec2(2u, 7u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(2u, 5u);
var v1 = new uvec2(7u, 1u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(9u, 6u);
var v1 = new uvec2(8u, 8u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(3u, 4u);
var v1 = new uvec2(5u, 3u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec2(7u, 5u);
var v1 = new uvec2(7u, 6u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
}
[Test]
public void InvariantAssociative()
{
{
var v0 = new uvec2(1u, 5u);
var v1 = new uvec2(0u, 3u);
var v2 = new uvec2(9u, 6u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(1u, 6u);
var v1 = new uvec2(0u, 3u);
var v2 = new uvec2(3u, 0u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(3u, 4u);
var v1 = new uvec2(7u, 3u);
var v2 = new uvec2(0u, 6u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(2u, 5u);
var v1 = new uvec2(0u, 3u);
var v2 = new uvec2(4u, 7u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(1u, 8u);
var v1 = new uvec2(7u, 8u);
var v2 = new uvec2(0u, 8u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(4u, 5u);
var v1 = new uvec2(9u, 6u);
var v2 = new uvec2(8u, 9u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(6u, 1u);
var v1 = new uvec2(0u, 5u);
var v2 = new uvec2(4u, 2u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(3u, 7u);
var v1 = new uvec2(7u, 7u);
var v2 = new uvec2(4u, 8u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(4u, 7u);
var v1 = new uvec2(4u, 9u);
var v2 = new uvec2(8u, 8u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec2(0u, 7u);
var v1 = new uvec2(0u, 3u);
var v2 = new uvec2(2u, 0u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
}
[Test]
public void TriangleInequality()
{
{
var v0 = new uvec2(3u, 2u);
var v1 = new uvec2(7u, 9u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(2u, 7u);
var v1 = new uvec2(5u, 8u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(6u, 9u);
var v1 = new uvec2(1u, 5u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(2u, 3u);
var v1 = new uvec2(9u, 6u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(4u, 7u);
var v1 = new uvec2(9u, 2u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(0u, 4u);
var v1 = new uvec2(8u, 9u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(5u, 6u);
var v1 = new uvec2(3u, 8u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(9u, 8u);
var v1 = new uvec2(2u, 4u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(1u, 0u);
var v1 = new uvec2(9u, 3u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec2(6u, 6u);
var v1 = new uvec2(1u, 9u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
}
[Test]
public void InvariantNorm()
{
{
var v0 = new uvec2(9u, 5u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(4u, 6u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(2u, 8u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(0u, 3u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(6u, 7u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(6u, 0u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(0u, 7u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(7u, 1u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(4u, 7u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec2(4u, 1u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
}
[Test]
public void RandomUniform0()
{
var random = new Random(642522786);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.Random(random, 0, 3);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 1, 1.0);
Assert.AreEqual(avg.y, 1, 1.0);
Assert.AreEqual(variance.x, 0.666666666666667, 3.0);
Assert.AreEqual(variance.y, 0.666666666666667, 3.0);
}
[Test]
public void RandomUniform1()
{
var random = new Random(2071438431);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomUniform(random, 1, 6);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 3, 1.0);
Assert.AreEqual(avg.y, 3, 1.0);
Assert.AreEqual(variance.x, 2, 3.0);
Assert.AreEqual(variance.y, 2, 3.0);
}
[Test]
public void RandomUniform2()
{
var random = new Random(1352870429);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.Random(random, 4, 9);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 6, 1.0);
Assert.AreEqual(avg.y, 6, 1.0);
Assert.AreEqual(variance.x, 2, 3.0);
Assert.AreEqual(variance.y, 2, 3.0);
}
[Test]
public void RandomUniform3()
{
var random = new Random(634302427);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomUniform(random, 1, 5);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.5, 1.0);
Assert.AreEqual(avg.y, 2.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
}
[Test]
public void RandomUniform4()
{
var random = new Random(1369311147);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.Random(random, 4, 8);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 5.5, 1.0);
Assert.AreEqual(avg.y, 5.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
}
[Test]
public void RandomPoisson0()
{
var random = new Random(1023436405);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomPoisson(random, 2.10027294028563);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.10027294028563, 1.0);
Assert.AreEqual(avg.y, 2.10027294028563, 1.0);
Assert.AreEqual(variance.x, 2.10027294028563, 3.0);
Assert.AreEqual(variance.y, 2.10027294028563, 3.0);
}
[Test]
public void RandomPoisson1()
{
var random = new Random(304868403);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomPoisson(random, 0.707460162792103);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.707460162792103, 1.0);
Assert.AreEqual(avg.y, 0.707460162792103, 1.0);
Assert.AreEqual(variance.x, 0.707460162792103, 3.0);
Assert.AreEqual(variance.y, 0.707460162792103, 3.0);
}
[Test]
public void RandomPoisson2()
{
var random = new Random(313088762);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomPoisson(random, 2.15502730927199);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.15502730927199, 1.0);
Assert.AreEqual(avg.y, 2.15502730927199, 1.0);
Assert.AreEqual(variance.x, 2.15502730927199, 3.0);
Assert.AreEqual(variance.y, 2.15502730927199, 3.0);
}
[Test]
public void RandomPoisson3()
{
var random = new Random(1742004407);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomPoisson(random, 0.81232586983234);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.81232586983234, 1.0);
Assert.AreEqual(avg.y, 0.81232586983234, 1.0);
Assert.AreEqual(variance.x, 0.81232586983234, 3.0);
Assert.AreEqual(variance.y, 0.81232586983234, 3.0);
}
[Test]
public void RandomPoisson4()
{
var random = new Random(1750224766);
var sum = new dvec2(0.0);
var sumSqr = new dvec2(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec2.RandomPoisson(random, 2.25989301631222);
sum += (dvec2)v;
sumSqr += glm.Pow2((dvec2)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.25989301631222, 1.0);
Assert.AreEqual(avg.y, 2.25989301631222, 1.0);
Assert.AreEqual(variance.x, 2.25989301631222, 3.0);
Assert.AreEqual(variance.y, 2.25989301631222, 3.0);
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Globalization;
using System.Text;
namespace Gallio.Common.Normalization
{
/// <summary>
/// Normalization utilities.
/// </summary>
public static class NormalizationUtils
{
/// <summary>
/// Normalizes a collection of normalizable values.
/// </summary>
/// <typeparam name="TCollection">The type of the collection.</typeparam>
/// <typeparam name="T">The type of the values in the collection.</typeparam>
/// <param name="collection">The collection of values to normalize, or null if none.</param>
/// <param name="collectionFactory">The factory to use to create a new collection if needed.</param>
/// <param name="normalize">The normalization function to apply to each value in the collection.</param>
/// <param name="compare">The comparer to compare normalized values to determine if a change occurred during normalization.</param>
/// <returns>The normalized collection, or null if none. The result will
/// be the same instance as <paramref name="collection"/> if it was already normalized.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="collectionFactory"/>,
/// <paramref name="normalize"/> or <paramref name="compare"/> is null.</exception>
public static TCollection NormalizeCollection<TCollection, T>(TCollection collection,
Func<TCollection> collectionFactory, Func<T, T> normalize, EqualityComparison<T> compare)
where TCollection : class, ICollection<T>
{
if (collectionFactory == null)
throw new ArgumentNullException("collectionFactory");
if (normalize == null)
throw new ArgumentNullException("normalize");
if (compare == null)
throw new ArgumentNullException("compare");
if (collection == null)
return null;
TCollection normalizedCollection = null;
int itemIndex = 0;
foreach (T item in collection)
{
T normalizedItem = normalize(item);
if (normalizedCollection == null)
{
if (! compare(item, normalizedItem))
{
normalizedCollection = collectionFactory();
if (itemIndex > 0)
{
int oldItemIndex = 0;
foreach (T oldItem in collection)
{
normalizedCollection.Add(oldItem);
oldItemIndex += 1;
if (oldItemIndex == itemIndex)
break;
}
}
normalizedCollection.Add(normalizedItem);
}
}
else
{
normalizedCollection.Add(normalizedItem);
}
itemIndex += 1;
}
return normalizedCollection ?? collection;
}
/// <summary>
/// Normalizes a string.
/// </summary>
/// <remarks>
/// <para>
/// Preserves all valid characters in the string and replaces others as requested.
/// </para>
/// </remarks>
/// <param name="str">The string to normalize, or null if none.</param>
/// <param name="valid">The predicate to determine whether a character is valid.
/// If the character consists of a surrogate pair, then the parameter will be
/// its UTF32 value.</param>
/// <param name="replace">The converter to provide a replacement for an invalid character.
/// If the character consists of a surrogate pair, then the parameters will be
/// its UTF32 value.</param>
/// <returns>The normalized text, or null if <paramref name="str"/> was null. The result will
/// be the same instance as <paramref name="str"/> if it was already normalized.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="valid"/>
/// or <paramref name="replace"/> is null.</exception>
public static string NormalizeString(string str, Predicate<int> valid, Converter<int, string> replace)
{
if (valid == null)
throw new ArgumentNullException("valid");
if (replace == null)
throw new ArgumentNullException("replace");
if (str == null)
return null;
int length = str.Length;
if (length == 0)
return str;
StringBuilder result = null;
for (int i = 0; i < length; i++)
{
char c = str[i];
if (valid(c))
{
if (result != null)
result.Append(c);
continue;
}
int pos = i;
int codePoint = c;
if (char.IsHighSurrogate(c) && i + 1 < length)
{
char c2 = str[i + 1];
if (char.IsLowSurrogate(c2))
{
i += 1;
codePoint = char.ConvertToUtf32(c, c2);
if (valid(codePoint))
{
if (result != null)
result.Append(c).Append(c2);
continue;
}
}
}
if (result == null)
{
result = new StringBuilder(length);
if (pos > 0)
result.Append(str, 0, pos);
}
result.Append(replace(codePoint));
}
return result != null ? result.ToString() : str;
}
/// <summary>
/// Normalizes a name by replacing characters that are not printable with a '?'.
/// </summary>
/// <param name="name">The name to normalize, or null if none.</param>
/// <returns>The normalized name, or null if <paramref name="name"/> was null. The result will
/// be the same instance as <paramref name="name"/> if it was already normalized.</returns>
public static string NormalizeName(string name)
{
return NormalizeString(name, IsValidNameCharacter, ReplaceInvalidCharacter);
}
private static bool IsValidNameCharacter(int c)
{
if (c >= 0x10000)
return false;
switch (char.GetUnicodeCategory((char) c))
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.LetterNumber:
case UnicodeCategory.OtherNumber:
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
case UnicodeCategory.MathSymbol:
case UnicodeCategory.CurrencySymbol:
case UnicodeCategory.ModifierSymbol:
case UnicodeCategory.OtherSymbol:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.EnclosingMark:
return true;
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Control:
case UnicodeCategory.Format:
case UnicodeCategory.Surrogate:
case UnicodeCategory.PrivateUse:
case UnicodeCategory.OtherNotAssigned:
default:
return false;
}
}
/// <summary>
/// Normalizes a name by replacing characters that are not printable ASCII with '?'.
/// </summary>
/// <param name="str">The string to normalize, or null if none.</param>
/// <returns>The normalized string, or null if <paramref name="str"/> was null. The result will
/// be the same instance as <paramref name="str"/> if it was already normalized.</returns>
public static string NormalizePrintableASCII(string str)
{
return NormalizeString(str, IsValidPrintableASCIICharacter, ReplaceInvalidCharacter);
}
private static bool IsValidPrintableASCIICharacter(int c)
{
return c >= '\u0020' && c <= '\u007e';
}
/// <summary>
/// Normalizes Xml text.
/// </summary>
/// <remarks>
/// <para>
/// Preserves all characters in the following ranges: \t, \n, \r, \u0020 - \uD7FF,
/// \uE000 - \uFFFD, and \U00010000 - \U0010FFFF. All other characters are replaced
/// with '?' to indicate that they cannot be represented in Xml.
/// </para>
/// </remarks>
/// <param name="text">The Xml text to normalize, or null if none.</param>
/// <returns>The normalized Xml text, or null if <paramref name="text"/> was null. The result will
/// be the same instance as <paramref name="text"/> if it was already normalized.</returns>
public static string NormalizeXmlText(string text)
{
return NormalizeString(text, IsValidXmlCharacter, ReplaceInvalidCharacter);
}
private static bool IsValidXmlCharacter(int c)
{
return c >= '\u0020' && c <= '\uD7FF'
|| c == '\n'
|| c == '\r'
|| c == '\t'
|| c >= '\uE000' && c <= '\uFFFD'
|| c >= 0x10000 && c <= 0x10FFFF;
}
private static string ReplaceInvalidCharacter(int c)
{
return "?";
}
}
}
| |
/*
* 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>
/// TaxRateResponse
/// </summary>
[DataContract]
public partial class TaxRateResponse : IEquatable<TaxRateResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxRateResponse" /> class.
/// </summary>
/// <param name="ObjectId">ObjectId.</param>
/// <param name="Confidence">Confidence.</param>
/// <param name="Jurisdiction">Jurisdiction.</param>
/// <param name="MatchedAddress">MatchedAddress.</param>
/// <param name="SalesTax">SalesTax.</param>
/// <param name="UseTax">UseTax.</param>
/// <param name="LatLongFields">LatLongFields.</param>
public TaxRateResponse(string ObjectId = null, double? Confidence = null, TaxJurisdiction Jurisdiction = null, MatchedAddress MatchedAddress = null, SalesTaxRate SalesTax = null, UseTaxRate UseTax = null, LatLongFields LatLongFields = null)
{
this.ObjectId = ObjectId;
this.Confidence = Confidence;
this.Jurisdiction = Jurisdiction;
this.MatchedAddress = MatchedAddress;
this.SalesTax = SalesTax;
this.UseTax = UseTax;
this.LatLongFields = LatLongFields;
}
/// <summary>
/// Gets or Sets ObjectId
/// </summary>
[DataMember(Name="objectId", EmitDefaultValue=false)]
public string ObjectId { get; set; }
/// <summary>
/// Gets or Sets Confidence
/// </summary>
[DataMember(Name="confidence", EmitDefaultValue=false)]
public double? Confidence { get; set; }
/// <summary>
/// Gets or Sets Jurisdiction
/// </summary>
[DataMember(Name="jurisdiction", EmitDefaultValue=false)]
public TaxJurisdiction Jurisdiction { get; set; }
/// <summary>
/// Gets or Sets MatchedAddress
/// </summary>
[DataMember(Name="matchedAddress", EmitDefaultValue=false)]
public MatchedAddress MatchedAddress { get; set; }
/// <summary>
/// Gets or Sets SalesTax
/// </summary>
[DataMember(Name="salesTax", EmitDefaultValue=false)]
public SalesTaxRate SalesTax { get; set; }
/// <summary>
/// Gets or Sets UseTax
/// </summary>
[DataMember(Name="useTax", EmitDefaultValue=false)]
public UseTaxRate UseTax { get; set; }
/// <summary>
/// Gets or Sets LatLongFields
/// </summary>
[DataMember(Name="latLongFields", EmitDefaultValue=false)]
public LatLongFields LatLongFields { 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 TaxRateResponse {\n");
sb.Append(" ObjectId: ").Append(ObjectId).Append("\n");
sb.Append(" Confidence: ").Append(Confidence).Append("\n");
sb.Append(" Jurisdiction: ").Append(Jurisdiction).Append("\n");
sb.Append(" MatchedAddress: ").Append(MatchedAddress).Append("\n");
sb.Append(" SalesTax: ").Append(SalesTax).Append("\n");
sb.Append(" UseTax: ").Append(UseTax).Append("\n");
sb.Append(" LatLongFields: ").Append(LatLongFields).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 TaxRateResponse);
}
/// <summary>
/// Returns true if TaxRateResponse instances are equal
/// </summary>
/// <param name="other">Instance of TaxRateResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxRateResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ObjectId == other.ObjectId ||
this.ObjectId != null &&
this.ObjectId.Equals(other.ObjectId)
) &&
(
this.Confidence == other.Confidence ||
this.Confidence != null &&
this.Confidence.Equals(other.Confidence)
) &&
(
this.Jurisdiction == other.Jurisdiction ||
this.Jurisdiction != null &&
this.Jurisdiction.Equals(other.Jurisdiction)
) &&
(
this.MatchedAddress == other.MatchedAddress ||
this.MatchedAddress != null &&
this.MatchedAddress.Equals(other.MatchedAddress)
) &&
(
this.SalesTax == other.SalesTax ||
this.SalesTax != null &&
this.SalesTax.Equals(other.SalesTax)
) &&
(
this.UseTax == other.UseTax ||
this.UseTax != null &&
this.UseTax.Equals(other.UseTax)
) &&
(
this.LatLongFields == other.LatLongFields ||
this.LatLongFields != null &&
this.LatLongFields.Equals(other.LatLongFields)
);
}
/// <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.ObjectId != null)
hash = hash * 59 + this.ObjectId.GetHashCode();
if (this.Confidence != null)
hash = hash * 59 + this.Confidence.GetHashCode();
if (this.Jurisdiction != null)
hash = hash * 59 + this.Jurisdiction.GetHashCode();
if (this.MatchedAddress != null)
hash = hash * 59 + this.MatchedAddress.GetHashCode();
if (this.SalesTax != null)
hash = hash * 59 + this.SalesTax.GetHashCode();
if (this.UseTax != null)
hash = hash * 59 + this.UseTax.GetHashCode();
if (this.LatLongFields != null)
hash = hash * 59 + this.LatLongFields.GetHashCode();
return hash;
}
}
}
}
| |
// 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;
using System;
using System.Reflection;
using System.Collections.Generic;
#pragma warning disable 0414
namespace System.Reflection.Tests
{
public class FieldInfoRTGenericTests
{
//Verify FieldInfo for generic Types
[Fact]
public static void TestGenericFields()
{
FieldInfoRTGenericTests myInstance = new FieldInfoRTGenericTests();
myInstance.populateScenario();
Type openType = typeof(PublicFieldGeneric<>);
foreach (Scenario sc in list)
{
Type type = openType.MakeGenericType(new Type[] { sc.gaType });
Object obj = Activator.CreateInstance(type);
FieldInfo fi = null;
fi = getField(type, sc.fieldName);
Assert.True((fi.GetValue(obj)).Equals(sc.initialValue), "Get Value should return value that was set for generic type: " + sc.fieldName);
fi.SetValue(obj, sc.changedValue);
Assert.True((fi.GetValue(obj)).Equals(sc.changedValue), "Get Value should return value that was set for generic type: " + sc.fieldName);
fi.SetValue(obj, null);
Assert.True((fi.GetValue(obj)).Equals(sc.initialValue), "Get Value should return value that was set for generic type: " + sc.fieldName);
}
}
//Verify FieldInfo for static generic Types
[Fact]
public static void TestStaticGenericFields()
{
FieldInfoRTGenericTests myInstance = new FieldInfoRTGenericTests();
myInstance.populateScenarioForStaticTests();
Type openType = typeof(StaticFieldGeneric<>);
foreach (Scenario sc in list)
{
Type type = openType.MakeGenericType(new Type[] { sc.gaType });
Object obj = Activator.CreateInstance(type);
FieldInfo fi = null;
fi = getField(type, sc.fieldName);
Assert.True((fi.GetValue(obj)).Equals(sc.initialValue), "Get Value should return value that was set for generic type: " + sc.fieldName);
fi.SetValue(obj, sc.changedValue);
Assert.True((fi.GetValue(obj)).Equals(sc.changedValue), "Get Value should return value that was set for generic type: " + sc.fieldName);
fi.SetValue(obj, null);
Assert.True((fi.GetValue(obj)).Equals(sc.initialValue), "Get Value should return value that was set for generic type: " + sc.fieldName);
}
}
// Helper method to get field from class FieldInfoRTGenericTests
private static FieldInfo getField(string field)
{
Type t = typeof(FieldInfoRTGenericTests);
TypeInfo ti = t.GetTypeInfo();
IEnumerator<FieldInfo> alldefinedFields = ti.DeclaredFields.GetEnumerator();
FieldInfo fi = null, found = null;
while (alldefinedFields.MoveNext())
{
fi = alldefinedFields.Current;
if (fi.Name.Equals(field))
{
//found type
found = fi;
break;
}
}
return found;
}
// Helper method to get field from Type type
private static FieldInfo getField(Type ptype, string field)
{
TypeInfo ti = ptype.GetTypeInfo();
IEnumerator<FieldInfo> alldefinedFields = ti.DeclaredFields.GetEnumerator();
FieldInfo fi = null, found = null;
while (alldefinedFields.MoveNext())
{
fi = alldefinedFields.Current;
if (fi.Name.Equals(field))
{
//found type
found = fi;
break;
}
}
return found;
}
private void populateScenario()
{
FieldInfoGeneric<int> g_int = new FieldInfoGeneric<int>();
PublicFieldGeneric<int> pfg_int = new PublicFieldGeneric<int>();
int[] gpa_int = new int[] { 300, 400 };
FieldInfoGeneric<int>[] ga_int = new FieldInfoGeneric<int>[] { g_int };
FieldInfoGeneric<string> g_string = new FieldInfoGeneric<string>();
PublicFieldGeneric<string> pfg_string = new PublicFieldGeneric<string>();
string[] gpa_string = new string[] { "forget", "about this" };
FieldInfoGeneric<string>[] ga_string = new FieldInfoGeneric<string>[] { g_string, g_string };
FieldInfoGeneric<object> g_object = new FieldInfoGeneric<object>();
PublicFieldGeneric<object> pfg_object = new PublicFieldGeneric<object>();
object[] gpa_object = new object[] { "world", 300, g_object };
FieldInfoGeneric<object>[] ga_object = new FieldInfoGeneric<object>[] { g_object, g_object, g_object };
FieldInfoGeneric<FieldInfoGeneric<object>> g_g_object = new FieldInfoGeneric<FieldInfoGeneric<object>>();
PublicFieldGeneric<FieldInfoGeneric<object>> pfg_g_object = new PublicFieldGeneric<FieldInfoGeneric<object>>();
FieldInfoGeneric<object>[] gpa_g_object = new FieldInfoGeneric<object>[] { g_object, g_object };
FieldInfoGeneric<FieldInfoGeneric<object>>[] ga_g_object = new FieldInfoGeneric<FieldInfoGeneric<object>>[] { g_g_object, g_g_object, g_g_object, g_g_object };
List<Scenario> list = new List<Scenario>();
list.Add(new Scenario(typeof(int), "genparamField", 0, -300));
list.Add(new Scenario(typeof(int), "dependField", null, g_int));
list.Add(new Scenario(typeof(int), "gparrayField", null, gpa_int));
list.Add(new Scenario(typeof(int), "arrayField", null, ga_int));
list.Add(new Scenario(typeof(string), "genparamField", null, "hello !"));
list.Add(new Scenario(typeof(string), "dependField", null, g_string));
list.Add(new Scenario(typeof(string), "gparrayField", null, gpa_string));
list.Add(new Scenario(typeof(string), "arrayField", null, ga_string));
list.Add(new Scenario(typeof(object), "genparamField", null, (object)300));
list.Add(new Scenario(typeof(object), "dependField", null, g_object));
list.Add(new Scenario(typeof(object), "gparrayField", null, gpa_object));
list.Add(new Scenario(typeof(object), "arrayField", null, ga_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "genparamField", null, g_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "dependField", null, g_g_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "gparrayField", null, gpa_g_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "arrayField", null, ga_g_object));
list.Add(new Scenario(typeof(int), "selfField", null, pfg_int));
list.Add(new Scenario(typeof(string), "selfField", null, pfg_string));
list.Add(new Scenario(typeof(object), "selfField", null, pfg_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "selfField", null, pfg_g_object));
}
private void populateScenarioForStaticTests()
{
List<Scenario> list = new List<Scenario>();
StaticFieldGeneric<int> sfg_int = new StaticFieldGeneric<int>();
StaticFieldGeneric<string> sfg_string = new StaticFieldGeneric<string>();
StaticFieldGeneric<object> sfg_object = new StaticFieldGeneric<object>();
StaticFieldGeneric<FieldInfoGeneric<object>> sfg_g_object = new StaticFieldGeneric<FieldInfoGeneric<object>>();
list.Add(new Scenario(typeof(int), "genparamField", 0, -300));
list.Add(new Scenario(typeof(int), "dependField", null, g_int));
list.Add(new Scenario(typeof(int), "gparrayField", null, gpa_int));
list.Add(new Scenario(typeof(int), "arrayField", null, ga_int));
list.Add(new Scenario(typeof(string), "genparamField", null, "hello !"));
list.Add(new Scenario(typeof(string), "dependField", null, g_string));
list.Add(new Scenario(typeof(string), "gparrayField", null, gpa_string));
list.Add(new Scenario(typeof(string), "arrayField", null, ga_string));
list.Add(new Scenario(typeof(object), "genparamField", null, (object)300));
list.Add(new Scenario(typeof(object), "dependField", null, g_object));
list.Add(new Scenario(typeof(object), "gparrayField", null, gpa_object));
list.Add(new Scenario(typeof(object), "arrayField", null, ga_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "genparamField", null, g_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "dependField", null, g_g_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "gparrayField", null, gpa_g_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "arrayField", null, ga_g_object));
list.Add(new Scenario(typeof(int), "selfField", null, sfg_int));
list.Add(new Scenario(typeof(string), "selfField", null, sfg_string));
list.Add(new Scenario(typeof(object), "selfField", null, sfg_object));
list.Add(new Scenario(typeof(FieldInfoGeneric<object>), "selfField", null, sfg_g_object));
}
//Reflection Fields
public FieldInfoGeneric<int> g_int;
public PublicFieldGeneric<int> pfg_int;
public int[] gpa_int;
public FieldInfoGeneric<int>[] ga_int;
public FieldInfoGeneric<string> g_string;
public PublicFieldGeneric<string> pfg_string;
public string[] gpa_string;
public FieldInfoGeneric<string>[] ga_string;
public FieldInfoGeneric<object> g_object;
public PublicFieldGeneric<object> pfg_object;
public object[] gpa_object;
public FieldInfoGeneric<object>[] ga_object;
public FieldInfoGeneric<FieldInfoGeneric<object>> g_g_object;
public PublicFieldGeneric<FieldInfoGeneric<object>> pfg_g_object;
public FieldInfoGeneric<object>[] gpa_g_object;
public FieldInfoGeneric<FieldInfoGeneric<object>>[] ga_g_object;
public static List<Scenario> list = new List<Scenario>();
}
// Fields for Refletion
public class FieldInfoGeneric<T> { public FieldInfoGeneric() { } }
public class PublicFieldGeneric<T>
{
public T genparamField;
public T[] gparrayField;
public FieldInfoGeneric<T> dependField;
public FieldInfoGeneric<T>[] arrayField;
public PublicFieldGeneric<T> selfField;
}
public class StaticFieldGeneric<T>
{
public static T genparamField;
public static T[] gparrayField;
public static FieldInfoGeneric<T> dependField;
public static FieldInfoGeneric<T>[] arrayField;
public static StaticFieldGeneric<T> selfField;
}
public class Scenario
{
public Type gaType;
public string fieldName;
public object initialValue;
public object changedValue;
public Scenario(Type t, string n, object v1, object v2)
{
gaType = t;
fieldName = n;
initialValue = v1;
changedValue = v2;
}
}
}
| |
// 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.DataLake.Analytics.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Azure.Management.DataLake.Analytics;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The Data Lake Analytics job statistics vertex stage information.
/// </summary>
public partial class JobStatisticsVertexStage
{
/// <summary>
/// Initializes a new instance of the JobStatisticsVertexStage class.
/// </summary>
public JobStatisticsVertexStage()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the JobStatisticsVertexStage class.
/// </summary>
/// <param name="dataRead">the amount of data read, in bytes.</param>
/// <param name="dataReadCrossPod">the amount of data read across
/// multiple pods, in bytes.</param>
/// <param name="dataReadIntraPod">the amount of data read in one pod,
/// in bytes.</param>
/// <param name="dataToRead">the amount of data remaining to be read,
/// in bytes.</param>
/// <param name="dataWritten">the amount of data written, in
/// bytes.</param>
/// <param name="duplicateDiscardCount">the number of duplicates that
/// were discarded.</param>
/// <param name="failedCount">the number of failures that occured in
/// this stage.</param>
/// <param name="maxVertexDataRead">the maximum amount of data read in
/// a single vertex, in bytes.</param>
/// <param name="minVertexDataRead">the minimum amount of data read in
/// a single vertex, in bytes.</param>
/// <param name="readFailureCount">the number of read failures in this
/// stage.</param>
/// <param name="revocationCount">the number of vertices that were
/// revoked during this stage.</param>
/// <param name="runningCount">the number of currently running vertices
/// in this stage.</param>
/// <param name="scheduledCount">the number of currently scheduled
/// vertices in this stage</param>
/// <param name="stageName">the name of this stage in job
/// execution.</param>
/// <param name="succeededCount">the number of vertices that succeeded
/// in this stage.</param>
/// <param name="tempDataWritten">the amount of temporary data written,
/// in bytes.</param>
/// <param name="totalCount">the total vertex count for this
/// stage.</param>
/// <param name="totalFailedTime">the amount of time that failed
/// vertices took up in this stage.</param>
/// <param name="totalProgress">the current progress of this stage, as
/// a percentage.</param>
/// <param name="totalSucceededTime">the amount of time all successful
/// vertices took in this stage.</param>
public JobStatisticsVertexStage(long? dataRead = default(long?), long? dataReadCrossPod = default(long?), long? dataReadIntraPod = default(long?), long? dataToRead = default(long?), long? dataWritten = default(long?), int? duplicateDiscardCount = default(int?), int? failedCount = default(int?), long? maxVertexDataRead = default(long?), long? minVertexDataRead = default(long?), int? readFailureCount = default(int?), int? revocationCount = default(int?), int? runningCount = default(int?), int? scheduledCount = default(int?), string stageName = default(string), int? succeededCount = default(int?), long? tempDataWritten = default(long?), int? totalCount = default(int?), System.TimeSpan? totalFailedTime = default(System.TimeSpan?), int? totalProgress = default(int?), System.TimeSpan? totalSucceededTime = default(System.TimeSpan?))
{
DataRead = dataRead;
DataReadCrossPod = dataReadCrossPod;
DataReadIntraPod = dataReadIntraPod;
DataToRead = dataToRead;
DataWritten = dataWritten;
DuplicateDiscardCount = duplicateDiscardCount;
FailedCount = failedCount;
MaxVertexDataRead = maxVertexDataRead;
MinVertexDataRead = minVertexDataRead;
ReadFailureCount = readFailureCount;
RevocationCount = revocationCount;
RunningCount = runningCount;
ScheduledCount = scheduledCount;
StageName = stageName;
SucceededCount = succeededCount;
TempDataWritten = tempDataWritten;
TotalCount = totalCount;
TotalFailedTime = totalFailedTime;
TotalProgress = totalProgress;
TotalSucceededTime = totalSucceededTime;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the amount of data read, in bytes.
/// </summary>
[JsonProperty(PropertyName = "dataRead")]
public long? DataRead { get; private set; }
/// <summary>
/// Gets the amount of data read across multiple pods, in bytes.
/// </summary>
[JsonProperty(PropertyName = "dataReadCrossPod")]
public long? DataReadCrossPod { get; private set; }
/// <summary>
/// Gets the amount of data read in one pod, in bytes.
/// </summary>
[JsonProperty(PropertyName = "dataReadIntraPod")]
public long? DataReadIntraPod { get; private set; }
/// <summary>
/// Gets the amount of data remaining to be read, in bytes.
/// </summary>
[JsonProperty(PropertyName = "dataToRead")]
public long? DataToRead { get; private set; }
/// <summary>
/// Gets the amount of data written, in bytes.
/// </summary>
[JsonProperty(PropertyName = "dataWritten")]
public long? DataWritten { get; private set; }
/// <summary>
/// Gets the number of duplicates that were discarded.
/// </summary>
[JsonProperty(PropertyName = "duplicateDiscardCount")]
public int? DuplicateDiscardCount { get; private set; }
/// <summary>
/// Gets the number of failures that occured in this stage.
/// </summary>
[JsonProperty(PropertyName = "failedCount")]
public int? FailedCount { get; private set; }
/// <summary>
/// Gets the maximum amount of data read in a single vertex, in bytes.
/// </summary>
[JsonProperty(PropertyName = "maxVertexDataRead")]
public long? MaxVertexDataRead { get; private set; }
/// <summary>
/// Gets the minimum amount of data read in a single vertex, in bytes.
/// </summary>
[JsonProperty(PropertyName = "minVertexDataRead")]
public long? MinVertexDataRead { get; private set; }
/// <summary>
/// Gets the number of read failures in this stage.
/// </summary>
[JsonProperty(PropertyName = "readFailureCount")]
public int? ReadFailureCount { get; private set; }
/// <summary>
/// Gets the number of vertices that were revoked during this stage.
/// </summary>
[JsonProperty(PropertyName = "revocationCount")]
public int? RevocationCount { get; private set; }
/// <summary>
/// Gets the number of currently running vertices in this stage.
/// </summary>
[JsonProperty(PropertyName = "runningCount")]
public int? RunningCount { get; private set; }
/// <summary>
/// Gets the number of currently scheduled vertices in this stage
/// </summary>
[JsonProperty(PropertyName = "scheduledCount")]
public int? ScheduledCount { get; private set; }
/// <summary>
/// Gets the name of this stage in job execution.
/// </summary>
[JsonProperty(PropertyName = "stageName")]
public string StageName { get; private set; }
/// <summary>
/// Gets the number of vertices that succeeded in this stage.
/// </summary>
[JsonProperty(PropertyName = "succeededCount")]
public int? SucceededCount { get; private set; }
/// <summary>
/// Gets the amount of temporary data written, in bytes.
/// </summary>
[JsonProperty(PropertyName = "tempDataWritten")]
public long? TempDataWritten { get; private set; }
/// <summary>
/// Gets the total vertex count for this stage.
/// </summary>
[JsonProperty(PropertyName = "totalCount")]
public int? TotalCount { get; private set; }
/// <summary>
/// Gets the amount of time that failed vertices took up in this stage.
/// </summary>
[JsonProperty(PropertyName = "totalFailedTime")]
public System.TimeSpan? TotalFailedTime { get; private set; }
/// <summary>
/// Gets the current progress of this stage, as a percentage.
/// </summary>
[JsonProperty(PropertyName = "totalProgress")]
public int? TotalProgress { get; private set; }
/// <summary>
/// Gets the amount of time all successful vertices took in this stage.
/// </summary>
[JsonProperty(PropertyName = "totalSucceededTime")]
public System.TimeSpan? TotalSucceededTime { get; private set; }
}
}
| |
//
// System.Web.Services.Protocols.HttpSimpleClientProtocol.cs
//
// Author:
// Tim Coleman ([email protected])
// Lluis Sanchez Gual ([email protected])
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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.Web.Services;
using System.Net;
using System.IO;
using System.Threading;
namespace System.Web.Services.Protocols {
public abstract class HttpSimpleClientProtocol : HttpWebClientProtocol {
#region Fields
internal HttpSimpleTypeStubInfo TypeStub;
#endregion // Fields
#region Constructors
protected HttpSimpleClientProtocol ()
{
}
#endregion // Constructors
#region Methods
protected IAsyncResult BeginInvoke (string methodName, string requestUrl, object[] parameters, AsyncCallback callback, object asyncState)
{
HttpSimpleMethodStubInfo method = (HttpSimpleMethodStubInfo) TypeStub.GetMethod (methodName);
SimpleWebClientAsyncResult ainfo = null;
try
{
MimeParameterWriter parameterWriter = (MimeParameterWriter) method.ParameterWriterType.Create ();
string url = parameterWriter.GetRequestUrl (requestUrl, parameters);
WebRequest req = GetWebRequest (new Uri(url));
ainfo = new SimpleWebClientAsyncResult (req, callback, asyncState);
ainfo.Parameters = parameters;
ainfo.ParameterWriter = parameterWriter;
ainfo.Method = method;
ainfo.Request = req;
ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
}
catch (Exception ex)
{
if (ainfo != null)
ainfo.SetCompleted (null, ex, false);
else
throw ex;
}
return ainfo;
}
void AsyncGetRequestStreamDone (IAsyncResult ar)
{
SimpleWebClientAsyncResult ainfo = (SimpleWebClientAsyncResult) ar.AsyncState;
try
{
if (ainfo.ParameterWriter.UsesWriteRequest)
{
Stream stream = ainfo.Request.GetRequestStream ();
ainfo.ParameterWriter.WriteRequest (stream, ainfo.Parameters);
stream.Close ();
}
ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
}
catch (Exception ex)
{
ainfo.SetCompleted (null, ex, true);
}
}
void AsyncGetResponseDone (IAsyncResult ar)
{
SimpleWebClientAsyncResult ainfo = (SimpleWebClientAsyncResult) ar.AsyncState;
WebResponse response = null;
try {
response = GetWebResponse (ainfo.Request, ar);
}
catch (WebException ex) {
response = ex.Response;
HttpWebResponse http_response = response as HttpWebResponse;
if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
ainfo.SetCompleted (null, ex, true);
return;
}
}
catch (Exception ex) {
ainfo.SetCompleted (null, ex, true);
return;
}
try {
MimeReturnReader returnReader = (MimeReturnReader) ainfo.Method.ReturnReaderType.Create ();
object result = returnReader.Read (response, response.GetResponseStream ());
ainfo.SetCompleted (result, null, true);
}
catch (Exception ex) {
ainfo.SetCompleted (null, ex, true);
}
}
protected object EndInvoke (IAsyncResult asyncResult)
{
if (!(asyncResult is SimpleWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
SimpleWebClientAsyncResult ainfo = (SimpleWebClientAsyncResult) asyncResult;
lock (ainfo)
{
if (!ainfo.IsCompleted) ainfo.WaitForComplete ();
if (ainfo.Exception != null) throw ainfo.Exception;
else return ainfo.Result;
}
}
protected object Invoke (string methodName, string requestUrl, object[] parameters)
{
HttpSimpleMethodStubInfo method = (HttpSimpleMethodStubInfo) TypeStub.GetMethod (methodName);
MimeParameterWriter parameterWriter = (MimeParameterWriter) method.ParameterWriterType.Create ();
string url = parameterWriter.GetRequestUrl (requestUrl, parameters);
WebRequest request = GetWebRequest (new Uri(url, true));
parameterWriter.InitializeRequest (request, parameters);
if (parameterWriter.UsesWriteRequest)
{
Stream stream = request.GetRequestStream ();
parameterWriter.WriteRequest (stream, parameters);
stream.Close ();
}
WebResponse response = GetWebResponse (request);
MimeReturnReader returnReader = (MimeReturnReader) method.ReturnReaderType.Create ();
return returnReader.Read (response, response.GetResponseStream ());
}
#if NET_2_0
protected void InvokeAsync (string methodName, string requestUrl, object[] parameters, SendOrPostCallback callback)
{
InvokeAsync (methodName, requestUrl, parameters, callback, null);
}
protected void InvokeAsync (string methodName, string requestUrl, object[] parameters, SendOrPostCallback callback, object userState)
{
InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
BeginInvoke (methodName, requestUrl, parameters, new AsyncCallback (InvokeAsyncCallback), info);
}
void InvokeAsyncCallback (IAsyncResult ar)
{
InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
SimpleWebClientAsyncResult sar = (SimpleWebClientAsyncResult) ar;
InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
if (info.Context != null)
info.Context.SendOrPost (info.Callback, args);
else
info.Callback (args);
}
#endif
#endregion // Methods
}
internal class SimpleWebClientAsyncResult : WebClientAsyncResult
{
public SimpleWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
: base (request, callback, asyncState)
{
}
public object[] Parameters;
public HttpSimpleMethodStubInfo Method;
public MimeParameterWriter ParameterWriter;
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Predator.Managers;
using System;
using VoidEngine.VGUI;
// ========================= //
// Possible Title: "Chimera" //
// ========================= //
namespace Predator
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
/// <summary>
/// The levels of the game.
/// </summary>
public enum GameLevels
{
SPLASH,
MENU,
OPTIONS,
GAME,
MAP,
STATS,
LOSE,
WIN,
INTRO,
CREDITS
}
/// <summary>
/// The GraphicsDeviceManager for the game.
/// </summary>
public GraphicsDeviceManager graphics;
/// <summary>
/// The main SpriteBatch of the game.
/// </summary>
SpriteBatch spriteBatch;
#region States
/// <summary>
/// The KeyboardState of the game.
/// </summary>
public KeyboardState KeyboardState, PreviousKeyboardState;
/// <summary>
/// The MouseState of the game.
/// </summary>
public MouseState MouseState, PreviousMouseState;
#endregion
#region Screen Properties
/// <summary>
/// Gets or sets the window size.
/// </summary>
public Point WindowSize
{
get
{
return new Point(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
}
set
{
graphics.PreferredBackBufferWidth = value.X;
graphics.PreferredBackBufferHeight = value.Y;
}
}
/// <summary>
/// Gets or sets if the game IsFullScreen.
/// </summary>
public bool Fullscreen
{
get
{
return graphics.IsFullScreen;
}
set
{
graphics.IsFullScreen = value;
}
}
#endregion
#region Game Levels
/// <summary>
/// The SplashScreenManager for the game.
/// </summary>
public SplashScreenManager splashScreenManager;
/// <summary>
/// The GameManager for the game.
/// </summary>
public GameManager gameManager;
/// <summary>
/// The MainMenuManager for the game.
/// </summary>
public MainMenuManager mainMenuManager;
/// <summary>
/// The OptionsManager for the game.
/// </summary>
//public OptionsManager optionsManager;
/// <summary>
/// The MapScreenManager for the game.
/// </summary>
public MapScreenManager mapScreenManager;
/// <summary>
/// The StatManager for the game.
/// </summary>
public StatManager statManager;
/// <summary>
/// The LoseManager for the game.
/// </summary>
public LoseManager loseManager;
/// <summary>
///
/// </summary>
public OptionsManager optionsManager;
/// <summary>
/// The GameLevels for the game.
/// </summary>
public GameLevels currentGameLevel;
public IntroManager introManager;
#endregion
#region Fonts
public SpriteFont segoeUIBold;
public SpriteFont segoeUIItalic;
public SpriteFont segoeUIMonoDebug;
public SpriteFont segoeUIMono;
public SpriteFont segoeUIRegular;
public SpriteFont grimGhostRegular;
public SpriteFont streetSoulRegular;
#endregion
#region Debug Stuff
/// <summary>
/// The value to debug the game.
/// </summary>
public bool IsGameDebug
{
get;
set;
}
/// <summary>
/// The label used for debuging.
/// </summary>
public Label debugLabel;
/// <summary>
/// The list of strings that are used for debuging.
/// </summary>
public string[] debugStrings = new string[25];
#endregion
#region Options Stuff
/// <summary>
/// Gets or sets if VSync is enabled.
/// </summary>
public bool VSync
{
get;
set;
}
/// <summary>
/// Gets or sets if the game should apply the current settings.
/// </summary>
public bool ApplySettings
{
get;
set;
}
/// <summary>
/// Gets or sets if the game should cancel the current settings.
/// </summary>
public bool CancelSettings
{
get;
set;
}
/// <summary>
/// Gets or sets if the game finished applying/canceling the current settings.
/// </summary>
public bool FinishedSettings
{
get;
set;
}
/// <summary>
/// Gets or sets the amount of times the options changed.
/// Used to check if they have against [OldOptionsChanged]
/// to update the positions and other things.
/// </summary>
public int OptionsChanged
{
get;
set;
}
/// <summary>
/// Gets or sets the old amount of times the options changed.
/// Used to check if they have against [OldOptionsChanged]
/// to update the positions and other things.
/// </summary>
public int OldOptionsChanged
{
get;
set;
}
/// <summary>
/// Gets or sets the temporary window size.
/// </summary>
public Point TempWindowSize
{
get;
set;
}
#endregion
public Random rng = new Random();
/// <summary>
/// Creates the game.
/// </summary>
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
Window.Title = "Predator";
WindowSize = new Point(1024, 768);
Fullscreen = false;
IsMouseVisible = true;
IsGameDebug = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
LoadTextures();
splashScreenManager = new SplashScreenManager(this);
mainMenuManager = new MainMenuManager(this);
gameManager = new GameManager(this);
mapScreenManager = new MapScreenManager(this);
statManager = new StatManager(this);
loseManager = new LoseManager(this);
optionsManager = new OptionsManager(this);
introManager = new IntroManager(this);
Components.Add(splashScreenManager);
Components.Add(mainMenuManager);
Components.Add(gameManager);
Components.Add(mapScreenManager);
Components.Add(statManager);
Components.Add(loseManager);
Components.Add(optionsManager);
Components.Add(introManager);
mapScreenManager.Enabled = false;
mapScreenManager.Visible = false;
gameManager.Enabled = false;
gameManager.Visible = false;
mainMenuManager.Enabled = false;
mainMenuManager.Visible = false;
statManager.Enabled = false;
statManager.Visible = false;
optionsManager.Enabled = false;
optionsManager.Visible = false;
debugLabel = new Label(new Vector2(0, 60), segoeUIMonoDebug, 1f, Color.White, "");
TempWindowSize = WindowSize;
ApplySettings = true;
SetCurrentLevel(GameLevels.MENU);
}
/// <summary>
/// Loads all the textures for the game.
/// </summary>
public void LoadTextures()
{
segoeUIRegular = Content.Load<SpriteFont>(@"fonts\segoeuiregular");
segoeUIMono = Content.Load<SpriteFont>(@"fonts\segoeuimono");
segoeUIMonoDebug = Content.Load<SpriteFont>(@"fonts\segoeuimonodebug");
segoeUIBold = Content.Load<SpriteFont>(@"fonts\segoeuibold");
segoeUIItalic = Content.Load<SpriteFont>(@"fonts\segoeuiitalic");
grimGhostRegular = Content.Load<SpriteFont>(@"fonts\grimghostregular");
streetSoulRegular = Content.Load<SpriteFont>(@"fonts\streetsoulregular");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
KeyboardState = Keyboard.GetState();
MouseState = Mouse.GetState();
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || (KeyboardState.IsKeyDown(Keys.Escape) && KeyboardState.IsKeyDown(Keys.LeftShift)))
{
this.Exit();
}
if (CheckKey(Keys.OemPlus) && currentGameLevel != GameLevels.MENU)
{
SetCurrentLevel(GameLevels.MENU);
}
if (ApplySettings)
{
graphics.SynchronizeWithVerticalRetrace = VSync;
if (new Point(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight) != TempWindowSize)
{
graphics.PreferredBackBufferWidth = TempWindowSize.X;
graphics.PreferredBackBufferHeight = TempWindowSize.Y;
WindowSize = new Point(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
}
graphics.ApplyChanges();
ApplySettings = false;
FinishedSettings = true;
OldOptionsChanged = OptionsChanged;
OptionsChanged += 1;
}
if (CancelSettings)
{
VSync = graphics.SynchronizeWithVerticalRetrace;
WindowSize = new Point(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
CancelSettings = false;
FinishedSettings = true;
}
base.Update(gameTime);
#region Debug Stuff
if (IsGameDebug)
{
debugLabel.Text = debugStrings[00] + "\n" +
debugStrings[01] + "\n" +
debugStrings[02] + "\n" +
debugStrings[03] + "\n" +
debugStrings[04] + "\n" +
debugStrings[05] + "\n" +
debugStrings[06] + "\n" +
debugStrings[07] + "\n" +
debugStrings[08] + "\n" +
debugStrings[09] + "\n" +
debugStrings[10] + "\n" +
debugStrings[11] + "\n" +
debugStrings[12] + "\n" +
debugStrings[13] + "\n" +
debugStrings[14] + "\n" +
debugStrings[15] + "\n" +
debugStrings[16] + "\n" +
debugStrings[17] + "\n" +
debugStrings[18] + "\n" +
debugStrings[19] + "\n" +
debugStrings[20] + "\n" +
debugStrings[21] + "\n" +
debugStrings[22] + "\n" +
debugStrings[23] + "\n" +
debugStrings[24];
}
#endregion
PreviousKeyboardState = KeyboardState;
PreviousMouseState = MouseState;
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
/// <summary>
/// This will check if the key specified is released.
/// </summary>
/// <param name="key">The key to check</param>
public bool CheckKey(Keys key)
{
if (KeyboardState.IsKeyUp(key) && PreviousKeyboardState.IsKeyDown(key))
{
return true;
}
return false;
}
/// <summary>
/// This sets the current scene or level that the game is at.
/// </summary>
/// <param name="level">The game level to change to.</param>
public void SetCurrentLevel(GameLevels level)
{
if (currentGameLevel != level)
{
currentGameLevel = level;
splashScreenManager.Enabled = false;
splashScreenManager.Visible = false;
mainMenuManager.Enabled = false;
mainMenuManager.Visible = false;
gameManager.Enabled = false;
gameManager.Visible = false;
optionsManager.Enabled = false;
optionsManager.Visible = false;
mapScreenManager.Enabled = false;
mapScreenManager.Visible = false;
statManager.Enabled = false;
statManager.Visible = false;
loseManager.Enabled = false;
loseManager.Visible = false;
introManager.Enabled = false;
introManager.Visible = false;
}
switch (currentGameLevel)
{
case GameLevels.SPLASH:
splashScreenManager.Enabled = true;
splashScreenManager.Visible = true;
break;
case GameLevels.MENU:
mainMenuManager.Enabled = true;
mainMenuManager.Visible = true;
break;
case GameLevels.OPTIONS:
optionsManager.Enabled = true;
optionsManager.Visible = true;
break;
case GameLevels.GAME:
gameManager.Enabled = true;
gameManager.Visible = true;
break;
case GameLevels.MAP:
gameManager.Visible = true;
mapScreenManager.Enabled = true;
mapScreenManager.Visible = true;
break;
case GameLevels.STATS:
gameManager.Visible = true;
statManager.Enabled = true;
statManager.Visible = true;
break;
case GameLevels.LOSE:
loseManager.Enabled = true;
loseManager.Visible = true;
break;
case GameLevels.INTRO:
introManager.Enabled = true;
introManager.Visible = true;
break;
case GameLevels.WIN:
break;
case GameLevels.CREDITS:
break;
default:
break;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PrimerProObjects;
using PrimerProLocalization;
namespace PrimerProForms
{
/// <summary>
/// Summary description for FormToneInventory.
/// </summary>
public class FormToneInventory : System.Windows.Forms.Form
{
private Settings m_Settings;
private int nCurrent; //index of current syllograph
private Tone tone; //current syllograph
private bool fIsUpdated; //Indicated the inventory has been updated
//private const string cSaveText = "Do you want to save changes?";
//private const string cSaveCaption = "Save Displayed Changes";
private System.Windows.Forms.TextBox tbFind;
private System.Windows.Forms.Button btnFind;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.TextBox tbCount;
private System.Windows.Forms.Label labOf;
private System.Windows.Forms.TextBox tbCurrent;
private System.Windows.Forms.Label labTone;
private System.Windows.Forms.Button btnPrevious;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.TextBox tbTone;
private System.Windows.Forms.Label labLevel;
private System.Windows.Forms.TextBox tbLevel;
private System.Windows.Forms.Label labTBU;
private System.Windows.Forms.TextBox tbTBU;
private TextBox tbUC;
private Label labUC;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FormToneInventory(Settings s)
{
InitializeComponent();
if (s == null)
m_Settings = new Settings();
else m_Settings = s;
Font font = m_Settings.OptionSettings.GetDefaultFont();
this.tbTone.Font = font;
this.tbUC.Font = font;
this.tbFind.Font = font;
nCurrent = 0; //First Tone
fIsUpdated = false;
this.UpdateFormForLocalization(m_Settings.LocalizationTable);
Redisplay();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form 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(FormToneInventory));
this.tbFind = new System.Windows.Forms.TextBox();
this.btnFind = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.tbCount = new System.Windows.Forms.TextBox();
this.labOf = new System.Windows.Forms.Label();
this.tbCurrent = new System.Windows.Forms.TextBox();
this.tbTone = new System.Windows.Forms.TextBox();
this.labTone = new System.Windows.Forms.Label();
this.btnPrevious = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.labLevel = new System.Windows.Forms.Label();
this.tbLevel = new System.Windows.Forms.TextBox();
this.labTBU = new System.Windows.Forms.Label();
this.tbTBU = new System.Windows.Forms.TextBox();
this.tbUC = new System.Windows.Forms.TextBox();
this.labUC = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// tbFind
//
this.tbFind.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbFind.Location = new System.Drawing.Point(280, 240);
this.tbFind.Name = "tbFind";
this.tbFind.Size = new System.Drawing.Size(97, 27);
this.tbFind.TabIndex = 15;
//
// btnFind
//
this.btnFind.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnFind.Location = new System.Drawing.Point(383, 240);
this.btnFind.Name = "btnFind";
this.btnFind.Size = new System.Drawing.Size(100, 32);
this.btnFind.TabIndex = 16;
this.btnFind.Text = "&Find";
this.btnFind.Click += new System.EventHandler(this.btnFind_Click);
//
// btnExit
//
this.btnExit.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnExit.Location = new System.Drawing.Point(386, 305);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(100, 32);
this.btnExit.TabIndex = 18;
this.btnExit.Text = "E&xit";
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// btnSave
//
this.btnSave.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSave.Location = new System.Drawing.Point(280, 305);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(100, 32);
this.btnSave.TabIndex = 17;
this.btnSave.Text = "&Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// tbCount
//
this.tbCount.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.tbCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbCount.Location = new System.Drawing.Point(216, 32);
this.tbCount.Name = "tbCount";
this.tbCount.ReadOnly = true;
this.tbCount.Size = new System.Drawing.Size(32, 17);
this.tbCount.TabIndex = 4;
this.tbCount.TabStop = false;
this.tbCount.Text = "???";
this.tbCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// labOf
//
this.labOf.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labOf.Location = new System.Drawing.Point(192, 32);
this.labOf.Name = "labOf";
this.labOf.Size = new System.Drawing.Size(24, 22);
this.labOf.TabIndex = 3;
this.labOf.Text = "of";
this.labOf.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// tbCurrent
//
this.tbCurrent.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.tbCurrent.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbCurrent.Location = new System.Drawing.Point(152, 32);
this.tbCurrent.Name = "tbCurrent";
this.tbCurrent.ReadOnly = true;
this.tbCurrent.Size = new System.Drawing.Size(32, 17);
this.tbCurrent.TabIndex = 2;
this.tbCurrent.TabStop = false;
this.tbCurrent.Text = "???";
this.tbCurrent.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// tbTone
//
this.tbTone.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbTone.Location = new System.Drawing.Point(80, 24);
this.tbTone.Name = "tbTone";
this.tbTone.Size = new System.Drawing.Size(40, 24);
this.tbTone.TabIndex = 1;
this.tbTone.Leave += new System.EventHandler(this.tbTone_Leave);
this.tbTone.Enter += new System.EventHandler(this.tbTone_Enter);
//
// labTone
//
this.labTone.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labTone.Location = new System.Drawing.Point(24, 32);
this.labTone.Name = "labTone";
this.labTone.Size = new System.Drawing.Size(50, 23);
this.labTone.TabIndex = 0;
this.labTone.Text = "Tone";
//
// btnPrevious
//
this.btnPrevious.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnPrevious.Location = new System.Drawing.Point(386, 80);
this.btnPrevious.Name = "btnPrevious";
this.btnPrevious.Size = new System.Drawing.Size(100, 32);
this.btnPrevious.TabIndex = 11;
this.btnPrevious.Text = "&Previous";
this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);
//
// btnDelete
//
this.btnDelete.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnDelete.Location = new System.Drawing.Point(386, 194);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(100, 32);
this.btnDelete.TabIndex = 14;
this.btnDelete.Text = "&Delete";
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnAdd
//
this.btnAdd.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnAdd.Location = new System.Drawing.Point(386, 156);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(100, 32);
this.btnAdd.TabIndex = 13;
this.btnAdd.Text = "&Add";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnNext
//
this.btnNext.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNext.Location = new System.Drawing.Point(386, 118);
this.btnNext.Name = "btnNext";
this.btnNext.Size = new System.Drawing.Size(100, 32);
this.btnNext.TabIndex = 12;
this.btnNext.Text = "&Next";
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// labLevel
//
this.labLevel.AutoSize = true;
this.labLevel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labLevel.Location = new System.Drawing.Point(24, 104);
this.labLevel.Name = "labLevel";
this.labLevel.Size = new System.Drawing.Size(154, 18);
this.labLevel.TabIndex = 7;
this.labLevel.Text = "Level (High, Mid, Low)";
//
// tbLevel
//
this.tbLevel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbLevel.Location = new System.Drawing.Point(27, 128);
this.tbLevel.Name = "tbLevel";
this.tbLevel.Size = new System.Drawing.Size(213, 24);
this.tbLevel.TabIndex = 8;
//
// labTBU
//
this.labTBU.AutoSize = true;
this.labTBU.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labTBU.Location = new System.Drawing.Point(24, 207);
this.labTBU.Name = "labTBU";
this.labTBU.Size = new System.Drawing.Size(174, 18);
this.labTBU.TabIndex = 9;
this.labTBU.Text = "Tone Bearing Unit (if any)";
//
// tbTBU
//
this.tbTBU.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbTBU.Location = new System.Drawing.Point(27, 240);
this.tbTBU.Name = "tbTBU";
this.tbTBU.Size = new System.Drawing.Size(64, 24);
this.tbTBU.TabIndex = 10;
//
// tbUC
//
this.tbUC.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbUC.Location = new System.Drawing.Point(382, 30);
this.tbUC.Name = "tbUC";
this.tbUC.Size = new System.Drawing.Size(65, 24);
this.tbUC.TabIndex = 6;
//
// labUC
//
this.labUC.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labUC.Location = new System.Drawing.Point(277, 31);
this.labUC.Name = "labUC";
this.labUC.Size = new System.Drawing.Size(96, 23);
this.labUC.TabIndex = 5;
this.labUC.Text = "Upper Case";
//
// FormToneInventory
//
this.AcceptButton = this.btnSave;
this.AutoScaleBaseSize = new System.Drawing.Size(7, 17);
this.CancelButton = this.btnExit;
this.ClientSize = new System.Drawing.Size(509, 364);
this.Controls.Add(this.tbUC);
this.Controls.Add(this.labUC);
this.Controls.Add(this.tbTBU);
this.Controls.Add(this.labTBU);
this.Controls.Add(this.tbLevel);
this.Controls.Add(this.labLevel);
this.Controls.Add(this.tbFind);
this.Controls.Add(this.btnFind);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.tbCount);
this.Controls.Add(this.labOf);
this.Controls.Add(this.tbCurrent);
this.Controls.Add(this.tbTone);
this.Controls.Add(this.labTone);
this.Controls.Add(this.btnPrevious);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnNext);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormToneInventory";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Update Tone Inventory";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void tbTone_Enter(object sender, EventArgs e)
{
if (m_Settings.GraphemeInventory.ToneCount() == 0)
{
Tone tone = new Tone(" ");
int nCount = m_Settings.GraphemeInventory.ToneCount();
m_Settings.GraphemeInventory.AddTone(tone);
nCurrent = nCount;
Redisplay();
}
}
private void tbTone_Leave(object sender, EventArgs e)
{
string str;
if (this.tbUC.Text == "")
{
str = this.tbTone.Text;
if (str.Length > 1)
str = str.Substring(0, 1).ToUpper() + str.Substring(1);
else str = str.ToUpper();
this.tbUC.Text = str;
}
}
private void btnPrevious_Click(object sender, System.EventArgs e)
{
if (HasChanged())
{
//if (MessageBox.Show("Do you want to save the changes?", "Save Displayed Tone", MessageBoxButtons.YesNo) == DialogResult.Yes)
// SaveIt();
string strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory1");
if (strText == "")
strText = "Do you want to save the changes?";
string strCaption = m_Settings.LocalizationTable.GetMessage("FormToneInventory2");
if (strCaption == "")
strCaption = "Save Displayed Tone";
if (MessageBox.Show(strText, strCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
SaveIt();
}
if (nCurrent > 0 )
nCurrent--;
Redisplay();
}
private void btnNext_Click(object sender, System.EventArgs e)
{
if (HasChanged())
{
//if (MessageBox.Show("Do you want to save the changes?", "Save Displayed Tone", MessageBoxButtons.YesNo) == DialogResult.Yes)
// SaveIt();
string strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory1");
if (strText == "")
strText = "Do you want to save the changes?";
string strCaption = m_Settings.LocalizationTable.GetMessage("FormToneInventory2");
if (strCaption == "")
strCaption = "Save Displayed Tone";
if (MessageBox.Show(strText, strCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
SaveIt();
}
if ( nCurrent < (m_Settings.GraphemeInventory.ToneCount()-1) )
nCurrent++;
Redisplay();
}
private void btnAdd_Click(object sender, System.EventArgs e)
{
if (HasChanged())
{
//if (MessageBox.Show("Do you want to save the changes?", "Save Displayed Tone", MessageBoxButtons.YesNo) == DialogResult.Yes)
// SaveIt();
string strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory1");
if (strText == "")
strText = "Do you want to save the changes?";
string strCaption = m_Settings.LocalizationTable.GetMessage("FormToneInventory2");
if (strCaption == "")
strCaption = "Save Displayed Tone";
if (MessageBox.Show(strText, strCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
SaveIt();
}
Tone tone = new Tone(" ");
int nCount = m_Settings.GraphemeInventory.ToneCount();
m_Settings.GraphemeInventory.AddTone(tone);
nCurrent = nCount;
Redisplay();
}
private void btnDelete_Click(object sender, System.EventArgs e)
{
int next = nCurrent;
m_Settings.GraphemeInventory.DelTone(nCurrent);
if ( next < m_Settings.GraphemeInventory.ToneCount() )
nCurrent = next;
else nCurrent = m_Settings.GraphemeInventory.ToneCount() - 1;
fIsUpdated = true;
Redisplay();
}
private void btnFind_Click(object sender, System.EventArgs e)
{
string strText = "";
string strCaption = "";
string strSymbol = this.tbFind.Text.Trim();
int n = 0;
if (HasChanged())
{
//if (MessageBox.Show("Do you want to save the changes?", "Save Displayed Tone", MessageBoxButtons.YesNo) == DialogResult.Yes)
// SaveIt();
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory1");
if (strText == "")
strText = "Do you want to save the changes?";
strCaption = m_Settings.LocalizationTable.GetMessage("FormToneInventory2");
if (strCaption == "")
strCaption = "Save Displayed Tone";
if (MessageBox.Show(strText, strCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
SaveIt();
}
if (strSymbol != "")
{
n = m_Settings.GraphemeInventory.FindToneIndex(strSymbol);
if ((n >= 0) && (n < m_Settings.GraphemeInventory.ToneCount()))
{
nCurrent = n;
Redisplay();
}
//else MessageBox.Show("Grapheme not found");
else
{
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory3");
if (strText == "")
strText = "Grapheme not found";
MessageBox.Show(strText);
}
}
//else MessageBox.Show("Grapheme must be specified in the adjacent box");
else
{
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory4");
if (strText == "")
strText = "Grapheme must be specified in the adjacent box";
MessageBox.Show(strText);
}
}
private void btnSave_Click(object sender, System.EventArgs e)
{
//if (m_Settings.GraphemeInventory.ToneCount() == 0)
// MessageBox.Show("Need to add first, before you can save");
//else SaveIt();
SaveIt();
return;
}
private void SaveIt()
{
string strText = "";
string strSymbol = this.tbTone.Text.Trim();
string strTBU = "";
if (strSymbol != "")
{
if ((!m_Settings.GraphemeInventory.IsInInventory(strSymbol))
|| (nCurrent == m_Settings.GraphemeInventory.GetGraphemeIndex(strSymbol)))
{
tone.Symbol = strSymbol;
tone.Key = tone.GetKey();
tone.UpperCase = this.tbUC.Text;
Grapheme seg = null;
GraphemeInventory gi = m_Settings.GraphemeInventory;
tone.Level = this.tbLevel.Text;
strTBU = this.tbTBU.Text;
if (strTBU != "")
{
if (gi.IsInInventory(strTBU))
{
seg = gi.GetGrapheme(strTBU);
tone.ToneBearingUnit = seg;
}
else
{
//MessageBox.Show("Tone Bearing Unit is not in Inventory");
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory5");
if (strText == "")
strText = "Tone Bearing Unit is not in Inventory";
MessageBox.Show(strText);
tone.ToneBearingUnit = null;
this.tbTBU.Text = "";
}
}
else tone.ToneBearingUnit = null;
fIsUpdated = true;
//MessageBox.Show("Tone saved");
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory6");
if (strText == "")
strText = "Tone saved";
MessageBox.Show(strText);
}
else
{
//MessageBox.Show("Tone is already in inventory");
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory7");
if (strText == "")
strText = "Tone is already in inventory";
MessageBox.Show(strText);
tone = m_Settings.GraphemeInventory.GetTone(nCurrent);
this.tbTone.Text = tone.Symbol;
}
}
//else MessageBox.Show("Tone must be specified");
else
{
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory8");
if (strText == "")
strText = "Tone must be specified";
MessageBox.Show(strText);
}
}
private void btnExit_Click(object sender, System.EventArgs e)
{
string strText = "";
string strCaption = "";
if (HasChanged())
{
//if (MessageBox.Show("Do you want to save the changes?", "Save Displayed Tone", MessageBoxButtons.YesNo) == DialogResult.Yes)
// SaveIt();
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory1");
if (strText == "")
strText = "Do you want to save the changes?";
strCaption = m_Settings.LocalizationTable.GetMessage("FormToneInventory2");
if (strCaption == "")
strCaption = "Save Displayed Tone";
if (MessageBox.Show(strText, strCaption, MessageBoxButtons.YesNo) == DialogResult.Yes)
SaveIt();
else
{
// delete empty tones
ArrayList alTones = m_Settings.GraphemeInventory.Tones;
for (int i = alTones.Count - 1; 0 <= i; i--)
{
Tone tone = (Tone) alTones[i];
if (tone.Symbol.Trim() == "")
m_Settings.GraphemeInventory.DelTone(i);
}
}
}
if (fIsUpdated)
{
//MessageBox.Show("Since the graphene inventory has been updated, you need to reimport the word list and text data.");
strText = m_Settings.LocalizationTable.GetMessage("FormToneInventory9");
if (strText == "")
strText = "Since the graphene inventory has been updated, you need to reimport the word list and text data.";
MessageBox.Show(strText);
}
this.Close();
}
private void AtClosed(object sender, System.EventArgs e)
{
GraphemeInventory gi = m_Settings.GraphemeInventory;
int nTones = gi.ToneCount();
if (nTones > 0)
{
Tone tone = null;
for (int i = nTones; 0 < i; i--)
{
tone = m_Settings.GraphemeInventory.GetTone(i - 1);
if (tone == null)
gi.DelTone(i - 1);
else if (tone.Symbol.Trim() == "")
gi.DelTone(i - 1);
}
m_Settings.GraphemeInventory = gi;
}
}
private void Redisplay ()
{
int n = 0;
if (m_Settings.GraphemeInventory.ToneCount() > 0)
{
n = nCurrent + 1;
tone = m_Settings.GraphemeInventory.GetTone(nCurrent);
}
else
{
tone = new Tone(" ");
}
this.tbFind.Text = ""; // Clear Find box
this.tbTone.Text = tone.Symbol;
this.tbUC.Text = tone.UpperCase;
this.tbCurrent.Text = n.ToString();
this.tbCount.Text = m_Settings.GraphemeInventory.ToneCount().ToString();
this.tbLevel.Text = tone.Level;
if (tone.ToneBearingUnit == null)
this.tbTBU.Text = "";
else this.tbTBU.Text = tone.ToneBearingUnit.Symbol;
this.tbTone.Focus();
}
private bool HasChanged()
{
bool fChange = false;
Tone tone = null;
int n = 0;
if (m_Settings.GraphemeInventory.ToneCount() > 0)
{
n = nCurrent + 1;
tone = m_Settings.GraphemeInventory.GetTone(nCurrent);
}
else return fChange;
if (this.tbTone.Text != tone.Symbol) fChange = true;
if (this.tbUC.Text != tone.UpperCase) fChange = true;
if (this.tbLevel.Text != tone.Level) fChange = true;
if (tone.ToneBearingUnit == null)
{
if (this.tbTBU.Text != "") fChange = true;
}
else
{
if (this.tbTBU.Text != tone.ToneBearingUnit.Symbol) fChange = true;
}
return fChange;
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormToneInventoryT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormToneInventory0");
if (strText != "")
this.labTone.Text = strText;
strText = table.GetForm("FormToneInventory3");
if (strText != "")
this.labOf.Text = strText;
strText = table.GetForm("FormToneInventory5");
if (strText != "")
this.labUC.Text = strText;
strText = table.GetForm("FormToneInventory7");
if (strText != "")
this.labLevel.Text = strText;
strText = table.GetForm("FormToneInventory9");
if (strText != "")
this.labTBU.Text = strText;
strText = table.GetForm("FormToneInventory11");
if (strText != "")
this.btnPrevious.Text = strText;
strText = table.GetForm("FormToneInventory12");
if (strText != "")
this.btnNext.Text = strText;
strText = table.GetForm("FormToneInventory13");
if (strText != "")
this.btnAdd.Text = strText;
strText = table.GetForm("FormToneInventory14");
if (strText != "")
this.btnDelete.Text = strText;
strText = table.GetForm("FormToneInventory16");
if (strText != "")
this.btnFind.Text = strText;
strText = table.GetForm("FormToneInventory17");
if (strText != "")
this.btnSave.Text = strText;
strText = table.GetForm("FormToneInventory18");
if (strText != "")
this.btnExit.Text = strText;
return;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This file utilizes partial class feature and contains
// only internal implementation of UriParser type
using System.Collections.Generic;
using System.Diagnostics;
namespace System
{
// This enum specifies the Uri syntax flags that is understood by builtin Uri parser.
[Flags]
internal enum UriSyntaxFlags
{
None = 0x0,
MustHaveAuthority = 0x1, // must have "//" after scheme:
OptionalAuthority = 0x2, // used by generic parser due to unknown Uri syntax
MayHaveUserInfo = 0x4,
MayHavePort = 0x8,
MayHavePath = 0x10,
MayHaveQuery = 0x20,
MayHaveFragment = 0x40,
AllowEmptyHost = 0x80,
AllowUncHost = 0x100,
AllowDnsHost = 0x200,
AllowIPv4Host = 0x400,
AllowIPv6Host = 0x800,
AllowAnInternetHost = AllowDnsHost | AllowIPv4Host | AllowIPv6Host,
AllowAnyOtherHost = 0x1000, // Relaxed authority syntax
FileLikeUri = 0x2000, //Special case to allow file:\\balbla or file://\\balbla
MailToLikeUri = 0x4000, //V1 parser inheritance mailTo:AuthorityButNoSlashes
V1_UnknownUri = 0x10000, // a Compatibility with V1 parser for an unknown scheme
SimpleUserSyntax = 0x20000, // It is safe to not call virtual UriParser methods
BuiltInSyntax = 0x40000, // This is a simple Uri plus it is hardcoded in the product
ParserSchemeOnly = 0x80000, // This is a Parser that does only Uri scheme parsing
AllowDOSPath = 0x100000, // will check for "x:\"
PathIsRooted = 0x200000, // For an authority based Uri the first path char is '/'
ConvertPathSlashes = 0x400000, // will turn '\' into '/'
CompressPath = 0x800000, // For an authority based Uri remove/compress /./ /../ in the path
CanonicalizeAsFilePath = 0x1000000, // remove/convert sequences /.../ /x../ /x./ dangerous for a DOS path
UnEscapeDotsAndSlashes = 0x2000000, // additionally unescape dots and slashes before doing path compression
AllowIdn = 0x4000000, // IDN host conversion allowed
AllowIriParsing = 0x10000000, // Iri parsing. String is normalized, bidi control
// characters are removed, unicode char limits are checked etc.
// KeepTailLWS = 0x8000000,
}
//
// Only internal members are included here
//
public abstract partial class UriParser
{
private static readonly LowLevelDictionary<string, UriParser> s_table;
private static LowLevelDictionary<string, UriParser> s_tempTable;
private UriSyntaxFlags _flags;
// Some flags (specified in c_UpdatableFlags) besides being set in the ctor, can also be set at a later
// point. Such "updatable" flags can be set using SetUpdatableFlags(); if this method is called,
// the value specified in the ctor is ignored (i.e. for all c_UpdatableFlags the value in m_Flags is
// ignored), and the new value is used (i.e. for all c_UpdatableFlags the value in m_UpdatableFlags is used).
private volatile UriSyntaxFlags _updatableFlags;
private volatile bool _updatableFlagsUsed;
// The following flags can be updated at any time.
private const UriSyntaxFlags c_UpdatableFlags = UriSyntaxFlags.UnEscapeDotsAndSlashes;
private int _port;
private string _scheme;
internal const int NoDefaultPort = -1;
private const int c_InitialTableSize = 25;
// These are always available without paying hashtable lookup cost
// Note: see UpdateStaticSyntaxReference()
internal static UriParser HttpUri;
internal static UriParser HttpsUri;
internal static UriParser WsUri;
internal static UriParser WssUri;
internal static UriParser FtpUri;
internal static UriParser FileUri;
internal static UriParser UnixFileUri;
internal static UriParser GopherUri;
internal static UriParser NntpUri;
internal static UriParser NewsUri;
internal static UriParser MailToUri;
internal static UriParser UuidUri;
internal static UriParser TelnetUri;
internal static UriParser LdapUri;
internal static UriParser NetTcpUri;
internal static UriParser NetPipeUri;
internal static UriParser VsMacrosUri;
internal static bool DontEnableStrictRFC3986ReservedCharacterSets
{
// In .NET Framework this would test against an AppContextSwitch. Since this is a potentially
// breaking change, we'll leave in the system used to disable it.
get
{
return false;
}
}
internal static bool DontKeepUnicodeBidiFormattingCharacters
{
// In .NET Framework this would test against an AppContextSwitch. Since this is a potentially
// breaking change, we'll leave in the system used to disable it.
get
{
return false;
}
}
static UriParser()
{
s_table = new LowLevelDictionary<string, UriParser>(c_InitialTableSize);
s_tempTable = new LowLevelDictionary<string, UriParser>(c_InitialTableSize);
//Now we will call for the instance constructors that will interrupt this static one.
// Below we simulate calls into FetchSyntax() but avoid using lock() and other things redundant for a .cctor
HttpUri = new BuiltInUriParser("http", 80, HttpSyntaxFlags);
s_table[HttpUri.SchemeName] = HttpUri; //HTTP
HttpsUri = new BuiltInUriParser("https", 443, HttpUri._flags);
s_table[HttpsUri.SchemeName] = HttpsUri; //HTTPS cloned from HTTP
WsUri = new BuiltInUriParser("ws", 80, HttpSyntaxFlags);
s_table[WsUri.SchemeName] = WsUri; // WebSockets
WssUri = new BuiltInUriParser("wss", 443, HttpSyntaxFlags);
s_table[WssUri.SchemeName] = WssUri; // Secure WebSockets
FtpUri = new BuiltInUriParser("ftp", 21, FtpSyntaxFlags);
s_table[FtpUri.SchemeName] = FtpUri; //FTP
FileUri = new BuiltInUriParser("file", NoDefaultPort, s_fileSyntaxFlags);
UnixFileUri = new BuiltInUriParser("file", NoDefaultPort, s_unixFileSyntaxFlags);
s_table[FileUri.SchemeName] = FileUri; //FILE
GopherUri = new BuiltInUriParser("gopher", 70, GopherSyntaxFlags);
s_table[GopherUri.SchemeName] = GopherUri; //GOPHER
NntpUri = new BuiltInUriParser("nntp", 119, NntpSyntaxFlags);
s_table[NntpUri.SchemeName] = NntpUri; //NNTP
NewsUri = new BuiltInUriParser("news", NoDefaultPort, NewsSyntaxFlags);
s_table[NewsUri.SchemeName] = NewsUri; //NEWS
MailToUri = new BuiltInUriParser("mailto", 25, MailtoSyntaxFlags);
s_table[MailToUri.SchemeName] = MailToUri; //MAILTO
UuidUri = new BuiltInUriParser("uuid", NoDefaultPort, NewsUri._flags);
s_table[UuidUri.SchemeName] = UuidUri; //UUID cloned from NEWS
TelnetUri = new BuiltInUriParser("telnet", 23, TelnetSyntaxFlags);
s_table[TelnetUri.SchemeName] = TelnetUri; //TELNET
LdapUri = new BuiltInUriParser("ldap", 389, LdapSyntaxFlags);
s_table[LdapUri.SchemeName] = LdapUri; //LDAP
NetTcpUri = new BuiltInUriParser("net.tcp", 808, NetTcpSyntaxFlags);
s_table[NetTcpUri.SchemeName] = NetTcpUri;
NetPipeUri = new BuiltInUriParser("net.pipe", NoDefaultPort, NetPipeSyntaxFlags);
s_table[NetPipeUri.SchemeName] = NetPipeUri;
VsMacrosUri = new BuiltInUriParser("vsmacros", NoDefaultPort, VsmacrosSyntaxFlags);
s_table[VsMacrosUri.SchemeName] = VsMacrosUri; //VSMACROS
}
private class BuiltInUriParser : UriParser
{
//
// All BuiltIn parsers use that ctor. They are marked with "simple" and "built-in" flags
//
internal BuiltInUriParser(string lwrCaseScheme, int defaultPort, UriSyntaxFlags syntaxFlags)
: base((syntaxFlags | UriSyntaxFlags.SimpleUserSyntax | UriSyntaxFlags.BuiltInSyntax))
{
_scheme = lwrCaseScheme;
_port = defaultPort;
}
}
internal UriSyntaxFlags Flags
{
get
{
return _flags;
}
}
internal bool NotAny(UriSyntaxFlags flags)
{
// Return true if none of the flags specified in 'flags' are set.
return IsFullMatch(flags, UriSyntaxFlags.None);
}
internal bool InFact(UriSyntaxFlags flags)
{
// Return true if at least one of the flags in 'flags' is set.
return !IsFullMatch(flags, UriSyntaxFlags.None);
}
internal bool IsAllSet(UriSyntaxFlags flags)
{
// Return true if all flags in 'flags' are set.
return IsFullMatch(flags, flags);
}
private bool IsFullMatch(UriSyntaxFlags flags, UriSyntaxFlags expected)
{
// Return true, if masking the current set of flags with 'flags' equals 'expected'.
// Definition 'current set of flags':
// a) if updatable flags were never set: m_Flags
// b) if updatable flags were set: set union between all flags in m_Flags which are not updatable
// (i.e. not part of c_UpdatableFlags) and all flags in m_UpdatableFlags
UriSyntaxFlags mergedFlags;
// if none of the flags in 'flags' is an updatable flag, we ignore m_UpdatableFlags
if (((flags & c_UpdatableFlags) == 0) || !_updatableFlagsUsed)
{
mergedFlags = _flags;
}
else
{
// mask m_Flags to only use the flags not in c_UpdatableFlags
mergedFlags = (_flags & (~c_UpdatableFlags)) | _updatableFlags;
}
return (mergedFlags & flags) == expected;
}
//
// Internal .ctor, any ctor eventually goes through this one
//
internal UriParser(UriSyntaxFlags flags)
{
_flags = flags;
_scheme = string.Empty;
}
private static void FetchSyntax(UriParser syntax, string lwrCaseSchemeName, int defaultPort)
{
if (syntax.SchemeName.Length != 0)
throw new InvalidOperationException(SR.Format(SR.net_uri_NeedFreshParser, syntax.SchemeName));
lock (s_table)
{
syntax._flags &= ~UriSyntaxFlags.V1_UnknownUri;
UriParser oldSyntax = null;
s_table.TryGetValue(lwrCaseSchemeName, out oldSyntax);
if (oldSyntax != null)
throw new InvalidOperationException(SR.Format(SR.net_uri_AlreadyRegistered, oldSyntax.SchemeName));
s_tempTable.TryGetValue(syntax.SchemeName, out oldSyntax);
if (oldSyntax != null)
{
// optimization on schemeName, will try to keep the first reference
lwrCaseSchemeName = oldSyntax._scheme;
s_tempTable.Remove(lwrCaseSchemeName);
}
syntax.OnRegister(lwrCaseSchemeName, defaultPort);
syntax._scheme = lwrCaseSchemeName;
syntax.CheckSetIsSimpleFlag();
syntax._port = defaultPort;
s_table[syntax.SchemeName] = syntax;
}
}
private const int c_MaxCapacity = 512;
//schemeStr must be in lower case!
internal static UriParser FindOrFetchAsUnknownV1Syntax(string lwrCaseScheme)
{
// check may be other thread just added one
UriParser syntax = null;
s_table.TryGetValue(lwrCaseScheme, out syntax);
if (syntax != null)
{
return syntax;
}
s_tempTable.TryGetValue(lwrCaseScheme, out syntax);
if (syntax != null)
{
return syntax;
}
lock (s_table)
{
if (s_tempTable.Count >= c_MaxCapacity)
{
s_tempTable = new LowLevelDictionary<string, UriParser>(c_InitialTableSize);
}
syntax = new BuiltInUriParser(lwrCaseScheme, NoDefaultPort, UnknownV1SyntaxFlags);
s_tempTable[lwrCaseScheme] = syntax;
return syntax;
}
}
internal static UriParser GetSyntax(string lwrCaseScheme)
{
UriParser ret = null;
s_table.TryGetValue(lwrCaseScheme, out ret);
if (ret == null)
{
s_tempTable.TryGetValue(lwrCaseScheme, out ret);
}
return ret;
}
//
// Builtin and User Simple syntaxes do not need custom validation/parsing (i.e. virtual method calls),
//
internal bool IsSimple
{
get
{
return InFact(UriSyntaxFlags.SimpleUserSyntax);
}
}
internal void CheckSetIsSimpleFlag()
{
Type type = this.GetType();
if ( type == typeof(GenericUriParser)
|| type == typeof(HttpStyleUriParser)
|| type == typeof(FtpStyleUriParser)
|| type == typeof(FileStyleUriParser)
|| type == typeof(NewsStyleUriParser)
|| type == typeof(GopherStyleUriParser)
|| type == typeof(NetPipeStyleUriParser)
|| type == typeof(NetTcpStyleUriParser)
|| type == typeof(LdapStyleUriParser)
)
{
_flags |= UriSyntaxFlags.SimpleUserSyntax;
}
}
//
// This method is used to update flags. The scenario where this is needed is when the user specifies
// flags in the config file. The config file is read after UriParser instances were created.
//
internal void SetUpdatableFlags(UriSyntaxFlags flags)
{
Debug.Assert(!_updatableFlagsUsed,
"SetUpdatableFlags() already called. It can only be called once per parser.");
Debug.Assert((flags & (~c_UpdatableFlags)) == 0, "Only updatable flags can be set.");
// No locks necessary. Reordering won't happen due to volatile.
_updatableFlags = flags;
_updatableFlagsUsed = true;
}
//
// These are simple internal wrappers that will call virtual protected methods
// (to avoid "protected internal" signatures in the public docs)
//
internal UriParser InternalOnNewUri()
{
UriParser effectiveParser = OnNewUri();
if ((object)this != (object)effectiveParser)
{
effectiveParser._scheme = _scheme;
effectiveParser._port = _port;
effectiveParser._flags = _flags;
}
return effectiveParser;
}
internal void InternalValidate(Uri thisUri, out UriFormatException parsingError)
{
InitializeAndValidate(thisUri, out parsingError);
}
internal string InternalResolve(Uri thisBaseUri, Uri uriLink, out UriFormatException parsingError)
{
return Resolve(thisBaseUri, uriLink, out parsingError);
}
internal bool InternalIsBaseOf(Uri thisBaseUri, Uri uriLink)
{
return IsBaseOf(thisBaseUri, uriLink);
}
internal string InternalGetComponents(Uri thisUri, UriComponents uriComponents, UriFormat uriFormat)
{
return GetComponents(thisUri, uriComponents, uriFormat);
}
internal bool InternalIsWellFormedOriginalString(Uri thisUri)
{
return IsWellFormedOriginalString(thisUri);
}
//
// Various Uri scheme syntax flags
//
private const UriSyntaxFlags UnknownV1SyntaxFlags =
UriSyntaxFlags.V1_UnknownUri | // This flag must be always set here
UriSyntaxFlags.OptionalAuthority |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveQuery |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.AllowEmptyHost |
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.AllowDOSPath | // V1 compat, actually we should not parse DOS file out of an unknown scheme
UriSyntaxFlags.ConvertPathSlashes | // V1 compat, it will always convert backslashes
UriSyntaxFlags.CompressPath | // V1 compat, it will always compress path even for non hierarchical Uris
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags HttpSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveQuery |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.PathIsRooted |
//
UriSyntaxFlags.ConvertPathSlashes |
UriSyntaxFlags.CompressPath |
UriSyntaxFlags.CanonicalizeAsFilePath |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags FtpSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.PathIsRooted |
//
UriSyntaxFlags.ConvertPathSlashes |
UriSyntaxFlags.CompressPath |
UriSyntaxFlags.CanonicalizeAsFilePath |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private static readonly UriSyntaxFlags s_fileSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.AllowEmptyHost |
UriSyntaxFlags.AllowUncHost |
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
UriSyntaxFlags.MayHaveQuery |
//
UriSyntaxFlags.FileLikeUri |
//
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.AllowDOSPath |
//
UriSyntaxFlags.ConvertPathSlashes |
UriSyntaxFlags.CompressPath |
UriSyntaxFlags.CanonicalizeAsFilePath |
UriSyntaxFlags.UnEscapeDotsAndSlashes |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private static readonly UriSyntaxFlags s_unixFileSyntaxFlags =
s_fileSyntaxFlags & ~UriSyntaxFlags.ConvertPathSlashes;
private const UriSyntaxFlags VsmacrosSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.AllowEmptyHost |
UriSyntaxFlags.AllowUncHost |
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.FileLikeUri |
//
UriSyntaxFlags.AllowDOSPath |
UriSyntaxFlags.ConvertPathSlashes |
UriSyntaxFlags.CompressPath |
UriSyntaxFlags.CanonicalizeAsFilePath |
UriSyntaxFlags.UnEscapeDotsAndSlashes |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags GopherSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
// UriSyntaxFlags.KeepTailLWS |
//Note that NNTP and NEWS are quite different in syntax
private const UriSyntaxFlags NewsSyntaxFlags =
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags NntpSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags TelnetSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags LdapSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
//
UriSyntaxFlags.AllowEmptyHost |
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveQuery |
UriSyntaxFlags.MayHaveFragment |
//
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags MailtoSyntaxFlags =
//
UriSyntaxFlags.AllowEmptyHost |
UriSyntaxFlags.AllowUncHost | // V1 compat
UriSyntaxFlags.AllowAnInternetHost |
//
UriSyntaxFlags.MayHaveUserInfo |
UriSyntaxFlags.MayHavePort |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveFragment |
UriSyntaxFlags.MayHaveQuery | //to maintain compat
//
UriSyntaxFlags.MailToLikeUri |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags NetPipeSyntaxFlags =
UriSyntaxFlags.MustHaveAuthority |
UriSyntaxFlags.MayHavePath |
UriSyntaxFlags.MayHaveQuery |
UriSyntaxFlags.MayHaveFragment |
UriSyntaxFlags.AllowAnInternetHost |
UriSyntaxFlags.PathIsRooted |
UriSyntaxFlags.ConvertPathSlashes |
UriSyntaxFlags.CompressPath |
UriSyntaxFlags.CanonicalizeAsFilePath |
UriSyntaxFlags.UnEscapeDotsAndSlashes |
UriSyntaxFlags.AllowIdn |
UriSyntaxFlags.AllowIriParsing;
private const UriSyntaxFlags NetTcpSyntaxFlags = NetPipeSyntaxFlags | UriSyntaxFlags.MayHavePort;
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;
using Nop.Core;
namespace Nop.Data
{
public static class DbContextExtensions
{
#region Utilities
private static T InnerGetCopy<T>(IDbContext context, T currentCopy, Func<DbEntityEntry<T>, DbPropertyValues> func) where T : BaseEntity
{
//Get the database context
DbContext dbContext = CastOrThrow(context);
//Get the entity tracking object
DbEntityEntry<T> entry = GetEntityOrReturnNull(currentCopy, dbContext);
//The output
T output = null;
//Try and get the values
if (entry != null)
{
DbPropertyValues dbPropertyValues = func(entry);
if (dbPropertyValues != null)
{
output = dbPropertyValues.ToObject() as T;
}
}
return output;
}
/// <summary>
/// Gets the entity or return null.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="currentCopy">The current copy.</param>
/// <param name="dbContext">The db context.</param>
/// <returns></returns>
private static DbEntityEntry<T> GetEntityOrReturnNull<T>(T currentCopy, DbContext dbContext) where T : BaseEntity
{
return dbContext.ChangeTracker.Entries<T>().FirstOrDefault(e => e.Entity == currentCopy);
}
private static DbContext CastOrThrow(IDbContext context)
{
var output = context as DbContext;
if (output == null)
{
throw new InvalidOperationException("Context does not support operation.");
}
return output;
}
#endregion
#region Methods
/// <summary>
/// Loads the original copy.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The context.</param>
/// <param name="currentCopy">The current copy.</param>
/// <returns></returns>
public static T LoadOriginalCopy<T>(this IDbContext context, T currentCopy) where T : BaseEntity
{
return InnerGetCopy(context, currentCopy, e => e.OriginalValues);
}
/// <summary>
/// Loads the database copy.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The context.</param>
/// <param name="currentCopy">The current copy.</param>
/// <returns></returns>
public static T LoadDatabaseCopy<T>(this IDbContext context, T currentCopy) where T : BaseEntity
{
return InnerGetCopy(context, currentCopy, e => e.GetDatabaseValues());
}
/// <summary>
/// Drop a plugin table
/// </summary>
/// <param name="context">Context</param>
/// <param name="tableName">Table name</param>
public static void DropPluginTable(this DbContext context, string tableName)
{
if (context == null)
throw new ArgumentNullException("context");
if (String.IsNullOrEmpty(tableName))
throw new ArgumentNullException("tableName");
//drop the table
if (context.Database.SqlQuery<int>("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = {0}", tableName).Any<int>())
{
var dbScript = "DROP TABLE [" + tableName + "]";
context.Database.ExecuteSqlCommand(dbScript);
}
context.SaveChanges();
}
/// <summary>
/// Get table name of entity
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <param name="context">Context</param>
/// <returns>Table name</returns>
public static string GetTableName<T>(this IDbContext context) where T : BaseEntity
{
//var tableName = typeof(T).Name;
//return tableName;
//this code works only with Entity Framework.
//If you want to support other database, then use the code above (commented)
var adapter = ((IObjectContextAdapter)context).ObjectContext;
var storageModel = (StoreItemCollection)adapter.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);
var containers = storageModel.GetItems<EntityContainer>();
var entitySetBase = containers.SelectMany(c => c.BaseEntitySets.Where(bes => bes.Name == typeof(T).Name)).First();
// Here are variables that will hold table and schema name
string tableName = entitySetBase.MetadataProperties.First(p => p.Name == "Table").Value.ToString();
//string schemaName = productEntitySetBase.MetadataProperties.First(p => p.Name == "Schema").Value.ToString();
return tableName;
}
/// <summary>
/// Get column maximum length
/// </summary>
/// <param name="context">Context</param>
/// <param name="entityTypeName">Entity type name</param>
/// <param name="columnName">Column name</param>
/// <returns>Maximum length. Null if such rule does not exist</returns>
public static int? GetColumnMaxLength(this IDbContext context, string entityTypeName, string columnName)
{
var rez = GetColumnsMaxLength(context, entityTypeName, columnName);
return rez.ContainsKey(columnName) ? rez[columnName] as int? : null;
}
/// <summary>
/// Get columns maximum length
/// </summary>
/// <param name="context">Context</param>
/// <param name="entityTypeName">Entity type name</param>
/// <param name="columnNames">Column names</param>
/// <returns></returns>
public static IDictionary<string, int> GetColumnsMaxLength(this IDbContext context, string entityTypeName, params string[] columnNames)
{
int temp;
var fildFacets = GetFildFacets(context, entityTypeName, "String", columnNames);
var queryResult = fildFacets
.Select(f => new { Name = f.Key, MaxLength = f.Value["MaxLength"].Value })
.Where(p => int.TryParse(p.MaxLength.ToString(), out temp))
.ToDictionary(p => p.Name, p => Convert.ToInt32(p.MaxLength));
return queryResult;
}
/// <summary>
/// Get maximum decimal values
/// </summary>
/// <param name="context">Context</param>
/// <param name="entityTypeName">Entity type name</param>
/// <param name="columnNames">Column names</param>
/// <returns></returns>
public static IDictionary<string, decimal> GetDecimalMaxValue(this IDbContext context, string entityTypeName, params string[] columnNames)
{
var fildFacets = GetFildFacets(context, entityTypeName, "Decimal", columnNames);
return fildFacets.ToDictionary(p => p.Key, p => int.Parse(p.Value["Precision"].Value.ToString()) - int.Parse(p.Value["Scale"].Value.ToString()))
.ToDictionary(p => p.Key, p => new decimal(Math.Pow(10, p.Value)));
}
private static Dictionary<string, ReadOnlyMetadataCollection<Facet>> GetFildFacets(this IDbContext context,
string entityTypeName, string edmTypeName, params string[] columnNames)
{
//original: http://stackoverflow.com/questions/5081109/entity-framework-4-0-automatically-truncate-trim-string-before-insert
var entType = Type.GetType(entityTypeName);
var adapter = ((IObjectContextAdapter)context).ObjectContext;
var metadataWorkspace = adapter.MetadataWorkspace;
var q = from meta in metadataWorkspace.GetItems(DataSpace.CSpace).Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties.Where(p => columnNames.Contains(p.Name) && p.TypeUsage.EdmType.Name == edmTypeName)
select p;
var queryResult = q.Where(p =>
{
var match = p.DeclaringType.Name == entityTypeName;
if (!match && entType != null)
{
//Is a fully qualified name....
match = entType.Name == p.DeclaringType.Name;
}
return match;
}).ToDictionary(p => p.Name, p => p.TypeUsage.Facets);
return queryResult;
}
public static string DbName(this IDbContext context)
{
var connection = ((IObjectContextAdapter)context).ObjectContext.Connection as EntityConnection;
if (connection == null)
return string.Empty;
return connection.StoreConnection.Database;
}
#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;
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class SequenceEqualTests
{
private const int DuplicateFactor = 8;
//
// SequenceEqual
//
public static IEnumerable<object[]> SequenceEqualData(int[] counts)
{
foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4)))
{
foreach (object[] right in Sources.Ranges(new[] { (int)left[1] }))
{
yield return new object[] { left[0], right[0], right[1] };
}
}
}
public static IEnumerable<object[]> SequenceEqualUnequalSizeData(int[] counts)
{
foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4)))
{
foreach (object[] right in Sources.Ranges(new[] { 1, ((int)left[1] - 1) / 2 + 1, (int)left[1] * 2 + 1 }.Distinct()))
{
yield return new object[] { left[0], left[1], right[0], right[1] };
}
}
}
public static IEnumerable<object[]> SequenceEqualUnequalData(int[] counts)
{
foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4)))
{
Func<int, IEnumerable<int>> items = x => new[] { 0, x / 8, x / 2, x * 7 / 8, x - 1 }.Distinct();
foreach (object[] right in Sources.Ranges(new[] { (int)left[1] }, items))
{
yield return new object[] { left[0], right[0], right[1], right[2] };
}
}
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })]
public static void SequenceEqual(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
Assert.True(leftQuery.SequenceEqual(rightQuery));
Assert.True(rightQuery.SequenceEqual(leftQuery));
Assert.True(leftQuery.SequenceEqual(leftQuery));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
SequenceEqual(left, right, count);
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })]
public static void SequenceEqual_CustomComparator(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
Assert.True(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(leftQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor)));
ParallelQuery<int> repeating = Enumerable.Range(0, (count + (DuplicateFactor - 1)) / DuplicateFactor).SelectMany(x => Enumerable.Range(0, DuplicateFactor)).Take(count).AsParallel().AsOrdered();
Assert.True(leftQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(rightQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(repeating.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(repeating.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor)));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
SequenceEqual_CustomComparator(left, right, count);
}
[Theory]
[MemberData(nameof(SequenceEqualUnequalSizeData), new[] { 0, 4, 16 })]
public static void SequenceEqual_UnequalSize(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
Assert.False(leftQuery.SequenceEqual(rightQuery));
Assert.False(rightQuery.SequenceEqual(leftQuery));
Assert.False(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(2)));
Assert.False(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(2)));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualUnequalSizeData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_UnequalSize_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
SequenceEqual_UnequalSize(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(SequenceEqualUnequalData), new[] { 1, 2, 16 })]
public static void SequenceEqual_Unequal(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item.Select(x => x == item ? -1 : x);
Assert.False(leftQuery.SequenceEqual(rightQuery));
Assert.False(rightQuery.SequenceEqual(leftQuery));
Assert.True(leftQuery.SequenceEqual(leftQuery));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualUnequalData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_Unequal_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item)
{
SequenceEqual_Unequal(left, right, count, item);
}
public static void SequenceEqual_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
public static void SequenceEqual_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.EventuallyCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void SequenceEqual_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.OtherTokenCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void SequenceEqual_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2)));
AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2), new ModularCongruenceComparer(1)));
AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source));
AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source, new ModularCongruenceComparer(1)));
}
[Theory]
[ActiveIssue("Cancellation token not shared")]
[MemberData("SequenceEqualData", new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_SharedLeft_Cancellation(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
CancellationTokenSource cs = new CancellationTokenSource();
Assert.Throws<OperationCanceledException>(() => left.Item.WithCancellation(cs.Token)
.SequenceEqual(right.Item.Except(ParallelEnumerable.Range(0, count).Select(x => { cs.Cancel(); seen.Add(x); return x; }))));
// Canceled query means some elements should not be seen.
Assert.False(seen.All(x => x.Value));
}
[Theory]
[ActiveIssue("Cancellation token not shared")]
[MemberData("SequenceEqualData", new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_SharedRight_Cancellation(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
CancellationTokenSource cs = new CancellationTokenSource();
Assert.Throws<OperationCanceledException>(() => left.Item.Except(ParallelEnumerable.Range(0, count).Select(x => { cs.Cancel(); seen.Add(x); return x; }))
.SequenceEqual(right.Item.WithCancellation(cs.Token)));
// Canceled query means some elements should not be seen.
Assert.False(seen.All(x => x.Value));
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 4 })]
public static void SequenceEqual_AggregateException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
AssertThrows.Wrapped<DeliberateTestException>(() => left.Item.SequenceEqual(right.Item, new FailingEqualityComparer<int>()));
}
[Fact]
// Should not get the same setting from both operands.
public static void SequenceEqual_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).SequenceEqual(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).SequenceEqual(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void SequenceEqual_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1)));
Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null));
Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null, EqualityComparer<int>.Default));
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })]
public static void SequenceEqual_DisposeException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
AssertThrows.Wrapped<TestDisposeException>(() => leftQuery.SequenceEqual(new DisposeExceptionEnumerable<int>(rightQuery).AsParallel()));
AssertThrows.Wrapped<TestDisposeException>(() => new DisposeExceptionEnumerable<int>(leftQuery).AsParallel().SequenceEqual(rightQuery));
}
private class DisposeExceptionEnumerable<T> : IEnumerable<T>
{
private IEnumerable<T> _enumerable;
public DisposeExceptionEnumerable(IEnumerable<T> enumerable)
{
_enumerable = enumerable;
}
public IEnumerator<T> GetEnumerator()
{
return new DisposeExceptionEnumerator(_enumerable.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class DisposeExceptionEnumerator : IEnumerator<T>
{
private IEnumerator<T> _enumerator;
public DisposeExceptionEnumerator(IEnumerator<T> enumerator)
{
_enumerator = enumerator;
}
public T Current
{
get { return _enumerator.Current; }
}
public void Dispose()
{
throw new TestDisposeException();
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public void Reset()
{
_enumerator.Reset();
}
}
}
private class TestDisposeException : Exception
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Reflection;
using System.Collections.Generic;
namespace System.Reflection.Tests
{
public class TypeInfoMethodTests
{
// Verify AsType() method
[Fact]
public static void TestAsType1()
{
Type runtimeType = typeof(MethodPublicClass);
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.AsType();
Assert.Equal(runtimeType, type);
}
// Verify AsType() method
[Fact]
public static void TestAsType2()
{
Type runtimeType = typeof(MethodPublicClass.PublicNestedType);
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.AsType();
Assert.Equal(runtimeType, type);
}
// Verify GetArrayRank() method
[Fact]
public static void TestGetArrayRank1()
{
int[] myArray = { 1, 2, 3, 4, 5, 6, 7 };
int expectedRank = 1;
Type type = myArray.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
int rank = typeInfo.GetArrayRank();
Assert.Equal(expectedRank, rank);
}
// Verify GetArrayRank() method
[Fact]
public static void TestGetArrayRank2()
{
string[] myArray = { "hello" };
int expectedRank = 1;
Type type = myArray.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
int rank = typeInfo.GetArrayRank();
Assert.Equal(expectedRank, rank);
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent1()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredEvent(typeInfo, "EventPublic");
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent2()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
EventInfo ei = typeInfo.GetDeclaredEvent("NoSuchEvent");
Assert.Null(ei);
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent3()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { EventInfo ei = typeInfo.GetDeclaredEvent(null); });
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField1()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredField(typeInfo, "PublicField");
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField2()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredField(typeInfo, "PublicStaticField");
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField3()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
FieldInfo fi = typeInfo.GetDeclaredField("NoSuchField");
Assert.Null(fi);
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField4()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { FieldInfo fi = typeInfo.GetDeclaredField(null); });
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod1()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethod(typeInfo, "PublicMethod");
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod2()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethod(typeInfo, "PublicStaticMethod");
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod3()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
MethodInfo mi = typeInfo.GetDeclaredMethod("NoSuchMethod");
Assert.Null(mi);
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod4()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { MethodInfo mi = typeInfo.GetDeclaredMethod(null); });
}
// Verify GetDeclaredMethods() method
[Fact]
public static void TestGetDeclaredMethods1()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethods(typeInfo, "overRiddenMethod", 4);
}
// Verify GetDeclaredMethods() method
[Fact]
public static void TestGetDeclaredMethods2()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethods(typeInfo, "NoSuchMethod", 0);
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType1()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredNestedType(typeInfo, "PublicNestedType");
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType2()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
TypeInfo nested_ti = typeInfo.GetDeclaredNestedType("NoSuchType");
Assert.Null(nested_ti);
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType3()
{
Type type = typeof(MethodPublicClass);
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { TypeInfo nested_ti = typeInfo.GetDeclaredNestedType(null); });
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType1()
{
Type runtimeType = typeof(MethodPublicClass);
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.Null(type);
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType2()
{
String[] myArray = { "a", "b", "c" };
Type runtimeType = myArray.GetType();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.NotNull(type);
Assert.Equal(typeof(String).Name, type.Name);
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType3()
{
int[] myArray = { 1, 2, 3, 4 };
Type runtimeType = myArray.GetType();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.NotNull(type);
Assert.Equal(typeof(int).Name, type.Name);
}
// Verify GetGenericParameterConstraints() method
[Fact]
public static void TestGetGenericParameterConstraints1()
{
Type def = typeof(TypeInfoMethodClassWithConstraints<,>);
TypeInfo ti = def.GetTypeInfo();
Type[] defparams = ti.GenericTypeParameters;
Assert.Equal(2, defparams.Length);
Type[] tpConstraints = defparams[0].GetTypeInfo().GetGenericParameterConstraints();
Assert.Equal(2, tpConstraints.Length);
Assert.Equal(typeof(TypeInfoMethodBase), tpConstraints[0]);
Assert.Equal(typeof(MethodITest), tpConstraints[1]);
}
// Verify GetGenericParameterConstraints() method
[Fact]
public static void TestGetGenericParameterConstraints2()
{
Type def = typeof(TypeInfoMethodClassWithConstraints<,>);
TypeInfo ti = def.GetTypeInfo();
Type[] defparams = ti.GenericTypeParameters;
Assert.Equal(2, defparams.Length);
Type[] tpConstraints = defparams[1].GetTypeInfo().GetGenericParameterConstraints();
Assert.Equal(0, tpConstraints.Length);
}
// Verify GetGenericTypeDefinition() method
[Fact]
public static void TestGetGenericTypeDefinition()
{
TypeInfoMethodGenericClass<int> genericObj = new TypeInfoMethodGenericClass<int>();
Type type = genericObj.GetType();
Type generictype = type.GetTypeInfo().GetGenericTypeDefinition();
Assert.NotNull(generictype);
Assert.Equal(typeof(TypeInfoMethodGenericClass<>), generictype);
}
// Verify IsSubClassOf() method
[Fact]
public static void TestIsSubClassOf1()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).GetTypeInfo();
bool isSubClass = t1.IsSubclassOf(t2.AsType());
Assert.False(isSubClass);
}
// Verify IsSubClassOf() method
[Fact]
public static void TestIsSubClassOf2()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).GetTypeInfo();
bool isSubClass = t2.IsSubclassOf(t1.AsType());
Assert.True(isSubClass, "Failed! isSubClass returned False when this class derives from input class ");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom1()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).GetTypeInfo();
bool isAssignable = t1.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom2()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).GetTypeInfo();
bool isAssignable = t2.IsAssignableFrom(t1);
Assert.False(isAssignable, "Failed! IsAssignableFrom returned True");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom3()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodBase).GetTypeInfo();
bool isAssignable = t2.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False for same Type");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom4()
{
TypeInfo t1 = typeof(MethodITest).GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodImplClass).GetTypeInfo();
bool isAssignable = t1.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False");
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayType1()
{
TypeInfo ti = typeof(String).GetTypeInfo();
Type arraytype = ti.MakeArrayType();
String[] strArray = { "a", "b", "c" };
Assert.NotNull(arraytype);
Assert.Equal(strArray.GetType(), arraytype);
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayType2()
{
TypeInfo ti = typeof(Int32).GetTypeInfo();
Type arraytype = ti.MakeArrayType();
int[] intArray = { 1, 2, 3 };
Assert.NotNull(arraytype);
Assert.Equal(intArray.GetType(), arraytype);
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank1()
{
TypeInfo ti = typeof(String).GetTypeInfo();
Type arraytype = ti.MakeArrayType(1);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank2()
{
GC.KeepAlive(typeof(int[,]));
TypeInfo ti = typeof(Int32).GetTypeInfo();
Type arraytype = ti.MakeArrayType(2);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayOfPointerType1()
{
TypeInfo ti = typeof(char*).GetTypeInfo();
Type arraytype = ti.MakeArrayType(3);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray);
Assert.Equal(arraytype.GetArrayRank(), 3);
Assert.Equal(arraytype.GetElementType(), typeof(char*));
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank3()
{
GC.KeepAlive(typeof(int[,,]));
TypeInfo ti = typeof(Int32).GetTypeInfo();
Type arraytype = ti.MakeArrayType(3);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType1()
{
TypeInfo ti = typeof(Int32).GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.NotNull(byreftype);
Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType2()
{
TypeInfo ti = typeof(String).GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.NotNull(byreftype);
Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType3()
{
TypeInfo ti = typeof(String).GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.Throws<TypeLoadException>(() => { Type byreftype2 = byreftype.MakeByRefType(); });
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType1()
{
TypeInfo ti = typeof(Int32).GetTypeInfo();
Type ptrtype = ti.MakePointerType();
Assert.NotNull(ptrtype);
Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer");
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType2()
{
TypeInfo ti = typeof(String).GetTypeInfo();
Type ptrtype = ti.MakePointerType();
Assert.NotNull(ptrtype);
Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer");
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType3()
{
TypeInfo ti = typeof(String).GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.Throws<TypeLoadException>(() => { Type ptrtype = byreftype.MakePointerType(); });
}
// Verify MakeGenericType() method
[Fact]
public static void TestMakeGenericType()
{
Type type = typeof(List<>);
Type[] typeArgs = { typeof(String) };
TypeInfo typeInfo = type.GetTypeInfo();
Type generictype = typeInfo.MakeGenericType(typeArgs);
Assert.NotNull(generictype);
Assert.True(generictype.GetTypeInfo().IsGenericType, "Failed!! MakeGenericType() returned type that is not generic");
}
// Verify ToString() method
[Fact]
public static void TestToString1()
{
Type type = typeof(string);
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Equal(typeInfo.ToString(), "System.String");
}
// Verify ToString() method
[Fact]
public static void TestToString2()
{
Type type = typeof(int);
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Equal(typeInfo.ToString(), "System.Int32");
}
//Private Helper Methods
private static void VerifyGetDeclaredEvent(TypeInfo ti, string eventName)
{
EventInfo ei = ti.GetDeclaredEvent(eventName);
Assert.NotNull(ei);
Assert.Equal(eventName, ei.Name);
}
private static void VerifyGetDeclaredField(TypeInfo ti, string fieldName)
{
FieldInfo fi = ti.GetDeclaredField(fieldName);
Assert.NotNull(fi);
Assert.Equal(fieldName, fi.Name);
}
private static void VerifyGetDeclaredMethod(TypeInfo ti, string methodName)
{
MethodInfo mi = ti.GetDeclaredMethod(methodName);
Assert.NotNull(mi);
Assert.Equal(methodName, mi.Name);
}
private static void VerifyGetDeclaredMethods(TypeInfo ti, string methodName, int count)
{
IEnumerator<MethodInfo> alldefinedMethods = ti.GetDeclaredMethods(methodName).GetEnumerator();
MethodInfo mi = null;
int numMethods = 0;
while (alldefinedMethods.MoveNext())
{
mi = alldefinedMethods.Current;
Assert.Equal(methodName, mi.Name);
numMethods++;
}
Assert.Equal(count, numMethods);
}
private static void VerifyGetDeclaredNestedType(TypeInfo ti, string name)
{
TypeInfo nested_ti = ti.GetDeclaredNestedType(name);
Assert.NotNull(nested_ti);
Assert.Equal(name, nested_ti.Name);
}
private static void VerifyGetDeclaredProperty(TypeInfo ti, string name)
{
PropertyInfo pi = ti.GetDeclaredProperty(name);
Assert.NotNull(pi);
Assert.Equal(name, pi.Name);
}
}
//Metadata for Reflection
public class MethodPublicClass
{
public int PublicField;
public static int PublicStaticField;
public MethodPublicClass() { }
public void PublicMethod() { }
public void overRiddenMethod() { }
public void overRiddenMethod(int i) { }
public void overRiddenMethod(string s) { }
public void overRiddenMethod(Object o) { }
public static void PublicStaticMethod() { }
public class PublicNestedType { }
public int PublicProperty { get { return default(int); } set { } }
#pragma warning disable 0067 // unused event (only used via reflection)
public event EventHandler EventPublic;
#pragma warning restore 0067
}
public interface MethodITest { }
public class TypeInfoMethodBase { }
public class TypeInfoMethodDerived : TypeInfoMethodBase { }
public class TypeInfoMethodImplClass : MethodITest { }
public class TypeInfoMethodGenericClass<T> { }
public class TypeInfoMethodClassWithConstraints<T, U>
where T : TypeInfoMethodBase, MethodITest
where U : class, new()
{ }
}
| |
/*
* Copyright 2008 ZXing authors
*
* 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;
namespace ZXing.QrCode.Internal
{
/// <summary>
///
/// </summary>
/// <author>Satoru Takabayashi</author>
/// <author>Daniel Switkin</author>
/// <author>Sean Owen</author>
public static class MaskUtil
{
// Penalty weights from section 6.8.2.1
private const int N1 = 3;
private const int N2 = 3;
private const int N3 = 40;
private const int N4 = 10;
/// <summary>
/// Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and
/// give penalty to them. Example: 00000 or 11111.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule1(ByteMatrix matrix)
{
return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false);
}
/// <summary>
/// Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give
/// penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a
/// penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule2(ByteMatrix matrix)
{
int penalty = 0;
var array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height - 1; y++)
{
for (int x = 0; x < width - 1; x++)
{
int value = array[y][x];
if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1])
{
penalty++;
}
}
}
return N2 * penalty;
}
/// <summary>
/// Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or
/// 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give
/// penalties twice (i.e. 40 * 2).
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule3(ByteMatrix matrix)
{
int penalty = 0;
var array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Tried to simplify following conditions but failed.
if (x + 6 < width &&
array[y][x] == 1 &&
array[y][x + 1] == 0 &&
array[y][x + 2] == 1 &&
array[y][x + 3] == 1 &&
array[y][x + 4] == 1 &&
array[y][x + 5] == 0 &&
array[y][x + 6] == 1 &&
((x + 10 < width &&
array[y][x + 7] == 0 &&
array[y][x + 8] == 0 &&
array[y][x + 9] == 0 &&
array[y][x + 10] == 0) ||
(x - 4 >= 0 &&
array[y][x - 1] == 0 &&
array[y][x - 2] == 0 &&
array[y][x - 3] == 0 &&
array[y][x - 4] == 0)))
{
penalty += N3;
}
if (y + 6 < height &&
array[y][x] == 1 &&
array[y + 1][x] == 0 &&
array[y + 2][x] == 1 &&
array[y + 3][x] == 1 &&
array[y + 4][x] == 1 &&
array[y + 5][x] == 0 &&
array[y + 6][x] == 1 &&
((y + 10 < height &&
array[y + 7][x] == 0 &&
array[y + 8][x] == 0 &&
array[y + 9][x] == 0 &&
array[y + 10][x] == 0) ||
(y - 4 >= 0 &&
array[y - 1][x] == 0 &&
array[y - 2][x] == 0 &&
array[y - 3][x] == 0 &&
array[y - 4][x] == 0)))
{
penalty += N3;
}
}
}
return penalty;
}
/// <summary>
/// Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give
/// penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule4(ByteMatrix matrix)
{
int numDarkCells = 0;
var array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height; y++)
{
var arrayY = array[y];
for (int x = 0; x < width; x++)
{
if (arrayY[x] == 1)
{
numDarkCells++;
}
}
}
var numTotalCells = matrix.Height * matrix.Width;
var darkRatio = (double)numDarkCells / numTotalCells;
var fivePercentVariances = (int)(Math.Abs(darkRatio - 0.5) * 20.0); // * 100.0 / 5.0
return fivePercentVariances * N4;
}
/// <summary>
/// Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
/// pattern conditions.
/// </summary>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
public static bool getDataMaskBit(int maskPattern, int x, int y)
{
int intermediate, temp;
switch (maskPattern)
{
case 0:
intermediate = (y + x) & 0x1;
break;
case 1:
intermediate = y & 0x1;
break;
case 2:
intermediate = x % 3;
break;
case 3:
intermediate = (y + x) % 3;
break;
case 4:
intermediate = (((int)((uint)y >> 1)) + (x / 3)) & 0x1;
break;
case 5:
temp = y * x;
intermediate = (temp & 0x1) + (temp % 3);
break;
case 6:
temp = y * x;
intermediate = (((temp & 0x1) + (temp % 3)) & 0x1);
break;
case 7:
temp = y * x;
intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1);
break;
default:
throw new ArgumentException("Invalid mask pattern: " + maskPattern);
}
return intermediate == 0;
}
/// <summary>
/// Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both
/// vertical and horizontal orders respectively.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="isHorizontal">if set to <c>true</c> [is horizontal].</param>
/// <returns></returns>
private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal)
{
int penalty = 0;
int iLimit = isHorizontal ? matrix.Height : matrix.Width;
int jLimit = isHorizontal ? matrix.Width : matrix.Height;
var array = matrix.Array;
for (int i = 0; i < iLimit; i++)
{
int numSameBitCells = 0;
int prevBit = -1;
for (int j = 0; j < jLimit; j++)
{
int bit = isHorizontal ? array[i][j] : array[j][i];
if (bit == prevBit)
{
numSameBitCells++;
}
else
{
if (numSameBitCells >= 5)
{
penalty += N1 + (numSameBitCells - 5);
}
numSameBitCells = 1; // Include the cell itself.
prevBit = bit;
}
}
if (numSameBitCells > 5)
{
penalty += N1 + (numSameBitCells - 5);
}
}
return penalty;
}
}
}
| |
//
// TimeAdaptor.cs
//
// Author:
// Ruben Vermeersch <[email protected]>
// Gabriel Burt <[email protected]>
// Larry Ewing <[email protected]>
// Stephane Delcroix <[email protected]>
//
// Copyright (C) 2004-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2005-2006 Gabriel Burt
// Copyright (C) 2004-2005 Larry Ewing
// Copyright (C) 2006, 2008 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Threading;
using System.Collections.Generic;
using FSpot.Core;
using FSpot.Query;
using Hyena;
namespace FSpot
{
public class TimeAdaptor : GroupAdaptor, ILimitable
{
Dictionary <int, int[]> years = new Dictionary<int, int[]> ();
public override event GlassSetHandler GlassSet;
public TimeAdaptor (PhotoQuery query, bool order_ascending) : base (query, order_ascending)
{ }
public override void SetGlass (int min)
{
DateTime date = DateFromIndex (min);
GlassSet?.Invoke (this, query.LookupItem (date));
}
public void SetLimits (int min, int max)
{
DateTime start = DateFromIndex (min);
DateTime end = DateFromIndex(max);
end = order_ascending ? end.AddMonths (1) : end.AddMonths(-1);
SetLimits (start, end);
}
public void SetLimits (DateTime start, DateTime end)
{
query.Range = (start > end) ? new DateRange (end, start) : new DateRange (start, end);
}
public override int Count ()
{
return years.Count * 12;
}
public override string GlassLabel (int item)
{
return string.Format ("{0} ({1})", DateFromIndex (item).ToString ("MMMM yyyy"), Value (item));
}
public override string TickLabel (int item)
{
DateTime start = DateFromIndex (item);
if ((start.Month == 12 && !order_ascending) || (start.Month == 1 && order_ascending))
return start.Year.ToString ();
return null;
}
public override int Value (int item)
{
if (order_ascending)
return years [startyear + item/12][item % 12];
return years [endyear - item/12][11 - item % 12];
}
public DateTime DateFromIndex (int item)
{
item = Math.Max (item, 0);
item = Math.Min (years.Count * 12 - 1, item);
if (order_ascending)
return DateFromIndexAscending (item);
return DateFromIndexDescending (item);
}
DateTime DateFromIndexAscending (int item)
{
int year = startyear + item/12;
int month = 1 + (item % 12);
return new DateTime(year, month, 1);
}
DateTime DateFromIndexDescending (int item)
{
int year = endyear - item/12;
int month = 12 - (item % 12);
year = Math.Max(1, year);
year = Math.Min(year, 9999);
month = Math.Max(1, month);
month = Math.Min(month, 12);
int daysInMonth = DateTime.DaysInMonth(year, month);
return new DateTime (year, month, daysInMonth).AddDays (1.0).AddMilliseconds (-.1);
}
public override int IndexFromPhoto (IPhoto photo)
{
if (order_ascending)
return IndexFromDateAscending (photo.Time);
return IndexFromDateDescending (photo.Time);
}
public int IndexFromDate (DateTime date)
{
if (order_ascending)
return IndexFromDateAscending(date);
return IndexFromDateDescending(date);
}
int IndexFromDateAscending(DateTime date)
{
int year = date.Year;
int min_year = startyear;
int max_year = endyear;
if (year < min_year || year > max_year) {
Log.DebugFormat ("TimeAdaptor.IndexFromDate year out of range[{1},{2}]: {0}", year, min_year, max_year);
return 0;
}
return (year - startyear) * 12 + date.Month - 1 ;
}
int IndexFromDateDescending(DateTime date)
{
int year = date.Year;
int min_year = startyear;
int max_year = endyear;
if (year < min_year || year > max_year) {
Log.DebugFormat ("TimeAdaptor.IndexFromPhoto year out of range[{1},{2}]: {0}", year, min_year, max_year);
return 0;
}
return 12 * (endyear - year) + 12 - date.Month;
}
public override IPhoto PhotoFromIndex (int item)
{
DateTime start = DateFromIndex (item);
return query [query.LookupItem (start)];
}
public override event ChangedHandler Changed;
uint timer;
protected override void Reload ()
{
timer = Log.DebugTimerStart ();
Thread reload = new Thread (new ThreadStart (DoReload));
reload.IsBackground = true;
reload.Priority = ThreadPriority.Lowest;
reload.Start ();
}
int startyear = Int32.MaxValue, endyear = Int32.MinValue;
void DoReload ()
{
Thread.Sleep (200);
var years_tmp = query.Store.PhotosPerMonth ();
int startyear_tmp = Int32.MaxValue;
int endyear_tmp = Int32.MinValue;
foreach (int year in years_tmp.Keys) {
startyear_tmp = Math.Min (year, startyear_tmp);
endyear_tmp = Math.Max (year, endyear_tmp);
}
ThreadAssist.ProxyToMain (() => {
years = years_tmp;
startyear = startyear_tmp;
endyear = endyear_tmp;
Changed?.Invoke (this);
});
Log.DebugTimerPrint (timer, "TimeAdaptor REAL Reload took {0}");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlCollation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.IO;
namespace System.Xml.Xsl.Runtime {
using Res = System.Xml.Utils.Res;
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class XmlCollation {
// lgid support for sort
private const int deDE = 0x0407;
private const int huHU = 0x040E;
private const int jaJP = 0x0411;
private const int kaGE = 0x0437;
private const int koKR = 0x0412;
private const int zhTW = 0x0404;
private const int zhCN = 0x0804;
private const int zhHK = 0x0C04;
private const int zhSG = 0x1004;
private const int zhMO = 0x1404;
private const int zhTWbopo = 0x030404;
private const int deDEphon = 0x010407;
private const int huHUtech = 0x01040e;
private const int kaGEmode = 0x010437;
// Invariant: compops == (options & Options.mask)
private CultureInfo cultInfo;
private Options options;
private CompareOptions compops;
/// <summary>
/// Extends System.Globalization.CompareOptions with additional flags.
/// </summary>
private struct Options {
public const int FlagUpperFirst = 0x1000;
public const int FlagEmptyGreatest = 0x2000;
public const int FlagDescendingOrder = 0x4000;
private const int Mask = FlagUpperFirst | FlagEmptyGreatest | FlagDescendingOrder;
private int value;
public Options(int value) {
this.value = value;
}
public bool GetFlag(int flag) {
return (this.value & flag) != 0;
}
public void SetFlag(int flag, bool value) {
if (value)
this.value |= flag;
else
this.value &= ~flag;
}
public bool UpperFirst {
get { return GetFlag(FlagUpperFirst); }
set { SetFlag(FlagUpperFirst, value); }
}
public bool EmptyGreatest {
get { return GetFlag(FlagEmptyGreatest); }
}
public bool DescendingOrder {
get { return GetFlag(FlagDescendingOrder); }
}
public bool IgnoreCase {
get { return GetFlag((int)CompareOptions.IgnoreCase); }
}
public bool Ordinal {
get { return GetFlag((int)CompareOptions.Ordinal); }
}
public CompareOptions CompareOptions {
get {
return (CompareOptions)(value & ~Mask);
}
set {
Debug.Assert(((int)value & Mask) == 0);
this.value = (this.value & Mask) | (int)value;
}
}
public static implicit operator int(Options options) {
return options.value;
}
}
//-----------------------------------------------
// Constructors
//-----------------------------------------------
/// <summary>
/// Construct a collation that uses the specified culture and compare options.
/// </summary>
private XmlCollation(CultureInfo cultureInfo, Options options) {
this.cultInfo = cultureInfo;
this.options = options;
this.compops = options.CompareOptions;
}
//-----------------------------------------------
// Create
//-----------------------------------------------
/// <summary>
/// Singleton collation that sorts according to Unicode code points.
/// </summary>
private static XmlCollation cp = new XmlCollation(CultureInfo.InvariantCulture, new Options((int)CompareOptions.Ordinal));
internal static XmlCollation CodePointCollation {
get { return cp; }
}
internal static XmlCollation Create(string collationLiteral) {
return Create(collationLiteral, /*throw:*/true);
}
// This function is used in both parser and F&O library, so just strictly map valid literals to XmlCollation.
// Set compare options one by one:
// 0, false: no effect; 1, true: yes
// Disregard unrecognized options.
internal static XmlCollation Create(string collationLiteral, bool throwOnError) {
Debug.Assert(collationLiteral != null, "collation literal should not be null");
if (collationLiteral == XmlReservedNs.NsCollCodePoint) {
return CodePointCollation;
}
Uri collationUri;
CultureInfo cultInfo = null;
Options options = new Options();
if (throwOnError) {
collationUri = new Uri(collationLiteral);
} else {
if (!Uri.TryCreate(collationLiteral, UriKind.Absolute, out collationUri)) {
return null;
}
}
string authority = collationUri.GetLeftPart(UriPartial.Authority);
if (authority == XmlReservedNs.NsCollationBase) {
// Language
// at least a '/' will be returned for Uri.LocalPath
string lang = collationUri.LocalPath.Substring(1);
if (lang.Length == 0) {
// Use default culture of current thread (cultinfo = null)
} else {
// Create culture from RFC 1766 string
try {
cultInfo = new CultureInfo(lang);
}
catch (ArgumentException) {
if (!throwOnError) return null;
throw new XslTransformException(Res.Coll_UnsupportedLanguage, lang);
}
}
} else if (collationUri.IsBaseOf(new Uri(XmlReservedNs.NsCollCodePoint))) {
// language with codepoint collation is not allowed
options.CompareOptions = CompareOptions.Ordinal;
} else {
// Unrecognized collation
if (!throwOnError) return null;
throw new XslTransformException(Res.Coll_Unsupported, collationLiteral);
}
// Sort & Compare option
// at least a '?' will be returned for Uri.Query if not empty
string query = collationUri.Query;
string sort = null;
if (query.Length != 0) {
foreach (string option in query.Substring(1).Split('&')) {
string[] pair = option.Split('=');
if (pair.Length != 2) {
if (!throwOnError) return null;
throw new XslTransformException(Res.Coll_BadOptFormat, option);
}
string optionName = pair[0].ToUpper(CultureInfo.InvariantCulture);
string optionValue = pair[1].ToUpper(CultureInfo.InvariantCulture);
if (optionName == "SORT") {
sort = optionValue;
}
else {
int flag;
switch (optionName) {
case "IGNORECASE": flag = (int)CompareOptions.IgnoreCase; break;
case "IGNORENONSPACE": flag = (int)CompareOptions.IgnoreNonSpace; break;
case "IGNORESYMBOLS": flag = (int)CompareOptions.IgnoreSymbols; break;
case "IGNOREKANATYPE": flag = (int)CompareOptions.IgnoreKanaType; break;
case "IGNOREWIDTH": flag = (int)CompareOptions.IgnoreWidth; break;
case "UPPERFIRST": flag = Options.FlagUpperFirst; break;
case "EMPTYGREATEST": flag = Options.FlagEmptyGreatest; break;
case "DESCENDINGORDER": flag = Options.FlagDescendingOrder; break;
default:
if (!throwOnError) return null;
throw new XslTransformException(Res.Coll_UnsupportedOpt, pair[0]);
}
switch (optionValue) {
case "0": case "FALSE": options.SetFlag(flag, false); break;
case "1": case "TRUE" : options.SetFlag(flag, true ); break;
default:
if (!throwOnError) return null;
throw new XslTransformException(Res.Coll_UnsupportedOptVal, pair[0], pair[1]);
}
}
}
}
// upperfirst option is only meaningful when not ignore case
if (options.UpperFirst && options.IgnoreCase)
options.UpperFirst = false;
// other CompareOptions are only meaningful if Ordinal comparison is not being used
if (options.Ordinal) {
options.CompareOptions = CompareOptions.Ordinal;
options.UpperFirst = false;
}
// new cultureinfo based on alternate sorting option
if (sort != null && cultInfo != null) {
int lgid = GetLangID(cultInfo.LCID);
switch (sort) {
case "bopo":
if (lgid == zhTW) {
cultInfo = new CultureInfo(zhTWbopo);
}
break;
case "strk":
if (lgid == zhCN || lgid == zhHK || lgid == zhSG || lgid == zhMO) {
cultInfo = new CultureInfo(MakeLCID(cultInfo.LCID, /*Stroke*/ 0x02));
}
break;
case "uni":
if (lgid == jaJP || lgid == koKR) {
cultInfo = new CultureInfo(MakeLCID(cultInfo.LCID, /*Unicode*/ 0x01));
}
break;
case "phn":
if (lgid == deDE) {
cultInfo = new CultureInfo(deDEphon);
}
break;
case "tech":
if (lgid == huHU) {
cultInfo = new CultureInfo(huHUtech);
}
break;
case "mod":
// ka-GE(Georgian - Georgia) Modern Sort: 0x00010437
if (lgid == kaGE) {
cultInfo = new CultureInfo(kaGEmode);
}
break;
case "pron": case "dict": case "trad":
// es-ES(Spanish - Spain) Traditional: 0x0000040A
// They are removing 0x040a (Spanish Traditional sort) in NLS+.
// So if you create 0x040a, it's just like 0x0c0a (Spanish International sort).
// Thus I don't handle it differently.
break;
default:
if (!throwOnError) return null;
throw new XslTransformException(Res.Coll_UnsupportedSortOpt, sort);
}
}
return new XmlCollation(cultInfo, options);
}
//-----------------------------------------------
// Collection Support
//-----------------------------------------------
// Redefine Equals and GetHashCode methods, they are needed for UniqueList<XmlCollation>
public override bool Equals(object obj) {
if (this == obj) {
return true;
}
XmlCollation that = obj as XmlCollation;
return that != null &&
this.options == that.options &&
object.Equals(this.cultInfo, that.cultInfo);
}
public override int GetHashCode() {
int hashCode = this.options;
if (this.cultInfo != null) {
hashCode ^= this.cultInfo.GetHashCode();
}
return hashCode;
}
//-----------------------------------------------
// Serialization Support
//-----------------------------------------------
// Denotes the current thread locale
private const int LOCALE_CURRENT = -1;
internal void GetObjectData(BinaryWriter writer) {
// NOTE: For CultureInfo we serialize only LCID. It seems to suffice for our purposes.
Debug.Assert(this.cultInfo == null || this.cultInfo.Equals(new CultureInfo(this.cultInfo.LCID)),
"Cannot serialize CultureInfo correctly");
writer.Write(this.cultInfo != null ? this.cultInfo.LCID : LOCALE_CURRENT);
writer.Write(this.options);
}
internal XmlCollation(BinaryReader reader) {
int lcid = reader.ReadInt32();
this.cultInfo = (lcid != LOCALE_CURRENT) ? new CultureInfo(lcid) : null;
this.options = new Options(reader.ReadInt32());
this.compops = options.CompareOptions;
}
//-----------------------------------------------
// Compare Properties
//-----------------------------------------------
internal bool UpperFirst {
get { return this.options.UpperFirst; }
}
internal bool EmptyGreatest {
get { return this.options.EmptyGreatest; }
}
internal bool DescendingOrder {
get { return this.options.DescendingOrder; }
}
internal CultureInfo Culture {
get {
// Use default thread culture if this.cultinfo = null
if (this.cultInfo == null)
return CultureInfo.CurrentCulture;
return this.cultInfo;
}
}
//-----------------------------------------------
//
//-----------------------------------------------
/// <summary>
/// Create a sort key that can be compared quickly with other keys.
/// </summary>
internal XmlSortKey CreateSortKey(string s) {
SortKey sortKey;
byte[] bytesKey;
int idx;
//
sortKey = Culture.CompareInfo.GetSortKey(s, this.compops);
// Create an XmlStringSortKey using the SortKey if possible
#if DEBUG
// In debug-only code, test other code path more frequently
if (!UpperFirst && DescendingOrder)
return new XmlStringSortKey(sortKey, DescendingOrder);
#else
if (!UpperFirst)
return new XmlStringSortKey(sortKey, DescendingOrder);
#endif
// Get byte buffer from SortKey and modify it
bytesKey = sortKey.KeyData;
if (UpperFirst && bytesKey.Length != 0) {
// By default lower-case is always sorted first for any locale (verified by empirical testing).
// In order to place upper-case first, invert the case weights in the generated sort key.
// Skip to case weight section (3rd weight section)
idx = 0;
while (bytesKey[idx] != 1)
idx++;
do {
idx++;
}
while (bytesKey[idx] != 1);
// Invert all case weights (including terminating 0x1)
do {
idx++;
bytesKey[idx] ^= 0xff;
}
while (bytesKey[idx] != 0xfe);
}
return new XmlStringSortKey(bytesKey, DescendingOrder);
}
#if not_used
/// <summary>
/// Compare two strings with each other. Return <0 if str1 sorts before str2, 0 if they're equal, and >0
/// if str1 sorts after str2.
/// </summary>
internal int Compare(string str1, string str2) {
CultureInfo cultinfo = Culture;
int result;
if (this.options.Ordinal) {
result = string.CompareOrdinal(str1, str2);
if (result < 0) result = -1;
else if (result > 0) result = 1;
}
else if (UpperFirst) {
// First compare case-insensitive, then break ties by considering case
result = cultinfo.CompareInfo.Compare(str1, str2, this.compops | CompareOptions.IgnoreCase);
if (result == 0)
result = -cultinfo.CompareInfo.Compare(str1, str2, this.compops);
}
else {
result = cultinfo.CompareInfo.Compare(str1, str2, this.compops);
}
if (DescendingOrder)
result = -result;
return result;
}
/// <summary>
/// Return the index of str1 in str2, or -1 if str1 is not a substring of str2.
/// </summary>
internal int IndexOf(string str1, string str2) {
return Culture.CompareInfo.IndexOf(str1, str2, this.compops);
}
/// <summary>
/// Return true if str1 ends with str2.
/// </summary>
internal bool IsSuffix(string str1, string str2) {
if (this.options.Ordinal){
if (str1.Length < str2.Length) {
return false;
} else {
return String.CompareOrdinal(str1, str1.Length - str2.Length, str2, 0, str2.Length) == 0;
}
}
return Culture.CompareInfo.IsSuffix (str1, str2, this.compops);
}
/// <summary>
/// Return true if str1 starts with str2.
/// </summary>
internal bool IsPrefix(string str1, string str2) {
if (this.options.Ordinal) {
if (str1.Length < str2.Length) {
return false;
} else {
return String.CompareOrdinal(str1, 0, str2, 0, str2.Length) == 0;
}
}
return Culture.CompareInfo.IsPrefix (str1, str2, this.compops);
}
#endif
//-----------------------------------------------
// Helper Functions
//-----------------------------------------------
private static int MakeLCID(int langid, int sortid) {
return (langid & 0xffff) | ((sortid & 0xf) << 16);
}
private static int GetLangID(int lcid) {
return (lcid & 0xffff);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using NUnit.Framework;
using Raksha.Crypto;
using Raksha.Pkix;
using Raksha.Security.Certificates;
using Raksha.Utilities.Collections;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
using Raksha.X509;
using Raksha.X509.Store;
namespace Raksha.Tests.Misc
{
[TestFixture]
public class CertPathTest
: SimpleTest
{
internal static readonly byte[] rootCertBin = Base64.Decode(
"MIIBqzCCARQCAQEwDQYJKoZIhvcNAQEFBQAwHjEcMBoGA1UEAxMTVGVzdCBDQSBDZXJ0aWZpY2F0ZTAeFw0wODA5MDQwNDQ1MDhaFw0wODA5MTEwNDQ1MDhaMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMRLUjhPe4YUdLo6EcjKcWUOG7CydFTH53Pr1lWjOkbmszYDpkhCTT9LOsI+disk18nkBxSl8DAHTqV+VxtuTPt64iyi10YxyDeep+DwZG/f8cVQv97U3hA9cLurZ2CofkMLGr6JpSGCMZ9FcstcTdHB4lbErIJ54YqfF4pNOs4/AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAgyrTEFY7ALpeY59jL6xFOLpuPqoBOWrUWv6O+zy5BCU0qiX71r3BpigtxRj+DYcfLIM9FNERDoHu3TthD3nwYWUBtFX8N0QUJIdJabxqAMhLjSC744koiFpCYse5Ye3ZvEdFwDzgAQsJTp5eFGgTZPkPzcdhkFJ2p9+OWs+cb24=");
internal static readonly byte[] interCertBin = Base64.Decode(
"MIICSzCCAbSgAwIBAgIBATANBgkqhkiG9w0BAQUFADAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlMB4XDTA4MDkwNDA0NDUwOFoXDTA4MDkxMTA0NDUwOFowKDEmMCQGA1UEAxMdVGVzdCBJbnRlcm1lZGlhdGUgQ2VydGlmaWNhdGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAISS9OOZ2wxzdWny9aVvk4Joq+dwSJ+oqvHUxX3PflZyuiLiCBUOUE4q59dGKdtNX5fIfwyK3cpV0e73Y/0fwfM3m9rOWFrCKOhfeswNTes0w/2PqPVVDDsF/nj7NApuqXwioeQlgTL251RDF4sVoxXqAU7lRkcqwZt3mwqS4KTJAgMBAAGjgY4wgYswRgYDVR0jBD8wPYAUhv8BOT27EB9JaCccJD4YASPP5XWhIqQgMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGWCAQEwHQYDVR0OBBYEFL/IwAGOkHzaQyPZegy79CwM5oTFMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4GBAE4TRgUz4sUvZyVdZxqV+XyNRnqXAeLOOqFGYv2D96tQrS+zjd0elVlT6lFrtchZdOmmX7R6/H/tjMWMcTBICZyRYrvK8cCAmDOI+EIdq5p6lj2Oq6Pbw/wruojAqNrpaR6IkwNpWtdOSSupv4IJL+YU9q2YFTh4R1j3tOkPoFGr");
internal static readonly byte[] finalCertBin = Base64.Decode(
"MIICRjCCAa+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAoMSYwJAYDVQQDEx1UZXN0IEludGVybWVkaWF0ZSBDZXJ0aWZpY2F0ZTAeFw0wODA5MDQwNDQ1MDhaFw0wODA5MTEwNDQ1MDhaMB8xHTAbBgNVBAMTFFRlc3QgRW5kIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChpUeo0tPYywWKiLlbWKNJBcCpSaLSlaZ+4+yer1AxI5yJIVHP6SAlBghlbD5Qne5ImnN/15cz1xwYAiul6vGKJkVPlFEe2Mr+g/J/WJPQQPsjbZ1G+vxbAwXEDA4KaQrnpjRZFq+CdKHwOjuPLYS/MYQNgdIvDVEQcTbPQ8GaiQIDAQABo4GIMIGFMEYGA1UdIwQ/MD2AFL/IwAGOkHzaQyPZegy79CwM5oTFoSKkIDAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlggEBMB0GA1UdDgQWBBSVkw+VpqBf3zsLc/9GdkK9TzHPwDAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQUFAAOBgQBLv/0bVDjzTs/y1vN3FUiZNknEbzupIZduTuXJjqv/vBX+LDPjUfu/+iOCXOSKoRn6nlOWhwB1z6taG2usQkFG8InMkRcPREi2uVgFdhJ/1C3dAWhsdlubjdL926bftXvxnx/koDzyrePW5U96RlOQM2qLvbaky2Giz6hrc3Wl+w==");
internal static readonly byte[] rootCrlBin = Base64.Decode(
"MIIBYjCBzAIBATANBgkqhkiG9w0BAQsFADAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlFw0wODA5MDQwNDQ1MDhaFw0wODA5MDQwNzMxNDhaMCIwIAIBAhcNMDgwOTA0MDQ0NTA4WjAMMAoGA1UdFQQDCgEJoFYwVDBGBgNVHSMEPzA9gBSG/wE5PbsQH0loJxwkPhgBI8/ldaEipCAwHjEcMBoGA1UEAxMTVGVzdCBDQSBDZXJ0aWZpY2F0ZYIBATAKBgNVHRQEAwIBATANBgkqhkiG9w0BAQsFAAOBgQCAbaFCo0BNG4AktVf6jjBLeawP1u0ELYkOCEGvYZE0mBpQ+OvFg7subZ6r3lRIj030nUli28sPFtu5ZQMBNcpE4nS1ziF44RfT3Lp5UgHx9x17Krz781iEyV+7zU8YxYMY9wULD+DCuK294kGKIssVNbmTYXZatBNoXQN5CLIocA==");
internal static readonly byte[] interCrlBin = Base64.Decode(
"MIIBbDCB1gIBATANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQDEx1UZXN0IEludGVybWVkaWF0ZSBDZXJ0aWZpY2F0ZRcNMDgwOTA0MDQ0NTA4WhcNMDgwOTA0MDczMTQ4WjAiMCACAQIXDTA4MDkwNDA0NDUwOFowDDAKBgNVHRUEAwoBCaBWMFQwRgYDVR0jBD8wPYAUv8jAAY6QfNpDI9l6DLv0LAzmhMWhIqQgMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGWCAQEwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQADgYEAEVCr5TKs5yguGgLH+dBzmSPoeSIWJFLsgWwJEit/iUDJH3dgYmaczOcGxIDtbYYHLWIHM+P2YRyQz3MEkCXEgm/cx4y7leAmux5l+xQWgmxFPz+197vaphPeCZo+B7V1CWtm518gcq4mrs9ovfgNqgyFj7KGjcBpWdJE32KMt50=");
/*
* certpath with a circular reference
*/
internal static readonly byte[] certA = Base64.Decode(
"MIIC6jCCAlOgAwIBAgIBBTANBgkqhkiG9w0BAQUFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIzMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ2NTda"
+ "Fw0xNzAzMzAwODQ0MDBaMIGlMScwJQYDVQQDHh4AQQByAG0AaQBuACAASADkAGIA"
+ "ZQByAGwAaQBuAGcxCzAJBgNVBAYTAkNIMQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNV"
+ "BAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNwaGVyZSBBRzEQMA4GA1UECxMHVGVzdGlu"
+ "ZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5AcHJpdmFzcGhlcmUuY29tMIGfMA0GCSqG"
+ "SIb3DQEBAQUAA4GNADCBiQKBgQCfHfyVs5dbxG35H/Thd29qR4NZU88taCu/OWA1"
+ "GdACI02lXWYpmLWiDgnU0ULP+GG8OnVp1IES9fz2zcrXKQ19xZzsen/To3h5sNte"
+ "cJpS00XMM24q/jDwy5NvkBP9YIfFKQ1E/0hFHXcqwlw+b/y/v6YGsZCU2h6QDzc4"
+ "5m0+BwIDAQABo0AwPjAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIE8DAeBglg"
+ "hkgBhvhCAQ0EERYPeGNhIGNlcnRpZmljYXRlMA0GCSqGSIb3DQEBBQUAA4GBAJEu"
+ "KiSfIwsY7SfobMLrv2v/BtLhGLi4RnmjiwzBhuv5rn4rRfBpq1ppmqQMJ2pmA67v"
+ "UWCY+mNwuyjHyivpCCyJGsZ9d5H09g2vqxzkDBMz7X9VNMZYFH8j/R3/Cfvqks31"
+ "z0OFslJkeKLa1I0P/dfVHsRKNkLRT3Ws5LKksErQ");
internal static readonly byte[] certB = Base64.Decode(
"MIICtTCCAh6gAwIBAgIBBDANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIyMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ2Mzha"
+ "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjMxCzAJBgNVBAYTAkNI"
+ "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw"
+ "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A"
+ "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxCXIB"
+ "QRnmVvl2h7Q+0SsRxDLnyM1dJG9jMa+UCCmHy0k/ZHs5VirSbjEJSjkQ9BGeh9SC"
+ "7JwbMpXO7UE+gcVc2RnWUY+MA+fWIeTV4KtkYA8WPu8wVGCXbN8wwh/StOocszxb"
+ "g+iLvGeh8CYSRqg6QN3S/02etH3o8H4e7Z0PZwIDAQABoyMwITAPBgNVHRMBAf8E"
+ "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCtWdirSsmt"
+ "+CBBCNn6ZnbU3QqQfiiQIomjenNEHESJgaS/+PvPE5i3xWFXsunTHLW321/Km16I"
+ "7+ZvT8Su1cqHg79NAT8QB0yke1saKSy2C0Pic4HwrNqVBWFNSxMU0hQzpx/ZXDbZ"
+ "DqIXAp5EfyRYBy2ul+jm6Rot6aFgzuopKg==");
internal static readonly byte[] certC = Base64.Decode(
"MIICtTCCAh6gAwIBAgIBAjANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIxMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ0Mzla"
+ "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjIxCzAJBgNVBAYTAkNI"
+ "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw"
+ "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A"
+ "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0rLr6"
+ "f2/ONeJzTb0q9M/NNX+MnAFMSqiQGVBkT76u5nOH4KLkpHXkzI82JI7GuQMzoT3a"
+ "+RP1hO6FneO92ms2soC6xiOFb4EC69Dfhh87Nww5O35JxVF0bzmbmIAWd6P/7zGh"
+ "nd2S4tKkaZcubps+C0j9Fgi0hipVicAOUVVoDQIDAQABoyMwITAPBgNVHRMBAf8E"
+ "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCLPvc1IMA4"
+ "YP+PmnEldyUoRWRnvPWjBGeu0WheBP7fdcnGBf93Nmc5j68ZN+eTZ5VMuZ99YdvH"
+ "CXGNX6oodONLU//LlFKdLl5xjLAS5X9p1RbOEGytnalqeiEpjk4+C/7rIBG1kllO"
+ "dItmI6LlEMV09Hkpg6ZRAUmRkb8KrM4X7A==");
internal static readonly byte[] certD = Base64.Decode(
"MIICtTCCAh6gAwIBAgIBBjANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50"
+ "ZXIzMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX"
+ "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq"
+ "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ5NTNa"
+ "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjExCzAJBgNVBAYTAkNI"
+ "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw"
+ "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A"
+ "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCae3TP"
+ "jIVKeASqvNabaiUHAMGUgFxB7L0yUsIj39azLcLtUj4S7XkDf7SMGtYV0JY1XNaQ"
+ "sHJAsnJivDZc50oiYvqDYfgFZx5+AsN5l5X5rjRzs/OX+Jo+k1OgsIyu6+mf9Kfb"
+ "5IdWOVB2EcOg4f9tPjLM8CIj9Pp7RbKLyqUUgwIDAQABoyMwITAPBgNVHRMBAf8E"
+ "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCgr9kUdWUT"
+ "Lt9UcztSzR3pnHRsyvS0E/z850OKQKS5/VxLEalpFvhj+3EcZ7Y6mFxaaS2B7vXg"
+ "2YWyqV1PRb6iF7/u9EXkpSTKGrJahwANirCa3V/HTUuPdCE2GITlnWI8h3eVA+xQ"
+ "D4LF0PXHOkXbwmhXRSb10lW1bSGkUxE9jg==");
private void doTestExceptions()
{
byte[] enc = { (byte)0, (byte)2, (byte)3, (byte)4, (byte)5 };
// MyCertPath mc = new MyCertPath(enc);
MemoryStream os = new MemoryStream();
MemoryStream ins;
byte[] arr;
// TODO Support serialization of cert paths?
// ObjectOutputStream oos = new ObjectOutputStream(os);
// oos.WriteObject(mc);
// oos.Flush();
// oos.Close();
try
{
// CertificateFactory cFac = CertificateFactory.GetInstance("X.509");
arr = os.ToArray();
ins = new MemoryStream(arr, false);
// cFac.generateCertPath(ins);
new PkixCertPath(ins);
}
catch (CertificateException)
{
// ignore okay
}
// CertificateFactory cf = CertificateFactory.GetInstance("X.509");
X509CertificateParser cf = new X509CertificateParser();
IList certCol = new ArrayList();
certCol.Add(cf.ReadCertificate(certA));
certCol.Add(cf.ReadCertificate(certB));
certCol.Add(cf.ReadCertificate(certC));
certCol.Add(cf.ReadCertificate(certD));
// CertPathBuilder pathBuilder = CertPathBuilder.GetInstance("PKIX");
PkixCertPathBuilder pathBuilder = new PkixCertPathBuilder();
X509CertStoreSelector select = new X509CertStoreSelector();
select.Subject = ((X509Certificate)certCol[0]).SubjectDN;
ISet trustanchors = new HashSet();
trustanchors.Add(new TrustAnchor(cf.ReadCertificate(rootCertBin), null));
// CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));
IX509Store x509CertStore = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certCol));
PkixBuilderParameters parameters = new PkixBuilderParameters(trustanchors, select);
parameters.AddStore(x509CertStore);
try
{
PkixCertPathBuilderResult result = pathBuilder.Build(parameters);
PkixCertPath path = result.CertPath;
Fail("found cert path in circular set");
}
catch (PkixCertPathBuilderException)
{
// expected
}
}
public override void PerformTest()
{
X509CertificateParser cf = new X509CertificateParser();
X509Certificate rootCert = cf.ReadCertificate(rootCertBin);
X509Certificate interCert = cf.ReadCertificate(interCertBin);
X509Certificate finalCert = cf.ReadCertificate(finalCertBin);
//Testing CertPath generation from List
IList list = new ArrayList();
list.Add(interCert);
// CertPath certPath1 = cf.generateCertPath(list);
PkixCertPath certPath1 = new PkixCertPath(list);
//Testing CertPath encoding as PkiPath
byte[] encoded = certPath1.GetEncoded("PkiPath");
//Testing CertPath generation from InputStream
MemoryStream inStream = new MemoryStream(encoded, false);
// CertPath certPath2 = cf.generateCertPath(inStream, "PkiPath");
PkixCertPath certPath2 = new PkixCertPath(inStream, "PkiPath");
//Comparing both CertPathes
if (!certPath2.Equals(certPath1))
{
Fail("CertPath differ after encoding and decoding.");
}
encoded = certPath1.GetEncoded("PKCS7");
//Testing CertPath generation from InputStream
inStream = new MemoryStream(encoded, false);
// certPath2 = cf.generateCertPath(inStream, "PKCS7");
certPath2 = new PkixCertPath(inStream, "PKCS7");
//Comparing both CertPathes
if (!certPath2.Equals(certPath1))
{
Fail("CertPath differ after encoding and decoding.");
}
encoded = certPath1.GetEncoded("PEM");
//Testing CertPath generation from InputStream
inStream = new MemoryStream(encoded, false);
// certPath2 = cf.generateCertPath(inStream, "PEM");
certPath2 = new PkixCertPath(inStream, "PEM");
//Comparing both CertPathes
if (!certPath2.Equals(certPath1))
{
Fail("CertPath differ after encoding and decoding.");
}
//
// empty list test
//
list = new ArrayList();
// CertPath certPath = CertificateFactory.GetInstance("X.509","BC").generateCertPath(list);
PkixCertPath certPath = new PkixCertPath(list);
if (certPath.Certificates.Count != 0)
{
Fail("list wrong size.");
}
//
// exception tests
//
doTestExceptions();
}
public override string Name
{
get { return "CertPath"; }
}
public static void Main(
string[] args)
{
RunTest(new CertPathTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
// private class MyCertificate : X509Certificate
// {
// private readonly string type;
// private readonly byte[] encoding;
//
// public MyCertificate(string type, byte[] encoding)
//// : base(type)
// {
// this.type = type;
//
// // don't copy to allow null parameter in test
// this.encoding = encoding;
// }
//
// public override byte[] GetEncoded()
// {
// // do copy to force NPE in test
// return (byte[])encoding.Clone();
// }
//
// public override void Verify(AsymmetricKeyParameter publicKey)
// {
// }
//
// public override string ToString()
// {
// return "[My test Certificate, type: " + type + "]";
// }
//
// public override AsymmetricKeyParameter GetPublicKey()
// {
// throw new NotImplementedException();
//
//// return new PublicKey()
//// {
//// public string getAlgorithm()
//// {
//// return "TEST";
//// }
////
//// public byte[] getEncoded()
//// {
//// return new byte[] { (byte)1, (byte)2, (byte)3 };
//// }
////
//// public string getFormat()
//// {
//// return "TEST_FORMAT";
//// }
//// };
// }
// }
// private class MyCertPath : PkixCertPath
// {
// private readonly ArrayList certificates;
//
// private readonly ArrayList encodingNames;
//
// private readonly byte[] encoding;
//
// public MyCertPath(byte[] encoding)
// : base("MyEncoding")
// {
// this.encoding = encoding;
// certificates = new ArrayList();
// certificates.Add(new MyCertificate("MyEncoding", encoding));
// encodingNames = new ArrayList();
// encodingNames.Add("MyEncoding");
// }
//
// public override IList Certificates
// {
// get { return CollectionUtilities.ReadOnly(certificates); }
// }
//
// public override byte[] GetEncoded()
// {
// return (byte[])encoding.Clone();
// }
//
// public override byte[] GetEncoded(
// string encoding)
// {
// if (Type.Equals(encoding))
// {
// return (byte[])this.encoding.Clone();
// }
// throw new CertificateEncodingException("Encoding not supported: "
// + encoding);
// }
//
// public override IEnumerable Encodings
// {
// get { return new EnumerableProxy(encodingNames); }
// }
// }
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using EmployeeDirectory.Data;
namespace EmployeeDirectory.ViewModels
{
public class PersonViewModel : ViewModelBase
{
private IFavoritesRepository FavoritesRepository { get; set; }
public PersonViewModel (Person person, IFavoritesRepository favoritesRepository)
{
if (person == null)
throw new ArgumentNullException ("person");
if (favoritesRepository == null)
throw new ArgumentNullException ("favoritesRepository");
Person = person;
FavoritesRepository = favoritesRepository;
PropertyGroups = new ObservableCollection<PropertyGroup> ();
var general = new PropertyGroup ("General");
general.Add ("Title", person.Title, PropertyType.Generic);
general.Add ("Department", person.Department, PropertyType.Generic);
general.Add ("Company", person.Company, PropertyType.Generic);
general.Add ("Manager", person.Manager, PropertyType.Generic);
general.Add ("Description", person.Description, PropertyType.Generic);
if (general.Properties.Count > 0)
PropertyGroups.Add (general);
var phone = new PropertyGroup ("Phone");
foreach (var p in person.TelephoneNumbers) {
phone.Add ("Phone", p, PropertyType.Phone);
}
foreach (var p in person.HomeNumbers) {
phone.Add ("Home", p, PropertyType.Phone);
}
foreach (var p in person.MobileNumbers) {
phone.Add ("Mobile", p, PropertyType.Phone);
}
if (phone.Properties.Count > 0)
PropertyGroups.Add (phone);
var online = new PropertyGroup ("Online");
online.Add ("Email", person.Email, PropertyType.Email);
online.Add ("WebPage", CleanUrl (person.WebPage), PropertyType.Url);
online.Add ("Twitter", CleanTwitter (person.Twitter), PropertyType.Twitter);
if (online.Properties.Count > 0)
PropertyGroups.Add (online);
var address = new PropertyGroup ("Address");
address.Add ("Office", person.Office, PropertyType.Generic);
address.Add ("Address", AddressString, PropertyType.Address);
if (address.Properties.Count > 0)
PropertyGroups.Add (address);
}
private static string CleanUrl (string url)
{
var trimmed = (url ?? "").Trim ();
if (trimmed.Length == 0) return "";
var upper = trimmed.ToUpperInvariant ();
if (!upper.StartsWith ("HTTP")) {
return "http://" + trimmed;
} else {
return trimmed;
}
}
private static string CleanTwitter (string username)
{
var trimmed = (username ?? "").Trim ();
if (trimmed.Length == 0) return "";
if (!trimmed.StartsWith ("@")) {
return "@" + trimmed;
} else {
return trimmed;
}
}
#region View Data
public Person Person { get; private set; }
public ObservableCollection<PropertyGroup> PropertyGroups { get; private set; }
public bool IsFavorite {
get { return FavoritesRepository.IsFavorite (Person); }
}
public bool IsNotFavorite {
get { return !FavoritesRepository.IsFavorite (Person); }
}
string AddressString {
get {
var sb = new StringBuilder ();
if (!string.IsNullOrWhiteSpace (Person.Street))
sb.AppendLine (Person.Street.Trim ());
if (!string.IsNullOrWhiteSpace (Person.POBox))
sb.AppendLine (Person.POBox.Trim ());
if (!string.IsNullOrWhiteSpace (Person.City))
sb.AppendLine (Person.City.Trim ());
if (!string.IsNullOrWhiteSpace (Person.State))
sb.AppendLine (Person.State.Trim ());
if (!string.IsNullOrWhiteSpace (Person.PostalCode))
sb.AppendLine (Person.PostalCode.Trim ());
if (!string.IsNullOrWhiteSpace (Person.Country))
sb.AppendLine (Person.Country.Trim ());
return sb.ToString ();
}
}
public class PropertyGroup : IEnumerable<Property>
{
public string Title { get; private set; }
public ObservableCollection<Property> Properties { get; private set; }
public PropertyGroup (string title)
{
Title = title;
Properties = new ObservableCollection<Property> ();
}
public void Add (string name, string value, PropertyType type)
{
if (!string.IsNullOrWhiteSpace (value))
Properties.Add (new Property (name, value, type));
}
IEnumerator<Property> IEnumerable<Property>.GetEnumerator ()
{
return Properties.GetEnumerator ();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return Properties.GetEnumerator ();
}
}
public class Property
{
public string Name { get; private set; }
public string Value { get; private set; }
public PropertyType Type { get; private set; }
public Property (string name, string value, PropertyType type)
{
Name = name;
Value = value.Trim ();
Type = type;
}
public override string ToString ()
{
return string.Format ("{0} = {1}", Name, Value);
}
}
public enum PropertyType
{
Generic,
Phone,
Email,
Url,
Twitter,
Address,
}
#endregion
#region Commands
public void ToggleFavorite ()
{
if (FavoritesRepository.IsFavorite (Person)) {
FavoritesRepository.Delete (Person);
} else {
FavoritesRepository.InsertOrUpdate (Person);
}
OnPropertyChanged ("IsFavorite");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
// ReSharper disable InconsistentNaming
namespace IdmNet.Models
{
/// <summary>
/// Group -
/// </summary>
public class Group : IdmResource
{
/// <summary>
/// Parameterless CTOR
/// </summary>
public Group()
{
ObjectType = ForcedObjType = "Group";
}
/// <summary>
/// Build a Group object from a IdmResource object
/// </summary>
/// <param name="resource">base class</param>
public Group(IdmResource resource)
{
Attributes = resource.Attributes;
ObjectType = ForcedObjType = "Group";
if (resource.Creator == null)
return;
Creator = resource.Creator;
}
readonly string ForcedObjType;
/// <summary>
/// Object Type (can only be Group)
/// </summary>
[Required]
public override sealed string ObjectType
{
get { return GetAttrValue("ObjectType"); }
set
{
if (value != ForcedObjType)
throw new InvalidOperationException("Object Type of Group can only be 'Group'");
SetAttrValue("ObjectType", value);
}
}
/// <summary>
/// Account Name - User's log on name
/// </summary>
public string AccountName
{
get { return GetAttrValue("AccountName"); }
set {
SetAttrValue("AccountName", value);
}
}
/// <summary>
/// Computed Member - Resources in the set that are computed from the membership filter
/// </summary>
public List<IdmResource> ComputedMember
{
get { return GetMultiValuedAttr("ComputedMember", _theComputedMember); }
set { SetMultiValuedAttr("ComputedMember", out _theComputedMember, value); }
}
private List<IdmResource> _theComputedMember;
/// <summary>
/// Deferred Evaluation - Determines when evaluation of the group happens with respect to request processing - real-time or deferred.
/// </summary>
public bool? msidmDeferredEvaluation
{
get { return AttrToNullableBool("msidmDeferredEvaluation"); }
set {
SetAttrValue("msidmDeferredEvaluation", value.ToString());
}
}
/// <summary>
/// Displayed Owner -
/// </summary>
public Person DisplayedOwner
{
get { return GetAttr("DisplayedOwner", _theDisplayedOwner); }
set
{
_theDisplayedOwner = value;
SetAttrValue("DisplayedOwner", ObjectIdOrNull(value));
}
}
private Person _theDisplayedOwner;
/// <summary>
/// Domain - Choose the domain where you want to create the user account for this user
/// </summary>
[Required]
public string Domain
{
get { return GetAttrValue("Domain"); }
set {
SetAttrValue("Domain", value);
}
}
/// <summary>
/// Domain Configuration - A reference to a the parent Domain resource for this resource.
/// </summary>
public DomainConfiguration DomainConfiguration
{
get { return GetAttr("DomainConfiguration", _theDomainConfiguration); }
set
{
_theDomainConfiguration = value;
SetAttrValue("DomainConfiguration", ObjectIdOrNull(value));
}
}
private DomainConfiguration _theDomainConfiguration;
/// <summary>
/// E-mail - Primary email address for the group.
/// </summary>
public string Email
{
get { return GetAttrValue("Email"); }
set {
SetAttrValue("Email", value);
}
}
/// <summary>
/// E-mail Alias - E-mail alias. It is used to create the e-mail address
/// </summary>
public string MailNickname
{
get { return GetAttrValue("MailNickname"); }
set {
SetAttrValue("MailNickname", value);
}
}
/// <summary>
/// Filter - A predicate defining a subset of the resources.
/// </summary>
public string Filter
{
get { return GetAttrValue("Filter"); }
set {
SetAttrValue("Filter", value);
}
}
/// <summary>
/// Manually-managed Membership - Members in the group that are manually managed.
/// </summary>
public List<IdmResource> ExplicitMember
{
get { return GetMultiValuedAttr("ExplicitMember", _theExplicitMember); }
set { SetMultiValuedAttr("ExplicitMember", out _theExplicitMember, value); }
}
private List<IdmResource> _theExplicitMember;
/// <summary>
/// Membership Add Workflow -
/// </summary>
[Required]
public string MembershipAddWorkflow
{
get { return GetAttrValue("MembershipAddWorkflow"); }
set {
SetAttrValue("MembershipAddWorkflow", value);
}
}
/// <summary>
/// Membership Locked -
/// </summary>
[Required]
public bool MembershipLocked
{
get { return AttrToBool("MembershipLocked"); }
set {
SetAttrValue("MembershipLocked", value.ToString());
}
}
/// <summary>
/// Owner -
/// </summary>
public List<Person> Owner
{
get { return GetMultiValuedAttr("Owner", _theOwner); }
set { SetMultiValuedAttr("Owner", out _theOwner, value); }
}
private List<Person> _theOwner;
/// <summary>
/// PAM Enabled - A boolean value that specifies if a Group is enabled for PAM.
/// </summary>
public bool? msidmPamEnabled
{
get { return AttrToNullableBool("msidmPamEnabled"); }
set {
SetAttrValue("msidmPamEnabled", value.ToString());
}
}
/// <summary>
/// PAM Group Source Domain Name - The Source domain of a PAM group.
/// </summary>
public string msidmPamSourceDomainName
{
get { return GetAttrValue("msidmPamSourceDomainName"); }
set {
SetAttrValue("msidmPamSourceDomainName", value);
}
}
/// <summary>
/// PAM Group Source SID - A binary value that specifies the Source security identifier (SID) of a PAM Group. The SID is a unique value used to identify the group as a security principal.
/// </summary>
public byte[] msidmPamSourceSid
{
get { return GetAttr("msidmPamSourceSid") == null ? null : GetAttr("msidmPamSourceSid").ToBinary(); }
set { SetAttrValue("msidmPamSourceSid", value == null ? null : Convert.ToBase64String(value)); }
}
/// <summary>
/// PAM Source Group Name - The name of the group that is shadowed by this group
/// </summary>
public string msidmPamSourceGroupName
{
get { return GetAttrValue("msidmPamSourceGroupName"); }
set {
SetAttrValue("msidmPamSourceGroupName", value);
}
}
/// <summary>
/// Resource SID - A binary value that specifies the security identifier (SID) of the user. The SID is a unique value used to identify the user as a security principal.
/// </summary>
public byte[] ObjectSID
{
get { return GetAttr("ObjectSID") == null ? null : GetAttr("ObjectSID").ToBinary(); }
set { SetAttrValue("ObjectSID", value == null ? null : Convert.ToBase64String(value)); }
}
/// <summary>
/// Scope -
/// </summary>
[Required]
public string Scope
{
get { return GetAttrValue("Scope"); }
set {
SetAttrValue("Scope", value);
}
}
/// <summary>
/// SID History - Contains previous SIDs used for the resource if the resource was moved from another domain.
/// </summary>
public List<byte[]> SIDHistory
{
get { return GetAttr("SIDHistory")?.ToBinaries(); }
set { SetAttrValues("SIDHistory", value?.Select(Convert.ToBase64String).ToList()); }
}
/// <summary>
/// Temporal - Defined by a filter that matches resources based on date and time attributes
/// </summary>
public bool? Temporal
{
get { return AttrToNullableBool("Temporal"); }
set {
SetAttrValue("Temporal", value.ToString());
}
}
/// <summary>
/// Type -
/// </summary>
[Required]
public string Type
{
get { return GetAttrValue("Type"); }
set {
SetAttrValue("Type", value);
}
}
/// <summary>
/// Uses SID history - Indicates if the PAM Group uses SID history.
/// </summary>
public bool? msidmPamUsesSIDHistory
{
get { return AttrToNullableBool("msidmPamUsesSIDHistory"); }
set {
SetAttrValue("msidmPamUsesSIDHistory", value.ToString());
}
}
}
}
| |
using MatterHackers.Agg.Image;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// [email protected]
// 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.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for high precision colors 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 System;
using image_filter_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_filter_scale_e;
using image_subpixel_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_subpixel_scale_e;
namespace MatterHackers.Agg
{
// it should be easy to write a 90 rotating or mirroring filter too. LBB 2012/01/14
public class span_image_filter_rgb_nn_stepXby1 : span_image_filter
{
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
public span_image_filter_rgb_nn_stepXby1(IImageBufferAccessor sourceAccessor, ISpanInterpolator spanInterpolator)
: base(sourceAccessor, spanInterpolator, null)
{
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ImageBuffer SourceRenderingBuffer = (ImageBuffer)GetImageBufferAccessor().SourceImage;
if (SourceRenderingBuffer.BitDepth != 24)
{
throw new NotSupportedException("The source is expected to be 32 bit.");
}
ISpanInterpolator spanInterpolator = interpolator();
spanInterpolator.begin(x + filter_dx_dbl(), y + filter_dy_dbl(), len);
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int bufferIndex;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
byte[] fg_ptr = SourceRenderingBuffer.GetBuffer();
#if USE_UNSAFE_CODE
unsafe
{
fixed (byte* pSource = fg_ptr)
{
do
{
span[spanIndex++] = *(RGBA_Bytes*)&(pSource[bufferIndex]);
bufferIndex += 4;
} while (--len != 0);
}
}
#else
Color color = Color.White;
do
{
color.blue = fg_ptr[bufferIndex++];
color.green = fg_ptr[bufferIndex++];
color.red = fg_ptr[bufferIndex++];
span[spanIndex++] = color;
} while (--len != 0);
#endif
}
}
//===============================================span_image_filter_rgb_nn
public class span_image_filter_rgb_nn : span_image_filter
{
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
//--------------------------------------------------------------------
public span_image_filter_rgb_nn(IImageBufferAccessor src, ISpanInterpolator inter)
: base(src, inter, null)
{
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ImageBuffer SourceRenderingBuffer = (ImageBuffer)GetImageBufferAccessor().SourceImage;
if (SourceRenderingBuffer.BitDepth != 24)
{
throw new NotSupportedException("The source is expected to be 32 bit.");
}
ISpanInterpolator spanInterpolator = interpolator();
spanInterpolator.begin(x + filter_dx_dbl(), y + filter_dy_dbl(), len);
int offset;
byte[] fg_ptr = SourceRenderingBuffer.GetBuffer(out offset);
do
{
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int bufferIndex;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
Color color;
color.blue = fg_ptr[bufferIndex++];
color.green = fg_ptr[bufferIndex++];
color.red = fg_ptr[bufferIndex++];
color.alpha = 255;
span[spanIndex] = color;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
};
//==========================================span_image_filter_rgb_bilinear
public class span_image_filter_rgb_bilinear : span_image_filter
{
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
//--------------------------------------------------------------------
public span_image_filter_rgb_bilinear(IImageBufferAccessor src,
ISpanInterpolator inter)
: base(src, inter, null)
{
if (src.SourceImage.GetBytesBetweenPixelsInclusive() != 3)
{
throw new System.NotSupportedException("span_image_filter_rgb must have a 24 bit DestImage");
}
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
ImageBuffer SourceRenderingBuffer = (ImageBuffer)base.GetImageBufferAccessor().SourceImage;
ISpanInterpolator spanInterpolator = base.interpolator();
int bufferIndex;
byte[] fg_ptr = SourceRenderingBuffer.GetBuffer(out bufferIndex);
unchecked
{
do
{
int tempR;
int tempG;
int tempB;
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= base.filter_dx_int();
y_hr -= base.filter_dy_int();
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int weight;
tempR =
tempG =
tempB = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
bufferIndex += 3;
weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
y_lr++;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
bufferIndex += 3;
weight = (x_hr * y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempR >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
tempG >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
tempB >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
Color color;
color.red = (byte)tempR;
color.green = (byte)tempG;
color.blue = (byte)tempB;
color.alpha = 255;
span[spanIndex] = color;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
}
private void BlendInFilterPixel(int[] fg, ref int src_alpha, int back_r, int back_g, int back_b, int back_a, ImageBuffer SourceRenderingBuffer, int maxx, int maxy, int x_lr, int y_lr, int weight)
{
throw new NotImplementedException(); /*
int[] fg_ptr;
int bufferIndex;
unchecked
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex);
fg[0] += (weight * (fg_ptr[bufferIndex] & (int)RGBA_Bytes.m_R) >> (int)RGBA_Bytes.Shift.R);
fg[1] += (weight * (fg_ptr[bufferIndex] & (int)RGBA_Bytes.m_G) >> (int)RGBA_Bytes.Shift.G);
fg[2] += (weight * (fg_ptr[bufferIndex] & (int)RGBA_Bytes.m_G) >> (int)RGBA_Bytes.Shift.B);
src_alpha += weight * base_mask;
}
else
{
fg[0] += (weight * back_r);
fg[1] += (weight * back_g);
fg[2] += (weight * back_b);
src_alpha += back_a * weight;
}
}
*/
}
};
//=====================================span_image_filter_rgb_bilinear_clip
public class span_image_filter_rgb_bilinear_clip : span_image_filter
{
private Color m_OutsideSourceColor;
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
//--------------------------------------------------------------------
public span_image_filter_rgb_bilinear_clip(IImageBufferAccessor src,
IColorType back_color,
ISpanInterpolator inter)
: base(src, inter, null)
{
m_OutsideSourceColor = back_color.ToColor();
}
public IColorType background_color()
{
return m_OutsideSourceColor;
}
public void background_color(IColorType v)
{
m_OutsideSourceColor = v.ToColor();
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int[] accumulatedColor = new int[3];
int sourceAlpha;
int back_r = m_OutsideSourceColor.red;
int back_g = m_OutsideSourceColor.green;
int back_b = m_OutsideSourceColor.blue;
int back_a = m_OutsideSourceColor.alpha;
int bufferIndex;
byte[] fg_ptr;
ImageBuffer SourceRenderingBuffer = (ImageBuffer)base.GetImageBufferAccessor().SourceImage;
int maxx = (int)SourceRenderingBuffer.Width - 1;
int maxy = (int)SourceRenderingBuffer.Height - 1;
ISpanInterpolator spanInterpolator = base.interpolator();
unchecked
{
do
{
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= base.filter_dx_int();
y_hr -= base.filter_dy_int();
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int weight;
if (x_lr >= 0 && y_lr >= 0 &&
x_lr < maxx && y_lr < maxy)
{
accumulatedColor[0] =
accumulatedColor[1] =
accumulatedColor[2] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
bufferIndex += 3;
weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
y_lr++;
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
bufferIndex += 3;
weight = (x_hr * y_hr);
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
accumulatedColor[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
sourceAlpha = base_mask;
}
else
{
if (x_lr < -1 || y_lr < -1 ||
x_lr > maxx || y_lr > maxy)
{
accumulatedColor[0] = back_r;
accumulatedColor[1] = back_g;
accumulatedColor[2] = back_b;
sourceAlpha = back_a;
}
else
{
accumulatedColor[0] =
accumulatedColor[1] =
accumulatedColor[2] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
sourceAlpha = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
BlendInFilterPixel(accumulatedColor, ref sourceAlpha, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
x_lr++;
weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
BlendInFilterPixel(accumulatedColor, ref sourceAlpha, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
x_lr--;
y_lr++;
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
BlendInFilterPixel(accumulatedColor, ref sourceAlpha, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
x_lr++;
weight = (x_hr * y_hr);
BlendInFilterPixel(accumulatedColor, ref sourceAlpha, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
accumulatedColor[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
sourceAlpha >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
}
}
span[spanIndex].red = (byte)accumulatedColor[0];
span[spanIndex].green = (byte)accumulatedColor[1];
span[spanIndex].blue = (byte)accumulatedColor[2];
span[spanIndex].alpha = (byte)sourceAlpha;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
}
private void BlendInFilterPixel(int[] accumulatedColor, ref int sourceAlpha, int back_r, int back_g, int back_b, int back_a, ImageBuffer SourceRenderingBuffer, int maxx, int maxy, int x_lr, int y_lr, int weight)
{
byte[] fg_ptr;
unchecked
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
int bufferIndex;
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex);
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
sourceAlpha += weight * base_mask;
}
else
{
accumulatedColor[0] += back_r * weight;
accumulatedColor[1] += back_g * weight;
accumulatedColor[2] += back_b * weight;
sourceAlpha += back_a * weight;
}
}
}
};
//===================================================span_image_filter_rgb
public class span_image_filter_rgb : span_image_filter
{
private const int base_mask = 255;
//--------------------------------------------------------------------
public span_image_filter_rgb(IImageBufferAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter)
: base(src, inter, filter)
{
if (src.SourceImage.GetBytesBetweenPixelsInclusive() != 3)
{
throw new System.NotSupportedException("span_image_filter_rgb must have a 24 bit DestImage");
}
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int f_r, f_g, f_b;
byte[] fg_ptr;
int diameter = m_filter.diameter();
int start = m_filter.start();
int[] weight_array = m_filter.weight_array();
int x_count;
int weight_y;
ISpanInterpolator spanInterpolator = base.interpolator();
do
{
spanInterpolator.coordinates(out x, out y);
x -= base.filter_dx_int();
y -= base.filter_dy_int();
int x_hr = x;
int y_hr = y;
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
f_b = f_g = f_r = (int)image_filter_scale_e.image_filter_scale / 2;
int x_fract = x_hr & (int)image_subpixel_scale_e.image_subpixel_mask;
int y_count = diameter;
y_hr = (int)image_subpixel_scale_e.image_subpixel_mask - (y_hr & (int)image_subpixel_scale_e.image_subpixel_mask);
int bufferIndex;
fg_ptr = GetImageBufferAccessor().span(x_lr + start, y_lr + start, diameter, out bufferIndex);
for (; ; )
{
x_count = (int)diameter;
weight_y = weight_array[y_hr];
x_hr = (int)image_subpixel_scale_e.image_subpixel_mask - x_fract;
for (; ; )
{
int weight = (weight_y * weight_array[x_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
(int)image_filter_scale_e.image_filter_shift;
f_b += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
f_g += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
f_r += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
if (--x_count == 0) break;
x_hr += (int)image_subpixel_scale_e.image_subpixel_scale;
GetImageBufferAccessor().next_x(out bufferIndex);
}
if (--y_count == 0) break;
y_hr += (int)image_subpixel_scale_e.image_subpixel_scale;
fg_ptr = GetImageBufferAccessor().next_y(out bufferIndex);
}
f_b >>= (int)image_filter_scale_e.image_filter_shift;
f_g >>= (int)image_filter_scale_e.image_filter_shift;
f_r >>= (int)image_filter_scale_e.image_filter_shift;
unchecked
{
if ((uint)f_b > base_mask)
{
if (f_b < 0) f_b = 0;
if (f_b > base_mask) f_b = (int)base_mask;
}
if ((uint)f_g > base_mask)
{
if (f_g < 0) f_g = 0;
if (f_g > base_mask) f_g = (int)base_mask;
}
if ((uint)f_r > base_mask)
{
if (f_r < 0) f_r = 0;
if (f_r > base_mask) f_r = (int)base_mask;
}
}
span[spanIndex].alpha = (byte)base_mask;
span[spanIndex].red = (byte)f_b;
span[spanIndex].green = (byte)f_g;
span[spanIndex].blue = (byte)f_r;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
};
//===============================================span_image_filter_rgb_2x2
public class span_image_filter_rgb_2x2 : span_image_filter
{
private const int base_mask = 255;
//--------------------------------------------------------------------
public span_image_filter_rgb_2x2(IImageBufferAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter)
: base(src, inter, filter)
{
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
throw new NotImplementedException(); /*
ISpanInterpolator spanInterpolator = base.interpolator();
spanInterpolator.begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int[] fg = new int[3];
int[] fg_ptr;
int bufferIndex;
int[] weight_array = filter().weight_array();
int weightArrayIndex = ((filter().diameter() / 2 - 1) << (int)image_subpixel_scale_e.image_subpixel_shift);
do
{
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= filter_dx_int();
y_hr -= filter_dy_int();
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int weight;
fg[0] = fg[1] = fg[2] = (int)image_filter_scale_e.image_filter_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
fg_ptr = source().span(x_lr, y_lr, 2, out bufferIndex);
weight = ((weight_array[x_hr + (int)image_subpixel_scale_e.image_subpixel_scale] *
weight_array[y_hr + (int)image_subpixel_scale_e.image_subpixel_scale] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
(int)image_filter_scale_e.image_filter_shift);
fg[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
fg[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
fg[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
fg_ptr = source().next_x(out bufferIndex);
weight = ((weight_array[x_hr] *
weight_array[y_hr + (int)image_subpixel_scale_e.image_subpixel_scale] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
(int)image_filter_scale_e.image_filter_shift);
fg[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
fg[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
fg[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
fg_ptr = source().next_y(out bufferIndex);
weight = ((weight_array[x_hr + (int)image_subpixel_scale_e.image_subpixel_scale] *
weight_array[y_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
(int)image_filter_scale_e.image_filter_shift);
fg[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
fg[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
fg[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
fg_ptr = source().next_x(out bufferIndex);
weight = ((weight_array[x_hr] *
weight_array[y_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
(int)image_filter_scale_e.image_filter_shift);
fg[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
fg[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
fg[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
fg[0] >>= (int)image_filter_scale_e.image_filter_shift;
fg[1] >>= (int)image_filter_scale_e.image_filter_shift;
fg[2] >>= (int)image_filter_scale_e.image_filter_shift;
if (fg[0] > base_mask) fg[0] = (int)base_mask;
if (fg[1] > base_mask) fg[1] = (int)base_mask;
if (fg[2] > base_mask) fg[2] = (int)base_mask;
span[spanIndex].m_ARGBData = base_mask << (int)RGBA_Bytes.Shift.A | fg[0] << (int)RGBA_Bytes.Shift.R | fg[1] << (int)RGBA_Bytes.Shift.G | fg[2] << (int)RGBA_Bytes.Shift.B;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
*/
}
};
/*
//==========================================span_image_resample_rgb_affine
template<class Source>
class span_image_resample_rgb_affine :
public span_image_resample_affine<Source>
{
public:
typedef Source source_type;
typedef typename source_type::color_type color_type;
typedef typename source_type::order_type order_type;
typedef span_image_resample_affine<source_type> base_type;
typedef typename base_type::interpolator_type interpolator_type;
typedef typename color_type::value_type value_type;
typedef typename color_type::long_type long_type;
enum base_scale_e
{
base_shift = 8,//color_type::base_shift,
base_mask = 255,//color_type::base_mask,
downscale_shift = image_filter_shift
};
//--------------------------------------------------------------------
span_image_resample_rgb_affine() {}
span_image_resample_rgb_affine(source_type& src,
interpolator_type& inter,
const ImageFilterLookUpTable& filter) :
base(src, inter, filter)
{}
//--------------------------------------------------------------------
void generate(color_type* span, int x, int y, unsigned len)
{
base_type::interpolator().begin(x + base_type::filter_dx_dbl(),
y + base_type::filter_dy_dbl(), len);
long_type fg[3];
int diameter = base_type::filter().diameter();
int filter_scale = diameter << image_subpixel_shift;
int radius_x = (diameter * base_type::m_rx) >> 1;
int radius_y = (diameter * base_type::m_ry) >> 1;
int len_x_lr =
(diameter * base_type::m_rx + image_subpixel_mask) >>
image_subpixel_shift;
const int16* weight_array = base_type::filter().weight_array();
do
{
base_type::interpolator().coordinates(&x, &y);
x += base_type::filter_dx_int() - radius_x;
y += base_type::filter_dy_int() - radius_y;
fg[0] = fg[1] = fg[2] = image_filter_scale / 2;
int y_lr = y >> image_subpixel_shift;
int y_hr = ((image_subpixel_mask - (y & image_subpixel_mask)) *
base_type::m_ry_inv) >>
image_subpixel_shift;
int total_weight = 0;
int x_lr = x >> image_subpixel_shift;
int x_hr = ((image_subpixel_mask - (x & image_subpixel_mask)) *
base_type::m_rx_inv) >>
image_subpixel_shift;
int x_hr2 = x_hr;
const value_type* fg_ptr =
source().pix_ptr(x_lr, y_lr, len_x_lr);
for(;;)
{
int weight_y = weight_array[y_hr];
x_hr = x_hr2;
for(;;)
{
int weight = (weight_y * weight_array[x_hr] +
image_filter_scale / 2) >>
downscale_shift;
fg[0] += *fg_ptr++ * weight;
fg[1] += *fg_ptr++ * weight;
fg[2] += *fg_ptr * weight;
total_weight += weight;
x_hr += base_type::m_rx_inv;
if(x_hr >= filter_scale) break;
fg_ptr = SourceRenderingBuffer.next_x();
}
y_hr += base_type::m_ry_inv;
if(y_hr >= filter_scale) break;
fg_ptr = SourceRenderingBuffer.next_y();
}
fg[0] /= total_weight;
fg[1] /= total_weight;
fg[2] /= total_weight;
if(fg[0] < 0) fg[0] = 0;
if(fg[1] < 0) fg[1] = 0;
if(fg[2] < 0) fg[2] = 0;
if(fg[order_type::R] > base_mask) fg[order_type::R] = base_mask;
if(fg[order_type::G] > base_mask) fg[order_type::G] = base_mask;
if(fg[order_type::B] > base_mask) fg[order_type::B] = base_mask;
span->r = (value_type)fg[order_type::R];
span->g = (value_type)fg[order_type::G];
span->b = (value_type)fg[order_type::B];
span->a = base_mask;
span++;
++base_type::interpolator();
} while(--len);
}
};
*/
//=================================================span_image_resample_rgb
public class span_image_resample_rgb
: span_image_resample
{
private const int base_mask = 255;
private const int downscale_shift = (int)ImageFilterLookUpTable.image_filter_scale_e.image_filter_shift;
//--------------------------------------------------------------------
public span_image_resample_rgb(IImageBufferAccessor src,
ISpanInterpolator inter,
ImageFilterLookUpTable filter) :
base(src, inter, filter)
{
if (src.SourceImage.GetRecieveBlender().NumPixelBits != 24)
{
throw new System.FormatException("You have to use a rgb blender with span_image_resample_rgb");
}
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ISpanInterpolator spanInterpolator = base.interpolator();
spanInterpolator.begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int[] fg = new int[3];
byte[] fg_ptr;
int[] weightArray = filter().weight_array();
int diameter = (int)base.filter().diameter();
int filter_scale = diameter << (int)image_subpixel_scale_e.image_subpixel_shift;
int[] weight_array = weightArray;
do
{
int rx;
int ry;
int rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale;
int ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale;
spanInterpolator.coordinates(out x, out y);
spanInterpolator.local_scale(out rx, out ry);
base.adjust_scale(ref rx, ref ry);
rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / rx;
ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / ry;
int radius_x = (diameter * rx) >> 1;
int radius_y = (diameter * ry) >> 1;
int len_x_lr =
(diameter * rx + (int)image_subpixel_scale_e.image_subpixel_mask) >>
(int)(int)image_subpixel_scale_e.image_subpixel_shift;
x += base.filter_dx_int() - radius_x;
y += base.filter_dy_int() - radius_y;
fg[0] = fg[1] = fg[2] = (int)image_filter_scale_e.image_filter_scale / 2;
int y_lr = y >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int y_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (y & (int)image_subpixel_scale_e.image_subpixel_mask)) *
ry_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int total_weight = 0;
int x_lr = x >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int x_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (x & (int)image_subpixel_scale_e.image_subpixel_mask)) *
rx_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int x_hr2 = x_hr;
int sourceIndex;
fg_ptr = base.GetImageBufferAccessor().span(x_lr, y_lr, len_x_lr, out sourceIndex);
for (; ; )
{
int weight_y = weight_array[y_hr];
x_hr = x_hr2;
for (; ; )
{
int weight = (weight_y * weight_array[x_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
downscale_shift;
fg[0] += fg_ptr[sourceIndex + ImageBuffer.OrderR] * weight;
fg[1] += fg_ptr[sourceIndex + ImageBuffer.OrderG] * weight;
fg[2] += fg_ptr[sourceIndex + ImageBuffer.OrderB] * weight;
total_weight += weight;
x_hr += rx_inv;
if (x_hr >= filter_scale) break;
fg_ptr = base.GetImageBufferAccessor().next_x(out sourceIndex);
}
y_hr += ry_inv;
if (y_hr >= filter_scale)
{
break;
}
fg_ptr = base.GetImageBufferAccessor().next_y(out sourceIndex);
}
fg[0] /= total_weight;
fg[1] /= total_weight;
fg[2] /= total_weight;
if (fg[0] < 0) fg[0] = 0;
if (fg[1] < 0) fg[1] = 0;
if (fg[2] < 0) fg[2] = 0;
if (fg[0] > base_mask) fg[0] = base_mask;
if (fg[1] > base_mask) fg[1] = base_mask;
if (fg[2] > base_mask) fg[2] = base_mask;
span[spanIndex].alpha = base_mask;
span[spanIndex].red = (byte)fg[0];
span[spanIndex].green = (byte)fg[1];
span[spanIndex].blue = (byte)fg[2];
spanIndex++;
interpolator().Next();
} while (--len != 0);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace DrillTime.WebApiNoEf.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections
{
public sealed partial class BitArray : System.Collections.ICollection, System.Collections.IEnumerable
{
public BitArray(bool[] values) { }
public BitArray(byte[] bytes) { }
public BitArray(System.Collections.BitArray bits) { }
public BitArray(int length) { }
public BitArray(int length, bool defaultValue) { }
public BitArray(int[] values) { }
public bool this[int index] { get { return default(bool); } set { } }
public int Length { get { return default(int); } set { } }
int System.Collections.ICollection.Count { get { return default(int); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public System.Collections.BitArray And(System.Collections.BitArray value) { return default(System.Collections.BitArray); }
public bool Get(int index) { return default(bool); }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public System.Collections.BitArray Not() { return default(System.Collections.BitArray); }
public System.Collections.BitArray Or(System.Collections.BitArray value) { return default(System.Collections.BitArray); }
public void Set(int index, bool value) { }
public void SetAll(bool value) { }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
public System.Collections.BitArray Xor(System.Collections.BitArray value) { return default(System.Collections.BitArray); }
}
public static partial class StructuralComparisons
{
public static System.Collections.IComparer StructuralComparer { get { return default(System.Collections.IComparer); } }
public static System.Collections.IEqualityComparer StructuralEqualityComparer { get { return default(System.Collections.IEqualityComparer); } }
}
}
namespace System.Collections.Generic
{
public abstract partial class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer
{
protected Comparer() { }
public static System.Collections.Generic.Comparer<T> Default { get { return default(System.Collections.Generic.Comparer<T>); } }
public abstract int Compare(T x, T y);
public static System.Collections.Generic.Comparer<T> Create(System.Comparison<T> comparison) { return default(System.Collections.Generic.Comparer<T>); }
int System.Collections.IComparer.Compare(object x, object y) { return default(int); }
}
public partial class Dictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public Dictionary() { }
public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public Dictionary(int capacity) { }
public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { return default(System.Collections.Generic.IEqualityComparer<TKey>); } }
public int Count { get { return default(int); } }
public TValue this[TKey key] { get { return default(TValue); } set { } }
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get { return default(System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection); } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } }
bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } }
object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } }
public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get { return default(System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection); } }
public void Add(TKey key, TValue value) { }
public void Clear() { }
public bool ContainsKey(TKey key) { return default(bool); }
public bool ContainsValue(TValue value) { return default(bool); }
public System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator GetEnumerator() { return default(System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator); }
public bool Remove(TKey key) { return default(bool); }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { return default(bool); }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable
{
public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { return default(System.Collections.Generic.KeyValuePair<TKey, TValue>); } }
System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { return default(System.Collections.DictionaryEntry); } }
object System.Collections.IDictionaryEnumerator.Key { get { return default(object); } }
object System.Collections.IDictionaryEnumerator.Value { get { return default(object); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable
{
public KeyCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { }
public int Count { get { return default(int); } }
bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void CopyTo(TKey[] array, int index) { }
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator); }
void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { }
void System.Collections.Generic.ICollection<TKey>.Clear() { }
bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { return default(bool); }
bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { return default(bool); }
System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TKey>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable
{
public TKey Current { get { return default(TKey); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ValueCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { }
public int Count { get { return default(int); } }
bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void CopyTo(TValue[] array, int index) { }
public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator); }
void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { }
void System.Collections.Generic.ICollection<TValue>.Clear() { }
bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { return default(bool); }
bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { return default(bool); }
System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TValue>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable
{
public TValue Current { get { return default(TValue); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
}
public abstract partial class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer
{
protected EqualityComparer() { }
public static System.Collections.Generic.EqualityComparer<T> Default { get { return default(System.Collections.Generic.EqualityComparer<T>); } }
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
bool System.Collections.IEqualityComparer.Equals(object x, object y) { return default(bool); }
int System.Collections.IEqualityComparer.GetHashCode(object obj) { return default(int); }
}
public partial class HashSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.IEnumerable
{
public HashSet() { }
public HashSet(System.Collections.Generic.IEnumerable<T> collection) { }
public HashSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer) { }
public HashSet(System.Collections.Generic.IEqualityComparer<T> comparer) { }
public System.Collections.Generic.IEqualityComparer<T> Comparer { get { return default(System.Collections.Generic.IEqualityComparer<T>); } }
public int Count { get { return default(int); } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } }
public bool Add(T item) { return default(bool); }
public void Clear() { }
public bool Contains(T item) { return default(bool); }
public void CopyTo(T[] array) { }
public void CopyTo(T[] array, int arrayIndex) { }
public void CopyTo(T[] array, int arrayIndex, int count) { }
public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.HashSet<T>.Enumerator); }
public void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { }
public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool Remove(T item) { return default(bool); }
public int RemoveWhere(System.Predicate<T> match) { return default(int); }
public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ICollection<T>.Add(T item) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public void TrimExcess() { }
public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { return default(T); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class LinkedList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public LinkedList() { }
public LinkedList(System.Collections.Generic.IEnumerable<T> collection) { }
public int Count { get { return default(int); } }
public System.Collections.Generic.LinkedListNode<T> First { get { return default(System.Collections.Generic.LinkedListNode<T>); } }
public System.Collections.Generic.LinkedListNode<T> Last { get { return default(System.Collections.Generic.LinkedListNode<T>); } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public System.Collections.Generic.LinkedListNode<T> AddAfter(System.Collections.Generic.LinkedListNode<T> node, T value) { return default(System.Collections.Generic.LinkedListNode<T>); }
public void AddAfter(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { }
public System.Collections.Generic.LinkedListNode<T> AddBefore(System.Collections.Generic.LinkedListNode<T> node, T value) { return default(System.Collections.Generic.LinkedListNode<T>); }
public void AddBefore(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { }
public System.Collections.Generic.LinkedListNode<T> AddFirst(T value) { return default(System.Collections.Generic.LinkedListNode<T>); }
public void AddFirst(System.Collections.Generic.LinkedListNode<T> node) { }
public System.Collections.Generic.LinkedListNode<T> AddLast(T value) { return default(System.Collections.Generic.LinkedListNode<T>); }
public void AddLast(System.Collections.Generic.LinkedListNode<T> node) { }
public void Clear() { }
public bool Contains(T value) { return default(bool); }
public void CopyTo(T[] array, int index) { }
public System.Collections.Generic.LinkedListNode<T> Find(T value) { return default(System.Collections.Generic.LinkedListNode<T>); }
public System.Collections.Generic.LinkedListNode<T> FindLast(T value) { return default(System.Collections.Generic.LinkedListNode<T>); }
public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.LinkedList<T>.Enumerator); }
public bool Remove(T value) { return default(bool); }
public void Remove(System.Collections.Generic.LinkedListNode<T> node) { }
public void RemoveFirst() { }
public void RemoveLast() { }
void System.Collections.Generic.ICollection<T>.Add(T value) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { return default(T); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public sealed partial class LinkedListNode<T>
{
public LinkedListNode(T value) { }
public System.Collections.Generic.LinkedList<T> List { get { return default(System.Collections.Generic.LinkedList<T>); } }
public System.Collections.Generic.LinkedListNode<T> Next { get { return default(System.Collections.Generic.LinkedListNode<T>); } }
public System.Collections.Generic.LinkedListNode<T> Previous { get { return default(System.Collections.Generic.LinkedListNode<T>); } }
public T Value { get { return default(T); } set { } }
}
public partial class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
public List() { }
public List(System.Collections.Generic.IEnumerable<T> collection) { }
public List(int capacity) { }
public int Capacity { get { return default(int); } set { } }
public int Count { get { return default(int); } }
public T this[int index] { get { return default(T); } set { } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IList.IsFixedSize { get { return default(bool); } }
bool System.Collections.IList.IsReadOnly { get { return default(bool); } }
object System.Collections.IList.this[int index] { get { return default(object); } set { } }
public void Add(T item) { }
public void AddRange(System.Collections.Generic.IEnumerable<T> collection) { }
public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly() { return default(System.Collections.ObjectModel.ReadOnlyCollection<T>); }
public int BinarySearch(T item) { return default(int); }
public int BinarySearch(T item, System.Collections.Generic.IComparer<T> comparer) { return default(int); }
public int BinarySearch(int index, int count, T item, System.Collections.Generic.IComparer<T> comparer) { return default(int); }
public void Clear() { }
public bool Contains(T item) { return default(bool); }
public void CopyTo(T[] array) { }
public void CopyTo(T[] array, int arrayIndex) { }
public void CopyTo(int index, T[] array, int arrayIndex, int count) { }
public bool Exists(System.Predicate<T> match) { return default(bool); }
public T Find(System.Predicate<T> match) { return default(T); }
public System.Collections.Generic.List<T> FindAll(System.Predicate<T> match) { return default(System.Collections.Generic.List<T>); }
public int FindIndex(int startIndex, int count, System.Predicate<T> match) { return default(int); }
public int FindIndex(int startIndex, System.Predicate<T> match) { return default(int); }
public int FindIndex(System.Predicate<T> match) { return default(int); }
public T FindLast(System.Predicate<T> match) { return default(T); }
public int FindLastIndex(int startIndex, int count, System.Predicate<T> match) { return default(int); }
public int FindLastIndex(int startIndex, System.Predicate<T> match) { return default(int); }
public int FindLastIndex(System.Predicate<T> match) { return default(int); }
public void ForEach(System.Action<T> action) { }
public System.Collections.Generic.List<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.List<T>.Enumerator); }
public System.Collections.Generic.List<T> GetRange(int index, int count) { return default(System.Collections.Generic.List<T>); }
public int IndexOf(T item) { return default(int); }
public int IndexOf(T item, int index) { return default(int); }
public int IndexOf(T item, int index, int count) { return default(int); }
public void Insert(int index, T item) { }
public void InsertRange(int index, System.Collections.Generic.IEnumerable<T> collection) { }
public int LastIndexOf(T item) { return default(int); }
public int LastIndexOf(T item, int index) { return default(int); }
public int LastIndexOf(T item, int index, int count) { return default(int); }
public bool Remove(T item) { return default(bool); }
public int RemoveAll(System.Predicate<T> match) { return default(int); }
public void RemoveAt(int index) { }
public void RemoveRange(int index, int count) { }
public void Reverse() { }
public void Reverse(int index, int count) { }
public void Sort() { }
public void Sort(System.Collections.Generic.IComparer<T> comparer) { }
public void Sort(System.Comparison<T> comparison) { }
public void Sort(int index, int count, System.Collections.Generic.IComparer<T> comparer) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
int System.Collections.IList.Add(object item) { return default(int); }
bool System.Collections.IList.Contains(object item) { return default(bool); }
int System.Collections.IList.IndexOf(object item) { return default(int); }
void System.Collections.IList.Insert(int index, object item) { }
void System.Collections.IList.Remove(object item) { }
public T[] ToArray() { return default(T[]); }
public void TrimExcess() { }
public bool TrueForAll(System.Predicate<T> match) { return default(bool); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { return default(T); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public Queue() { }
public Queue(System.Collections.Generic.IEnumerable<T> collection) { }
public Queue(int capacity) { }
public int Count { get { return default(int); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void Clear() { }
public bool Contains(T item) { return default(bool); }
public void CopyTo(T[] array, int arrayIndex) { }
public T Dequeue() { return default(T); }
public void Enqueue(T item) { }
public System.Collections.Generic.Queue<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.Queue<T>.Enumerator); }
public T Peek() { return default(T); }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public T[] ToArray() { return default(T[]); }
public void TrimExcess() { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { return default(T); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class SortedDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public SortedDictionary() { }
public SortedDictionary(System.Collections.Generic.IComparer<TKey> comparer) { }
public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { }
public System.Collections.Generic.IComparer<TKey> Comparer { get { return default(System.Collections.Generic.IComparer<TKey>); } }
public int Count { get { return default(int); } }
public TValue this[TKey key] { get { return default(TValue); } set { } }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection Keys { get { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection); } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } }
bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } }
object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection Values { get { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection); } }
public void Add(TKey key, TValue value) { }
public void Clear() { }
public bool ContainsKey(TKey key) { return default(bool); }
public bool ContainsValue(TValue value) { return default(bool); }
public void CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator); }
public bool Remove(TKey key) { return default(bool); }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { return default(bool); }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable
{
public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { return default(System.Collections.Generic.KeyValuePair<TKey, TValue>); } }
System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { return default(System.Collections.DictionaryEntry); } }
object System.Collections.IDictionaryEnumerator.Key { get { return default(object); } }
object System.Collections.IDictionaryEnumerator.Value { get { return default(object); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable
{
public KeyCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { }
public int Count { get { return default(int); } }
bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void CopyTo(TKey[] array, int index) { }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator); }
void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { }
void System.Collections.Generic.ICollection<TKey>.Clear() { }
bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { return default(bool); }
bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { return default(bool); }
System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TKey>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable
{
public TKey Current { get { return default(TKey); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ValueCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { }
public int Count { get { return default(int); } }
bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void CopyTo(TValue[] array, int index) { }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator); }
void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { }
void System.Collections.Generic.ICollection<TValue>.Clear() { }
bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { return default(bool); }
bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { return default(bool); }
System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TValue>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable
{
public TValue Current { get { return default(TValue); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
}
public partial class SortedList<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public SortedList() { }
public SortedList(System.Collections.Generic.IComparer<TKey> comparer) { }
public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { }
public SortedList(int capacity) { }
public SortedList(int capacity, System.Collections.Generic.IComparer<TKey> comparer) { }
public int Capacity { get { return default(int); } set { } }
public System.Collections.Generic.IComparer<TKey> Comparer { get { return default(System.Collections.Generic.IComparer<TKey>); } }
public int Count { get { return default(int); } }
public TValue this[TKey key] { get { return default(TValue); } set { } }
public System.Collections.Generic.IList<TKey> Keys { get { return default(System.Collections.Generic.IList<TKey>); } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } }
bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } }
object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } }
public System.Collections.Generic.IList<TValue> Values { get { return default(System.Collections.Generic.IList<TValue>); } }
public void Add(TKey key, TValue value) { }
public void Clear() { }
public bool ContainsKey(TKey key) { return default(bool); }
public bool ContainsValue(TValue value) { return default(bool); }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); }
public int IndexOfKey(TKey key) { return default(int); }
public int IndexOfValue(TValue value) { return default(int); }
public bool Remove(TKey key) { return default(bool); }
public void RemoveAt(int index) { }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); }
void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { return default(bool); }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public void TrimExcess() { }
public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); }
}
public partial class SortedSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public SortedSet() { }
public SortedSet(System.Collections.Generic.IComparer<T> comparer) { }
public SortedSet(System.Collections.Generic.IEnumerable<T> collection) { }
public SortedSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IComparer<T> comparer) { }
public System.Collections.Generic.IComparer<T> Comparer { get { return default(System.Collections.Generic.IComparer<T>); } }
public int Count { get { return default(int); } }
public T Max { get { return default(T); } }
public T Min { get { return default(T); } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public bool Add(T item) { return default(bool); }
public virtual void Clear() { }
public virtual bool Contains(T item) { return default(bool); }
public void CopyTo(T[] array) { }
public void CopyTo(T[] array, int index) { }
public void CopyTo(T[] array, int index, int count) { }
public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
public System.Collections.Generic.SortedSet<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedSet<T>.Enumerator); }
public virtual System.Collections.Generic.SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { return default(System.Collections.Generic.SortedSet<T>); }
public virtual void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { }
public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public bool Remove(T item) { return default(bool); }
public int RemoveWhere(System.Predicate<T> match) { return default(int); }
public System.Collections.Generic.IEnumerable<T> Reverse() { return default(System.Collections.Generic.IEnumerable<T>); }
public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { return default(bool); }
public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ICollection<T>.Add(T item) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { return default(T); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public Stack() { }
public Stack(System.Collections.Generic.IEnumerable<T> collection) { }
public Stack(int capacity) { }
public int Count { get { return default(int); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void Clear() { }
public bool Contains(T item) { return default(bool); }
public void CopyTo(T[] array, int arrayIndex) { }
public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.Stack<T>.Enumerator); }
public T Peek() { return default(T); }
public T Pop() { return default(T); }
public void Push(T item) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public T[] ToArray() { return default(T[]); }
public void TrimExcess() { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { return default(T); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public void Dispose() { }
public bool MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* 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 *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MLifterErrorHandler.Properties;
using System.Xml;
using System.Diagnostics;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using MLifterErrorHandler.BusinessLayer;
namespace MLifterErrorHandler
{
/// <summary>
/// This form shows some information about the error, the
/// error report and the options which a user have if
/// an error occured
/// </summary>
/// <remarks>Documented by Dev07, 2009-07-15</remarks>
public partial class ErrorHandlerForm : Form
{
/// <summary>
/// height of the form if detailed information are shown
/// </summary>
private int ExpandedSize = 535;
private bool Fatal = false;
private FileInfo report = null;
private ErrorReportHandler errorReportHandler = null;
/// <summary>
/// height of the form if no detailed information are shown
/// </summary>
private int NotExpandedSize = 345;
/// <summary>
/// Initializes a new instance of the <see cref="ErrorHandlerForm"/> class.
/// </summary>
/// <remarks>Documented by Dev07, 2009-07-15</remarks>
public ErrorHandlerForm()
{
InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorHandlerForm"/> class.
/// </summary>
/// <param name="fatal">if set to <c>true</c> [fatal].</param>
/// <param name="report">The report.</param>
/// <remarks>Documented by Dev07, 2009-07-16</remarks>
public ErrorHandlerForm(bool fatal, FileInfo report)
{
this.Fatal = fatal;
this.report = report;
InitializeComponent();
}
/// <summary>
/// Handles the Load event of the ErrorHandlerForm control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev07, 2009-07-15</remarks>
private void ErrorHandlerForm_Load(object sender, EventArgs e)
{
this.Height = NotExpandedSize;
// Load the appropriate text in the header
if (Fatal)
labelErrorOccuredInformationMessage.Text = Resources.ERROR_OCCURED_INFORMATION_MESSAGE_FATAL;
else
labelErrorOccuredInformationMessage.Text = Resources.ERROR_OCCURED_INFORMATION_MESSAGE_NOT_FATAL;
//restart MemoryLifter
checkBoxRestartMemoryLifter.Checked = Fatal;
// Load the zip file and display the content in the list view
using (Stream stream = report.Open(FileMode.Open))
{
if (stream != null)
{
foreach (ZipEntry i in GetZipContent(stream))
{
ListViewItem listViewItem = new ListViewItem();
listViewItem.Tag = i.Name;
listViewItem.ToolTipText = i.Name;
listViewItem.Text = string.Format("{0} ({1:0.0} KB)", i.Name, i.Size / 1024D);
listViewItem.Checked = i.Name.StartsWith("ErrorReport.") ? true : false;
listViewFiles.Items.Add(listViewItem);
}
}
}
errorReportHandler = new ErrorReportHandler(report);
try
{
labelErrorMessage.Text = errorReportHandler.GetValue(Resources.ERRORREPORTPATH_MESSAGE);
}
catch (Exception exp)
{
Trace.WriteLine("Reading error data from ErrorReport Exception: " + exp.ToString());
}
}
/// <summary>
/// Handles the Click event of the buttonSend control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev07, 2009-07-15</remarks>
private void buttonSend_Click(object sender, EventArgs e)
{
try
{
PrepareErrorReport();
BusinessLayer.ErrorReportSender.SendReport(report.FullName, true);
}
catch (Exception ex)
{
InternalErrorHandler(ex, false);
}
finally
{
Close();
RestartMemoryLifter();
}
}
/// <summary>
/// Prepares the error report.
/// (Expands it with the user's information and removes unchecked files.)
/// </summary>
/// <remarks>Documented by Dev02, 2009-07-16</remarks>
private void PrepareErrorReport()
{
try
{
errorReportHandler.SetValue(Resources.ERRORREPORTPATH_USEREMAIL, textBoxEmailAddress.Text);
errorReportHandler.SetValue(Resources.ERRORREPORTPATH_USERDESCRIPTION, textBoxAdditionalInformation.Text);
errorReportHandler.CommitUpdates();
}
catch (Exception ex)
{
Trace.WriteLine("Error during adding user fields to error report:");
Trace.WriteLine(ex.ToString());
}
try
{
//remove unchecked files
foreach (ListViewItem item in listViewFiles.Items)
{
string filename = item.Tag as string;
if (!item.Checked && !String.IsNullOrEmpty(filename))
errorReportHandler.RemoveFile(filename);
}
}
catch (Exception ex)
{
Trace.WriteLine("Error during removing error report files:");
Trace.WriteLine(ex.ToString());
}
}
/// <summary>
/// Handles the Click event of the buttonDontSend control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2009-07-16</remarks>
private void buttonDontSend_Click(object sender, EventArgs e)
{
try
{
BusinessLayer.ErrorReportSender.ArchiveReport(report.FullName);
}
catch (Exception ex)
{
InternalErrorHandler(ex, false);
}
finally
{
Close();
RestartMemoryLifter();
}
}
/// <summary>
/// Restarts the memory lifter.
/// </summary>
/// <remarks>Documented by Dev02, 2009-07-16</remarks>
private void RestartMemoryLifter()
{
try
{
if (checkBoxRestartMemoryLifter.Checked)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Resources.MLIFTER_MAINPROGRAM);
if (File.Exists(psi.FileName))
Process.Start(psi);
}
}
catch (Exception exp)
{
Trace.WriteLine("Exception during restart of MemoryLifter:");
Trace.WriteLine(exp.ToString());
}
}
/// <summary>
/// Handles the MouseDoubleClick event of the listViewAdditionalInformation control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev07, 2009-07-16</remarks>
private void listViewAdditionalInformation_MouseDoubleClick(object sender, MouseEventArgs e)
{
//double click opens the program associated to the selected file
if (e.Button == MouseButtons.Left)
{
//undo the change of the checkstate (results from doubleclicking an item)
listViewFiles.SelectedItems[0].Checked = !listViewFiles.SelectedItems[0].Checked;
try
{
string name = listViewFiles.SelectedItems[0].Tag as string;
string ext = Path.GetExtension(name);
PreviewForm preview = new PreviewForm(ext == ".xml" || ext == ".xsl" ? PreviewType.HTML :
ext == ".mlcfg" || ext == ".txt" ? PreviewType.Text :
PreviewType.Image,
errorReportHandler.GetEntry(content.Find(i => i.Name == name)));
preview.Text = name;
preview.ShowDialog(this);
}
catch (Exception ex)
{
InternalErrorHandler(ex, false);
}
}
}
/// <summary>
/// Displays a messagebox for internal exceptions.
/// </summary>
/// <param name="ex">The exeption.</param>
/// <param name="closeform">If set to <c>true</c> closes the form.</param>
/// <remarks>Documented by Dev02, 2007-11-09</remarks>
public void InternalErrorHandler(Exception exception, bool closeform)
{
MessageBox.Show(string.Format(Properties.Resources.ERROR_INTERNALERROR, Environment.NewLine + Environment.NewLine, exception.Message + exception.StackTrace), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
try
{
Clipboard.SetDataObject(exception.ToString(), true);
}
catch { }
if (closeform)
this.Close();
}
List<ZipEntry> content = null;
/// <summary>
/// Gets the content of the zip.
/// </summary>
/// <param name="zipFile">The zip file.</param>
/// <returns></returns>
/// <remarks>Documented by Dev07, 2009-07-16</remarks>
public List<ZipEntry> GetZipContent(Stream zipFile)
{
content = new List<ZipEntry>();
ZipEntry zipEntry;
int nBytes = 2048;
byte[] data = new byte[nBytes];
try
{
using (ZipInputStream zipStream = new ZipInputStream(zipFile))
{
while ((zipEntry = zipStream.GetNextEntry()) != null)
{
if (zipEntry.IsFile)
{
content.Add(zipEntry);
}
}
}
}
catch (Exception ze)
{ Trace.WriteLine("Zip Exception: " + ze.ToString()); }
return content;
}
private void listViewFiles_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if (e.Item.Tag.ToString().ToLower() == Resources.ERRORFILE_NAME.ToLower())
{
if (!e.Item.Checked)
e.Item.Checked = !e.Item.Checked;
}
}
/// <summary>
/// Handles the Click event of the linkLabelErrorReportDetails control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2009-07-17</remarks>
private void linkLabelErrorReportDetails_Click(object sender, EventArgs e)
{
if (this.Height == NotExpandedSize)
{
this.Height = ExpandedSize;
labelErrorMessage.Visible = true;
linkLabelErrorReportDetails.Image = Resources.arrow_up_bw;
}
else if (this.Height == ExpandedSize)
{
this.Height = NotExpandedSize;
labelErrorMessage.Visible = false;
linkLabelErrorReportDetails.Image = Resources.arrow_down_bw;
}
}
}
}
| |
/*
Copyright (c) 2012-2015 Antmicro <www.antmicro.com>
Authors:
* Konrad Kruczynski ([email protected])
* Piotr Zierhoffer ([email protected])
* Mateusz Holenko ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Text;
namespace Antmicro.Migrant
{
/// <summary>
/// Provides the mechanism for reading primitive values from a stream.
/// </summary>
/// <remarks>
/// Can be used as a replacement for the <see cref="System.IO.BinaryReader" /> . Provides
/// more compact output and reads no more data from the stream than requested. Although
/// the underlying format is not specified at this point, it is guaranteed to be consistent with
/// <see cref="Antmicro.Migrant.PrimitiveWriter" />. Reader has to be disposed after used,
/// otherwise stream position corruption can occur. Reader does not possess the stream
/// and does not close it after dispose.
/// </remarks>
public sealed class PrimitiveReader : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="Antmicro.Migrant.PrimitiveReader" /> class.
/// </summary>
/// <param name='stream'>
/// The underlying stream which will be used to read data. Has to be readable.
/// </param>
/// <param name='buffered'>
/// True if reads should assume that corresponding PrimitiveWriter used buffering. False otherwise,
/// then no read prefetching or padding is used. Note that corresponding PrimitiveWriter always have
/// to have the same value for this parameter.
/// </param>
public PrimitiveReader(Stream stream, bool buffered = true)
{
this.stream = stream;
if(buffered)
{
// buffer size is the size of the maximal padding
buffer = new byte[Helpers.MaximalPadding];
}
this.buffered = buffered;
}
/// <summary>
/// Gets the current position.
/// </summary>
/// <value>
/// The position, which is the number of bytes read after this object was
/// constructed.
/// </value>
public long Position
{
get
{
return currentPosition - currentBufferSize + currentBufferPosition;
}
}
/// <summary>
/// Reads and returns <see cref="System.Double" />.
/// </summary>
public double ReadDouble()
{
return BitConverter.Int64BitsToDouble(ReadInt64());
}
/// <summary>
/// Reads and returns <see cref="System.Single" />.
/// </summary>
public float ReadSingle()
{
return (float)BitConverter.Int64BitsToDouble(ReadInt64());
}
/// <summary>
/// Reads and returns <see cref="System.DateTime" />.
/// </summary>
public DateTime ReadDateTime()
{
return Helpers.DateTimeEpoch + ReadTimeSpan();
}
/// <summary>
/// Reads and returns <see cref="System.TimeSpan" />.
/// </summary>
public TimeSpan ReadTimeSpan()
{
var type = ReadByte();
switch(type)
{
case Helpers.TickIndicator:
return TimeSpan.FromTicks(ReadInt64());
}
var tms = ReadUInt16();
var days = ReadInt32();
return new TimeSpan(days, type, tms / 60, tms % 60);
}
/// <summary>
/// Reads and returns <see cref="System.Byte" />.
/// </summary>
public byte ReadByte()
{
if(buffered)
{
CheckBuffer();
return buffer[currentBufferPosition++];
}
var result = stream.ReadByteOrThrow();
currentBufferPosition++;
return result;
}
/// <summary>
/// Reads and returns <see cref="System.SByte" />.
/// </summary>
public sbyte ReadSByte()
{
return (sbyte)ReadByte();
}
/// <summary>
/// Reads and returns <see cref="System.Int16" />.
/// </summary>
public short ReadInt16()
{
#if DEBUG
if(PrimitiveWriter.DontUseIntegerCompression)
{
return (short)InnerReadInteger();
}
#endif
var value = (short)InnerReadInteger();
return (short)(((value >> 1) & AllButMostSignificantShort) ^ -(value & 1));
}
/// <summary>
/// Reads and returns <see cref="System.UInt16" />.
/// </summary>
public ushort ReadUInt16()
{
return (ushort)InnerReadInteger();
}
/// <summary>
/// Reads and returns <see cref="System.Int32" />.
/// </summary>
public int ReadInt32()
{
#if DEBUG
if(PrimitiveWriter.DontUseIntegerCompression)
{
return (int)InnerReadInteger();
}
#endif
var value = (int)InnerReadInteger();
return ((value >> 1) & AllButMostSignificantInt) ^ -(value & 1);
}
/// <summary>
/// Reads and returns <see cref="System.UInt32" />.
/// </summary>
public uint ReadUInt32()
{
return (uint)InnerReadInteger();
}
/// <summary>
/// Reads and returns <see cref="System.Int64" />.
/// </summary>
public long ReadInt64()
{
#if DEBUG
if(PrimitiveWriter.DontUseIntegerCompression)
{
return (long)InnerReadInteger();
}
#endif
var value = (long)InnerReadInteger();
return ((value >> 1) & AllButMostSignificantLong) ^ -(value & 1);
}
/// <summary>
/// Reads and returns <see cref="System.UInt64" />.
/// </summary>
public ulong ReadUInt64()
{
return InnerReadInteger();
}
/// <summary>
/// Reads and returns <see cref="System.Char" />.
/// </summary>
public char ReadChar()
{
return (char)ReadUInt16();
}
/// <summary>
/// Reads and returns <see cref="System.Boolean" />.
/// </summary>
public bool ReadBoolean()
{
return ReadByte() == 1;
}
/// <summary>
/// Reads and returns <see cref="System.Guid" />.
/// </summary>
public Guid ReadGuid()
{
return new Guid(ReadBytes(16));
}
/// <summary>
/// Reads and returns string.
/// </summary>
public string ReadString()
{
bool fake;
var length = ReadInt32(); // length prefix
var chunk = InnerChunkRead(length, out fake);
return Encoding.UTF8.GetString(chunk.Array, chunk.Offset, chunk.Count);
}
/// <summary>
/// Reads the <see cref="System.Decimal"/> .
/// </summary>
public decimal ReadDecimal()
{
var lo = ReadInt32();
var mid = ReadInt32();
var hi = ReadInt32();
var scale = ReadInt32();
return new Decimal(lo, mid, hi,
(scale & DecimalSignMask) != 0,
(byte)((scale & DecimalScaleMask) >> DecimalScaleShift));
}
/// <summary>
/// Reads the given number of bytes.
/// </summary>
/// <returns>
/// The array holding read bytes.
/// </returns>
/// <param name='count'>
/// Number of bytes to read.
/// </param>
public byte[] ReadBytes(int count)
{
bool bufferCreated;
var chunk = InnerChunkRead(count, out bufferCreated);
if(bufferCreated)
{
return chunk.Array;
}
var result = new byte[count];
Array.Copy(chunk.Array, chunk.Offset, result, 0, chunk.Count);
return result;
}
/// <summary>
/// Copies given number of bytes to a given stream.
/// </summary>
/// <param name='destination'>
/// Writeable stream to which data will be copied.
/// </param>
/// <param name='howMuch'>
/// The number of bytes which will be copied to the destination stream.
/// </param>
public void CopyTo(Stream destination, long howMuch)
{
var localBuffer = new byte[Helpers.MaximalPadding];
if(buffered)
{
// first we need to flush the inner buffer into a stream
var dataLeft = currentBufferSize - currentBufferPosition;
var toRead = (int)Math.Min(dataLeft, howMuch);
destination.Write(buffer, currentBufferPosition, toRead);
currentBufferPosition += toRead;
howMuch -= toRead;
if(howMuch <= 0)
{
return;
}
}
// we can reuse the regular buffer since it is invalidated at this point anyway
int read;
while((read = stream.Read(localBuffer, 0, (int)Math.Min(localBuffer.Length, howMuch))) > 0)
{
howMuch -= read;
destination.Write(localBuffer, 0, read);
currentPosition += read;
}
if(howMuch > 0)
{
throw new EndOfStreamException(string.Format("End of stream reached while {0} more bytes expected.", howMuch));
}
}
/// <summary>
/// After this call stream's position is updated to match the padding used by <see cref="Antmicro.Migrant.PrimitiveWriter"/>.
/// It is needed to be called if one expects consecutive reads (of data written previously by consecutive writes). It is not necessary
/// to call this method when buffering is not used.
/// </summary>
/// <remarks>
/// Call <see cref="Dispose"/> when you are finished using the <see cref="Antmicro.Migrant.PrimitiveReader"/>. The
/// <see cref="Dispose"/> method leaves the <see cref="Antmicro.Migrant.PrimitiveReader"/> in an unusable state. After
/// calling <see cref="Dispose"/>, you must release all references to the
/// <see cref="Antmicro.Migrant.PrimitiveReader"/> so the garbage collector can reclaim the memory that the
/// <see cref="Antmicro.Migrant.PrimitiveReader"/> was occupying.
/// </remarks>
public void Dispose()
{
if(!buffered)
{
return;
}
// we have to leave the stream in aligned position
var toRead = Helpers.GetCurrentPaddingValue(currentPosition);
stream.ReadOrThrow(buffer, 0, toRead);
}
private ulong InnerReadInteger()
{
ulong next;
var result = 0UL;
#if DEBUG
if(PrimitiveWriter.DontUseIntegerCompression)
{
for(int i = 0; i < sizeof(ulong); ++i)
{
next = ReadByte();
result |= (next << 8 * (sizeof(ulong) - i - 1));
}
return result;
}
#endif
var shift = 0;
do
{
next = ReadByte();
result |= (next & 0x7FU) << shift;
shift += 7;
}
while((next & 128) > 0);
return result;
}
private void CheckBuffer()
{
if(currentBufferSize <= currentBufferPosition)
{
ReloadBuffer();
}
}
private void ReloadBuffer()
{
// how much can we read?
var toRead = Helpers.GetNextBytesToRead(currentPosition);
stream.ReadOrThrow(buffer, 0, toRead);
currentPosition += toRead;
currentBufferSize = toRead;
currentBufferPosition = 0;
}
private ArraySegment<byte> InnerChunkRead(int byteNumber, out bool bufferCreated)
{
if(!buffered)
{
bufferCreated = true;
var data = new byte[byteNumber];
stream.ReadOrThrow(data, 0, byteNumber);
currentBufferPosition += byteNumber;
return new ArraySegment<byte>(data);
}
bufferCreated = false;
var dataLeft = currentBufferSize - currentBufferPosition;
if(byteNumber > dataLeft)
{
var data = new byte[byteNumber];
bufferCreated = true;
var toRead = byteNumber - dataLeft;
Array.Copy(buffer, currentBufferPosition, data, 0, dataLeft);
currentBufferPosition += dataLeft;
stream.ReadOrThrow(data, dataLeft, toRead);
currentPosition += toRead;
return new ArraySegment<byte>(data, 0, byteNumber);
}
var result = new ArraySegment<byte>(buffer, currentBufferPosition, byteNumber);
currentBufferPosition += byteNumber;
return result;
}
/*
* Since we want the shift in zigzag decoding to be unsigned shift, we simulate it here, turning off
* the most significant bit (which is always zero in unsigned shift).
*/
private const int AllButMostSignificantShort = unchecked((short)~(1 << 15));
private const int AllButMostSignificantInt = ~(1 << 31);
private const long AllButMostSignificantLong = ~(1L << 63);
private const int DecimalScaleMask = 0x00FF0000;
private const int DecimalScaleShift = 16;
private const uint DecimalSignMask = 0x80000000;
private long currentPosition;
private readonly byte[] buffer;
private int currentBufferSize;
private int currentBufferPosition;
private readonly Stream stream;
private readonly bool buffered;
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// SelectByAttributes.
/// </summary>
public partial class SelectByAttributes : Form
{
#region Fields
private IFeatureLayer _activeLayer;
private IFeatureLayer[] _layersToSelect;
private IFrame _mapFrame;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SelectByAttributes"/> class.
/// </summary>
public SelectByAttributes()
{
InitializeComponent();
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="SelectByAttributes"/> class.
/// </summary>
/// <param name="mapFrame">The MapFrame containing the layers.</param>
public SelectByAttributes(IFrame mapFrame)
{
_mapFrame = mapFrame;
InitializeComponent();
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="SelectByAttributes"/> class.
/// </summary>
/// <param name="layersToSelect">Layers to select.</param>
public SelectByAttributes(params IFeatureLayer[] layersToSelect)
{
if (layersToSelect == null) throw new ArgumentNullException(nameof(layersToSelect));
_layersToSelect = layersToSelect;
InitializeComponent();
Configure();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the map frame to use for this control.
/// </summary>
public IFrame MapFrame
{
get
{
return _mapFrame;
}
set
{
_layersToSelect = null;
_mapFrame = value;
Configure();
}
}
#endregion
#region Methods
private void ApplyFilter()
{
string filter = sqlQueryControl1.ExpressionText;
if (_activeLayer != null)
{
try
{
_activeLayer.SelectByAttribute(filter, GetSelectMode());
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
MessageBox.Show(SymbologyFormsMessageStrings.SelectByAttributes_ErrorWhileAttemptingToApplyExpression);
}
}
}
private void BtnApplyClick(object sender, EventArgs e)
{
ApplyFilter();
}
private void BtnCloseClick(object sender, EventArgs e)
{
Close();
}
private void BtnOkClick(object sender, EventArgs e)
{
ApplyFilter();
Close();
}
private void CmbLayersSelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drv = cmbLayers.SelectedValue as DataRowView;
if (drv != null)
{
_activeLayer = drv.Row["Value"] as IFeatureLayer;
}
else
{
_activeLayer = cmbLayers.SelectedValue as IFeatureLayer;
}
if (_activeLayer == null) return;
if (!_activeLayer.DataSet.AttributesPopulated && _activeLayer.DataSet.NumRows() < 50000)
{
_activeLayer.DataSet.FillAttributes();
}
if (_activeLayer.EditMode || _activeLayer.DataSet.AttributesPopulated)
{
sqlQueryControl1.Table = _activeLayer.DataSet.DataTable;
}
else
{
sqlQueryControl1.AttributeSource = _activeLayer.DataSet;
}
}
private void Configure()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Value", typeof(IFeatureLayer));
IEnumerable<ILayer> layersSource;
if (_layersToSelect != null)
{
layersSource = _layersToSelect;
}
else if (_mapFrame != null)
{
layersSource = _mapFrame;
}
else
{
layersSource = Enumerable.Empty<ILayer>();
}
foreach (var layer in layersSource.OfType<IFeatureLayer>())
{
DataRow dr = dt.NewRow();
dr["Name"] = layer.LegendText;
dr["Value"] = layer;
dt.Rows.Add(dr);
}
cmbLayers.DataSource = dt;
cmbLayers.DisplayMember = "Name";
cmbLayers.ValueMember = "Value";
cmbMethod.SelectedIndex = 0;
if (cmbLayers.Items.Count > 0)
{
cmbLayers.SelectedIndex = 0;
}
}
private ModifySelectionMode GetSelectMode()
{
switch (cmbMethod.SelectedIndex)
{
case 0:
return ModifySelectionMode.Replace;
case 1:
return ModifySelectionMode.Append;
case 2:
return ModifySelectionMode.Subtract;
case 3:
return ModifySelectionMode.SelectFrom;
}
return ModifySelectionMode.Replace;
}
#endregion
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
using NUnit.Framework;
using Grpc.Testing;
namespace Grpc.IntegrationTesting
{
/// <summary>
/// Helper methods to start client runners for performance testing.
/// </summary>
public class ClientRunners
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientRunners>();
/// <summary>
/// Creates a started client runner.
/// </summary>
public static IClientRunner CreateStarted(ClientConfig config)
{
Logger.Debug("ClientConfig: {0}", config);
string target = config.ServerTargets.Single();
GrpcPreconditions.CheckArgument(config.LoadParams.LoadCase == LoadParams.LoadOneofCase.ClosedLoop,
"Only closed loop scenario supported for C#");
GrpcPreconditions.CheckArgument(config.ClientChannels == 1, "ClientConfig.ClientChannels needs to be 1");
if (config.OutstandingRpcsPerChannel != 0)
{
Logger.Warning("ClientConfig.OutstandingRpcsPerChannel is not supported for C#. Ignoring the value");
}
if (config.AsyncClientThreads != 0)
{
Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value");
}
if (config.CoreLimit != 0)
{
Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value");
}
if (config.CoreList.Count > 0)
{
Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value");
}
var credentials = config.SecurityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure;
List<ChannelOption> channelOptions = null;
if (config.SecurityParams != null && config.SecurityParams.ServerHostOverride != "")
{
channelOptions = new List<ChannelOption>
{
new ChannelOption(ChannelOptions.SslTargetNameOverride, config.SecurityParams.ServerHostOverride)
};
}
var channel = new Channel(target, credentials, channelOptions);
return new ClientRunnerImpl(channel,
config.ClientType,
config.RpcType,
config.PayloadConfig,
config.HistogramParams);
}
}
public class ClientRunnerImpl : IClientRunner
{
const double SecondsToNanos = 1e9;
readonly Channel channel;
readonly ClientType clientType;
readonly RpcType rpcType;
readonly PayloadConfig payloadConfig;
readonly Histogram histogram;
readonly BenchmarkService.IBenchmarkServiceClient client;
readonly Task runnerTask;
readonly CancellationTokenSource stoppedCts;
readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch();
public ClientRunnerImpl(Channel channel, ClientType clientType, RpcType rpcType, PayloadConfig payloadConfig, HistogramParams histogramParams)
{
this.channel = GrpcPreconditions.CheckNotNull(channel);
this.clientType = clientType;
this.rpcType = rpcType;
this.payloadConfig = payloadConfig;
this.histogram = new Histogram(histogramParams.Resolution, histogramParams.MaxPossible);
this.stoppedCts = new CancellationTokenSource();
this.client = BenchmarkService.NewClient(channel);
var threadBody = GetThreadBody();
this.runnerTask = Task.Factory.StartNew(threadBody, TaskCreationOptions.LongRunning);
}
public ClientStats GetStats(bool reset)
{
var histogramData = histogram.GetSnapshot(reset);
var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds;
// TODO: populate user time and system time
return new ClientStats
{
Latencies = histogramData,
TimeElapsed = secondsElapsed,
TimeUser = 0,
TimeSystem = 0
};
}
public async Task StopAsync()
{
stoppedCts.Cancel();
await runnerTask;
await channel.ShutdownAsync();
}
private void RunClosedLoopUnary()
{
var request = CreateSimpleRequest();
var stopwatch = new Stopwatch();
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
client.UnaryCall(request);
stopwatch.Stop();
// spec requires data point in nanoseconds.
histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
}
}
private async Task RunClosedLoopUnaryAsync()
{
var request = CreateSimpleRequest();
var stopwatch = new Stopwatch();
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
await client.UnaryCallAsync(request);
stopwatch.Stop();
// spec requires data point in nanoseconds.
histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
}
}
private async Task RunClosedLoopStreamingAsync()
{
var request = CreateSimpleRequest();
var stopwatch = new Stopwatch();
using (var call = client.StreamingCall())
{
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
await call.RequestStream.WriteAsync(request);
await call.ResponseStream.MoveNext();
stopwatch.Stop();
// spec requires data point in nanoseconds.
histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
}
// finish the streaming call
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
}
private async Task RunGenericClosedLoopStreamingAsync()
{
var request = CreateByteBufferRequest();
var stopwatch = new Stopwatch();
var callDetails = new CallInvocationDetails<byte[], byte[]>(channel, GenericService.StreamingCallMethod, new CallOptions());
using (var call = Calls.AsyncDuplexStreamingCall(callDetails))
{
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
await call.RequestStream.WriteAsync(request);
await call.ResponseStream.MoveNext();
stopwatch.Stop();
// spec requires data point in nanoseconds.
histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
}
// finish the streaming call
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
}
private Action GetThreadBody()
{
if (payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams)
{
GrpcPreconditions.CheckArgument(clientType == ClientType.ASYNC_CLIENT, "Generic client only supports async API");
GrpcPreconditions.CheckArgument(rpcType == RpcType.STREAMING, "Generic client only supports streaming calls");
return () =>
{
RunGenericClosedLoopStreamingAsync().Wait();
};
}
GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams);
if (clientType == ClientType.SYNC_CLIENT)
{
GrpcPreconditions.CheckArgument(rpcType == RpcType.UNARY, "Sync client can only be used for Unary calls in C#");
return RunClosedLoopUnary;
}
else if (clientType == ClientType.ASYNC_CLIENT)
{
switch (rpcType)
{
case RpcType.UNARY:
return () =>
{
RunClosedLoopUnaryAsync().Wait();
};
case RpcType.STREAMING:
return () =>
{
RunClosedLoopStreamingAsync().Wait();
};
}
}
throw new ArgumentException("Unsupported configuration.");
}
private SimpleRequest CreateSimpleRequest()
{
GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams);
return new SimpleRequest
{
Payload = CreateZerosPayload(payloadConfig.SimpleParams.ReqSize),
ResponseSize = payloadConfig.SimpleParams.RespSize
};
}
private byte[] CreateByteBufferRequest()
{
return new byte[payloadConfig.BytebufParams.ReqSize];
}
private static Payload CreateZerosPayload(int size)
{
return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
}
}
}
| |
// Reload help contents
using System;
using System.Collections;
using System.IO;
using Server;
using Server.Gumps;
using Server.Mobiles;
using Server.Network;
namespace Knives.Chat3
{
public class General
{
private static string s_Version = "3.0 Beta 9";
private static string s_SavePath = "Saves/ChatBeta8";
private static DateTime s_ReleaseDate = new DateTime(2007, 3, 1);
public static string Version { get { return s_Version; } }
public static string SavePath { get { return s_SavePath; } }
public static DateTime ReleaseDate { get { return s_ReleaseDate; } }
private static ArrayList s_Locals = new ArrayList();
private static Hashtable s_Help = new Hashtable();
public static Hashtable Help { get { return s_Help; } }
public static void Configure()
{
EventSink.WorldLoad += new WorldLoadEventHandler(OnLoad);
EventSink.WorldSave += new WorldSaveEventHandler(OnSave);
}
public static void Initialize()
{
EventSink.Speech += new SpeechEventHandler(OnSpeech);
EventSink.Login += new LoginEventHandler(OnLogin);
EventSink.CharacterCreated += new CharacterCreatedEventHandler(OnCreate);
}
private static void OnLoad()
{
LoadLocalFile();
LoadHelpFile();
LoadFilterFile();
Data.Load();
Channel.Load();
GumpInfo.Load();
if (Data.IrcAutoConnect)
IrcConnection.Connection.Connect();
}
private static void OnSave(WorldSaveEventArgs args)
{
DateTime time = DateTime.Now;
if (Data.Debug)
{
Console.WriteLine("");
Console.WriteLine(General.Local(241));
}
Data.Save();
Channel.Save();
GumpInfo.Save();
foreach (Data data in Data.Datas.Values)
if (data.SevenDays)
foreach (Message msg in new ArrayList(data.Messages))
if (msg.Received < DateTime.Now - TimeSpan.FromDays(7))
data.Messages.Remove(msg);
if (Data.Debug)
{
TimeSpan elapsed = DateTime.Now - time;
Console.WriteLine(General.Local(240) + " {0}", (elapsed.Minutes != 0 ? elapsed.Minutes + " minutes" : "") + (elapsed.Seconds != 0 ? elapsed.Seconds + " seconds" : "") + elapsed.Milliseconds + " milliseconds");
}
}
private static void OnSpeech(SpeechEventArgs args)
{
if (Data.GetData(args.Mobile).Recording is SendMessageGump)
{
if (!args.Mobile.HasGump(typeof(SendMessageGump)))
{
Data.GetData(args.Mobile).Recording = null;
return;
}
args.Mobile.CloseGump(typeof(SendMessageGump));
((SendMessageGump)Data.GetData(args.Mobile).Recording).AddText(" " + args.Speech);
args.Handled = true;
args.Speech = "";
return;
}
if (Data.FilterSpeech)
args.Speech = Filter.FilterText(args.Mobile, args.Speech, false);
foreach (Data data in Data.Datas.Values)
if (data.Mobile.AccessLevel >= args.Mobile.AccessLevel && ((data.GlobalW && !data.GIgnores.Contains(args.Mobile)) || data.GListens.Contains(args.Mobile)) && !data.Mobile.InRange(args.Mobile.Location, 10))
data.Mobile.SendMessage(data.GlobalWC, String.Format("(Global) <World> {0}: {1}", args.Mobile.RawName, args.Speech));
}
private static void OnLogin(LoginEventArgs args)
{
if (Data.GetData(args.Mobile).NewMsg())
PmNotify(args.Mobile);
if(!Data.GetData(args.Mobile).WhenFull)
args.Mobile.SendMessage(Data.GetData(args.Mobile).SystemC, General.Local(258), Data.GetData(args.Mobile).Messages.Count, Data.MaxMsgs);
foreach (Data data in Data.Datas.Values)
{
if (data.Friends.Contains(args.Mobile) && data.FriendAlert)
data.Mobile.SendMessage(data.SystemC, args.Mobile.RawName + " " + Local(173));
}
}
private static void OnCreate(CharacterCreatedEventArgs args)
{
if (args.Mobile == null)
return;
Data data = Data.GetData(args.Mobile);
foreach (Channel c in Channel.Channels)
if (c.NewChars)
c.Join(args.Mobile);
}
public static void LoadLocalFile()
{
s_Locals.Clear();
if (File.Exists("Data/ChatLocal.txt"))
{
using (FileStream bin = new FileStream("Data/ChatLocal.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader reader = new StreamReader(bin);
string text = "";
while (true)
{
try
{
text = reader.ReadLine();
if (text.IndexOf("//") == 0 || text.Trim().Length == 0)
continue;
if (text == "EndOfFile")
break;
s_Locals.Add(text);
}
catch { break; }
}
reader.Close();
}
}
if (s_Locals.Count == 0)
s_Locals = DefaultLocal.Load();
}
public static void LoadHelpFile()
{
s_Help.Clear();
if (File.Exists("Data/HelpContents.txt"))
{
using (FileStream bin = new FileStream("Data/HelpContents.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader reader = new StreamReader(bin);
string name = "";
string text = "";
while (true)
{
try
{
name = reader.ReadLine();
if (name.IndexOf("//") == 0 || name.Trim().Length == 0)
continue;
if (name == "EndOfFile")
break;
text = reader.ReadLine();
if (text.IndexOf("//") == 0 || text.Trim().Length == 0)
continue;
if (text == "EndOfFile")
break;
s_Help[name] = text;
}
catch { break; }
}
reader.Close();
}
}
}
public static string Local(int num)
{
if (num < 0 || num >= s_Locals.Count)
return "Local Error";
return s_Locals[num].ToString();
}
public static string GetHelp(string str)
{
if (s_Help[str] == null)
return "Help Error";
return s_Help[str].ToString();
}
public static void LoadFilterFile()
{
if (File.Exists("Data/ChatFilters.txt"))
{
using (FileStream bin = new FileStream("Data/ChatFilters.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader reader = new StreamReader(bin);
string text = "";
while (true)
{
try
{
text = reader.ReadLine();
if (text.IndexOf("//") == 0 || text.Trim().Length == 0)
continue;
if (text == "EndOfFile")
break;
if (!Data.Filters.Contains(text.ToLower()))
Data.Filters.Add(text.ToLower());
}
catch { break; }
}
reader.Close();
}
}
}
public static void LoadBacksFile()
{
if (File.Exists("Data/ChatBacks.txt"))
{
using (FileStream bin = new FileStream("Data/ChatBacks.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader reader = new StreamReader(bin);
string text = "";
while (true)
{
try
{
text = reader.ReadLine();
if (text.IndexOf("//") == 0 || text.Trim().Length == 0)
continue;
if (text == "EndOfFile")
break;
if(!GumpInfo.Backgrounds.Contains(Utility.ToInt32(text)))
GumpInfo.Backgrounds.Add(Utility.ToInt32(text));
}
catch { break; }
}
reader.Close();
}
}
}
public static void LoadColorsFile()
{
if (File.Exists("Data/ChatColors.txt"))
{
using (FileStream bin = new FileStream("Data/ChatColors.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader reader = new StreamReader(bin);
string text = "";
while (true)
{
try
{
text = reader.ReadLine();
if (text.IndexOf("//") == 0 || text.Trim().Length == 0)
continue;
if (text == "EndOfFile")
break;
if (!GumpInfo.TextColors.Contains(text))
GumpInfo.TextColors.Add(text);
}
catch { break; }
}
reader.Close();
}
}
}
public static void LoadAvatarFile()
{
if (File.Exists("Data/ChatAvatars.txt"))
{
using (FileStream bin = new FileStream("Data/ChatAvatars.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader reader = new StreamReader(bin);
string id = "";
string xoff = "";
string yoff = "";
while (true)
{
try
{
id = reader.ReadLine();
if (id.IndexOf("//") == 0 || id.Trim().Length == 0)
continue;
if (id == "EndOfFile")
break;
xoff = reader.ReadLine();
yoff = reader.ReadLine();
if (!Avatar.Avatars.Contains(Utility.ToInt32(id)))
new Avatar(Utility.ToInt32(id), Utility.ToInt32(xoff), Utility.ToInt32(yoff));
}
catch { break; }
}
reader.Close();
}
}
}
public static void List(Mobile m, int page)
{
switch (Data.GetData(m).MenuSkin)
{
case Skin.Three:
new ListGump(m, page);
break;
case Skin.Two:
new ListGump20(m, page);
break;
default:
new ListGump10(m, page);
break;
}
}
public static void List(Mobile m, Mobile targ)
{
switch (Data.GetData(m).MenuSkin)
{
case Skin.Three:
new ListGump(m, targ);
break;
case Skin.Two:
new ListGump20(m, targ);
break;
default:
break;
}
}
public static void PmNotify(Mobile m)
{
switch (Data.GetData(m).MenuSkin)
{
case Skin.Three:
new PmNotifyGump(m);
break;
case Skin.Two:
new PmNotifyGump20(m);
break;
default:
new PmNotifyGump10(m);
break;
}
}
public static bool IsInFaction(Mobile m)
{
if (m == null || !m.Player)
return false;
return (((PlayerMobile)m).FactionPlayerState != null && ((PlayerMobile)m).FactionPlayerState.Faction != null);
}
public static string FactionName(Mobile m)
{
if (!IsInFaction(m))
return "";
return ((PlayerMobile)m).FactionPlayerState.Faction.Definition.PropName;
}
public static string FactionTitle(Mobile m)
{
if (!IsInFaction(m))
return "";
return ((PlayerMobile)m).FactionPlayerState.Rank.Title;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using NuGet.Common;
using NuGet.Packaging.Core;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Test.Helpers;
using NuGet.Versioning;
using Sleet;
using Test.Common;
using Xunit;
namespace NuGetMirror.Tests
{
public class NupkgCommandTests
{
[Fact]
public async Task VerifyPackagesAreDownloadedInV2Structure()
{
// Arrange
using (var cache = new LocalCache())
using (var cacheContext = new SourceCacheContext())
using (var workingDir = new TestFolder())
{
var beforeDate = DateTimeOffset.UtcNow;
var catalogLog = new TestLogger();
var log = new TestLogger();
var baseUri = Sleet.UriUtility.CreateUri("https://localhost:8080/testFeed/");
var feedFolder = Path.Combine(workingDir, "feed");
var nupkgsFolder = Path.Combine(workingDir, "nupkgs");
var nupkgsOutFolder = Path.Combine(workingDir, "nupkgsout");
Directory.CreateDirectory(feedFolder);
Directory.CreateDirectory(nupkgsFolder);
Directory.CreateDirectory(nupkgsOutFolder);
var packageA = new TestNupkg("a", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageA);
await CatalogReaderTestHelpers.CreateCatalogAsync(workingDir, feedFolder, nupkgsFolder, baseUri, catalogLog);
var feedUri = Sleet.UriUtility.CreateUri(baseUri.AbsoluteUri + "index.json");
var httpSource = CatalogReaderTestHelpers.GetHttpSource(cache, feedFolder, baseUri);
var args = new string[] { "nupkgs", "-o", nupkgsOutFolder, "--folder-format", "v2", feedUri.AbsoluteUri, "--delay", "0" };
var exitCode = await NuGetMirror.Program.MainCore(args, httpSource, log);
exitCode.Should().Be(0);
var results = LocalFolderUtility.GetPackagesV2(nupkgsOutFolder, catalogLog).ToList();
results.Select(e => e.Identity).ShouldBeEquivalentTo(new[] { new PackageIdentity("a", NuGetVersion.Parse("1.0.0")) });
var afterDate = DateTimeOffset.UtcNow;
var cursor = MirrorUtility.LoadCursor(new DirectoryInfo(nupkgsOutFolder));
(cursor <= afterDate && cursor >= beforeDate).Should().BeTrue("the cursor should match the catalog");
var errorLog = Path.Combine(nupkgsOutFolder, "lastRunErrors.txt");
File.Exists(errorLog).Should().BeFalse();
}
}
[Fact]
public async Task VerifyPackagesAreDownloadedInV3Structure()
{
// Arrange
using (var cache = new LocalCache())
using (var cacheContext = new SourceCacheContext())
using (var workingDir = new TestFolder())
{
var beforeDate = DateTimeOffset.UtcNow;
var catalogLog = new TestLogger();
var log = new TestLogger();
var baseUri = Sleet.UriUtility.CreateUri("https://localhost:8080/testFeed/");
var feedFolder = Path.Combine(workingDir, "feed");
var nupkgsFolder = Path.Combine(workingDir, "nupkgs");
var nupkgsOutFolder = Path.Combine(workingDir, "nupkgsout");
Directory.CreateDirectory(feedFolder);
Directory.CreateDirectory(nupkgsFolder);
Directory.CreateDirectory(nupkgsOutFolder);
var packageA = new TestNupkg("a", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageA);
await CatalogReaderTestHelpers.CreateCatalogAsync(workingDir, feedFolder, nupkgsFolder, baseUri, catalogLog);
var feedUri = Sleet.UriUtility.CreateUri(baseUri.AbsoluteUri + "index.json");
var httpSource = CatalogReaderTestHelpers.GetHttpSource(cache, feedFolder, baseUri);
var args = new string[] { "nupkgs", "-o", nupkgsOutFolder, feedUri.AbsoluteUri, "--delay", "0" };
var exitCode = await NuGetMirror.Program.MainCore(args, httpSource, log);
exitCode.Should().Be(0);
var results = LocalFolderUtility.GetPackagesV3(nupkgsOutFolder, catalogLog).ToList();
results.Select(e => e.Identity).ShouldBeEquivalentTo(new[] { new PackageIdentity("a", NuGetVersion.Parse("1.0.0")) });
var afterDate = DateTimeOffset.UtcNow;
var cursor = MirrorUtility.LoadCursor(new DirectoryInfo(nupkgsOutFolder));
(cursor <= afterDate && cursor >= beforeDate).Should().BeTrue("the cursor should match the catalog");
var errorLog = Path.Combine(nupkgsOutFolder, "lastRunErrors.txt");
File.Exists(errorLog).Should().BeFalse();
}
}
[Fact]
public async Task GivenMultiplePackagesVerifyIncludeTakesOnlyMatches()
{
// Arrange
using (var cache = new LocalCache())
using (var cacheContext = new SourceCacheContext())
using (var workingDir = new TestFolder())
{
var beforeDate = DateTimeOffset.UtcNow;
var catalogLog = new TestLogger();
var log = new TestLogger();
var baseUri = Sleet.UriUtility.CreateUri("https://localhost:8080/testFeed/");
var feedFolder = Path.Combine(workingDir, "feed");
var nupkgsFolder = Path.Combine(workingDir, "nupkgs");
var nupkgsOutFolder = Path.Combine(workingDir, "nupkgsout");
Directory.CreateDirectory(feedFolder);
Directory.CreateDirectory(nupkgsFolder);
Directory.CreateDirectory(nupkgsOutFolder);
var packageA = new TestNupkg("aa", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageA);
var packageB = new TestNupkg("ab", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageB);
var packageC = new TestNupkg("c", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageC);
await CatalogReaderTestHelpers.CreateCatalogAsync(workingDir, feedFolder, nupkgsFolder, baseUri, catalogLog);
var feedUri = Sleet.UriUtility.CreateUri(baseUri.AbsoluteUri + "index.json");
var httpSource = CatalogReaderTestHelpers.GetHttpSource(cache, feedFolder, baseUri);
var args = new string[] { "nupkgs", "-o", nupkgsOutFolder, feedUri.AbsoluteUri, "--delay", "0", "-i", "a*" };
var exitCode = await NuGetMirror.Program.MainCore(args, httpSource, log);
exitCode.Should().Be(0);
var results = LocalFolderUtility.GetPackagesV3(nupkgsOutFolder, catalogLog).ToList();
results.Select(e => e.Identity).ShouldBeEquivalentTo(
new[] {
new PackageIdentity("aa", NuGetVersion.Parse("1.0.0")),
new PackageIdentity("ab", NuGetVersion.Parse("1.0.0"))
});
}
}
[Fact]
public async Task GivenMultiplePackagesVerifyExcludeRemovesC()
{
// Arrange
using (var cache = new LocalCache())
using (var cacheContext = new SourceCacheContext())
using (var workingDir = new TestFolder())
{
var beforeDate = DateTimeOffset.UtcNow;
var catalogLog = new TestLogger();
var log = new TestLogger();
var baseUri = Sleet.UriUtility.CreateUri("https://localhost:8080/testFeed/");
var feedFolder = Path.Combine(workingDir, "feed");
var nupkgsFolder = Path.Combine(workingDir, "nupkgs");
var nupkgsOutFolder = Path.Combine(workingDir, "nupkgsout");
Directory.CreateDirectory(feedFolder);
Directory.CreateDirectory(nupkgsFolder);
Directory.CreateDirectory(nupkgsOutFolder);
var packageA = new TestNupkg("aa", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageA);
var packageB = new TestNupkg("ab", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageB);
var packageC = new TestNupkg("c", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageC);
await CatalogReaderTestHelpers.CreateCatalogAsync(workingDir, feedFolder, nupkgsFolder, baseUri, catalogLog);
var feedUri = Sleet.UriUtility.CreateUri(baseUri.AbsoluteUri + "index.json");
var httpSource = CatalogReaderTestHelpers.GetHttpSource(cache, feedFolder, baseUri);
var args = new string[] { "nupkgs", "-o", nupkgsOutFolder, feedUri.AbsoluteUri, "--delay", "0", "-e", "a*" };
var exitCode = await NuGetMirror.Program.MainCore(args, httpSource, log);
exitCode.Should().Be(0);
var results = LocalFolderUtility.GetPackagesV3(nupkgsOutFolder, catalogLog).ToList();
results.Select(e => e.Identity).ShouldBeEquivalentTo(
new[] {
new PackageIdentity("c", NuGetVersion.Parse("1.0.0"))
});
}
}
[Fact]
public async Task GivenALargeNumberOfPackagesVerifyAllAreDownloaded()
{
// Arrange
using (var cache = new LocalCache())
using (var cacheContext = new SourceCacheContext())
using (var workingDir = new TestFolder())
{
var catalogLog = new TestLogger();
var log = new TestLogger();
var baseUri = Sleet.UriUtility.CreateUri("https://localhost:8080/testFeed/");
var feedFolder = Path.Combine(workingDir, "feed");
var nupkgsFolder = Path.Combine(workingDir, "nupkgs");
var nupkgsOutFolder = Path.Combine(workingDir, "nupkgsout");
Directory.CreateDirectory(feedFolder);
Directory.CreateDirectory(nupkgsFolder);
Directory.CreateDirectory(nupkgsOutFolder);
var expected = new HashSet<PackageIdentity>();
for (var i = 0; i < 200; i++)
{
var identity = new PackageIdentity(Guid.NewGuid().ToString(), NuGetVersion.Parse($"{i}.0.0"));
if (expected.Add(identity))
{
var package = new TestNupkg(identity.Id, identity.Version.ToNormalizedString());
TestNupkg.Save(nupkgsFolder, package);
}
}
await CatalogReaderTestHelpers.CreateCatalogAsync(workingDir, feedFolder, nupkgsFolder, baseUri, catalogLog);
var feedUri = Sleet.UriUtility.CreateUri(baseUri.AbsoluteUri + "index.json");
var httpSource = CatalogReaderTestHelpers.GetHttpSource(cache, feedFolder, baseUri);
var args = new string[] { "nupkgs", "-o", nupkgsOutFolder, feedUri.AbsoluteUri, "--delay", "0" };
var exitCode = await NuGetMirror.Program.MainCore(args, httpSource, log);
var errors = log.GetMessages(LogLevel.Error);
exitCode.Should().Be(0, errors);
var results = LocalFolderUtility.GetPackagesV3(nupkgsOutFolder, catalogLog).ToList();
results.Select(e => e.Identity).ShouldBeEquivalentTo(expected);
var errorLog = Path.Combine(nupkgsOutFolder, "lastRunErrors.txt");
File.Exists(errorLog).Should().BeFalse();
}
}
[Fact]
public async Task GivenLatestOnlyOptionVerifyDownloadsOnlyLatest()
{
// Arrange
using (var cache = new LocalCache())
using (var cacheContext = new SourceCacheContext())
using (var workingDir = new TestFolder())
{
var beforeDate = DateTimeOffset.UtcNow;
var catalogLog = new TestLogger();
var log = new TestLogger();
var baseUri = Sleet.UriUtility.CreateUri("https://localhost:8080/testFeed/");
var feedFolder = Path.Combine(workingDir, "feed");
var nupkgsFolder = Path.Combine(workingDir, "nupkgs");
var nupkgsOutFolder = Path.Combine(workingDir, "nupkgsout");
Directory.CreateDirectory(feedFolder);
Directory.CreateDirectory(nupkgsFolder);
Directory.CreateDirectory(nupkgsOutFolder);
var packageA1 = new TestNupkg("a", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageA1);
var packageA2 = new TestNupkg("a", "2.0.0");
TestNupkg.Save(nupkgsFolder, packageA2);
var packageB1 = new TestNupkg("b", "1.0.0");
TestNupkg.Save(nupkgsFolder, packageB1);
var packageB2 = new TestNupkg("b", "2.0.0");
TestNupkg.Save(nupkgsFolder, packageB2);
await CatalogReaderTestHelpers.CreateCatalogAsync(workingDir, feedFolder, nupkgsFolder, baseUri, catalogLog);
var feedUri = Sleet.UriUtility.CreateUri(baseUri.AbsoluteUri + "index.json");
var httpSource = CatalogReaderTestHelpers.GetHttpSource(cache, feedFolder, baseUri);
var args = new string[] { "nupkgs", "-o", nupkgsOutFolder, feedUri.AbsoluteUri, "--delay", "0", "--latest-only" };
var exitCode = await NuGetMirror.Program.MainCore(args, httpSource, log);
exitCode.Should().Be(0);
var results = LocalFolderUtility.GetPackagesV3(nupkgsOutFolder, catalogLog).ToList();
results.Select(e => e.Identity).ShouldBeEquivalentTo(
new[] {
new PackageIdentity("a", NuGetVersion.Parse("2.0.0")),
new PackageIdentity("b", NuGetVersion.Parse("2.0.0"))
});
}
}
}
}
| |
//
// Reflect.cs: Creates Element classes from an instance
//
// Author:
// Miguel de Icaza ([email protected])
//
// Copyright 2010, Novell, Inc.
//
// Code licensed under the MIT X11 license
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Drawing;
#if __UNIFIED__
using UIKit;
using Foundation;
using NSAction = global::System.Action;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
#endif
namespace MonoTouch.Dialog
{
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class EntryAttribute : Attribute {
public EntryAttribute () : this (null) { }
public EntryAttribute (string placeholder)
{
Placeholder = placeholder;
}
public string Placeholder;
public UIKeyboardType KeyboardType;
public UITextAutocorrectionType AutocorrectionType;
public UITextAutocapitalizationType AutocapitalizationType;
public UITextFieldViewMode ClearButtonMode;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class DateAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class TimeAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CheckboxAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class MultilineAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class HtmlAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SkipAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class PasswordAttribute : EntryAttribute {
public PasswordAttribute (string placeholder) : base (placeholder) {}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class AlignmentAttribute : Attribute {
public AlignmentAttribute (UITextAlignment alignment) {
Alignment = alignment;
}
public UITextAlignment Alignment;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class RadioSelectionAttribute : Attribute {
public string Target;
public RadioSelectionAttribute (string target)
{
Target = target;
}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class OnTapAttribute : Attribute {
public OnTapAttribute (string method)
{
Method = method;
}
public string Method;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CaptionAttribute : Attribute {
public CaptionAttribute (string caption)
{
Caption = caption;
}
public string Caption;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SectionAttribute : Attribute {
public SectionAttribute () {}
public SectionAttribute (string caption)
{
Caption = caption;
}
public SectionAttribute (string caption, string footer)
{
Caption = caption;
Footer = footer;
}
public string Caption, Footer;
}
public class RangeAttribute : Attribute {
public RangeAttribute (float low, float high)
{
Low = low;
High = high;
}
public float Low, High;
public bool ShowCaption;
}
public class BindingContext : IDisposable {
public RootElement Root;
Dictionary<Element,MemberAndInstance> mappings;
class MemberAndInstance {
public MemberAndInstance (MemberInfo mi, object o)
{
Member = mi;
Obj = o;
}
public MemberInfo Member;
public object Obj;
}
static object GetValue (MemberInfo mi, object o)
{
var fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (o);
var pi = mi as PropertyInfo;
var getMethod = pi.GetGetMethod ();
return getMethod.Invoke (o, new object [0]);
}
static void SetValue (MemberInfo mi, object o, object val)
{
var fi = mi as FieldInfo;
if (fi != null){
fi.SetValue (o, val);
return;
}
var pi = mi as PropertyInfo;
var setMethod = pi.GetSetMethod ();
setMethod.Invoke (o, new object [] { val });
}
static string MakeCaption (string name)
{
var sb = new StringBuilder (name.Length);
bool nextUp = true;
foreach (char c in name){
if (nextUp){
sb.Append (Char.ToUpper (c));
nextUp = false;
} else {
if (c == '_'){
sb.Append (' ');
continue;
}
if (Char.IsUpper (c))
sb.Append (' ');
sb.Append (c);
}
}
return sb.ToString ();
}
// Returns the type for fields and properties and null for everything else
static Type GetTypeForMember (MemberInfo mi)
{
if (mi is FieldInfo)
return ((FieldInfo) mi).FieldType;
else if (mi is PropertyInfo)
return ((PropertyInfo) mi).PropertyType;
return null;
}
public BindingContext (object callbacks, object o, string title)
{
if (o == null)
throw new ArgumentNullException ("o");
mappings = new Dictionary<Element,MemberAndInstance> ();
Root = new RootElement (title);
Populate (callbacks, o, Root);
}
void Populate (object callbacks, object o, RootElement root)
{
MemberInfo last_radio_index = null;
var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
Section section = null;
foreach (var mi in members){
Type mType = GetTypeForMember (mi);
if (mType == null)
continue;
string caption = null;
object [] attrs = mi.GetCustomAttributes (false);
bool skip = false;
foreach (var attr in attrs){
if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute)
skip = true;
else if (attr is CaptionAttribute)
caption = ((CaptionAttribute) attr).Caption;
else if (attr is SectionAttribute){
if (section != null)
root.Add (section);
var sa = attr as SectionAttribute;
section = new Section (sa.Caption, sa.Footer);
}
}
if (skip)
continue;
if (caption == null)
caption = MakeCaption (mi.Name);
if (section == null)
section = new Section ();
Element element = null;
if (mType == typeof (string)){
PasswordAttribute pa = null;
AlignmentAttribute align = null;
EntryAttribute ea = null;
object html = null;
NSAction invoke = null;
bool multi = false;
foreach (object attr in attrs){
if (attr is PasswordAttribute)
pa = attr as PasswordAttribute;
else if (attr is EntryAttribute)
ea = attr as EntryAttribute;
else if (attr is MultilineAttribute)
multi = true;
else if (attr is HtmlAttribute)
html = attr;
else if (attr is AlignmentAttribute)
align = attr as AlignmentAttribute;
if (attr is OnTapAttribute){
string mname = ((OnTapAttribute) attr).Method;
if (callbacks == null){
throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor");
}
var method = callbacks.GetType ().GetMethod (mname);
if (method == null)
throw new Exception ("Did not find method " + mname);
invoke = delegate {
method.Invoke (method.IsStatic ? null : callbacks, new object [0]);
};
}
}
string value = (string) GetValue (mi, o);
if (pa != null)
element = new EntryElement (caption, pa.Placeholder, value, true);
else if (ea != null)
element = new EntryElement (caption, ea.Placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode };
else if (multi)
element = new MultilineElement (caption, value);
else if (html != null)
element = new HtmlElement (caption, value);
else {
var selement = new StringElement (caption, value);
element = selement;
if (align != null)
selement.Alignment = align.Alignment;
}
if (invoke != null)
((StringElement) element).Tapped += invoke;
} else if (mType == typeof (float)){
var floatElement = new FloatElement (null, null, (float) GetValue (mi, o));
floatElement.Caption = caption;
element = floatElement;
foreach (object attr in attrs){
if (attr is RangeAttribute){
var ra = attr as RangeAttribute;
floatElement.MinValue = ra.Low;
floatElement.MaxValue = ra.High;
floatElement.ShowCaption = ra.ShowCaption;
}
}
} else if (mType == typeof (bool)){
bool checkbox = false;
foreach (object attr in attrs){
if (attr is CheckboxAttribute)
checkbox = true;
}
if (checkbox)
element = new CheckboxElement (caption, (bool) GetValue (mi, o));
else
element = new BooleanElement (caption, (bool) GetValue (mi, o));
} else if (mType == typeof (DateTime)){
var dateTime = (DateTime) GetValue (mi, o);
bool asDate = false, asTime = false;
foreach (object attr in attrs){
if (attr is DateAttribute)
asDate = true;
else if (attr is TimeAttribute)
asTime = true;
}
if (asDate)
element = new DateElement (caption, dateTime);
else if (asTime)
element = new TimeElement (caption, dateTime);
else
element = new DateTimeElement (caption, dateTime);
} else if (mType.IsEnum){
var csection = new Section ();
ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null);
int idx = 0;
int selected = 0;
foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)){
ulong v = Convert.ToUInt64 (GetValue (fi, null));
if (v == evalue)
selected = idx;
CaptionAttribute ca = Attribute.GetCustomAttribute(fi, typeof(CaptionAttribute)) as CaptionAttribute;
csection.Add (new RadioElement (ca != null ? ca.Caption : MakeCaption (fi.Name)));
idx++;
}
element = new RootElement (caption, new RadioGroup (null, selected)) { csection };
} else if (mType == typeof (UIImage)){
element = new ImageElement ((UIImage) GetValue (mi, o));
} else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)){
var csection = new Section ();
int count = 0;
if (last_radio_index == null)
throw new Exception ("IEnumerable found, but no previous int found");
foreach (var e in (IEnumerable) GetValue (mi, o)){
csection.Add (new RadioElement (e.ToString ()));
count++;
}
int selected = (int) GetValue (last_radio_index, o);
if (selected >= count || selected < 0)
selected = 0;
element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection };
last_radio_index = null;
} else if (typeof (int) == mType){
foreach (object attr in attrs){
if (attr is RadioSelectionAttribute){
last_radio_index = mi;
break;
}
}
} else {
var nested = GetValue (mi, o);
if (nested != null){
var newRoot = new RootElement (caption);
Populate (callbacks, nested, newRoot);
element = newRoot;
}
}
if (element == null)
continue;
section.Add (element);
mappings [element] = new MemberAndInstance (mi, o);
}
root.Add (section);
}
class MemberRadioGroup : RadioGroup {
public MemberInfo mi;
public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected)
{
this.mi = mi;
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing){
foreach (var element in mappings.Keys){
element.Dispose ();
}
mappings = null;
}
}
public void Fetch ()
{
foreach (var dk in mappings){
Element element = dk.Key;
MemberInfo mi = dk.Value.Member;
object obj = dk.Value.Obj;
if (element is DateTimeElement)
SetValue (mi, obj, ((DateTimeElement) element).DateValue);
else if (element is FloatElement)
SetValue (mi, obj, ((FloatElement) element).Value);
else if (element is BooleanElement)
SetValue (mi, obj, ((BooleanElement) element).Value);
else if (element is CheckboxElement)
SetValue (mi, obj, ((CheckboxElement) element).Value);
else if (element is EntryElement){
var entry = (EntryElement) element;
entry.FetchValue ();
SetValue (mi, obj, entry.Value);
} else if (element is ImageElement)
SetValue (mi, obj, ((ImageElement) element).Value);
else if (element is RootElement){
var re = element as RootElement;
if (re.group as MemberRadioGroup != null){
var group = re.group as MemberRadioGroup;
SetValue (group.mi, obj, re.RadioSelected);
} else if (re.group as RadioGroup != null){
var mType = GetTypeForMember (mi);
var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected];
SetValue (mi, obj, fi.GetValue (null));
}
}
}
}
}
}
| |
/*
* CP10029.cs - Latin II (Mac) code page.
*
* Copyright (c) 2002 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 "mac-10029.ucm".
namespace I18N.West
{
using System;
using I18N.Common;
public class CP10029 : ByteEncoding
{
public CP10029()
: base(10029, ToChars, "Latin II (Mac)",
"windows-10029", "windows-10029", "windows-10029",
false, false, false, false, 1250)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u00C4', '\u0100', '\u0101', '\u00C9',
'\u0104', '\u00D6', '\u00DC', '\u00E1', '\u0105', '\u010C',
'\u00E4', '\u010D', '\u0106', '\u0107', '\u00E9', '\u0179',
'\u017A', '\u010E', '\u00ED', '\u010F', '\u0112', '\u0113',
'\u0116', '\u00F3', '\u0117', '\u00F4', '\u00F6', '\u00F5',
'\u00FA', '\u011A', '\u011B', '\u00FC', '\u2020', '\u00B0',
'\u0118', '\u00A3', '\u00A7', '\u2022', '\u00B6', '\u00DF',
'\u00AE', '\u00A9', '\u2122', '\u0119', '\u00A8', '\u2260',
'\u0123', '\u012E', '\u012F', '\u012A', '\u2264', '\u2265',
'\u012B', '\u0136', '\u2202', '\u2211', '\u0142', '\u013B',
'\u013C', '\u013D', '\u013E', '\u0139', '\u013A', '\u0145',
'\u0146', '\u0143', '\u00AC', '\u221A', '\u0144', '\u0147',
'\u2206', '\u00AB', '\u00BB', '\u2026', '\u00A0', '\u0148',
'\u0150', '\u00D5', '\u0151', '\u014C', '\u2013', '\u2014',
'\u201C', '\u201D', '\u2018', '\u2019', '\u00F7', '\u25CA',
'\u014D', '\u0154', '\u0155', '\u0158', '\u2039', '\u203A',
'\u0159', '\u0156', '\u0157', '\u0160', '\u201A', '\u201E',
'\u0161', '\u015A', '\u015B', '\u00C1', '\u0164', '\u0165',
'\u00CD', '\u017D', '\u017E', '\u016A', '\u00D3', '\u00D4',
'\u016B', '\u016E', '\u00DA', '\u016F', '\u0170', '\u0171',
'\u0172', '\u0173', '\u00DD', '\u00FD', '\u0137', '\u017B',
'\u0141', '\u017C', '\u0122', '\u02C7',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A3:
case 0x00A9:
break;
case 0x00A0: ch = 0xCA; break;
case 0x00A7: ch = 0xA4; break;
case 0x00A8: ch = 0xAC; break;
case 0x00AB: ch = 0xC7; break;
case 0x00AC: ch = 0xC2; break;
case 0x00AE: ch = 0xA8; break;
case 0x00B0: ch = 0xA1; break;
case 0x00B6: ch = 0xA6; break;
case 0x00BB: ch = 0xC8; break;
case 0x00C1: ch = 0xE7; break;
case 0x00C4: ch = 0x80; break;
case 0x00C9: ch = 0x83; break;
case 0x00CD: ch = 0xEA; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEF; break;
case 0x00D5: ch = 0xCD; break;
case 0x00D6: ch = 0x85; break;
case 0x00DA: ch = 0xF2; break;
case 0x00DC: ch = 0x86; break;
case 0x00DD: ch = 0xF8; break;
case 0x00DF: ch = 0xA7; break;
case 0x00E1: ch = 0x87; break;
case 0x00E4: ch = 0x8A; break;
case 0x00E9: ch = 0x8E; break;
case 0x00ED: ch = 0x92; break;
case 0x00F3: ch = 0x97; break;
case 0x00F4: ch = 0x99; break;
case 0x00F5: ch = 0x9B; break;
case 0x00F6: ch = 0x9A; break;
case 0x00F7: ch = 0xD6; break;
case 0x00FA: ch = 0x9C; break;
case 0x00FC: ch = 0x9F; break;
case 0x00FD: ch = 0xF9; break;
case 0x0100: ch = 0x81; break;
case 0x0101: ch = 0x82; break;
case 0x0104: ch = 0x84; break;
case 0x0105: ch = 0x88; break;
case 0x0106: ch = 0x8C; break;
case 0x0107: ch = 0x8D; break;
case 0x010C: ch = 0x89; break;
case 0x010D: ch = 0x8B; break;
case 0x010E: ch = 0x91; break;
case 0x010F: ch = 0x93; break;
case 0x0112: ch = 0x94; break;
case 0x0113: ch = 0x95; break;
case 0x0116: ch = 0x96; break;
case 0x0117: ch = 0x98; break;
case 0x0118: ch = 0xA2; break;
case 0x0119: ch = 0xAB; break;
case 0x011A: ch = 0x9D; break;
case 0x011B: ch = 0x9E; break;
case 0x0122: ch = 0xFE; break;
case 0x0123: ch = 0xAE; break;
case 0x012A: ch = 0xB1; break;
case 0x012B: ch = 0xB4; break;
case 0x012E: ch = 0xAF; break;
case 0x012F: ch = 0xB0; break;
case 0x0136: ch = 0xB5; break;
case 0x0137: ch = 0xFA; break;
case 0x0139: ch = 0xBD; break;
case 0x013A: ch = 0xBE; break;
case 0x013B:
case 0x013C:
case 0x013D:
case 0x013E:
ch -= 0x0082;
break;
case 0x0141: ch = 0xFC; break;
case 0x0142: ch = 0xB8; break;
case 0x0143: ch = 0xC1; break;
case 0x0144: ch = 0xC4; break;
case 0x0145: ch = 0xBF; break;
case 0x0146: ch = 0xC0; break;
case 0x0147: ch = 0xC5; break;
case 0x0148: ch = 0xCB; break;
case 0x014C: ch = 0xCF; break;
case 0x014D: ch = 0xD8; break;
case 0x0150: ch = 0xCC; break;
case 0x0151: ch = 0xCE; break;
case 0x0154: ch = 0xD9; break;
case 0x0155: ch = 0xDA; break;
case 0x0156: ch = 0xDF; break;
case 0x0157: ch = 0xE0; break;
case 0x0158: ch = 0xDB; break;
case 0x0159: ch = 0xDE; break;
case 0x015A: ch = 0xE5; break;
case 0x015B: ch = 0xE6; break;
case 0x0160: ch = 0xE1; break;
case 0x0161: ch = 0xE4; break;
case 0x0164: ch = 0xE8; break;
case 0x0165: ch = 0xE9; break;
case 0x016A: ch = 0xED; break;
case 0x016B: ch = 0xF0; break;
case 0x016E: ch = 0xF1; break;
case 0x016F:
case 0x0170:
case 0x0171:
case 0x0172:
case 0x0173:
ch -= 0x007C;
break;
case 0x0179: ch = 0x8F; break;
case 0x017A: ch = 0x90; break;
case 0x017B: ch = 0xFB; break;
case 0x017C: ch = 0xFD; break;
case 0x017D: ch = 0xEB; break;
case 0x017E: ch = 0xEC; break;
case 0x02C7: ch = 0xFF; break;
case 0x2013: ch = 0xD0; break;
case 0x2014: ch = 0xD1; break;
case 0x2018: ch = 0xD4; break;
case 0x2019: ch = 0xD5; break;
case 0x201A: ch = 0xE2; break;
case 0x201C: ch = 0xD2; break;
case 0x201D: ch = 0xD3; break;
case 0x201E: ch = 0xE3; break;
case 0x2020: ch = 0xA0; break;
case 0x2022: ch = 0xA5; break;
case 0x2026: ch = 0xC9; break;
case 0x2039: ch = 0xDC; break;
case 0x203A: ch = 0xDD; break;
case 0x2122: ch = 0xAA; break;
case 0x2202: ch = 0xB6; break;
case 0x2206: ch = 0xC6; break;
case 0x2211: ch = 0xB7; break;
case 0x221A: ch = 0xC3; break;
case 0x2260: ch = 0xAD; break;
case 0x2264: ch = 0xB2; break;
case 0x2265: ch = 0xB3; break;
case 0x25CA: ch = 0xD7; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A3:
case 0x00A9:
break;
case 0x00A0: ch = 0xCA; break;
case 0x00A7: ch = 0xA4; break;
case 0x00A8: ch = 0xAC; break;
case 0x00AB: ch = 0xC7; break;
case 0x00AC: ch = 0xC2; break;
case 0x00AE: ch = 0xA8; break;
case 0x00B0: ch = 0xA1; break;
case 0x00B6: ch = 0xA6; break;
case 0x00BB: ch = 0xC8; break;
case 0x00C1: ch = 0xE7; break;
case 0x00C4: ch = 0x80; break;
case 0x00C9: ch = 0x83; break;
case 0x00CD: ch = 0xEA; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEF; break;
case 0x00D5: ch = 0xCD; break;
case 0x00D6: ch = 0x85; break;
case 0x00DA: ch = 0xF2; break;
case 0x00DC: ch = 0x86; break;
case 0x00DD: ch = 0xF8; break;
case 0x00DF: ch = 0xA7; break;
case 0x00E1: ch = 0x87; break;
case 0x00E4: ch = 0x8A; break;
case 0x00E9: ch = 0x8E; break;
case 0x00ED: ch = 0x92; break;
case 0x00F3: ch = 0x97; break;
case 0x00F4: ch = 0x99; break;
case 0x00F5: ch = 0x9B; break;
case 0x00F6: ch = 0x9A; break;
case 0x00F7: ch = 0xD6; break;
case 0x00FA: ch = 0x9C; break;
case 0x00FC: ch = 0x9F; break;
case 0x00FD: ch = 0xF9; break;
case 0x0100: ch = 0x81; break;
case 0x0101: ch = 0x82; break;
case 0x0104: ch = 0x84; break;
case 0x0105: ch = 0x88; break;
case 0x0106: ch = 0x8C; break;
case 0x0107: ch = 0x8D; break;
case 0x010C: ch = 0x89; break;
case 0x010D: ch = 0x8B; break;
case 0x010E: ch = 0x91; break;
case 0x010F: ch = 0x93; break;
case 0x0112: ch = 0x94; break;
case 0x0113: ch = 0x95; break;
case 0x0116: ch = 0x96; break;
case 0x0117: ch = 0x98; break;
case 0x0118: ch = 0xA2; break;
case 0x0119: ch = 0xAB; break;
case 0x011A: ch = 0x9D; break;
case 0x011B: ch = 0x9E; break;
case 0x0122: ch = 0xFE; break;
case 0x0123: ch = 0xAE; break;
case 0x012A: ch = 0xB1; break;
case 0x012B: ch = 0xB4; break;
case 0x012E: ch = 0xAF; break;
case 0x012F: ch = 0xB0; break;
case 0x0136: ch = 0xB5; break;
case 0x0137: ch = 0xFA; break;
case 0x0139: ch = 0xBD; break;
case 0x013A: ch = 0xBE; break;
case 0x013B:
case 0x013C:
case 0x013D:
case 0x013E:
ch -= 0x0082;
break;
case 0x0141: ch = 0xFC; break;
case 0x0142: ch = 0xB8; break;
case 0x0143: ch = 0xC1; break;
case 0x0144: ch = 0xC4; break;
case 0x0145: ch = 0xBF; break;
case 0x0146: ch = 0xC0; break;
case 0x0147: ch = 0xC5; break;
case 0x0148: ch = 0xCB; break;
case 0x014C: ch = 0xCF; break;
case 0x014D: ch = 0xD8; break;
case 0x0150: ch = 0xCC; break;
case 0x0151: ch = 0xCE; break;
case 0x0154: ch = 0xD9; break;
case 0x0155: ch = 0xDA; break;
case 0x0156: ch = 0xDF; break;
case 0x0157: ch = 0xE0; break;
case 0x0158: ch = 0xDB; break;
case 0x0159: ch = 0xDE; break;
case 0x015A: ch = 0xE5; break;
case 0x015B: ch = 0xE6; break;
case 0x0160: ch = 0xE1; break;
case 0x0161: ch = 0xE4; break;
case 0x0164: ch = 0xE8; break;
case 0x0165: ch = 0xE9; break;
case 0x016A: ch = 0xED; break;
case 0x016B: ch = 0xF0; break;
case 0x016E: ch = 0xF1; break;
case 0x016F:
case 0x0170:
case 0x0171:
case 0x0172:
case 0x0173:
ch -= 0x007C;
break;
case 0x0179: ch = 0x8F; break;
case 0x017A: ch = 0x90; break;
case 0x017B: ch = 0xFB; break;
case 0x017C: ch = 0xFD; break;
case 0x017D: ch = 0xEB; break;
case 0x017E: ch = 0xEC; break;
case 0x02C7: ch = 0xFF; break;
case 0x2013: ch = 0xD0; break;
case 0x2014: ch = 0xD1; break;
case 0x2018: ch = 0xD4; break;
case 0x2019: ch = 0xD5; break;
case 0x201A: ch = 0xE2; break;
case 0x201C: ch = 0xD2; break;
case 0x201D: ch = 0xD3; break;
case 0x201E: ch = 0xE3; break;
case 0x2020: ch = 0xA0; break;
case 0x2022: ch = 0xA5; break;
case 0x2026: ch = 0xC9; break;
case 0x2039: ch = 0xDC; break;
case 0x203A: ch = 0xDD; break;
case 0x2122: ch = 0xAA; break;
case 0x2202: ch = 0xB6; break;
case 0x2206: ch = 0xC6; break;
case 0x2211: ch = 0xB7; break;
case 0x221A: ch = 0xC3; break;
case 0x2260: ch = 0xAD; break;
case 0x2264: ch = 0xB2; break;
case 0x2265: ch = 0xB3; break;
case 0x25CA: ch = 0xD7; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP10029
public class ENCwindows_10029 : CP10029
{
public ENCwindows_10029() : base() {}
}; // class ENCwindows_10029
}; // namespace I18N.West
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A05_CountryColl (editable child list).<br/>
/// This is a generated base class of <see cref="A05_CountryColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="A04_SubContinent"/> editable child object.<br/>
/// The items of the collection are <see cref="A06_Country"/> objects.
/// </remarks>
[Serializable]
public partial class A05_CountryColl : BusinessListBase<A05_CountryColl, A06_Country>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="A06_Country"/> item from the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to be removed.</param>
public void Remove(int country_ID)
{
foreach (var a06_Country in this)
{
if (a06_Country.Country_ID == country_ID)
{
Remove(a06_Country);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="A06_Country"/> item is in the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the A06_Country is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int country_ID)
{
foreach (var a06_Country in this)
{
if (a06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="A06_Country"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the A06_Country is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int country_ID)
{
foreach (var a06_Country in DeletedList)
{
if (a06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="A06_Country"/> item of the <see cref="A05_CountryColl"/> collection, based on item key properties.
/// </summary>
/// <param name="country_ID">The Country_ID.</param>
/// <returns>A <see cref="A06_Country"/> object.</returns>
public A06_Country FindA06_CountryByParentProperties(int country_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Country_ID.Equals(country_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A05_CountryColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="A05_CountryColl"/> collection.</returns>
internal static A05_CountryColl NewA05_CountryColl()
{
return DataPortal.CreateChild<A05_CountryColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="A05_CountryColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A05_CountryColl"/> object.</returns>
internal static A05_CountryColl GetA05_CountryColl(SafeDataReader dr)
{
A05_CountryColl obj = new A05_CountryColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A05_CountryColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A05_CountryColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="A05_CountryColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(A06_Country.GetA06_Country(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="A06_Country"/> items on the A05_CountryObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="A03_SubContinentColl"/> collection.</param>
internal void LoadItems(A03_SubContinentColl collection)
{
foreach (var item in this)
{
var obj = collection.FindA04_SubContinentByParentProperties(item.parent_SubContinent_ID);
var rlce = obj.A05_CountryObjects.RaiseListChangedEvents;
obj.A05_CountryObjects.RaiseListChangedEvents = false;
obj.A05_CountryObjects.Add(item);
obj.A05_CountryObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
namespace EdiEngine.Standards.X12_004010.DataElements
{
public class C001 : MapCompositeDataElement
{
public C001()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0355 { ReqDes = RequirementDesignator.Mandatory },
new E_1018 { ReqDes = RequirementDesignator.Optional },
new E_0649 { ReqDes = RequirementDesignator.Optional },
new E_0355 { ReqDes = RequirementDesignator.Optional },
new E_1018 { ReqDes = RequirementDesignator.Optional },
new E_0649 { ReqDes = RequirementDesignator.Optional },
new E_0355 { ReqDes = RequirementDesignator.Optional },
new E_1018 { ReqDes = RequirementDesignator.Optional },
new E_0649 { ReqDes = RequirementDesignator.Optional },
new E_0355 { ReqDes = RequirementDesignator.Optional },
new E_1018 { ReqDes = RequirementDesignator.Optional },
new E_0649 { ReqDes = RequirementDesignator.Optional },
new E_0355 { ReqDes = RequirementDesignator.Optional },
new E_1018 { ReqDes = RequirementDesignator.Optional },
new E_0649 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C002 : MapCompositeDataElement
{
public C002()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0704 { ReqDes = RequirementDesignator.Mandatory },
new E_0704 { ReqDes = RequirementDesignator.Optional },
new E_0704 { ReqDes = RequirementDesignator.Optional },
new E_0704 { ReqDes = RequirementDesignator.Optional },
new E_0704 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C003 : MapCompositeDataElement
{
public C003()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0235 { ReqDes = RequirementDesignator.Mandatory },
new E_0234 { ReqDes = RequirementDesignator.Mandatory },
new E_1339 { ReqDes = RequirementDesignator.Optional },
new E_1339 { ReqDes = RequirementDesignator.Optional },
new E_1339 { ReqDes = RequirementDesignator.Optional },
new E_1339 { ReqDes = RequirementDesignator.Optional },
new E_0352 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C004 : MapCompositeDataElement
{
public C004()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1328 { ReqDes = RequirementDesignator.Mandatory },
new E_1328 { ReqDes = RequirementDesignator.Optional },
new E_1328 { ReqDes = RequirementDesignator.Optional },
new E_1328 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C005 : MapCompositeDataElement
{
public C005()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1369 { ReqDes = RequirementDesignator.Mandatory },
new E_1369 { ReqDes = RequirementDesignator.Optional },
new E_1369 { ReqDes = RequirementDesignator.Optional },
new E_1369 { ReqDes = RequirementDesignator.Optional },
new E_1369 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C006 : MapCompositeDataElement
{
public C006()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1361 { ReqDes = RequirementDesignator.Mandatory },
new E_1361 { ReqDes = RequirementDesignator.Optional },
new E_1361 { ReqDes = RequirementDesignator.Optional },
new E_1361 { ReqDes = RequirementDesignator.Optional },
new E_1361 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C007 : MapCompositeDataElement
{
public C007()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0522 { ReqDes = RequirementDesignator.Mandatory },
new E_0522 { ReqDes = RequirementDesignator.Optional },
new E_1638 { ReqDes = RequirementDesignator.Optional },
new E_0935 { ReqDes = RequirementDesignator.Optional },
new E_0344 { ReqDes = RequirementDesignator.Optional },
new E_1637 { ReqDes = RequirementDesignator.Optional },
new E_0935 { ReqDes = RequirementDesignator.Optional },
new E_0352 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C022 : MapCompositeDataElement
{
public C022()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1270 { ReqDes = RequirementDesignator.Mandatory },
new E_1271 { ReqDes = RequirementDesignator.Mandatory },
new E_1250 { ReqDes = RequirementDesignator.Optional },
new E_1251 { ReqDes = RequirementDesignator.Optional },
new E_0782 { ReqDes = RequirementDesignator.Optional },
new E_0380 { ReqDes = RequirementDesignator.Optional },
new E_0799 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C023 : MapCompositeDataElement
{
public C023()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1331 { ReqDes = RequirementDesignator.Mandatory },
new E_1332 { ReqDes = RequirementDesignator.Optional },
new E_1325 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C024 : MapCompositeDataElement
{
public C024()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1362 { ReqDes = RequirementDesignator.Mandatory },
new E_1362 { ReqDes = RequirementDesignator.Optional },
new E_1362 { ReqDes = RequirementDesignator.Optional },
new E_0156 { ReqDes = RequirementDesignator.Optional },
new E_0026 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C030 : MapCompositeDataElement
{
public C030()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0722 { ReqDes = RequirementDesignator.Mandatory },
new E_1528 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C033 : MapCompositeDataElement
{
public C033()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1572 { ReqDes = RequirementDesignator.Mandatory },
new E_1573 { ReqDes = RequirementDesignator.Mandatory },
});
}
}
public class C035 : MapCompositeDataElement
{
public C035()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1222 { ReqDes = RequirementDesignator.Mandatory },
new E_0559 { ReqDes = RequirementDesignator.Optional },
new E_1073 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C036 : MapCompositeDataElement
{
public C036()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1395 { ReqDes = RequirementDesignator.Optional },
new E_0127 { ReqDes = RequirementDesignator.Optional },
new E_0127 { ReqDes = RequirementDesignator.Optional },
new E_0863 { ReqDes = RequirementDesignator.Optional },
new E_0864 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C037 : MapCompositeDataElement
{
public C037()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0817 { ReqDes = RequirementDesignator.Mandatory },
new E_0647 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C040 : MapCompositeDataElement
{
public C040()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0128 { ReqDes = RequirementDesignator.Mandatory },
new E_0127 { ReqDes = RequirementDesignator.Mandatory },
new E_0128 { ReqDes = RequirementDesignator.Optional },
new E_0127 { ReqDes = RequirementDesignator.Optional },
new E_0128 { ReqDes = RequirementDesignator.Optional },
new E_0127 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C042 : MapCompositeDataElement
{
public C042()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0426 { ReqDes = RequirementDesignator.Mandatory },
new E_0127 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C043 : MapCompositeDataElement
{
public C043()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1271 { ReqDes = RequirementDesignator.Mandatory },
new E_1271 { ReqDes = RequirementDesignator.Mandatory },
new E_0098 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C045 : MapCompositeDataElement
{
public C045()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1321 { ReqDes = RequirementDesignator.Mandatory },
new E_1321 { ReqDes = RequirementDesignator.Optional },
new E_1321 { ReqDes = RequirementDesignator.Optional },
new E_1321 { ReqDes = RequirementDesignator.Optional },
new E_1321 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C046 : MapCompositeDataElement
{
public C046()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_0122 { ReqDes = RequirementDesignator.Mandatory },
new E_0122 { ReqDes = RequirementDesignator.Optional },
new E_0122 { ReqDes = RequirementDesignator.Optional },
new E_0122 { ReqDes = RequirementDesignator.Optional },
new E_0122 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C047 : MapCompositeDataElement
{
public C047()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1074 { ReqDes = RequirementDesignator.Mandatory },
new E_1074 { ReqDes = RequirementDesignator.Optional },
new E_1074 { ReqDes = RequirementDesignator.Optional },
new E_1074 { ReqDes = RequirementDesignator.Optional },
new E_1074 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C048 : MapCompositeDataElement
{
public C048()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1082 { ReqDes = RequirementDesignator.Mandatory },
new E_1680 { ReqDes = RequirementDesignator.Optional },
new E_1082 { ReqDes = RequirementDesignator.Optional },
});
}
}
public class C050 : MapCompositeDataElement
{
public C050()
{
Content.AddRange(new MapSimpleDataElement[] {
new E_1675 { ReqDes = RequirementDesignator.Mandatory },
new E_1570 { ReqDes = RequirementDesignator.Mandatory },
new E_0799 { ReqDes = RequirementDesignator.Mandatory },
new E_1565 { ReqDes = RequirementDesignator.Mandatory },
new E_1675 { ReqDes = RequirementDesignator.Optional },
new E_1570 { ReqDes = RequirementDesignator.Optional },
new E_0799 { ReqDes = RequirementDesignator.Optional },
new E_1565 { ReqDes = RequirementDesignator.Optional },
new E_1675 { ReqDes = RequirementDesignator.Optional },
new E_1570 { ReqDes = RequirementDesignator.Optional },
new E_0799 { ReqDes = RequirementDesignator.Optional },
new E_1565 { ReqDes = RequirementDesignator.Optional },
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrByte()
{
var test = new SimpleBinaryOpTest__OrByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Byte);
private const int Op2ElementCount = VectorSize / sizeof(Byte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable;
static SimpleBinaryOpTest__OrByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__OrByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Or(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Or(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Or(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrByte();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// Copyright (c) 2014 Piotr Fusik <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 Sooda.QL;
using Sooda.Schema;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Sooda.ObjectMapper
{
public abstract class SoodaObjectCollectionBase : IList, ISoodaObjectList
{
protected readonly SoodaTransaction transaction;
protected readonly ClassInfo classInfo;
protected List<SoodaObject> itemsArray = null;
protected Dictionary<SoodaObject, int> items = null;
protected SoodaObjectCollectionBase(SoodaTransaction transaction, ClassInfo classInfo)
{
this.transaction = transaction;
this.classInfo = classInfo;
}
public SoodaObject GetItem(int pos)
{
if (itemsArray == null)
LoadData();
return itemsArray[pos];
}
public int Length
{
get
{
if (itemsArray == null)
LoadData();
return itemsArray.Count;
}
}
public IEnumerator GetEnumerator()
{
if (itemsArray == null)
LoadData();
return itemsArray.GetEnumerator();
}
public abstract int Add(object obj);
public abstract void Remove(object obj);
public abstract bool Contains(object obj);
protected abstract void LoadData();
public bool IsReadOnly
{
get
{
return true;
}
}
object IList.this[int index]
{
get
{
return GetItem(index);
}
set
{
throw new NotSupportedException();
}
}
public void RemoveAt(int index)
{
Remove(GetItem(index));
}
public void Insert(int index, object value)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public int IndexOf(object value)
{
if (items == null)
LoadData();
int pos;
if (items.TryGetValue((SoodaObject) value, out pos))
return pos;
else
return -1;
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public int PagedCount
{
get { return this.Length; }
}
public int Count
{
get
{
return this.Length;
}
}
public void CopyTo(Array array, int index)
{
if (itemsArray == null)
LoadData();
((ICollection) itemsArray).CopyTo(array, index);
}
public object SyncRoot
{
get
{
return this;
}
}
public ISoodaObjectList GetSnapshot()
{
return new SoodaObjectListSnapshot(this);
}
public ISoodaObjectList SelectFirst(int n)
{
return new SoodaObjectListSnapshot(this, 0, n);
}
public ISoodaObjectList SelectLast(int n)
{
return new SoodaObjectListSnapshot(this, this.Length - n, n);
}
public ISoodaObjectList SelectRange(int from, int to)
{
return new SoodaObjectListSnapshot(this, from, to - from);
}
public ISoodaObjectList Filter(SoodaObjectFilter filter)
{
return new SoodaObjectListSnapshot(this, filter);
}
public ISoodaObjectList Filter(SoqlBooleanExpression filterExpression)
{
return new SoodaObjectListSnapshot(this, filterExpression);
}
public ISoodaObjectList Filter(SoodaWhereClause whereClause)
{
return new SoodaObjectListSnapshot(this, whereClause);
}
public ISoodaObjectList Sort(IComparer comparer)
{
return new SoodaObjectListSnapshot(this, comparer);
}
public ISoodaObjectList Sort(string sortOrder)
{
return new SoodaObjectListSnapshot(this).Sort(sortOrder);
}
public ISoodaObjectList Sort(SoqlExpression expression, SortOrder sortOrder)
{
return new SoodaObjectListSnapshot(this).Sort(expression, sortOrder);
}
public ISoodaObjectList Sort(SoqlExpression expression)
{
return new SoodaObjectListSnapshot(this).Sort(expression, SortOrder.Ascending);
}
}
}
| |
using System;
using System.IO;
using System.Data;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace LumiSoft.Net.FTP.Server
{
#region Event delegates
/// <summary>
/// Represents the method that will handle the AuthUser event for FTP_Server.
/// </summary>
/// <param name="sender">The source of the event. </param>
/// <param name="e">A AuthUser_EventArgs that contains the event data.</param>
public delegate void AuthUserEventHandler(object sender,AuthUser_EventArgs e);
/// <summary>
/// Represents the method that will handle the filsystem rerlated events for FTP_Server.
/// </summary>
public delegate void FileSysEntryEventHandler(object sender,FileSysEntry_EventArgs e);
#endregion
/// <summary>
/// FTP Server component.
/// </summary>
public class FTP_Server : SocketServer
{
#region Event declarations
/// <summary>
/// Occurs when new computer connected to FTP server.
/// </summary>
public event ValidateIPHandler ValidateIPAddress = null;
/// <summary>
/// Occurs when connected user tryes to authenticate.
/// </summary>
public event AuthUserEventHandler AuthUser = null;
/// <summary>
/// Occurs when server needs directory info (directories,files in deirectory).
/// </summary>
public event FileSysEntryEventHandler GetDirInfo = null;
/// <summary>
/// Occurs when server needs to validatee directory.
/// </summary>
public event FileSysEntryEventHandler DirExists = null;
/// <summary>
/// Occurs when server needs needs to create directory.
/// </summary>
public event FileSysEntryEventHandler CreateDir = null;
/// <summary>
/// Occurs when server needs needs to delete directory.
/// </summary>
public event FileSysEntryEventHandler DeleteDir = null;
/// <summary>
/// Occurs when server needs needs validate file.
/// </summary>
public event FileSysEntryEventHandler FileExists = null;
/// <summary>
/// Occurs when server needs needs to store file.
/// </summary>
public event FileSysEntryEventHandler StoreFile = null;
/// <summary>
/// Occurs when server needs needs to get file.
/// </summary>
public event FileSysEntryEventHandler GetFile = null;
/// <summary>
/// Occurs when server needs needs to delete file.
/// </summary>
public event FileSysEntryEventHandler DeleteFile = null;
/// <summary>
/// Occurs when server needs needs to rname directory or file.
/// </summary>
public event FileSysEntryEventHandler RenameDirFile = null;
/// <summary>
/// Occurs when POP3 session has finished and session log is available.
/// </summary>
public event LogEventHandler SessionLog = null;
#endregion
private IPAddress m_pPassivePublicIP = null;
private int m_PassiveStartPort = 20000;
/// <summary>
/// Defalut constructor.
/// </summary>
public FTP_Server() : base()
{
this.BindInfo = new IPBindInfo[]{new IPBindInfo("",IPAddress.Any,21,SslMode.None,null)};
}
#region override InitNewSession
/// <summary>
/// Initialize and start new session here. Session isn't added to session list automatically,
/// session must add itself to server session list by calling AddSession().
/// </summary>
/// <param name="socket">Connected client socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
protected override void InitNewSession(Socket socket,IPBindInfo bindInfo)
{
string sessionID = Guid.NewGuid().ToString();
SocketEx socketEx = new SocketEx(socket);
if(LogCommands){
socketEx.Logger = new SocketLogger(socket,this.SessionLog);
socketEx.Logger.SessionID = sessionID;
}
FTP_Session session = new FTP_Session(sessionID,socketEx,bindInfo,this);
}
#endregion
#region Properties implementation
/// <summary>
/// Gets active sessions.
/// </summary>
public new FTP_Session[] Sessions
{
get{
SocketServerSession[] sessions = base.Sessions;
FTP_Session[] ftpSessions = new FTP_Session[sessions.Length];
sessions.CopyTo(ftpSessions,0);
return ftpSessions;
}
}
/// <summary>
/// Gets or sets passive mode public IP address what is reported to clients.
/// This property is manly needed if FTP server is running behind NAT.
/// Value null means not spcified.
/// </summary>
public IPAddress PassivePublicIP
{
get{ return m_pPassivePublicIP; }
set{ m_pPassivePublicIP = value; }
}
/// <summary>
/// Gets or sets passive mode start port form which server starts using ports.
/// </summary>
/// <exception cref="ArgumentException">Is raised when ivalid value is passed.</exception>
public int PassiveStartPort
{
get{ return m_PassiveStartPort; }
set{
if(value < 1){
throw new ArgumentException("Valu must be > 0 !");
}
m_PassiveStartPort = value;
}
}
#endregion
#region Events Implementation
#region function OnValidate_IpAddress
/// <summary>
/// Raises event ValidateIP event.
/// </summary>
/// <param name="localEndPoint">Server IP.</param>
/// <param name="remoteEndPoint">Connected client IP.</param>
/// <returns>Returns true if connection allowed.</returns>
internal virtual bool OnValidate_IpAddress(IPEndPoint localEndPoint,IPEndPoint remoteEndPoint)
{
ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(localEndPoint,remoteEndPoint);
if(this.ValidateIPAddress != null){
this.ValidateIPAddress(this, oArg);
}
return oArg.Validated;
}
#endregion
#region function OnAuthUser
/// <summary>
/// Authenticates user.
/// </summary>
/// <param name="session">Reference to current pop3 session.</param>
/// <param name="userName">User name.</param>
/// <param name="passwData"></param>
/// <param name="data"></param>
/// <param name="authType"></param>
/// <returns></returns>
internal virtual bool OnAuthUser(FTP_Session session,string userName,string passwData,string data,AuthType authType)
{
AuthUser_EventArgs oArg = new AuthUser_EventArgs(session,userName,passwData,data,authType);
if(this.AuthUser != null){
this.AuthUser(this,oArg);
}
return oArg.Validated;
}
#endregion
#region method OnGetDirInfo
internal FileSysEntry_EventArgs OnGetDirInfo(FTP_Session session,string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,dir,"");
if(this.GetDirInfo != null){
this.GetDirInfo(this,oArg);
}
return oArg;
}
#endregion
#region method OnDirExists
internal bool OnDirExists(FTP_Session session,string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,dir,"");
if(this.DirExists != null){
this.DirExists(this,oArg);
}
return oArg.Validated;
}
#endregion
#region method OnCreateDir
internal bool OnCreateDir(FTP_Session session,string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,dir,"");
if(this.CreateDir != null){
this.CreateDir(this,oArg);
}
return oArg.Validated;
}
#endregion
#region method OnDeleteDir
internal bool OnDeleteDir(FTP_Session session,string dir)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,dir,"");
if(this.DeleteDir != null){
this.DeleteDir(this,oArg);
}
return oArg.Validated;
}
#endregion
#region method OnRenameDirFile
internal bool OnRenameDirFile(FTP_Session session,string from,string to)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,from,to);
if(this.RenameDirFile != null){
this.RenameDirFile(this,oArg);
}
return oArg.Validated;
}
#endregion
#region method OnFileExists
internal bool OnFileExists(FTP_Session session,string file)
{
// Remove last /
file = file.Substring(0,file.Length - 1);
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,file,"");
if(this.FileExists != null){
this.FileExists(this,oArg);
}
return oArg.Validated;
}
#endregion
#region method OnGetFile
internal Stream OnGetFile(FTP_Session session,string file)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,file,"");
if(this.GetFile != null){
this.GetFile(this,oArg);
}
return oArg.FileStream;
}
#endregion
#region method OnStoreFile
internal Stream OnStoreFile(FTP_Session session,string file)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,file,"");
if(this.StoreFile != null){
this.StoreFile(this,oArg);
}
return oArg.FileStream;
}
#endregion
#region method OnDeleteFile
internal bool OnDeleteFile(FTP_Session session,string file)
{
FileSysEntry_EventArgs oArg = new FileSysEntry_EventArgs(session,file,"");
if(this.DeleteFile != null){
this.DeleteFile(this,oArg);
}
return oArg.Validated;
}
#endregion
#endregion
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap 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 of the License, or
// (at your option) any later version.
//
// SharpMap 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 SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using SharpMap.Styles;
namespace SharpMap.Rendering
{
/// <summary>
/// Defines an axis-aligned box around a label, used for collision detection
/// </summary>
public class LabelBox : IComparable<LabelBox>
{
private float _height;
private float _left;
private float _top;
private float _width;
/// <summary>
/// Initializes a new LabelBox instance
/// </summary>
/// <param name="left">Left side of box</param>
/// <param name="top">Top of box</param>
/// <param name="width">Width of the box</param>
/// <param name="height">Height of the box</param>
public LabelBox(float left, float top, float width, float height)
{
_left = left;
_top = top;
_width = width;
_height = height;
}
/// <summary>
/// Initializes a new LabelBox instance based on a rectangle
/// </summary>
/// <param name="rectangle"></param>
public LabelBox(RectangleF rectangle)
{
_left = rectangle.X;
_top = rectangle.Y;
_width = rectangle.Width;
_height = rectangle.Height;
}
/// <summary>
/// The Left tie-point for the Label
/// </summary>
public float Left
{
get { return _left; }
set { _left = value; }
}
/// <summary>
/// The Top tie-point for the label
/// </summary>
public float Top
{
get { return _top; }
set { _top = value; }
}
/// <summary>
/// Width of the box
/// </summary>
public float Width
{
get { return _width; }
set { _width = value; }
}
/// <summary>
/// Height of the box
/// </summary>
public float Height
{
get { return _height; }
set { _height = value; }
}
/// <summary>
/// Right side of the box
/// </summary>
public float Right
{
get { return _left + _width; }
}
/// <summary>
/// Bottom of the box
/// </summary>
public float Bottom
{
get { return _top - _height; }
}
#region IComparable<LabelBox> Members
/// <summary>
/// Returns 0 if the boxes intersects each other
/// </summary>
/// <param name="other">labelbox to perform intersectiontest with</param>
/// <returns>0 if the intersect</returns>
public int CompareTo(LabelBox other)
{
if (Intersects(other))
return 0;
else if (other.Left > Right ||
other.Bottom > Top)
return 1;
else
return -1;
}
#endregion
/// <summary>
/// Determines whether the boundingbox intersects another boundingbox
/// </summary>
/// <param name="box"></param>
/// <returns></returns>
public bool Intersects(LabelBox box)
{
return !(box.Left > Right ||
box.Right < Left ||
box.Bottom > Top ||
box.Top < Bottom);
}
}
/// <summary>
/// Class for storing a label instance
/// </summary>
public abstract class BaseLabel : IComparable<BaseLabel>, IComparer<BaseLabel>
{
private LabelBox _box;
private Font _Font;
//private PointF _LabelPoint;
private int _Priority;
private float _Rotation;
private bool _show;
private LabelStyle _Style;
private string _Text;
private TextOnPath _textOnPath = null;
/// <summary>
/// Render text on path
/// </summary>
public TextOnPath TextOnPathLabel
{
get { return _textOnPath; }
set { _textOnPath = value; }
}
/// <summary>
/// Initializes a new Label instance
/// </summary>
/// <param name="text">Text to write</param>
/// <param name="rotation">Rotation</param>
/// <param name="priority">Label priority used for collision detection</param>
/// <param name="collisionbox">Box around label for collision detection</param>
/// <param name="style">The style of the label</param>
protected BaseLabel(string text, float rotation, int priority, LabelBox collisionbox,
LabelStyle style)
{
_Text = text;
//_LabelPoint = labelpoint;
_Rotation = rotation;
_Priority = priority;
_box = collisionbox;
_Style = style;
_show = true;
}
/// <summary>
/// Initializes a new Label instance
/// </summary>
/// <param name="text"></param>
/// <param name="rotation"></param>
/// <param name="priority"></param>
/// <param name="style"></param>
protected BaseLabel(string text, float rotation, int priority,
LabelStyle style)
{
_Text = text;
//_LabelPoint = labelpoint;
_Rotation = rotation;
_Priority = priority;
_Style = style;
_show = true;
}
/// <summary>
/// Show this label or don't
/// </summary>
public bool Show
{
get { return _show; }
set { _show = value; }
}
/// <summary>
/// The text of the label
/// </summary>
public string Text
{
get { return _Text; }
set { _Text = value; }
}
/// <summary>
/// Label font
/// </summary>
public Font Font
{
get { return _Font; }
set { _Font = value; }
}
/// <summary>
/// Label rotation
/// </summary>
public float Rotation
{
get { return _Rotation; }
set { _Rotation = value; }
}
/// <summary>
/// Value indicating rendering priority
/// </summary>
public int Priority
{
get { return _Priority; }
set { _Priority = value; }
}
/// <summary>
/// Label box
/// </summary>
public LabelBox Box
{
get { return _box; }
set { _box = value; }
}
/// <summary>
/// Gets or sets the <see cref="SharpMap.Styles.LabelStyle"/> of this label
/// </summary>
public LabelStyle Style
{
get { return _Style; }
set { _Style = value; }
}
#region IComparable<Label> Members
/// <summary>
/// Tests if two label boxes intersects
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(BaseLabel other)
{
if (this.TextOnPathLabel != null)
{
return CompareToTextOnPath(other);
}
if (this == other)
return 0;
if (_box == null)
return -1;
if (other.Box == null)
return 1;
return _box.CompareTo(other.Box);
}
private int CompareToTextOnPath(BaseLabel other)
{
if (this == other)
return 0;
if (TextOnPathLabel == null)
return -1;
if (other.TextOnPathLabel == null)
return 1;
for (int i = 0; i < TextOnPathLabel.RegionList.Count; i++)
{
for (int j = 0; j < other.TextOnPathLabel.RegionList.Count; j++)
{
if (TextOnPathLabel.RegionList[i].IntersectsWith(other.TextOnPathLabel.RegionList[j]))
return 0;
}
}
if (_box == null)
return -1;
if (other.Box == null)
return 1;
if (other.Box.Left > this.Box.Right ||
other.Box.Bottom > this.Box.Top)
return 1;
else
return -1;
}
#endregion
#region IComparer<BaseLabel> Members
/// <summary>
/// Checks if two labels intersect
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(BaseLabel x, BaseLabel y)
{
return x.CompareTo(y);
}
#endregion
}
/// <summary>
/// Type specific base label class
/// </summary>
/// <typeparam name="T">The type of the location</typeparam>
public abstract class BaseLabel<T> : BaseLabel
{
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="text">The label text</param>
/// <param name="location">The position of label</param>
/// <param name="rotation">The rotation of the label (in degrees)</param>
/// <param name="priority">A priority value. Labels with lower priority are less likely to be rendered</param>
/// <param name="collisionbox">A bounding box for collision detection</param>
/// <param name="style">The label style to apply upon rendering</param>
protected BaseLabel(string text, T location, float rotation, int priority, LabelBox collisionbox, LabelStyle style)
: base(text, rotation, priority, collisionbox, style)
{
//if (typeof(T) is ValueType)
if (location==null)
return;
if (!(location is PointF || location is GraphicsPath))
throw new ArgumentException("Invalid location type", "location");
Location = location;
}
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="text">The label text</param>
/// <param name="location">The position of label</param>
/// <param name="rotation">The rotation of the label (in degrees)</param>
/// <param name="priority">A priority value. Labels with lower priority are less likely to be rendered</param>
/// <param name="style">The label style to apply upon rendering</param>
protected BaseLabel(string text, T location, float rotation, int priority, LabelStyle style)
: base(text, rotation, priority, style)
{
if (location == null)
return;
if (!(location is PointF || location is GraphicsPath))
throw new ArgumentException("Invalid location type", "location");
Location = location;
}
/// <summary>
/// Gets or sets the location of the label
/// </summary>
public T Location { get; set; }
}
/// <summary>
/// A label that is to be rendered on a <see cref="GraphicsPath"/>
/// </summary>
public class PathLabel : BaseLabel<GraphicsPath>
{
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="text">The label text</param>
/// <param name="location">The position of label</param>
/// <param name="rotation">The rotation of the label (in degrees)</param>
/// <param name="priority">A priority value. Labels with lower priority are less likely to be rendered</param>
/// <param name="collisionbox">A bounding box used for collision detection</param>
/// <param name="style">The label style to apply upon rendering</param>
public PathLabel(string text, GraphicsPath location, float rotation, int priority, LabelBox collisionbox, LabelStyle style)
: base(text, location, rotation, priority, collisionbox, style)
{
}
}
/// <summary>
/// A label that is to be rendered at or around a <see cref="PointF"/>
/// </summary>
public class Label : BaseLabel<PointF>
{
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="text">The label text</param>
/// <param name="location">The position of label</param>
/// <param name="rotation">The rotation of the label (in degrees)</param>
/// <param name="priority">A priority value. Labels with lower priority are less likely to be rendered</param>
/// <param name="collisionbox">A bounding box used for collision detection</param>
/// <param name="style">The label style to apply upon rendering</param>
public Label(string text, PointF location, float rotation, int priority, LabelBox collisionbox, LabelStyle style)
: base(text, location, rotation, priority, collisionbox, style)
{
LabelPoint = location;
}
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="text">The label text</param>
/// <param name="location">The position of label</param>
/// <param name="rotation">The rotation of the label (in degrees)</param>
/// <param name="priority">A priority value. Labels with lower priority are less likely to be rendered</param>
/// <param name="style">The label style to apply upon rendering</param>
public Label(string text, PointF location, float rotation, int priority, LabelStyle style)
: base(text, location, rotation, priority, style)
{
LabelPoint = location;
}
/// <summary>
/// Label position
/// </summary>
public PointF LabelPoint
{
get;
set;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Security;
namespace System.DirectoryServices.Protocols
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class Luid
{
private readonly int _lowPart;
private readonly int _highPart;
public int LowPart => _lowPart;
public int HighPart => _highPart;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class SEC_WINNT_AUTH_IDENTITY_EX
{
public int version;
public int length;
public string user;
public int userLength;
public string domain;
public int domainLength;
public string password;
public int passwordLength;
public int flags;
public string packageList;
public int packageListLength;
}
internal enum BindMethod : uint
{
LDAP_AUTH_OTHERKIND = 0x86,
LDAP_AUTH_SICILY = LDAP_AUTH_OTHERKIND | 0x0200,
LDAP_AUTH_MSN = LDAP_AUTH_OTHERKIND | 0x0800,
LDAP_AUTH_NTLM = LDAP_AUTH_OTHERKIND | 0x1000,
LDAP_AUTH_DPA = LDAP_AUTH_OTHERKIND | 0x2000,
LDAP_AUTH_NEGOTIATE = LDAP_AUTH_OTHERKIND | 0x0400,
LDAP_AUTH_SSPI = LDAP_AUTH_NEGOTIATE,
LDAP_AUTH_DIGEST = LDAP_AUTH_OTHERKIND | 0x4000,
LDAP_AUTH_EXTERNAL = LDAP_AUTH_OTHERKIND | 0x0020
}
internal enum LdapOption
{
LDAP_OPT_DESC = 0x01,
LDAP_OPT_DEREF = 0x02,
LDAP_OPT_SIZELIMIT = 0x03,
LDAP_OPT_TIMELIMIT = 0x04,
LDAP_OPT_REFERRALS = 0x08,
LDAP_OPT_RESTART = 0x09,
LDAP_OPT_SSL = 0x0a,
LDAP_OPT_REFERRAL_HOP_LIMIT = 0x10,
LDAP_OPT_VERSION = 0x11,
LDAP_OPT_API_FEATURE_INFO = 0x15,
LDAP_OPT_HOST_NAME = 0x30,
LDAP_OPT_ERROR_NUMBER = 0x31,
LDAP_OPT_ERROR_STRING = 0x32,
LDAP_OPT_SERVER_ERROR = 0x33,
LDAP_OPT_SERVER_EXT_ERROR = 0x34,
LDAP_OPT_HOST_REACHABLE = 0x3E,
LDAP_OPT_PING_KEEP_ALIVE = 0x36,
LDAP_OPT_PING_WAIT_TIME = 0x37,
LDAP_OPT_PING_LIMIT = 0x38,
LDAP_OPT_DNSDOMAIN_NAME = 0x3B,
LDAP_OPT_GETDSNAME_FLAGS = 0x3D,
LDAP_OPT_PROMPT_CREDENTIALS = 0x3F,
LDAP_OPT_TCP_KEEPALIVE = 0x40,
LDAP_OPT_FAST_CONCURRENT_BIND = 0x41,
LDAP_OPT_SEND_TIMEOUT = 0x42,
LDAP_OPT_REFERRAL_CALLBACK = 0x70,
LDAP_OPT_CLIENT_CERTIFICATE = 0x80,
LDAP_OPT_SERVER_CERTIFICATE = 0x81,
LDAP_OPT_AUTO_RECONNECT = 0x91,
LDAP_OPT_SSPI_FLAGS = 0x92,
LDAP_OPT_SSL_INFO = 0x93,
LDAP_OPT_SIGN = 0x95,
LDAP_OPT_ENCRYPT = 0x96,
LDAP_OPT_SASL_METHOD = 0x97,
LDAP_OPT_AREC_EXCLUSIVE = 0x98,
LDAP_OPT_SECURITY_CONTEXT = 0x99,
LDAP_OPT_ROOTDSE_CACHE = 0x9a
}
internal enum ResultAll
{
LDAP_MSG_ALL = 1,
LDAP_MSG_RECEIVED = 2,
LDAP_MSG_POLLINGALL = 3
}
[StructLayout(LayoutKind.Sequential)]
internal sealed class LDAP_TIMEVAL
{
public int tv_sec;
public int tv_usec;
}
[StructLayout(LayoutKind.Sequential)]
internal sealed class berval
{
public int bv_len = 0;
public IntPtr bv_val = IntPtr.Zero;
public berval() { }
}
[StructLayout(LayoutKind.Sequential)]
internal sealed class SafeBerval
{
public int bv_len = 0;
public IntPtr bv_val = IntPtr.Zero;
~SafeBerval()
{
if (bv_val != IntPtr.Zero)
{
Marshal.FreeHGlobal(bv_val);
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class LdapControl
{
public IntPtr ldctl_oid = IntPtr.Zero;
public berval ldctl_value = null;
public bool ldctl_iscritical = false;
public LdapControl() { }
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct LdapReferralCallback
{
public int sizeofcallback;
public QUERYFORCONNECTIONInternal query;
public NOTIFYOFNEWCONNECTIONInternal notify;
public DEREFERENCECONNECTIONInternal dereference;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct CRYPTOAPI_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct SecPkgContext_IssuerListInfoEx
{
public IntPtr aIssuers;
public int cIssuers;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class LdapMod
{
public int type = 0;
public IntPtr attribute = IntPtr.Zero;
public IntPtr values = IntPtr.Zero;
~LdapMod()
{
if (attribute != IntPtr.Zero)
{
Marshal.FreeHGlobal(attribute);
}
if (values != IntPtr.Zero)
{
Marshal.FreeHGlobal(values);
}
}
}
internal class Wldap32
{
private const string Wldap32dll = "wldap32.dll";
public const int SEC_WINNT_AUTH_IDENTITY_UNICODE = 0x2;
public const int SEC_WINNT_AUTH_IDENTITY_VERSION = 0x200;
public const string MICROSOFT_KERBEROS_NAME_W = "Kerberos";
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_bind_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_bind_s([In]ConnectionHandle ldapHandle, string dn, SEC_WINNT_AUTH_IDENTITY_EX credentials, BindMethod method);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_initW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_init(string hostName, int portNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_connect", CharSet = CharSet.Unicode)]
public static extern int ldap_connect([In] ConnectionHandle ldapHandle, LDAP_TIMEVAL timeout);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_unbind", CharSet = CharSet.Unicode)]
public static extern int ldap_unbind([In] IntPtr ldapHandle);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int inValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr inValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_sechandle([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref SecurityHandle outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_secInfo([In] ConnectionHandle ldapHandle, [In] LdapOption option, [In, Out] SecurityPackageContextConnectionInformation outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_referral([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref LdapReferralCallback outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_clientcert([In] ConnectionHandle ldapHandle, [In] LdapOption option, QUERYCLIENTCERT outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_servercert([In] ConnectionHandle ldapHandle, [In] LdapOption option, VERIFYSERVERCERT outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "LdapGetLastError")]
public static extern int LdapGetLastError();
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "cldap_openW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr cldap_open(string hostName, int portNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_simple_bind_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_simple_bind_s([In] ConnectionHandle ldapHandle, string distinguishedName, string password);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_delete_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_delete_ext([In] ConnectionHandle ldapHandle, string dn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int ldap_result([In] ConnectionHandle ldapHandle, int messageId, int all, LDAP_TIMEVAL timeout, ref IntPtr Mesage);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref int serverError, ref IntPtr dn, ref IntPtr message, ref IntPtr referral, ref IntPtr control, byte freeIt);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_result_referral([In] ConnectionHandle ldapHandle, [In] IntPtr result, IntPtr serverError, IntPtr dn, IntPtr message, ref IntPtr referral, IntPtr control, byte freeIt);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_memfreeW", CharSet = CharSet.Unicode)]
public static extern void ldap_memfree([In] IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_value_free([In] IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_controls_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_controls_free([In] IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_abandon", CharSet = CharSet.Unicode)]
public static extern int ldap_abandon([In] ConnectionHandle ldapHandle, [In] int messagId);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_start_tls_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_start_tls(ConnectionHandle ldapHandle, ref int ServerReturnValue, ref IntPtr Message, IntPtr ServerControls, IntPtr ClientControls);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_stop_tls_s", CharSet = CharSet.Unicode)]
public static extern byte ldap_stop_tls(ConnectionHandle ldapHandle);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_rename_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_rename([In] ConnectionHandle ldapHandle, string dn, string newRdn, string newParentDn, int deleteOldRdn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_compare_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_compare([In] ConnectionHandle ldapHandle, string dn, string attributeName, string strValue, berval binaryValue, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_add_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_add([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_modify_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_modify([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_extended_operationW", CharSet = CharSet.Unicode)]
public static extern int ldap_extended_operation([In] ConnectionHandle ldapHandle, string oid, berval data, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_extended_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_extended_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr oid, ref IntPtr data, byte freeIt);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_msgfree", CharSet = CharSet.Unicode)]
public static extern int ldap_msgfree([In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_search_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_search([In] ConnectionHandle ldapHandle, string dn, int scope, string filter, IntPtr attributes, bool attributeOnly, IntPtr servercontrol, IntPtr clientcontrol, int timelimit, int sizelimit, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_entry", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_entry", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_reference", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_reference", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_dnW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_get_dn([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_attributeW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr address);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_attributeW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, [In, Out] IntPtr address);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_free", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_free([In] IntPtr berelement, int option);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_values_lenW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_get_values_len([In] ConnectionHandle ldapHandle, [In] IntPtr result, string name);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_free_len", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_value_free_len([In] IntPtr berelement);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_referenceW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr referrals);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_alloc_t", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_alloc(int option);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_emptyarg(BerSafeHandle berElement, string format);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_int(BerSafeHandle berElement, string format, int value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_bytearray(BerSafeHandle berElement, string format, HGlobalMemHandle value, int length);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_berarray(BerSafeHandle berElement, string format, IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_flatten", CharSet = CharSet.Unicode)]
public static extern int ber_flatten(BerSafeHandle berElement, ref IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_init", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_init(berval value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf(BerSafeHandle berElement, string format);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_int(BerSafeHandle berElement, string format, ref int value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_ptr(BerSafeHandle berElement, string format, ref IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_bitstring(BerSafeHandle berElement, string format, ref IntPtr value, ref int length);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvfree", CharSet = CharSet.Unicode)]
public static extern int ber_bvfree(IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvecfree", CharSet = CharSet.Unicode)]
public static extern int ber_bvecfree(IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_create_sort_controlW", CharSet = CharSet.Unicode)]
public static extern int ldap_create_sort_control(ConnectionHandle handle, IntPtr keys, byte critical, ref IntPtr control);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_control_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_control_free(IntPtr control);
[DllImport("Crypt32.dll", EntryPoint = "CertFreeCRLContext", CharSet = CharSet.Unicode)]
public static extern int CertFreeCRLContext(IntPtr certContext);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result2error", CharSet = CharSet.Unicode)]
public static extern int ldap_result2error([In] ConnectionHandle ldapHandle, [In] IntPtr result, int freeIt);
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Controls;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
using Point = System.Drawing.Point;
namespace DotSpatial.Plugins.ShapeEditor
{
/// <summary>
/// This function allows interacting with the map through mouse clicks to create a new shape.
/// </summary>
public class AddShapeFunction : SnappableMapFunction, IDisposable
{
#region Fields
private ContextMenu _context;
private CoordinateDialog _coordinateDialog;
private List<Coordinate> _coordinates;
private IFeatureSet _featureSet;
private MenuItem _finishPart;
private IFeatureLayer _layer;
private Point _mousePosition;
private List<List<Coordinate>> _parts;
private bool _standBy;
private IMapLineLayer _tempLayer;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AddShapeFunction"/> class. This specifies the Map that this function should be applied to.
/// </summary>
/// <param name="map">The map control that implements the IMap interface that this function uses.</param>
public AddShapeFunction(IMap map)
: base(map)
{
Configure();
}
/// <summary>
/// Finalizes an instance of the <see cref="AddShapeFunction"/> class.
/// </summary>
~AddShapeFunction()
{
Dispose(false);
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether the "dispose" method has been called.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Gets or sets the layer to which the shape is added.
/// </summary>
public IFeatureLayer Layer
{
get
{
return _layer;
}
set
{
if (_layer == value) return;
_layer = value;
_featureSet = _layer?.DataSet;
}
}
#endregion
#region Methods
/// <summary>
/// Delete the shape currently being edited.
/// </summary>
/// <param name="sender">The sender of the DeleteShape event.</param>
/// <param name="e">An empty EventArgument.</param>
public void DeleteShape(object sender, EventArgs e)
{
_coordinates = new List<Coordinate>();
_parts = new List<List<Coordinate>>();
Map.Invalidate();
}
/// <summary>
/// Actually, this creates disposable items but doesn't own them.
/// When the ribbon disposes it will remove the items.
/// </summary>
public void Dispose()
{
Dispose(true);
// This exists to prevent FX Cop from complaining.
GC.SuppressFinalize(this);
}
/// <summary>
/// Finish the part of the shape being edited.
/// </summary>
/// <param name="sender">The object sender.</param>
/// <param name="e">An empty EventArgs class.</param>
public void FinishPart(object sender, EventArgs e)
{
if (_featureSet.FeatureType == FeatureType.Polygon && !_coordinates[0].Equals2D(_coordinates[_coordinates.Count - 1])) _coordinates.Add(_coordinates[0]); // close polygons because they must be closed
_parts.Add(_coordinates);
_coordinates = new List<Coordinate>();
Map.Invalidate();
}
/// <summary>
/// Finish the shape.
/// </summary>
/// <param name="sender">The object sender.</param>
/// <param name="e">An empty EventArgs class.</param>
public void FinishShape(object sender, EventArgs e)
{
if (_featureSet != null && !_featureSet.IsDisposed)
{
Feature f = null;
if (_featureSet.FeatureType == FeatureType.MultiPoint)
{
f = new Feature(new MultiPoint(_coordinates.CastToPointArray()));
}
if (_featureSet.FeatureType == FeatureType.Line || _featureSet.FeatureType == FeatureType.Polygon)
{
FinishPart(sender, e);
Shape shp = new Shape(_featureSet.FeatureType);
foreach (List<Coordinate> part in _parts)
{
if (part.Count >= 2)
{
shp.AddPart(part, _featureSet.CoordinateType);
}
}
f = new Feature(shp);
}
if (f != null)
{
_featureSet.Features.Add(f);
}
_featureSet.ShapeIndices = null; // Reset shape indices
_featureSet.UpdateExtent();
_layer.AssignFastDrawnStates();
_featureSet.InvalidateVertices();
}
_coordinates = new List<Coordinate>();
_parts = new List<List<Coordinate>>();
}
/// <summary>
/// Disposes this handler, removing any buttons that it is responsible for adding.
/// </summary>
/// <param name="disposeManagedResources">Disposes of the resources.</param>
protected virtual void Dispose(bool disposeManagedResources)
{
if (!IsDisposed)
{
// One option would be to leave the non-working tools,
// but if this gets disposed we should clean up after
// ourselves and remove any added controls.
if (disposeManagedResources)
{
if (!_coordinateDialog.IsDisposed)
{
_coordinateDialog.Dispose();
}
_context?.Dispose();
_finishPart?.Dispose();
_featureSet = null;
_coordinates = null;
_coordinateDialog = null;
_tempLayer = null;
_context = null;
_finishPart = null;
_parts = null;
_layer = null;
}
IsDisposed = true;
}
}
/// <summary>
/// Forces this function to begin collecting points for building a new shape.
/// </summary>
protected override void OnActivate()
{
if (_coordinateDialog == null) _coordinateDialog = new CoordinateDialog();
_coordinateDialog.ShowZValues = _featureSet.CoordinateType == CoordinateType.Z;
_coordinateDialog.ShowMValues = _featureSet.CoordinateType == CoordinateType.M || _featureSet.CoordinateType == CoordinateType.Z;
if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint)
{
if (_context.MenuItems.Contains(_finishPart)) _context.MenuItems.Remove(_finishPart);
}
else if (!_context.MenuItems.Contains(_finishPart))
{
_context.MenuItems.Add(1, _finishPart);
}
_coordinateDialog.Show();
_coordinateDialog.FormClosing += CoordinateDialogFormClosing;
if (!_standBy) _coordinates = new List<Coordinate>();
if (_tempLayer != null)
{
Map.MapFrame.DrawingLayers.Remove(_tempLayer);
Map.MapFrame.Invalidate();
Map.Invalidate();
_tempLayer = null;
}
_standBy = false;
base.OnActivate();
}
/// <summary>
/// Allows for new behavior during deactivation.
/// </summary>
protected override void OnDeactivate()
{
if (_standBy)
{
return;
}
// Don't completely deactivate, but rather go into standby mode
// where we draw only the content that we have actually locked in.
_standBy = true;
_coordinateDialog?.Hide();
if (_coordinates != null && _coordinates.Count > 1)
{
LineString ls = new LineString(_coordinates.ToArray());
FeatureSet fs = new FeatureSet(FeatureType.Line);
fs.Features.Add(new Feature(ls));
MapLineLayer gll = new MapLineLayer(fs)
{
Symbolizer =
{
ScaleMode = ScaleMode.Symbolic,
Smoothing = true
},
MapFrame = Map.MapFrame
};
_tempLayer = gll;
Map.MapFrame.DrawingLayers.Add(gll);
Map.MapFrame.Invalidate();
Map.Invalidate();
}
Deactivate();
}
/// <summary>
/// Handles drawing of editing features.
/// </summary>
/// <param name="e">The drawing args for the draw method.</param>
protected override void OnDraw(MapDrawArgs e)
{
if (_standBy)
{
return;
}
// Begin snapping changes
DoSnapDrawing(e.Graphics, _mousePosition);
// End snapping changes
if (_featureSet.FeatureType == FeatureType.Point)
{
return;
}
// Draw any completed parts first so that they are behind my active drawing content.
if (_parts != null)
{
GraphicsPath gp = new GraphicsPath();
List<Point> partPoints = new List<Point>();
foreach (List<Coordinate> part in _parts)
{
partPoints.AddRange(part.Select(c => Map.ProjToPixel(c)));
if (_featureSet.FeatureType == FeatureType.Line)
{
gp.AddLines(partPoints.ToArray());
}
if (_featureSet.FeatureType == FeatureType.Polygon)
{
gp.AddPolygon(partPoints.ToArray());
}
partPoints.Clear();
}
e.Graphics.DrawPath(Pens.Blue, gp);
if (_featureSet.FeatureType == FeatureType.Polygon)
{
Brush fill = new SolidBrush(Color.FromArgb(70, Color.LightCyan));
e.Graphics.FillPath(fill, gp);
fill.Dispose();
}
}
Pen bluePen = new Pen(Color.Blue, 2F);
Pen redPen = new Pen(Color.Red, 3F);
Brush redBrush = new SolidBrush(Color.Red);
List<Point> points = new List<Point>();
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
if (_coordinates != null)
{
points.AddRange(_coordinates.Select(coord => Map.ProjToPixel(coord)));
foreach (Point pt in points)
{
e.Graphics.FillRectangle(redBrush, new Rectangle(pt.X - 2, pt.Y - 2, 4, 4));
}
if (points.Count > 1)
{
if (_featureSet.FeatureType != FeatureType.MultiPoint)
{
e.Graphics.DrawLines(bluePen, points.ToArray());
}
}
if (points.Count > 0 && _standBy == false)
{
if (_featureSet.FeatureType != FeatureType.MultiPoint)
{
e.Graphics.DrawLine(redPen, points[points.Count - 1], _mousePosition);
}
}
}
bluePen.Dispose();
redPen.Dispose();
redBrush.Dispose();
base.OnDraw(e);
}
/// <summary>
/// This method occurs as the mouse moves.
/// </summary>
/// <param name="e">The GeoMouseArcs class describes the mouse condition along with geographic coordinates.</param>
protected override void OnMouseMove(GeoMouseArgs e)
{
if (_standBy)
{
return;
}
// Begin snapping changes
Coordinate snappedCoord = e.GeographicLocation;
bool prevWasSnapped = IsSnapped;
IsSnapped = ComputeSnappedLocation(e, ref snappedCoord);
_coordinateDialog.X = snappedCoord.X;
_coordinateDialog.Y = snappedCoord.Y;
// End snapping changes
if (_coordinates != null && _coordinates.Count > 0)
{
List<Point> points = _coordinates.Select(coord => Map.ProjToPixel(coord)).ToList();
Rectangle oldRect = SymbologyGlobal.GetRectangle(_mousePosition, points[points.Count - 1]);
Rectangle newRect = SymbologyGlobal.GetRectangle(e.Location, points[points.Count - 1]);
Rectangle invalid = Rectangle.Union(newRect, oldRect);
invalid.Inflate(20, 20);
Map.Invalidate(invalid);
}
// Begin snapping changes
_mousePosition = IsSnapped ? Map.ProjToPixel(snappedCoord) : e.Location;
DoMouseMoveForSnapDrawing(prevWasSnapped, _mousePosition);
// End snapping changes
base.OnMouseMove(e);
}
/// <summary>
/// Handles the Mouse-Up situation.
/// </summary>
/// <param name="e">The GeoMouseArcs class describes the mouse condition along with geographic coordinates.</param>
protected override void OnMouseUp(GeoMouseArgs e)
{
if (_standBy)
{
return;
}
if (_featureSet == null || _featureSet.IsDisposed)
{
return;
}
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right)
{
// Add the current point to the featureset
if (_featureSet.FeatureType == FeatureType.Point)
{
// Begin snapping changes
Coordinate snappedCoord = _coordinateDialog.Coordinate;
ComputeSnappedLocation(e, ref snappedCoord);
// End snapping changes
Feature f = new Feature(snappedCoord);
_featureSet.Features.Add(f);
_featureSet.ShapeIndices = null; // Reset shape indices
_featureSet.UpdateExtent();
_layer.AssignFastDrawnStates();
_featureSet.InvalidateVertices();
return;
}
if (e.Button == MouseButtons.Right)
{
_context.Show((Control)Map, e.Location);
}
else
{
if (_coordinates == null)
{
_coordinates = new List<Coordinate>();
}
// Begin snapping changes
Coordinate snappedCoord = e.GeographicLocation;
ComputeSnappedLocation(e, ref snappedCoord);
// End snapping changes
_coordinates.Add(snappedCoord); // Snapping changes
if (_coordinates.Count > 1)
{
Point p1 = Map.ProjToPixel(_coordinates[_coordinates.Count - 1]);
Point p2 = Map.ProjToPixel(_coordinates[_coordinates.Count - 2]);
Rectangle invalid = SymbologyGlobal.GetRectangle(p1, p2);
invalid.Inflate(20, 20);
Map.Invalidate(invalid);
}
}
}
base.OnMouseUp(e);
}
/// <summary>
/// Occurs when this function is removed.
/// </summary>
protected override void OnUnload()
{
if (Enabled)
{
_coordinates = null;
_coordinateDialog.Hide();
}
if (_tempLayer != null)
{
Map.MapFrame.DrawingLayers.Remove(_tempLayer);
Map.MapFrame.Invalidate();
_tempLayer = null;
}
Map.Invalidate();
}
private void Configure()
{
YieldStyle = YieldStyles.LeftButton | YieldStyles.RightButton;
_context = new ContextMenu();
_context.MenuItems.Add("Delete", DeleteShape);
_finishPart = new MenuItem("Finish Part", FinishPart);
_context.MenuItems.Add(_finishPart);
_context.MenuItems.Add("Finish Shape", FinishShape);
_parts = new List<List<Coordinate>>();
}
private void CoordinateDialogFormClosing(object sender, FormClosingEventArgs e)
{
// This signals that we are done with editing, and should therefore close up shop
Enabled = false;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.TeleTrust;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Security
{
/// <summary>
/// Signer Utility class contains methods that can not be specifically grouped into other classes.
/// </summary>
public sealed class SignerUtilities
{
private SignerUtilities()
{
}
internal static readonly IDictionary algorithms = Platform.CreateHashtable();
internal static readonly IDictionary oids = Platform.CreateHashtable();
static SignerUtilities()
{
algorithms["MD2WITHRSA"] = "MD2withRSA";
algorithms["MD2WITHRSAENCRYPTION"] = "MD2withRSA";
algorithms[PkcsObjectIdentifiers.MD2WithRsaEncryption.Id] = "MD2withRSA";
algorithms["MD4WITHRSA"] = "MD4withRSA";
algorithms["MD4WITHRSAENCRYPTION"] = "MD4withRSA";
algorithms[PkcsObjectIdentifiers.MD4WithRsaEncryption.Id] = "MD4withRSA";
algorithms["MD5WITHRSA"] = "MD5withRSA";
algorithms["MD5WITHRSAENCRYPTION"] = "MD5withRSA";
algorithms[PkcsObjectIdentifiers.MD5WithRsaEncryption.Id] = "MD5withRSA";
algorithms["SHA1WITHRSA"] = "SHA-1withRSA";
algorithms["SHA1WITHRSAENCRYPTION"] = "SHA-1withRSA";
algorithms[PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id] = "SHA-1withRSA";
algorithms["SHA-1WITHRSA"] = "SHA-1withRSA";
algorithms["SHA224WITHRSA"] = "SHA-224withRSA";
algorithms["SHA224WITHRSAENCRYPTION"] = "SHA-224withRSA";
algorithms[PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id] = "SHA-224withRSA";
algorithms["SHA-224WITHRSA"] = "SHA-224withRSA";
algorithms["SHA256WITHRSA"] = "SHA-256withRSA";
algorithms["SHA256WITHRSAENCRYPTION"] = "SHA-256withRSA";
algorithms[PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id] = "SHA-256withRSA";
algorithms["SHA-256WITHRSA"] = "SHA-256withRSA";
algorithms["SHA384WITHRSA"] = "SHA-384withRSA";
algorithms["SHA384WITHRSAENCRYPTION"] = "SHA-384withRSA";
algorithms[PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id] = "SHA-384withRSA";
algorithms["SHA-384WITHRSA"] = "SHA-384withRSA";
algorithms["SHA512WITHRSA"] = "SHA-512withRSA";
algorithms["SHA512WITHRSAENCRYPTION"] = "SHA-512withRSA";
algorithms[PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id] = "SHA-512withRSA";
algorithms["SHA-512WITHRSA"] = "SHA-512withRSA";
algorithms["PSSWITHRSA"] = "PSSwithRSA";
algorithms["RSASSA-PSS"] = "PSSwithRSA";
algorithms[PkcsObjectIdentifiers.IdRsassaPss.Id] = "PSSwithRSA";
algorithms["RSAPSS"] = "PSSwithRSA";
algorithms["SHA1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1";
algorithms["SHA-1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1";
algorithms["SHA1WITHRSA/PSS"] = "SHA-1withRSAandMGF1";
algorithms["SHA-1WITHRSA/PSS"] = "SHA-1withRSAandMGF1";
algorithms["SHA224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1";
algorithms["SHA-224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1";
algorithms["SHA224WITHRSA/PSS"] = "SHA-224withRSAandMGF1";
algorithms["SHA-224WITHRSA/PSS"] = "SHA-224withRSAandMGF1";
algorithms["SHA256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1";
algorithms["SHA-256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1";
algorithms["SHA256WITHRSA/PSS"] = "SHA-256withRSAandMGF1";
algorithms["SHA-256WITHRSA/PSS"] = "SHA-256withRSAandMGF1";
algorithms["SHA384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1";
algorithms["SHA-384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1";
algorithms["SHA384WITHRSA/PSS"] = "SHA-384withRSAandMGF1";
algorithms["SHA-384WITHRSA/PSS"] = "SHA-384withRSAandMGF1";
algorithms["SHA512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1";
algorithms["SHA-512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1";
algorithms["SHA512WITHRSA/PSS"] = "SHA-512withRSAandMGF1";
algorithms["SHA-512WITHRSA/PSS"] = "SHA-512withRSAandMGF1";
algorithms["RIPEMD128WITHRSA"] = "RIPEMD128withRSA";
algorithms["RIPEMD128WITHRSAENCRYPTION"] = "RIPEMD128withRSA";
algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128.Id] = "RIPEMD128withRSA";
algorithms["RIPEMD160WITHRSA"] = "RIPEMD160withRSA";
algorithms["RIPEMD160WITHRSAENCRYPTION"] = "RIPEMD160withRSA";
algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160.Id] = "RIPEMD160withRSA";
algorithms["RIPEMD256WITHRSA"] = "RIPEMD256withRSA";
algorithms["RIPEMD256WITHRSAENCRYPTION"] = "RIPEMD256withRSA";
algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256.Id] = "RIPEMD256withRSA";
algorithms["NONEWITHRSA"] = "RSA";
algorithms["RSAWITHNONE"] = "RSA";
algorithms["RAWRSA"] = "RSA";
algorithms["RAWRSAPSS"] = "RAWRSASSA-PSS";
algorithms["NONEWITHRSAPSS"] = "RAWRSASSA-PSS";
algorithms["NONEWITHRSASSA-PSS"] = "RAWRSASSA-PSS";
algorithms["NONEWITHDSA"] = "NONEwithDSA";
algorithms["DSAWITHNONE"] = "NONEwithDSA";
algorithms["RAWDSA"] = "NONEwithDSA";
algorithms["DSA"] = "SHA-1withDSA";
algorithms["DSAWITHSHA1"] = "SHA-1withDSA";
algorithms["DSAWITHSHA-1"] = "SHA-1withDSA";
algorithms["SHA/DSA"] = "SHA-1withDSA";
algorithms["SHA1/DSA"] = "SHA-1withDSA";
algorithms["SHA-1/DSA"] = "SHA-1withDSA";
algorithms["SHA1WITHDSA"] = "SHA-1withDSA";
algorithms["SHA-1WITHDSA"] = "SHA-1withDSA";
algorithms[X9ObjectIdentifiers.IdDsaWithSha1.Id] = "SHA-1withDSA";
algorithms["DSAWITHSHA224"] = "SHA-224withDSA";
algorithms["DSAWITHSHA-224"] = "SHA-224withDSA";
algorithms["SHA224/DSA"] = "SHA-224withDSA";
algorithms["SHA-224/DSA"] = "SHA-224withDSA";
algorithms["SHA224WITHDSA"] = "SHA-224withDSA";
algorithms["SHA-224WITHDSA"] = "SHA-224withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha224.Id] = "SHA-224withDSA";
algorithms["DSAWITHSHA256"] = "SHA-256withDSA";
algorithms["DSAWITHSHA-256"] = "SHA-256withDSA";
algorithms["SHA256/DSA"] = "SHA-256withDSA";
algorithms["SHA-256/DSA"] = "SHA-256withDSA";
algorithms["SHA256WITHDSA"] = "SHA-256withDSA";
algorithms["SHA-256WITHDSA"] = "SHA-256withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha256.Id] = "SHA-256withDSA";
algorithms["DSAWITHSHA384"] = "SHA-384withDSA";
algorithms["DSAWITHSHA-384"] = "SHA-384withDSA";
algorithms["SHA384/DSA"] = "SHA-384withDSA";
algorithms["SHA-384/DSA"] = "SHA-384withDSA";
algorithms["SHA384WITHDSA"] = "SHA-384withDSA";
algorithms["SHA-384WITHDSA"] = "SHA-384withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha384.Id] = "SHA-384withDSA";
algorithms["DSAWITHSHA512"] = "SHA-512withDSA";
algorithms["DSAWITHSHA-512"] = "SHA-512withDSA";
algorithms["SHA512/DSA"] = "SHA-512withDSA";
algorithms["SHA-512/DSA"] = "SHA-512withDSA";
algorithms["SHA512WITHDSA"] = "SHA-512withDSA";
algorithms["SHA-512WITHDSA"] = "SHA-512withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha512.Id] = "SHA-512withDSA";
algorithms["NONEWITHECDSA"] = "NONEwithECDSA";
algorithms["ECDSAWITHNONE"] = "NONEwithECDSA";
algorithms["ECDSA"] = "SHA-1withECDSA";
algorithms["SHA1/ECDSA"] = "SHA-1withECDSA";
algorithms["SHA-1/ECDSA"] = "SHA-1withECDSA";
algorithms["ECDSAWITHSHA1"] = "SHA-1withECDSA";
algorithms["ECDSAWITHSHA-1"] = "SHA-1withECDSA";
algorithms["SHA1WITHECDSA"] = "SHA-1withECDSA";
algorithms["SHA-1WITHECDSA"] = "SHA-1withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha1.Id] = "SHA-1withECDSA";
algorithms[TeleTrusTObjectIdentifiers.ECSignWithSha1.Id] = "SHA-1withECDSA";
algorithms["SHA224/ECDSA"] = "SHA-224withECDSA";
algorithms["SHA-224/ECDSA"] = "SHA-224withECDSA";
algorithms["ECDSAWITHSHA224"] = "SHA-224withECDSA";
algorithms["ECDSAWITHSHA-224"] = "SHA-224withECDSA";
algorithms["SHA224WITHECDSA"] = "SHA-224withECDSA";
algorithms["SHA-224WITHECDSA"] = "SHA-224withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha224.Id] = "SHA-224withECDSA";
algorithms["SHA256/ECDSA"] = "SHA-256withECDSA";
algorithms["SHA-256/ECDSA"] = "SHA-256withECDSA";
algorithms["ECDSAWITHSHA256"] = "SHA-256withECDSA";
algorithms["ECDSAWITHSHA-256"] = "SHA-256withECDSA";
algorithms["SHA256WITHECDSA"] = "SHA-256withECDSA";
algorithms["SHA-256WITHECDSA"] = "SHA-256withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha256.Id] = "SHA-256withECDSA";
algorithms["SHA384/ECDSA"] = "SHA-384withECDSA";
algorithms["SHA-384/ECDSA"] = "SHA-384withECDSA";
algorithms["ECDSAWITHSHA384"] = "SHA-384withECDSA";
algorithms["ECDSAWITHSHA-384"] = "SHA-384withECDSA";
algorithms["SHA384WITHECDSA"] = "SHA-384withECDSA";
algorithms["SHA-384WITHECDSA"] = "SHA-384withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha384.Id] = "SHA-384withECDSA";
algorithms["SHA512/ECDSA"] = "SHA-512withECDSA";
algorithms["SHA-512/ECDSA"] = "SHA-512withECDSA";
algorithms["ECDSAWITHSHA512"] = "SHA-512withECDSA";
algorithms["ECDSAWITHSHA-512"] = "SHA-512withECDSA";
algorithms["SHA512WITHECDSA"] = "SHA-512withECDSA";
algorithms["SHA-512WITHECDSA"] = "SHA-512withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha512.Id] = "SHA-512withECDSA";
algorithms["RIPEMD160/ECDSA"] = "RIPEMD160withECDSA";
algorithms["ECDSAWITHRIPEMD160"] = "RIPEMD160withECDSA";
algorithms["RIPEMD160WITHECDSA"] = "RIPEMD160withECDSA";
algorithms[TeleTrusTObjectIdentifiers.ECSignWithRipeMD160.Id] = "RIPEMD160withECDSA";
algorithms["GOST-3410"] = "GOST3410";
algorithms["GOST-3410-94"] = "GOST3410";
algorithms["GOST3411WITHGOST3410"] = "GOST3410";
algorithms[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94.Id] = "GOST3410";
algorithms["ECGOST-3410"] = "ECGOST3410";
algorithms["ECGOST-3410-2001"] = "ECGOST3410";
algorithms["GOST3411WITHECGOST3410"] = "ECGOST3410";
algorithms[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001.Id] = "ECGOST3410";
oids["MD2withRSA"] = PkcsObjectIdentifiers.MD2WithRsaEncryption;
oids["MD4withRSA"] = PkcsObjectIdentifiers.MD4WithRsaEncryption;
oids["MD5withRSA"] = PkcsObjectIdentifiers.MD5WithRsaEncryption;
oids["SHA-1withRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption;
oids["SHA-224withRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption;
oids["SHA-256withRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption;
oids["SHA-384withRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption;
oids["SHA-512withRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption;
oids["PSSwithRSA"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-1withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-224withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-256withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-384withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-512withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["RIPEMD128withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128;
oids["RIPEMD160withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160;
oids["RIPEMD256withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256;
oids["SHA-1withDSA"] = X9ObjectIdentifiers.IdDsaWithSha1;
oids["SHA-1withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha1;
oids["SHA-224withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha224;
oids["SHA-256withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha256;
oids["SHA-384withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha384;
oids["SHA-512withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha512;
oids["GOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94;
oids["ECGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001;
}
/// <summary>
/// Returns an ObjectIdentifier for a given encoding.
/// </summary>
/// <param name="mechanism">A string representation of the encoding.</param>
/// <returns>A DerObjectIdentifier, null if the OID is not available.</returns>
// TODO Don't really want to support this
public static DerObjectIdentifier GetObjectIdentifier(
string mechanism)
{
if (mechanism == null)
throw new ArgumentNullException("mechanism");
mechanism = Platform.ToUpperInvariant(mechanism);
string aliased = (string) algorithms[mechanism];
if (aliased != null)
mechanism = aliased;
return (DerObjectIdentifier) oids[mechanism];
}
public static ICollection Algorithms
{
get { return oids.Keys; }
}
public static Asn1Encodable GetDefaultX509Parameters(
DerObjectIdentifier id)
{
return GetDefaultX509Parameters(id.Id);
}
public static Asn1Encodable GetDefaultX509Parameters(
string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
algorithm = Platform.ToUpperInvariant(algorithm);
string mechanism = (string) algorithms[algorithm];
if (mechanism == null)
mechanism = algorithm;
if (mechanism == "PSSwithRSA")
{
// TODO The Sha1Digest here is a default. In JCE version, the actual digest
// to be used can be overridden by subsequent parameter settings.
return GetPssX509Parameters("SHA-1");
}
if (mechanism.EndsWith("withRSAandMGF1"))
{
string digestName = mechanism.Substring(0, mechanism.Length - "withRSAandMGF1".Length);
return GetPssX509Parameters(digestName);
}
return DerNull.Instance;
}
private static Asn1Encodable GetPssX509Parameters(
string digestName)
{
AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
DigestUtilities.GetObjectIdentifier(digestName), DerNull.Instance);
// TODO Is it possible for the MGF hash alg to be different from the PSS one?
AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
PkcsObjectIdentifiers.IdMgf1, hashAlgorithm);
int saltLen = DigestUtilities.GetDigest(digestName).GetDigestSize();
return new RsassaPssParameters(hashAlgorithm, maskGenAlgorithm,
new DerInteger(saltLen), new DerInteger(1));
}
public static ISigner GetSigner(
DerObjectIdentifier id)
{
return GetSigner(id.Id);
}
public static ISigner GetSigner(
string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
algorithm = Platform.ToUpperInvariant(algorithm);
string mechanism = (string) algorithms[algorithm];
if (mechanism == null)
mechanism = algorithm;
if (mechanism.Equals("RSA"))
{
return (new RsaDigestSigner(new NullDigest(), (AlgorithmIdentifier)null));
}
if (mechanism.Equals("MD2withRSA"))
{
return (new RsaDigestSigner(new MD2Digest()));
}
if (mechanism.Equals("MD4withRSA"))
{
return (new RsaDigestSigner(new MD4Digest()));
}
if (mechanism.Equals("MD5withRSA"))
{
return (new RsaDigestSigner(new MD5Digest()));
}
if (mechanism.Equals("SHA-1withRSA"))
{
return (new RsaDigestSigner(new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withRSA"))
{
return (new RsaDigestSigner(new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withRSA"))
{
return (new RsaDigestSigner(new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withRSA"))
{
return (new RsaDigestSigner(new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withRSA"))
{
return (new RsaDigestSigner(new Sha512Digest()));
}
if (mechanism.Equals("RIPEMD128withRSA"))
{
return (new RsaDigestSigner(new RipeMD128Digest()));
}
if (mechanism.Equals("RIPEMD160withRSA"))
{
return (new RsaDigestSigner(new RipeMD160Digest()));
}
if (mechanism.Equals("RIPEMD256withRSA"))
{
return (new RsaDigestSigner(new RipeMD256Digest()));
}
if (mechanism.Equals("RAWRSASSA-PSS"))
{
// TODO Add support for other parameter settings
return PssSigner.CreateRawSigner(new RsaBlindedEngine(), new Sha1Digest());
}
if (mechanism.Equals("PSSwithRSA"))
{
// TODO The Sha1Digest here is a default. In JCE version, the actual digest
// to be used can be overridden by subsequent parameter settings.
return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-1withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha512Digest()));
}
if (mechanism.Equals("NONEwithDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new NullDigest()));
}
if (mechanism.Equals("SHA-1withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha512Digest()));
}
if (mechanism.Equals("NONEwithECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new NullDigest()));
}
if (mechanism.Equals("SHA-1withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha512Digest()));
}
if (mechanism.Equals("RIPEMD160withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new RipeMD160Digest()));
}
if (mechanism.Equals("SHA1WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha1Digest()));
}
if (mechanism.Equals("SHA224WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha224Digest()));
}
if (mechanism.Equals("SHA256WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha256Digest()));
}
if (mechanism.Equals("SHA384WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha384Digest()));
}
if (mechanism.Equals("SHA512WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha512Digest()));
}
if (mechanism.Equals("GOST3410"))
{
return new Gost3410DigestSigner(new Gost3410Signer(), new Gost3411Digest());
}
if (mechanism.Equals("ECGOST3410"))
{
return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411Digest());
}
if (mechanism.Equals("SHA1WITHRSA/ISO9796-2"))
{
return new Iso9796d2Signer(new RsaBlindedEngine(), new Sha1Digest(), true);
}
if (mechanism.Equals("MD5WITHRSA/ISO9796-2"))
{
return new Iso9796d2Signer(new RsaBlindedEngine(), new MD5Digest(), true);
}
if (mechanism.Equals("RIPEMD160WITHRSA/ISO9796-2"))
{
return new Iso9796d2Signer(new RsaBlindedEngine(), new RipeMD160Digest(), true);
}
if (mechanism.EndsWith("/X9.31"))
{
string x931 = mechanism.Substring(0, mechanism.Length - "/X9.31".Length);
int withPos = x931.IndexOf("WITH");
if (withPos > 0)
{
int endPos = withPos + "WITH".Length;
string digestName = x931.Substring(0, withPos);
IDigest digest = DigestUtilities.GetDigest(digestName);
string cipherName = x931.Substring(endPos, x931.Length - endPos);
if (cipherName.Equals("RSA"))
{
IAsymmetricBlockCipher cipher = new RsaBlindedEngine();
return new X931Signer(cipher, digest);
}
}
}
throw new SecurityUtilityException("Signer " + algorithm + " not recognised.");
}
public static string GetEncodingName(
DerObjectIdentifier oid)
{
return (string) algorithms[oid.Id];
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type GroupPhotosCollectionRequest.
/// </summary>
public partial class GroupPhotosCollectionRequest : BaseRequest, IGroupPhotosCollectionRequest
{
/// <summary>
/// Constructs a new GroupPhotosCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public GroupPhotosCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified ProfilePhoto to the collection via POST.
/// </summary>
/// <param name="profilePhoto">The ProfilePhoto to add.</param>
/// <returns>The created ProfilePhoto.</returns>
public System.Threading.Tasks.Task<ProfilePhoto> AddAsync(ProfilePhoto profilePhoto)
{
return this.AddAsync(profilePhoto, CancellationToken.None);
}
/// <summary>
/// Adds the specified ProfilePhoto to the collection via POST.
/// </summary>
/// <param name="profilePhoto">The ProfilePhoto to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ProfilePhoto.</returns>
public System.Threading.Tasks.Task<ProfilePhoto> AddAsync(ProfilePhoto profilePhoto, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<ProfilePhoto>(profilePhoto, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IGroupPhotosCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IGroupPhotosCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<GroupPhotosCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Expand(Expression<Func<ProfilePhoto, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Select(Expression<Func<ProfilePhoto, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IGroupPhotosCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien 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.
#endregion
#if DOTNET35
using System;
using System.Collections.Generic;
using Rhino.Mocks.Exceptions;
using Rhino.Mocks.Generated;
using Rhino.Mocks.Impl.RemotingMock;
using Rhino.Mocks.Interfaces;
namespace Rhino.Mocks
{
/// <summary>
/// A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks
/// </summary>
public static class RhinoMocksExtensions
{
/// <summary>
/// Create an expectation on this mock for this action to occur
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<VoidType> Expect<T>(this T mock, Action<T> action)
where T : class
{
return Expect<T, VoidType>(mock, t =>
{
action(t);
return null;
});
}
/// <summary>
/// Reset all expectations on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
public static void BackToRecord<T>(this T mock)
{
BackToRecord(mock, BackToRecordOptions.All);
}
/// <summary>
/// Reset the selected expectation on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="options">The options to reset the expectations on this mock.</param>
public static void BackToRecord<T>(this T mock, BackToRecordOptions options)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
var mocks = mockedObject.Repository;
mocks.BackToRecord(mock, options);
}
/// <summary>
/// Cause the mock state to change to replay, any further call is compared to the
/// ones that were called in the record state.
/// </summary>
/// <param name="mock">the mocked object to move to replay state</param>
public static void Replay<T>(this T mock)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
var mocks = mockedObject.Repository;
if (mocks.IsInReplayMode(mock) != true)
mocks.Replay(mockedObject);
}
/// <summary>
/// Gets the mock repository for this specificied mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <returns></returns>
public static MockRepository GetMockRepository<T>(this T mock)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
return mockedObject.Repository;
}
/// <summary>
/// Create an expectation on this mock for this action to occur
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<R> Expect<T, R>(this T mock, Function<T, R> action)
where T : class
{
if (mock == null)
throw new ArgumentNullException("mock", "You cannot mock a null instance");
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
MockRepository mocks = mockedObject.Repository;
var isInReplayMode = mocks.IsInReplayMode(mock);
mocks.BackToRecord(mock, BackToRecordOptions.None);
action(mock);
IMethodOptions<R> options = LastCall.GetOptions<R>();
options.TentativeReturn();
if (isInReplayMode)
mocks.ReplayCore(mock, false);
return options;
}
/// <summary>
/// Tell the mock object to perform a certain action when a matching
/// method is called.
/// Does not create an expectation for this method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<object> Stub<T>(this T mock, Action<T> action)
where T : class
{
return Stub<T, object>(mock, t =>
{
action(t);
return null;
});
}
/// <summary>
/// Tell the mock object to perform a certain action when a matching
/// method is called.
/// Does not create an expectation for this method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<R> Stub<T, R>(this T mock, Function<T, R> action)
where T : class
{
return Expect(mock, action).Repeat.Times(0, int.MaxValue);
}
/// <summary>
/// Gets the arguments for calls made on this mock object and the method that was called
/// in the action.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
/// <example>
/// Here we will get all the arguments for all the calls made to DoSomething(int)
/// <code>
/// var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0))
/// </code>
/// </example>
public static IList<object[]> GetArgumentsForCallsMadeOn<T>(this T mock, Action<T> action)
{
return GetArgumentsForCallsMadeOn(mock, action, DefaultConstraintSetup);
}
/// <summary>
/// Gets the arguments for calls made on this mock object and the method that was called
/// in the action and matches the given constraints
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
/// <returns></returns>
/// <example>
/// Here we will get all the arguments for all the calls made to DoSomething(int)
/// <code>
/// var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0))
/// </code>
/// </example>
public static IList<object[]> GetArgumentsForCallsMadeOn<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
return GetExpectationsToVerify(mock, action, setupConstraints).ArgumentsForAllCalls;
}
/// <summary>
/// Asserts that a particular method was called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasCalled<T>(this T mock, Action<T> action)
{
AssertWasCalled(mock, action, DefaultConstraintSetup);
}
private static void DefaultConstraintSetup(IMethodOptions<object> options)
{
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasCalled<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints);
foreach (var args in verificationInformation.ArgumentsForAllCalls)
{
if (verificationInformation.Expected.IsExpected(args))
{
verificationInformation.Expected.AddActualCall();
}
}
if (verificationInformation.Expected.ExpectationSatisfied)
return;
throw new ExpectationViolationException(verificationInformation.Expected.BuildVerificationFailureMessage());
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasCalled<T>(this T mock, Func<T, object> action)
{
var newAction = new Action<T>(t => action(t));
AssertWasCalled(mock, newAction, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasCalled<T>(this T mock, Func<T, object> action, Action<IMethodOptions<object>> setupConstraints)
{
var newAction = new Action<T>(t => action(t));
AssertWasCalled(mock, newAction, setupConstraints);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasNotCalled<T>(this T mock, Action<T> action)
{
AssertWasNotCalled(mock, action, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasNotCalled<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints);
foreach (var args in verificationInformation.ArgumentsForAllCalls)
{
if (verificationInformation.Expected.IsExpected(args))
throw new ExpectationViolationException("Expected that " +
verificationInformation.Expected.ErrorMessage +
" would not be called, but it was found on the actual calls made on the mocked object.");
}
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasNotCalled<T>(this T mock, Func<T, object> action)
{
var newAction = new Action<T>(t => action(t));
AssertWasNotCalled(mock, newAction, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasNotCalled<T>(this T mock, Func<T, object> action, Action<IMethodOptions<object>> setupConstraints)
{
var newAction = new Action<T>(t => action(t));
AssertWasNotCalled(mock, newAction, setupConstraints);
}
private static ExpectationVerificationInformation GetExpectationsToVerify<T>(T mock, Action<T> action,
Action<IMethodOptions<object>>
setupConstraints)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
MockRepository mocks = mockedObject.Repository;
if (mocks.IsInReplayMode(mockedObject) == false)
{
throw new InvalidOperationException(
"Cannot assert on an object that is not in replay mode. Did you forget to call ReplayAll() ?");
}
var mockToRecordExpectation =
(T)mocks.DynamicMock(FindAppropriteType<T>(mockedObject), mockedObject.ConstructorArguments);
action(mockToRecordExpectation);
AssertExactlySingleExpectaton(mocks, mockToRecordExpectation);
IMethodOptions<object> lastMethodCall = mocks.LastMethodCall<object>(mockToRecordExpectation);
lastMethodCall.TentativeReturn();
if (setupConstraints != null)
{
setupConstraints(lastMethodCall);
}
ExpectationsList expectationsToVerify = mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation);
if (expectationsToVerify.Count == 0)
throw new InvalidOperationException(
"The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()");
IExpectation expected = expectationsToVerify[0];
ICollection<object[]> argumentsForAllCalls = mockedObject.GetCallArgumentsFor(expected.Method);
return new ExpectationVerificationInformation
{
ArgumentsForAllCalls = new List<object[]>(argumentsForAllCalls),
Expected = expected
};
}
/// <summary>
/// Finds the approprite implementation type of this item.
/// This is the class or an interface outside of the rhino mocks.
/// </summary>
/// <param name="mockedObj">The mocked obj.</param>
/// <returns></returns>
private static Type FindAppropriteType<T>(IMockedObject mockedObj)
{
foreach (var type in mockedObj.ImplementedTypes)
{
if(type.IsClass && typeof(T).IsAssignableFrom(type))
return type;
}
foreach (var type in mockedObj.ImplementedTypes)
{
if(type.Assembly==typeof(IMockedObject).Assembly || !typeof(T).IsAssignableFrom(type))
continue;
return type;
}
return mockedObj.ImplementedTypes[0];
}
/// <summary>
/// Verifies all expectations on this mock object
/// </summary>
/// <param name="mockObject">The mock object.</param>
public static void VerifyAllExpectations(this object mockObject)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mockObject);
mockedObject.Repository.Verify(mockedObject);
}
/// <summary>
/// Gets the event raiser for the event that was called in the action passed
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <returns></returns>
public static IEventRaiser GetEventRaiser<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription)
where TEventSource : class
{
return mockObject
.Stub(eventSubscription)
.IgnoreArguments()
.GetEventRaiser();
}
/// <summary>
/// Raise the specified event using the passed arguments.
/// The even is extracted from the passed labmda
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public static void Raise<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription, object sender, EventArgs args)
where TEventSource : class
{
var eventRaiser = GetEventRaiser(mockObject, eventSubscription);
eventRaiser.Raise(sender, args);
}
/// <summary>
/// Raise the specified event using the passed arguments.
/// The even is extracted from the passed labmda
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <param name="args">The args.</param>
public static void Raise<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription, params object[] args)
where TEventSource : class
{
var eventRaiser = GetEventRaiser(mockObject, eventSubscription);
eventRaiser.Raise(args);
}
/// <summary>TODO: Make this better! It currently breaks down when mocking classes or
/// ABC's that call other virtual methods which are getting intercepted too. I wish
/// we could just walk Expression{Action{Action{T}} to assert only a single
/// method is being made.
///
/// The workaround is to not call foo.AssertWasCalled .. rather foo.VerifyAllExpectations()</summary>
/// <typeparam name="T">The type of mock object</typeparam>
/// <param name="mocks">The mock repository</param>
/// <param name="mockToRecordExpectation">The actual mock object to assert expectations on.</param>
private static void AssertExactlySingleExpectaton<T>(MockRepository mocks, T mockToRecordExpectation)
{
if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count == 0)
throw new InvalidOperationException(
"No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call");
if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count > 1)
throw new InvalidOperationException(
"You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations");
}
#region Nested type: VoidType
/// <summary>
/// Fake type that disallow creating it.
/// Should have been System.Type, but we can't use it.
/// </summary>
public class VoidType
{
private VoidType()
{
}
}
#endregion
internal static IMockedObject AsMockObject(this object mockedInstance)
{
IMockedObject mockedObj = mockedInstance.AsMockObjectOrNull();
if (mockedObj == null)
throw new InvalidOperationException("The object '" + mockedInstance +
"' is not a mocked object.");
return mockedObj;
}
/// <summary>
/// Method: GetMockedObjectOrNull
/// Get an IProxy from a mocked object instance, or null if the
/// object is not a mock object.
/// </summary>
internal static IMockedObject AsMockObjectOrNull(this object mockedInstance)
{
Delegate mockedDelegate = mockedInstance as Delegate;
if (mockedDelegate != null)
{
mockedInstance = mockedDelegate.Target;
}
// must be careful not to call any methods on mocked objects,
// or it may cause infinite recursion
if (mockedInstance is IMockedObject)
{
return (IMockedObject)mockedInstance;
}
if (RemotingMockGenerator.IsRemotingProxy(mockedInstance))
{
return RemotingMockGenerator.GetMockedObjectFromProxy(mockedInstance);
}
return null;
}
}
}
#endif
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_IOS
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using MsgPack.Serialization.DefaultSerializers;
namespace MsgPack.Serialization
{
/// <summary>
/// <strong>This is intened to MsgPack for CLI internal use. Do not use this type from application directly.</strong>
/// Defines serialization helper APIs.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class UnpackHelpers
{
private static readonly MessagePackSerializer<MessagePackObject> _messagePackObjectSerializer =
new MessagePackSerializer<MessagePackObject>(new MsgPack_MessagePackObjectMessagePackSerializer(PackerCompatibilityOptions.None));
/// <summary>
/// Unpacks the array to the specified array.
/// </summary>
/// <typeparam name="T">The type of the array element.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="serializer">The serializer to deserialize array.</param>
/// <param name="array">The array instance to be filled.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void UnpackArrayTo<T>(Unpacker unpacker, MessagePackSerializer<T> serializer, T[] array)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (array == null)
{
throw new ArgumentNullException("array");
}
if (!unpacker.IsArrayHeader)
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
T item;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
item = serializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
item = serializer.UnpackFrom(subtreeUnpacker);
}
}
array[i] = item;
}
}
/// <summary>
/// Unpacks the collection with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="collection">The non-generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void UnpackCollectionTo(Unpacker unpacker, IEnumerable collection, Action<object> addition)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (!unpacker.IsArrayHeader)
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
MessagePackObject item;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
item = _messagePackObjectSerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
item = _messagePackObjectSerializer.UnpackFrom(subtreeUnpacker);
}
}
addition(item);
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="serializer">The serializer to deserialize elements.</param>
/// <param name="collection">The generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void UnpackCollectionTo<T>(Unpacker unpacker, MessagePackSerializer<T> serializer, IEnumerable<T> collection, Action<T> addition)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (!unpacker.IsArrayHeader)
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
T item;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
item = serializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
item = serializer.UnpackFrom(subtreeUnpacker);
}
}
addition(item);
}
}
/// <summary>
/// Unpacks the collection with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="TDiscarded">The return type of Add method.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="collection">The non-generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void UnpackCollectionTo<TDiscarded>(Unpacker unpacker, IEnumerable collection, Func<object, TDiscarded> addition)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (!unpacker.IsArrayHeader)
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
MessagePackObject item;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
item = _messagePackObjectSerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
item = _messagePackObjectSerializer.UnpackFrom(subtreeUnpacker);
}
}
addition(item);
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <typeparam name="TDiscarded">The return type of Add method.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="serializer">The serializer to deserialize elements.</param>
/// <param name="collection">The generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void UnpackCollectionTo<T, TDiscarded>(Unpacker unpacker, MessagePackSerializer serializer, IEnumerable<T> collection, Func<T, TDiscarded> addition)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (!unpacker.IsArrayHeader)
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
T item;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
item = (T)serializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
item = (T)serializer.UnpackFrom(subtreeUnpacker);
}
}
addition(item);
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="TKey">The type of keys.</typeparam>
/// <typeparam name="TValue">The type of values.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="keySerializer">The serializer to deserialize key elements.</param>
/// <param name="valueSerializer">The serializer to deserialize value elements.</param>
/// <param name="dictionary">The generic dictionary instance to be added unpacked elements.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
#if UNITY_IOS
public static void UnpackMapToDictionary(Unpacker unpacker, MessagePackSerializer keySerializer, MessagePackSerializer valueSerializer, object dictionary)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
if (!unpacker.IsMapHeader)
{
throw SerializationExceptions.NewIsNotMapHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
object key;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
key = keySerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
key = keySerializer.UnpackFrom(subtreeUnpacker);
}
}
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
object value;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
value = valueSerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
value = valueSerializer.UnpackFrom(subtreeUnpacker);
}
}
var addMethod = dictionary.GetType().GetMethod("Add", new[] { keySerializer.TargetType, valueSerializer.TargetType });
addMethod.Invoke(dictionary, new[] { key, value });
}
}
#else
public static void UnpackMapTo<TKey, TValue>(Unpacker unpacker, MessagePackSerializer keySerializer, MessagePackSerializer valueSerializer, Dictionary<TKey, TValue> dictionary)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
if (!unpacker.IsMapHeader)
{
throw SerializationExceptions.NewIsNotMapHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
TKey key;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
key = (TKey)keySerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
key = (TKey)keySerializer.UnpackFrom(subtreeUnpacker);
}
}
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
TValue value;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
value = (TValue)valueSerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
value = (TValue)valueSerializer.UnpackFrom(subtreeUnpacker);
}
}
dictionary.Add(key, value);
}
}
#endif
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="dictionary">The non-generic dictionary instance to be added unpacked elements.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void UnpackMapTo(Unpacker unpacker, IDictionary dictionary)
{
#if DEBUG
if (unpacker == null)
{
throw new ArgumentNullException("unpacker");
}
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
if (!unpacker.IsMapHeader)
{
throw SerializationExceptions.NewIsNotMapHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount(unpacker);
for (int i = 0; i < count; i++)
{
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
MessagePackObject key;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
key = _messagePackObjectSerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
key = _messagePackObjectSerializer.UnpackFrom(subtreeUnpacker);
}
}
if (!unpacker.Read())
{
throw SerializationExceptions.NewMissingItem(i);
}
MessagePackObject value;
if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
{
value = _messagePackObjectSerializer.UnpackFrom(unpacker);
}
else
{
using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
{
value = _messagePackObjectSerializer.UnpackFrom(subtreeUnpacker);
}
}
dictionary.Add(key, value);
}
}
internal static int GetItemsCount(Unpacker unpacker)
{
long rawItemsCount;
try
{
rawItemsCount = unpacker.ItemsCount;
}
catch (InvalidOperationException ex)
{
throw SerializationExceptions.NewIsIncorrectStream(ex);
}
if (rawItemsCount > Int32.MaxValue)
{
throw SerializationExceptions.NewIsTooLargeCollection();
}
int count = unchecked((int)rawItemsCount);
return count;
}
internal static bool IsReadOnlyAppendableCollectionMember(MemberInfo memberInfo)
{
Contract.Requires(memberInfo != null);
if (memberInfo.CanSetValue())
{
// Not read only
return false;
}
Type memberValueType = memberInfo.GetMemberValueType();
if (memberValueType.IsArray)
{
// Not appendable
return false;
}
CollectionTraits traits = memberValueType.GetCollectionTraits();
return traits.CollectionType != CollectionKind.NotCollection && traits.AddMethod != null;
}
/// <summary>
/// Ensures the boxed type is not null thus it cannot be unboxing.
/// </summary>
/// <typeparam name="T">The type of the member.</typeparam>
/// <param name="boxed">The boxed deserializing value.</param>
/// <param name="name">The name of the member.</param>
/// <param name="targetType">The type of the target.</param>
/// <returns>The unboxed value.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static T ConvertWithEnsuringNotNull<T>(object boxed, string name, Type targetType)
{
if (typeof(T).GetIsValueType() && boxed == null && Nullable.GetUnderlyingType(typeof(T)) == null)
{
throw SerializationExceptions.NewValueTypeCannotBeNull(name, typeof(T), targetType);
}
return (T)boxed;
}
}
}
#else // UNITY_IOS
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using MsgPack.Serialization.DefaultSerializers;
namespace MsgPack.Serialization
{
/// <summary>
/// <strong>This is intened to MsgPack for CLI internal use. Do not use this type from application directly.</strong>
/// Defines serialization helper APIs.
/// </summary>
[EditorBrowsable( EditorBrowsableState.Never )]
public static class UnpackHelpers
{
private static readonly MessagePackSerializer<MessagePackObject> _messagePackObjectSerializer =
new MsgPack_MessagePackObjectMessagePackSerializer( PackerCompatibilityOptions.None );
/// <summary>
/// Unpacks the array to the specified array.
/// </summary>
/// <typeparam name="T">The type of the array element.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="serializer">The serializer to deserialize array.</param>
/// <param name="array">The array instance to be filled.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackArrayTo<T>( Unpacker unpacker, MessagePackSerializer<T> serializer, T[] array )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( array == null )
{
throw new ArgumentNullException( "array" );
}
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
T item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = serializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
item = serializer.UnpackFrom( subtreeUnpacker );
}
}
array[ i ] = item;
}
}
/// <summary>
/// Unpacks the collection with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="collection">The non-generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackCollectionTo( Unpacker unpacker, IEnumerable collection, Action<object> addition )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( collection == null )
{
throw new ArgumentNullException( "collection" );
}
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
MessagePackObject item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = _messagePackObjectSerializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
item = _messagePackObjectSerializer.UnpackFrom( subtreeUnpacker );
}
}
addition( item );
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="serializer">The serializer to deserialize elements.</param>
/// <param name="collection">The generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackCollectionTo<T>( Unpacker unpacker, MessagePackSerializer<T> serializer, IEnumerable<T> collection, Action<T> addition )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( collection == null )
{
throw new ArgumentNullException( "collection" );
}
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
T item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = serializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
item = serializer.UnpackFrom( subtreeUnpacker );
}
}
addition( item );
}
}
/// <summary>
/// Unpacks the collection with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="TDiscarded">The return type of Add method.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="collection">The non-generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackCollectionTo<TDiscarded>( Unpacker unpacker, IEnumerable collection, Func<object, TDiscarded> addition )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( collection == null )
{
throw new ArgumentNullException( "collection" );
}
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
MessagePackObject item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = _messagePackObjectSerializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
item = _messagePackObjectSerializer.UnpackFrom( subtreeUnpacker );
}
}
addition( item );
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <typeparam name="TDiscarded">The return type of Add method.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="serializer">The serializer to deserialize elements.</param>
/// <param name="collection">The generic collection instance to be added unpacked elements.</param>
/// <param name="addition">The delegate which contains the instance method of the <paramref name="collection"/>. The parameter is unpacked object.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackCollectionTo<T, TDiscarded>( Unpacker unpacker, MessagePackSerializer<T> serializer, IEnumerable<T> collection, Func<T, TDiscarded> addition )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( collection == null )
{
throw new ArgumentNullException( "collection" );
}
if ( !unpacker.IsArrayHeader )
{
throw SerializationExceptions.NewIsNotArrayHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
T item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = serializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
item = serializer.UnpackFrom( subtreeUnpacker );
}
}
addition( item );
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <typeparam name="TKey">The type of keys.</typeparam>
/// <typeparam name="TValue">The type of values.</typeparam>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="keySerializer">The serializer to deserialize key elements.</param>
/// <param name="valueSerializer">The serializer to deserialize value elements.</param>
/// <param name="dictionary">The generic dictionary instance to be added unpacked elements.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackMapTo<TKey, TValue>( Unpacker unpacker, MessagePackSerializer<TKey> keySerializer, MessagePackSerializer<TValue> valueSerializer, IDictionary<TKey, TValue> dictionary )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( dictionary == null )
{
throw new ArgumentNullException( "dictionary" );
}
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotMapHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
TKey key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = keySerializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
key = keySerializer.UnpackFrom( subtreeUnpacker );
}
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
TValue value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = valueSerializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
value = valueSerializer.UnpackFrom( subtreeUnpacker );
}
}
dictionary.Add( key, value );
}
}
/// <summary>
/// Unpacks the dictionary with the specified method as colletion of <see cref="MessagePackObject"/>.
/// </summary>
/// <param name="unpacker">The unpacker to unpack the underlying stream.</param>
/// <param name="dictionary">The non-generic dictionary instance to be added unpacked elements.</param>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialization.
/// </exception>
[EditorBrowsable( EditorBrowsableState.Never )]
public static void UnpackMapTo( Unpacker unpacker, IDictionary dictionary )
{
#if DEBUG
if ( unpacker == null )
{
throw new ArgumentNullException( "unpacker" );
}
if ( dictionary == null )
{
throw new ArgumentNullException( "dictionary" );
}
if ( !unpacker.IsMapHeader )
{
throw SerializationExceptions.NewIsNotMapHeader();
}
Contract.EndContractBlock();
#endif
int count = GetItemsCount( unpacker );
for ( int i = 0; i < count; i++ )
{
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
MessagePackObject key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = _messagePackObjectSerializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
key = _messagePackObjectSerializer.UnpackFrom( subtreeUnpacker );
}
}
if ( !unpacker.Read() )
{
throw SerializationExceptions.NewMissingItem( i );
}
MessagePackObject value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = _messagePackObjectSerializer.UnpackFrom( unpacker );
}
else
{
using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
{
value = _messagePackObjectSerializer.UnpackFrom( subtreeUnpacker );
}
}
dictionary.Add( key, value );
}
}
internal static int GetItemsCount( Unpacker unpacker )
{
long rawItemsCount;
try
{
rawItemsCount = unpacker.ItemsCount;
}
catch ( InvalidOperationException ex )
{
throw SerializationExceptions.NewIsIncorrectStream( ex );
}
if ( rawItemsCount > Int32.MaxValue )
{
throw SerializationExceptions.NewIsTooLargeCollection();
}
int count = unchecked( ( int )rawItemsCount );
return count;
}
internal static bool IsReadOnlyAppendableCollectionMember( MemberInfo memberInfo )
{
Contract.Requires( memberInfo != null );
if ( memberInfo.CanSetValue() )
{
// Not read only
return false;
}
Type memberValueType = memberInfo.GetMemberValueType();
if ( memberValueType.IsArray )
{
// Not appendable
return false;
}
CollectionTraits traits = memberValueType.GetCollectionTraits();
return traits.CollectionType != CollectionKind.NotCollection && traits.AddMethod != null;
}
/// <summary>
/// Ensures the boxed type is not null thus it cannot be unboxing.
/// </summary>
/// <typeparam name="T">The type of the member.</typeparam>
/// <param name="boxed">The boxed deserializing value.</param>
/// <param name="name">The name of the member.</param>
/// <param name="targetType">The type of the target.</param>
/// <returns>The unboxed value.</returns>
[EditorBrowsable( EditorBrowsableState.Never )]
public static T ConvertWithEnsuringNotNull<T>( object boxed, string name, Type targetType )
{
if ( typeof( T ).GetIsValueType() && boxed == null && Nullable.GetUnderlyingType( typeof( T ) ) == null )
{
throw SerializationExceptions.NewValueTypeCannotBeNull( name, typeof( T ), targetType );
}
return ( T )boxed;
}
/// <summary>
/// Invokes <see cref="MessagePackSerializer{T}.UnpackFromCore"/> FAMANDASM method directly.
/// </summary>
/// <typeparam name="T">The type of deserializing object.</typeparam>
/// <param name="serializer">The invocation target <see cref="MessagePackSerializer{T}"/>.</param>
/// <param name="unpacker">The unpacker to be passed to the method.</param>
/// <returns>A deserialized value.</returns>
[EditorBrowsable( EditorBrowsableState.Never )]
public static T InvokeUnpackFrom<T>( MessagePackSerializer<T> serializer, Unpacker unpacker )
{
return serializer.UnpackFromCore( unpacker );
}
}
}
#endif
| |
/*
* Copyright (c) 2011, Cloud Hsu
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Cloud Hsu 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 CLOUD HSU "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 REGENTS AND 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.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace CloudBox.TcpObject
{
/// <summary>
/// TCP IP Client
/// </summary>
public sealed class TCPIPClient : TCPSocket
{
/// <summary>
/// not use
/// </summary>
private TCPIPClient() { }
/// <summary>
/// MTCPIPClient construct
/// </summary>
/// <param name="a_i1ClientID">Client ID</param>
public TCPIPClient(byte a_i1ClientID)
: base(a_i1ClientID)
{
} // end of MTCPIPClient(string a_sClientID)
/// <summary>
/// MTCPIPClient Construct
/// </summary>
/// <param name="a_i1ClientID">Client ID</param>
/// <param name="a_sTargetName">Target Name</param>
/// <param name="a_sIP">Remote IP</param>
/// <param name="a_i4Port">Remote Port</param>
public TCPIPClient(byte a_i1ClientID,string a_sTargetName, string a_sIP, int a_i4Port)
: base(a_i1ClientID,a_sTargetName,a_sIP,a_i4Port)
{
} // end of MTCPIPClient(byte a_i1ClientID,string a_sIP,int a_i4Port)
/// <summary>
/// MTCPIPClient Construct, using for server accept a new client
/// </summary>
/// <param name="a_pClient">Socket Client</param>
/// <param name="a_i1ClientID">Client ID</param>
public TCPIPClient(Socket a_pClient, byte a_i1ClientID)
: base(a_pClient, a_i1ClientID)
{
} // end of MTCPIPClient(Socket a_pClient, string a_sClientID)
/// <summary>
/// Destructor
/// </summary>
~TCPIPClient()
{
Destory();
} // end of ~MTCPIPClient()
/// <summary>
/// Connect to server and set Client ID to server and start receive.
/// </summary>
public void Connect()
{
try
{
if (!IsConnected)
{
// new TCP/IP Socket
m_pClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_pClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 409600);
// connect to server
m_pClient.Connect(new IPEndPoint(IPAddress.Parse(m_sIP), m_i4Port));
TraceLog(LogLevel.LOG_LEVEL_NORMAL, "Connect to " + m_sIP + ":" + m_i4Port + " succeed.");
// create ID Message
MessageContent t_pMsg = new MessageContent(MessageConst.TYPE_CLIENT_ID, ClientID, MessageConst.SERVER_ID, new byte[] { ClientID });
// send ID to server
m_pClient.Send(t_pMsg.GetBytes());
TraceLog(LogLevel.LOG_LEVEL_NORMAL, "Send Client ID:" + ClientID + " succeed");
m_dtLastHandshakeTime = DateTime.Now;
m_pMsgHandshakeList.Clear();
// Start Receive Data
StartReceive();
} // end if(!m_bIsConnected)
}
catch (SocketException ex)
{
Debug.WriteLine(ex.NativeErrorCode + ":" + ex.Message + " In [Connect]");
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[ErrorCode]:{0},[SocketException]:{1} In [Connect]", ex.NativeErrorCode, ex.Message));
throw;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + " In [Connect]");
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[Exception]:{0} In [Connect]", ex.Message));
throw;
}
} // end of Connect()
/// <summary>
/// Retry connect to server and set Client ID to server and start receive.
/// </summary>
void RetryConnect()
{
try
{
if (!IsConnected)
{
// new TCP/IP Socket
m_pClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_pClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 409600);
// connect to server
m_pClient.Connect(new IPEndPoint(IPAddress.Parse(m_sIP), m_i4Port));
// create ID Message
MessageContent t_pMsg = new MessageContent(MessageConst.TYPE_CLIENT_ID, ClientID, MessageConst.SERVER_ID, new byte[] { ClientID });
// send ID to server
m_pClient.Send(t_pMsg.GetBytes());
m_dtLastHandshakeTime = DateTime.Now;
m_pMsgHandshakeList.Clear();
// Start Receive Data
StartReceive();
} // end if(!m_bIsConnected)
}
catch (SocketException)
{
throw;
}
catch (Exception)
{
throw;
}
} // end of RetryConnect()
/// <summary>
/// Connect to server and set Client ID to server and start receive.
/// If using no parameter construct, can call this function.
/// </summary>
/// <param name="a_sIP">Remote IP</param>
/// <param name="a_i4Port">Remote Port</param>
public void Connect(string a_sIP, int a_i4Port)
{
m_sIP = a_sIP;
m_i4Port = a_i4Port;
Connect();
} // end of Connect(string a_sIP, int a_i4Port)
/// <summary>
/// Disconnect the connection.
/// </summary>
void Disconnect()
{
try
{
if (m_pClient != null)
{
MessageContent t_pMsg = new MessageContent(MessageConst.TYPE_SHUTDOWN,
ClientID, MessageConst.SERVER_ID, ASCIIEncoding.ASCII.GetBytes("ByeBye"));
SendMessage(t_pMsg);
Thread.Sleep(100);
TraceLog(LogLevel.LOG_LEVEL_NORMAL, this.ToString() + " Disconnect Succeed.");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + " In [Disconnect]");
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[Exception]:{0} In [Disconnect]", ex.Message));
}
} // end of Disconnect()
/// <summary>
/// if auto handshake fail, reconnect(MsgType == TYPE_HANDSHAKE).
/// if message type is other message type do normal handshake fail
/// </summary>
/// <param name="a_pHandshakeMsg"></param>
protected override void DoHandshakeFail(MessageContent a_pHandshakeMsg)
{
if (a_pHandshakeMsg.MessageType == MessageConst.TYPE_HANDSHAKE)
{
TraceLog(LogLevel.LOG_LEVEL_WARRING, "Handshaking fail, it will shutdown socket.");
Disconnect();
Shutdown();
TraceLog(LogLevel.LOG_LEVEL_WARRING, "Handshaking fail, shutdown socket succeed.");
Thread.Sleep(500);
RetryConnect();
TraceLog(LogLevel.LOG_LEVEL_WARRING, "Handshaking fail, then retry connect succeed.");
}
else
{
base.DoHandshakeFail(a_pHandshakeMsg);
}
}
/// <summary>
/// Before shutdown, client need to send disconnect message to server.
/// </summary>
public override void Destory()
{
Disconnect();
base.Destory();
}
/// <summary>
/// do auto handshake for client(chamber/mainframe)
/// </summary>
protected override void AutoHandshake()
{
TimeSpan t_IdleTime = DateTime.Now.Subtract(m_dtLastHandshakeTime);
if (t_IdleTime.TotalSeconds >= AUTO_HANDSHAKE_TIME && IsConnected)
{
MessageContent t_pMsg = new MessageContent(MessageConst.TYPE_HANDSHAKE,
ClientID, MessageConst.SERVER_ID, ASCIIEncoding.ASCII.GetBytes("Handshaking Check"));
SendMessage(t_pMsg);
}
else if (t_IdleTime.TotalSeconds >= RETRY_CONNECT_TIME && !IsConnected)
{
m_dtLastHandshakeTime = DateTime.Now;
RetryConnect();
}
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial;
namespace Internal.Cryptography
{
internal static partial class PkcsHelpers
{
private static readonly byte[] s_pSpecifiedDefaultParameters = { 0x04, 0x00 };
#if !NETCOREAPP && !NETSTANDARD2_1
// Compatibility API.
internal static void AppendData(this IncrementalHash hasher, ReadOnlySpan<byte> data)
{
hasher.AppendData(data.ToArray());
}
#endif
internal static HashAlgorithmName GetDigestAlgorithm(Oid oid)
{
Debug.Assert(oid != null);
return GetDigestAlgorithm(oid.Value);
}
internal static HashAlgorithmName GetDigestAlgorithm(string oidValue, bool forVerification = false)
{
switch (oidValue)
{
case Oids.Md5:
case Oids.RsaPkcs1Md5 when forVerification:
return HashAlgorithmName.MD5;
case Oids.Sha1:
case Oids.RsaPkcs1Sha1 when forVerification:
return HashAlgorithmName.SHA1;
case Oids.Sha256:
case Oids.RsaPkcs1Sha256 when forVerification:
return HashAlgorithmName.SHA256;
case Oids.Sha384:
case Oids.RsaPkcs1Sha384 when forVerification:
return HashAlgorithmName.SHA384;
case Oids.Sha512:
case Oids.RsaPkcs1Sha512 when forVerification:
return HashAlgorithmName.SHA512;
default:
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, oidValue);
}
}
internal static string GetOidFromHashAlgorithm(HashAlgorithmName algName)
{
if (algName == HashAlgorithmName.MD5)
return Oids.Md5;
if (algName == HashAlgorithmName.SHA1)
return Oids.Sha1;
if (algName == HashAlgorithmName.SHA256)
return Oids.Sha256;
if (algName == HashAlgorithmName.SHA384)
return Oids.Sha384;
if (algName == HashAlgorithmName.SHA512)
return Oids.Sha512;
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algName.Name);
}
/// <summary>
/// This is not just a convenience wrapper for Array.Resize(). In DEBUG builds, it forces the array to move in memory even if no resize is needed. This should be used by
/// helper methods that do anything of the form "call a native api once to get the estimated size, call it again to get the data and return the data in a byte[] array."
/// Sometimes, that data consist of a native data structure containing pointers to other parts of the block. Using such a helper to retrieve such a block results in an intermittent
/// AV. By using this helper, you make that AV repro every time.
/// </summary>
public static byte[] Resize(this byte[] a, int size)
{
Array.Resize(ref a, size);
#if DEBUG
a = a.CloneByteArray();
#endif
return a;
}
public static void RemoveAt<T>(ref T[] arr, int idx)
{
Debug.Assert(arr != null);
Debug.Assert(idx >= 0);
Debug.Assert(idx < arr.Length);
if (arr.Length == 1)
{
arr = Array.Empty<T>();
return;
}
T[] tmp = new T[arr.Length - 1];
if (idx != 0)
{
Array.Copy(arr, 0, tmp, 0, idx);
}
if (idx < tmp.Length)
{
Array.Copy(arr, idx + 1, tmp, idx, tmp.Length - idx);
}
arr = tmp;
}
public static AttributeAsn[] NormalizeAttributeSet(
AttributeAsn[] setItems,
Action<byte[]> encodedValueProcessor = null)
{
byte[] normalizedValue;
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.PushSetOf();
foreach (AttributeAsn item in setItems)
{
item.Encode(writer);
}
writer.PopSetOf();
normalizedValue = writer.Encode();
if (encodedValueProcessor != null)
{
encodedValueProcessor(normalizedValue);
}
}
AsnReader reader = new AsnReader(normalizedValue, AsnEncodingRules.DER);
AsnReader setReader = reader.ReadSetOf();
AttributeAsn[] decodedSet = new AttributeAsn[setItems.Length];
int i = 0;
while (setReader.HasData)
{
AttributeAsn.Decode(setReader, out AttributeAsn item);
decodedSet[i] = item;
i++;
}
return decodedSet;
}
internal static byte[] EncodeContentInfo(
ReadOnlyMemory<byte> content,
string contentType,
AsnEncodingRules ruleSet = AsnEncodingRules.DER)
{
ContentInfoAsn contentInfo = new ContentInfoAsn
{
ContentType = contentType,
Content = content,
};
using (AsnWriter writer = new AsnWriter(ruleSet))
{
contentInfo.Encode(writer);
return writer.Encode();
}
}
public static CmsRecipientCollection DeepCopy(this CmsRecipientCollection recipients)
{
CmsRecipientCollection recipientsCopy = new CmsRecipientCollection();
foreach (CmsRecipient recipient in recipients)
{
X509Certificate2 originalCert = recipient.Certificate;
X509Certificate2 certCopy = new X509Certificate2(originalCert.Handle);
CmsRecipient recipientCopy;
if (recipient.RSAEncryptionPadding is null)
{
recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy);
}
else
{
recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy, recipient.RSAEncryptionPadding);
}
recipientsCopy.Add(recipientCopy);
GC.KeepAlive(originalCert);
}
return recipientsCopy;
}
public static byte[] UnicodeToOctetString(this string s)
{
byte[] octets = new byte[2 * (s.Length + 1)];
Encoding.Unicode.GetBytes(s, 0, s.Length, octets, 0);
return octets;
}
public static string OctetStringToUnicode(this byte[] octets)
{
if (octets.Length < 2)
return string.Empty; // Desktop compat: 0-length byte array maps to string.empty. 1-length byte array gets passed to Marshal.PtrToStringUni() with who knows what outcome.
string s = Encoding.Unicode.GetString(octets, 0, octets.Length - 2);
return s;
}
public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly)
{
using (X509Store store = new X509Store(storeName, storeLocation))
{
OpenFlags flags = OpenFlags.ReadOnly | OpenFlags.IncludeArchived;
if (openExistingOnly)
flags |= OpenFlags.OpenExistingOnly;
store.Open(flags);
X509Certificate2Collection certificates = store.Certificates;
return certificates;
}
}
/// <summary>
/// Desktop compat: We do not complain about multiple matches. Just take the first one and ignore the rest.
/// </summary>
public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
{
//
// Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly.
// Therefore, we trust that the string-ized byte array (serial or ski) in it is correct and canonicalized.
//
SubjectIdentifierType recipientIdentifierType = recipientIdentifier.Type;
switch (recipientIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value);
byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
string issuer = issuerSerial.IssuerName;
foreach (X509Certificate2 candidate in certs)
{
byte[] candidateSerialNumber = candidate.GetSerialNumber();
if (AreByteArraysEqual(candidateSerialNumber, serialNumber) && candidate.Issuer == issuer)
return candidate;
}
}
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
{
string skiString = (string)(recipientIdentifier.Value);
byte[] ski = skiString.ToSkiBytes();
foreach (X509Certificate2 cert in certs)
{
byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(cert);
if (AreByteArraysEqual(ski, candidateSki))
return cert;
}
}
break;
default:
// RecipientInfo's can only be created by this package so if this an invalid type, it's the package's fault.
Debug.Fail($"Invalid recipientIdentifier type: {recipientIdentifierType}");
throw new CryptographicException();
}
return null;
}
internal static bool AreByteArraysEqual(byte[] ba1, byte[] ba2)
{
if (ba1.Length != ba2.Length)
return false;
for (int i = 0; i < ba1.Length; i++)
{
if (ba1[i] != ba2[i])
return false;
}
return true;
}
/// <summary>
/// Asserts on bad or non-canonicalized input. Input must come from trusted sources.
///
/// Subject Key Identifier is string-ized as an upper case hex string. This format is part of the public api behavior and cannot be changed.
/// </summary>
internal static byte[] ToSkiBytes(this string skiString)
{
return skiString.UpperHexStringToByteArray();
}
public static string ToSkiString(this byte[] skiBytes)
{
return ToUpperHexString(skiBytes);
}
public static string ToBigEndianHex(this ReadOnlySpan<byte> bytes)
{
return ToUpperHexString(bytes);
}
/// <summary>
/// Asserts on bad or non-canonicalized input. Input must come from trusted sources.
///
/// Serial number is string-ized as a reversed upper case hex string. This format is part of the public api behavior and cannot be changed.
/// </summary>
internal static byte[] ToSerialBytes(this string serialString)
{
byte[] ba = serialString.UpperHexStringToByteArray();
Array.Reverse(ba);
return ba;
}
public static string ToSerialString(this byte[] serialBytes)
{
serialBytes = serialBytes.CloneByteArray();
Array.Reverse(serialBytes);
return ToUpperHexString(serialBytes);
}
#if NETCOREAPP || NETSTANDARD2_1
private static unsafe string ToUpperHexString(ReadOnlySpan<byte> ba)
{
fixed (byte* baPtr = ba)
{
return string.Create(ba.Length * 2, (Ptr: new IntPtr(baPtr), ba.Length), (span, args) =>
{
const string HexValues = "0123456789ABCDEF";
int p = 0;
foreach (byte b in new ReadOnlySpan<byte>((byte*)args.Ptr, args.Length))
{
span[p++] = HexValues[b >> 4];
span[p++] = HexValues[b & 0xF];
}
});
}
}
#else
private static string ToUpperHexString(ReadOnlySpan<byte> ba)
{
StringBuilder sb = new StringBuilder(ba.Length * 2);
for (int i = 0; i < ba.Length; i++)
{
sb.Append(ba[i].ToString("X2"));
}
return sb.ToString();
}
#endif
/// <summary>
/// Asserts on bad input. Input must come from trusted sources.
/// </summary>
private static byte[] UpperHexStringToByteArray(this string normalizedString)
{
Debug.Assert((normalizedString.Length & 0x1) == 0);
byte[] ba = new byte[normalizedString.Length / 2];
for (int i = 0; i < ba.Length; i++)
{
char c = normalizedString[i * 2];
byte b = (byte)(UpperHexCharToNybble(c) << 4);
c = normalizedString[i * 2 + 1];
b |= UpperHexCharToNybble(c);
ba[i] = b;
}
return ba;
}
/// <summary>
/// Asserts on bad input. Input must come from trusted sources.
/// </summary>
private static byte UpperHexCharToNybble(char c)
{
if (c >= '0' && c <= '9')
return (byte)(c - '0');
if (c >= 'A' && c <= 'F')
return (byte)(c - 'A' + 10);
Debug.Fail($"Invalid hex character: {c}");
throw new CryptographicException(); // This just keeps the compiler happy. We don't expect to reach this.
}
/// <summary>
/// Useful helper for "upgrading" well-known CMS attributes to type-specific objects such as Pkcs9DocumentName, Pkcs9DocumentDescription, etc.
/// </summary>
public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, byte[] encodedAttribute)
{
Pkcs9AttributeObject attributeObject = new Pkcs9AttributeObject(oid, encodedAttribute);
switch (oid.Value)
{
case Oids.DocumentName:
attributeObject = Upgrade<Pkcs9DocumentName>(attributeObject);
break;
case Oids.DocumentDescription:
attributeObject = Upgrade<Pkcs9DocumentDescription>(attributeObject);
break;
case Oids.SigningTime:
attributeObject = Upgrade<Pkcs9SigningTime>(attributeObject);
break;
case Oids.ContentType:
attributeObject = Upgrade<Pkcs9ContentType>(attributeObject);
break;
case Oids.MessageDigest:
attributeObject = Upgrade<Pkcs9MessageDigest>(attributeObject);
break;
#if NETCOREAPP || NETSTANDARD2_1
case Oids.LocalKeyId:
attributeObject = Upgrade<Pkcs9LocalKeyId>(attributeObject);
break;
#endif
default:
break;
}
return attributeObject;
}
private static T Upgrade<T>(Pkcs9AttributeObject basicAttribute) where T : Pkcs9AttributeObject, new()
{
T enhancedAttribute = new T();
enhancedAttribute.CopyFrom(basicAttribute);
return enhancedAttribute;
}
internal static byte[] OneShot(this ICryptoTransform transform, byte[] data)
{
return OneShot(transform, data, 0, data.Length);
}
internal static byte[] OneShot(this ICryptoTransform transform, byte[] data, int offset, int length)
{
if (transform.CanTransformMultipleBlocks)
{
return transform.TransformFinalBlock(data, offset, length);
}
using (MemoryStream memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, offset, length);
}
return memoryStream.ToArray();
}
}
public static ReadOnlyMemory<byte> DecodeOctetStringAsMemory(ReadOnlyMemory<byte> encodedOctetString)
{
AsnReader reader = new AsnReader(encodedOctetString, AsnEncodingRules.BER);
if (reader.PeekEncodedValue().Length != encodedOctetString.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (reader.TryReadPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> primitiveContents))
{
return primitiveContents;
}
byte[] tooBig = new byte[encodedOctetString.Length];
if (reader.TryCopyOctetStringBytes(tooBig, out int bytesWritten))
{
return tooBig.AsMemory(0, bytesWritten);
}
Debug.Fail("TryCopyOctetStringBytes failed with an over-allocated array");
throw new CryptographicException();
}
public static byte[] DecodeOctetString(ReadOnlyMemory<byte> encodedOctets)
{
// Read using BER because the CMS specification says the encoding is BER.
AsnReader reader = new AsnReader(encodedOctets, AsnEncodingRules.BER);
const int ArbitraryStackLimit = 256;
Span<byte> tmp = stackalloc byte[ArbitraryStackLimit];
// Use stackalloc 0 so data can later hold a slice of tmp.
ReadOnlySpan<byte> data = stackalloc byte[0];
byte[] poolBytes = null;
try
{
if (!reader.TryReadPrimitiveOctetStringBytes(out var contents))
{
if (reader.TryCopyOctetStringBytes(tmp, out int bytesWritten))
{
data = tmp.Slice(0, bytesWritten);
}
else
{
poolBytes = CryptoPool.Rent(reader.PeekContentBytes().Length);
if (!reader.TryCopyOctetStringBytes(poolBytes, out bytesWritten))
{
Debug.Fail("TryCopyOctetStringBytes failed with a provably-large-enough buffer");
throw new CryptographicException();
}
data = new ReadOnlySpan<byte>(poolBytes, 0, bytesWritten);
}
}
else
{
data = contents.Span;
}
reader.ThrowIfNotEmpty();
return data.ToArray();
}
finally
{
if (poolBytes != null)
{
CryptoPool.Return(poolBytes, data.Length);
}
}
}
public static byte[] EncodeOctetString(byte[] octets)
{
// Write using DER to support the most readers.
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.WriteOctetString(octets);
return writer.Encode();
}
}
private static readonly byte[] s_invalidEmptyOid = { 0x06, 0x00 };
public static byte[] EncodeUtcTime(DateTime utcTime)
{
const int maxLegalYear = 2049;
// Write using DER to support the most readers.
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
try
{
// Sending the DateTime through ToLocalTime here will cause the right normalization
// of DateTimeKind.Unknown.
//
// Unknown => Local (adjust) => UTC (adjust "back", add Z marker; matches Windows)
if (utcTime.Kind == DateTimeKind.Unspecified)
{
writer.WriteUtcTime(utcTime.ToLocalTime(), maxLegalYear);
}
else
{
writer.WriteUtcTime(utcTime, maxLegalYear);
}
return writer.Encode();
}
catch (ArgumentException ex)
{
throw new CryptographicException(ex.Message, ex);
}
}
}
public static DateTime DecodeUtcTime(byte[] encodedUtcTime)
{
// Read using BER because the CMS specification says the encoding is BER.
AsnReader reader = new AsnReader(encodedUtcTime, AsnEncodingRules.BER);
DateTimeOffset value = reader.ReadUtcTime();
reader.ThrowIfNotEmpty();
return value.UtcDateTime;
}
public static string DecodeOid(byte[] encodedOid)
{
// Windows compat.
if (s_invalidEmptyOid.AsSpan().SequenceEqual(encodedOid))
{
return string.Empty;
}
// Read using BER because the CMS specification says the encoding is BER.
AsnReader reader = new AsnReader(encodedOid, AsnEncodingRules.BER);
string value = reader.ReadObjectIdentifierAsString();
reader.ThrowIfNotEmpty();
return value;
}
public static bool TryGetRsaOaepEncryptionPadding(
ReadOnlyMemory<byte>? parameters,
out RSAEncryptionPadding rsaEncryptionPadding,
out Exception exception)
{
exception = null;
rsaEncryptionPadding = null;
if (parameters == null || parameters.Value.IsEmpty)
{
exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
return false;
}
try
{
OaepParamsAsn oaepParameters = OaepParamsAsn.Decode(parameters.Value, AsnEncodingRules.DER);
if (oaepParameters.MaskGenFunc.Algorithm.Value != Oids.Mgf1 ||
oaepParameters.MaskGenFunc.Parameters == null ||
oaepParameters.PSourceFunc.Algorithm.Value != Oids.PSpecified
)
{
exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
return false;
}
AlgorithmIdentifierAsn mgf1AlgorithmIdentifier = AlgorithmIdentifierAsn.Decode(oaepParameters.MaskGenFunc.Parameters.Value, AsnEncodingRules.DER);
if (mgf1AlgorithmIdentifier.Algorithm.Value != oaepParameters.HashFunc.Algorithm.Value)
{
exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
return false;
}
if (oaepParameters.PSourceFunc.Parameters != null &&
!oaepParameters.PSourceFunc.Parameters.Value.Span.SequenceEqual(s_pSpecifiedDefaultParameters))
{
exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
return false;
}
switch (oaepParameters.HashFunc.Algorithm.Value)
{
case Oids.Sha1:
rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA1;
return true;
case Oids.Sha256:
rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA256;
return true;
case Oids.Sha384:
rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA384;
return true;
case Oids.Sha512:
rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA512;
return true;
default:
exception = new CryptographicException(
SR.Cryptography_Cms_UnknownAlgorithm,
oaepParameters.HashFunc.Algorithm.Value);
return false;
}
}
catch (CryptographicException e)
{
exception = e;
return false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#if !UNIX
using System;
using System.Management.Automation;
using Dbg = System.Management.Automation.Diagnostics;
using System.Collections;
using System.IO;
using System.Management.Automation.Provider;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the base class from which all catalog commands are derived.
/// </summary>
public abstract class CatalogCommandsBase : PSCmdlet
{
/// <summary>
/// Path of folder/file to generate or validate the catalog file.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
public string CatalogFilePath
{
get
{
return catalogFilePath;
}
set
{
catalogFilePath = value;
}
}
private string catalogFilePath;
/// <summary>
/// Path of folder/file to generate or validate the catalog file.
/// </summary>
[Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
public string[] Path
{
get
{
return path;
}
set
{
path = value;
}
}
private string[] path;
//
// name of this command
//
private string commandName;
/// <summary>
/// Initializes a new instance of the CatalogCommandsBase class,
/// using the given command name.
/// </summary>
/// <param name="name">
/// The name of the command.
/// </param>
protected CatalogCommandsBase(string name) : base()
{
commandName = name;
}
private CatalogCommandsBase() : base() { }
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command either generate the Catalog or
/// Validates the existing Catalog.
/// </summary>
protected override void ProcessRecord()
{
//
// this cannot happen as we have specified the Path
// property to be mandatory parameter
//
Dbg.Assert((CatalogFilePath != null) && (CatalogFilePath.Length > 0),
"CatalogCommands: Param binder did not bind catalogFilePath");
Collection<string> paths = new Collection<string>();
if (Path != null)
{
foreach (string p in Path)
{
foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
{
if (ShouldProcess("Including path " + tempPath.ProviderPath, string.Empty, string.Empty))
{
paths.Add(tempPath.ProviderPath);
}
}
}
}
string drive = null;
// resolve catalog destination Path
if (!SessionState.Path.IsPSAbsolute(catalogFilePath, out drive) && !System.IO.Path.IsPathRooted(catalogFilePath))
{
catalogFilePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(catalogFilePath);
}
if (ShouldProcess(catalogFilePath))
{
PerformAction(paths, catalogFilePath);
}
}
/// <summary>
/// Performs the action i.e. Generate or Validate the Windows Catalog File.
/// </summary>
/// <param name="path">
/// The name of the Folder or file on which to perform the action.
/// </param>
/// <param name="catalogFilePath">
/// Path to Catalog
/// </param>
protected abstract void PerformAction(Collection<string> path, string catalogFilePath);
}
/// <summary>
/// Defines the implementation of the 'New-FileCatalog' cmdlet.
/// This cmdlet generates the catalog for File or Folder.
/// </summary>
[Cmdlet(VerbsCommon.New, "FileCatalog", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath",
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=786749")]
[OutputType(typeof(FileInfo))]
public sealed class NewFileCatalogCommand : CatalogCommandsBase
{
/// <summary>
/// Initializes a new instance of the New-FileCatalog class.
/// </summary>
public NewFileCatalogCommand() : base("New-FileCatalog") { }
/// <summary>
/// Catalog version.
/// </summary>
[Parameter()]
public int CatalogVersion
{
get
{
return catalogVersion;
}
set
{
catalogVersion = value;
}
}
// Based on the Catalog version we will decide which hashing Algorithm to use
private int catalogVersion = 1;
/// <summary>
/// Generate the Catalog for the Path.
/// </summary>
/// <param name="path">
/// File or Folder Path
/// </param>
/// <param name="catalogFilePath">
/// Path to Catalog
/// </param>
/// <returns>
/// True if able to Create Catalog or else False
/// </returns>
protected override void PerformAction(Collection<string> path, string catalogFilePath)
{
if (path.Count == 0)
{
// if user has not provided the path use current directory to generate catalog
path.Add(SessionState.Path.CurrentFileSystemLocation.Path);
}
FileInfo catalogFileInfo = new FileInfo(catalogFilePath);
// If Path points to the expected cat file make sure
// parent Directory exists other wise CryptoAPI fails to create a .cat file
if (catalogFileInfo.Extension.Equals(".cat", StringComparison.Ordinal))
{
System.IO.Directory.CreateDirectory(catalogFileInfo.Directory.FullName);
}
else
{
// This only creates Directory if it does not exists, Append a default name
System.IO.Directory.CreateDirectory(catalogFilePath);
catalogFilePath = System.IO.Path.Combine(catalogFilePath, "catalog.cat");
}
FileInfo catalogFile = CatalogHelper.GenerateCatalog(this, path, catalogFilePath, catalogVersion);
if (catalogFile != null)
{
WriteObject(catalogFile);
}
}
}
/// <summary>
/// Defines the implementation of the 'Test-FileCatalog' cmdlet.
/// This cmdlet validates the Integrity of catalog.
/// </summary>
[Cmdlet(VerbsDiagnostic.Test, "FileCatalog", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath",
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=786750")]
[OutputType(typeof(CatalogValidationStatus))]
[OutputType(typeof(CatalogInformation))]
public sealed class TestFileCatalogCommand : CatalogCommandsBase
{
/// <summary>
/// Initializes a new instance of the New-FileCatalog class.
/// </summary>
public TestFileCatalogCommand() : base("Test-FileCatalog") { }
/// <summary>
/// </summary>
[Parameter()]
public SwitchParameter Detailed
{
get { return detailed; }
set { detailed = value; }
}
private bool detailed = false;
/// <summary>
/// Patterns used to exclude files from DiskPaths and Catalog.
/// </summary>
[Parameter()]
public string[] FilesToSkip
{
get
{
return filesToSkip;
}
set
{
filesToSkip = value;
this.excludedPatterns = new WildcardPattern[filesToSkip.Length];
for (int i = 0; i < filesToSkip.Length; i++)
{
this.excludedPatterns[i] = WildcardPattern.Get(filesToSkip[i], WildcardOptions.IgnoreCase);
}
}
}
private string[] filesToSkip = null;
internal WildcardPattern[] excludedPatterns = null;
/// <summary>
/// Validate the Integrity of given Catalog.
/// </summary>
/// <param name="path">
/// File or Folder Path
/// </param>
/// <param name="catalogFilePath">
/// Path to Catalog
/// </param>
/// <returns>
/// True if able to Validate the Catalog and its not tampered or else False
/// </returns>
protected override void PerformAction(Collection<string> path, string catalogFilePath)
{
if (path.Count == 0)
{
// if user has not provided the path use the path of catalog file itself.
path.Add(new FileInfo(catalogFilePath).Directory.FullName);
}
CatalogInformation catalogInfo = CatalogHelper.ValidateCatalog(this, path, catalogFilePath, excludedPatterns);
if (detailed)
{
WriteObject(catalogInfo);
}
else
{
WriteObject(catalogInfo.Status);
}
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.