context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/rpc/ota_channel_provider_svc.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.RPC { /// <summary>Holder for reflection information generated from booking/rpc/ota_channel_provider_svc.proto</summary> public static partial class OtaChannelProviderSvcReflection { #region Descriptor /// <summary>File descriptor for booking/rpc/ota_channel_provider_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OtaChannelProviderSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cipib29raW5nL3JwYy9vdGFfY2hhbm5lbF9wcm92aWRlcl9zdmMucHJvdG8S", "F2hvbG1zLnR5cGVzLmJvb2tpbmcucnBjGhtnb29nbGUvcHJvdG9idWYvZW1w", "dHkucHJvdG8aNWJvb2tpbmcvY2hhbm5lbHMvb3RhX2NoYW5uZWxfcHJvdmlk", "ZXJfaW5kaWNhdG9yLnByb3RvGitib29raW5nL2NoYW5uZWxzL290YV9jaGFu", "bmVsX3Byb3ZpZGVyLnByb3RvGipwcmltaXRpdmUvc2VydmVyX2FjdGlvbl9j", "b25maXJtYXRpb24ucHJvdG8iMwoaT1RBQ2hhbm5lbFByb3ZpZGVyU3ZjUXVl", "cnkSFQoNcHJvdmlkZXJfY29kZRgBIAEoCSJhCh1PVEFDaGFubmVsUHJvdmlk", "ZXJBbGxSZXNwb25zZRJACgZyZXN1bHQYASADKAsyMC5ob2xtcy50eXBlcy5i", "b29raW5nLmNoYW5uZWxzLk9UQUNoYW5uZWxQcm92aWRlciKtAQodT1RBQ2hh", "bm5lbFByb3ZpZGVyU3ZjUmVzcG9uc2USSAoGcmVzdWx0GAEgASgOMjguaG9s", "bXMudHlwZXMuYm9va2luZy5ycGMuT1RBQ2hhbm5lbFByb3ZpZGVyU3ZjQ1JV", "RFJlc3VsdBJCCghwcm92aWRlchgCIAEoCzIwLmhvbG1zLnR5cGVzLmJvb2tp", "bmcuY2hhbm5lbHMuT1RBQ2hhbm5lbFByb3ZpZGVyKs4BCh9PVEFDaGFubmVs", "UHJvdmlkZXJTdmNDUlVEUmVzdWx0EjAKLE9UQV9DSEFOTkVMX1BST1ZJREVS", "X1NWQ19DUlVEX1JFU1VMVF9TVUNDRVNTEAASQAo8T1RBX0NIQU5ORUxfUFJP", "VklERVJfU1ZDX0NSVURfUkVTVUxUX0RVUExJQ0FURV9QUk9WSURFUl9DT0RF", "EAESNwozT1RBX0NIQU5ORUxfUFJPVklERVJfU1ZDX0NSVURfUkVTVUxUX1VO", "S09XTl9GQUlMVVJFEAIytwUKFU9UQUNoYW5uZWxQcm92aWRlclN2YxJVCgNB", "bGwSFi5nb29nbGUucHJvdG9idWYuRW1wdHkaNi5ob2xtcy50eXBlcy5ib29r", "aW5nLnJwYy5PVEFDaGFubmVsUHJvdmlkZXJBbGxSZXNwb25zZRJ6ChFHZXRC", "eVByb3ZpZGVyQ29kZRIzLmhvbG1zLnR5cGVzLmJvb2tpbmcucnBjLk9UQUNo", "YW5uZWxQcm92aWRlclN2Y1F1ZXJ5GjAuaG9sbXMudHlwZXMuYm9va2luZy5j", "aGFubmVscy5PVEFDaGFubmVsUHJvdmlkZXISdgoHR2V0QnlJZBI5LmhvbG1z", "LnR5cGVzLmJvb2tpbmcuY2hhbm5lbHMuT1RBQ2hhbm5lbFByb3ZpZGVySW5k", "aWNhdG9yGjAuaG9sbXMudHlwZXMuYm9va2luZy5jaGFubmVscy5PVEFDaGFu", "bmVsUHJvdmlkZXIScgoGQ3JlYXRlEjAuaG9sbXMudHlwZXMuYm9va2luZy5j", "aGFubmVscy5PVEFDaGFubmVsUHJvdmlkZXIaNi5ob2xtcy50eXBlcy5ib29r", "aW5nLnJwYy5PVEFDaGFubmVsUHJvdmlkZXJTdmNSZXNwb25zZRJyCgZVcGRh", "dGUSMC5ob2xtcy50eXBlcy5ib29raW5nLmNoYW5uZWxzLk9UQUNoYW5uZWxQ", "cm92aWRlcho2LmhvbG1zLnR5cGVzLmJvb2tpbmcucnBjLk9UQUNoYW5uZWxQ", "cm92aWRlclN2Y1Jlc3BvbnNlEmsKBkRlbGV0ZRIwLmhvbG1zLnR5cGVzLmJv", "b2tpbmcuY2hhbm5lbHMuT1RBQ2hhbm5lbFByb3ZpZGVyGi8uaG9sbXMudHlw", "ZXMucHJpbWl0aXZlLlNlcnZlckFjdGlvbkNvbmZpcm1hdGlvbkInWgtib29r", "aW5nL3JwY6oCF0hPTE1TLlR5cGVzLkJvb2tpbmcuUlBDYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.Booking.Channels.OtaChannelProviderIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Channels.OtaChannelProviderReflection.Descriptor, global::HOLMS.Types.Primitive.ServerActionConfirmationReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcCRUDResult), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcQuery), global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcQuery.Parser, new[]{ "ProviderCode" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.OTAChannelProviderAllResponse), global::HOLMS.Types.Booking.RPC.OTAChannelProviderAllResponse.Parser, new[]{ "Result" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcResponse), global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcResponse.Parser, new[]{ "Result", "Provider" }, null, null, null) })); } #endregion } #region Enums public enum OTAChannelProviderSvcCRUDResult { [pbr::OriginalName("OTA_CHANNEL_PROVIDER_SVC_CRUD_RESULT_SUCCESS")] Success = 0, [pbr::OriginalName("OTA_CHANNEL_PROVIDER_SVC_CRUD_RESULT_DUPLICATE_PROVIDER_CODE")] DuplicateProviderCode = 1, [pbr::OriginalName("OTA_CHANNEL_PROVIDER_SVC_CRUD_RESULT_UNKOWN_FAILURE")] UnkownFailure = 2, } #endregion #region Messages public sealed partial class OTAChannelProviderSvcQuery : pb::IMessage<OTAChannelProviderSvcQuery> { private static readonly pb::MessageParser<OTAChannelProviderSvcQuery> _parser = new pb::MessageParser<OTAChannelProviderSvcQuery>(() => new OTAChannelProviderSvcQuery()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OTAChannelProviderSvcQuery> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.OtaChannelProviderSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderSvcQuery() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderSvcQuery(OTAChannelProviderSvcQuery other) : this() { providerCode_ = other.providerCode_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderSvcQuery Clone() { return new OTAChannelProviderSvcQuery(this); } /// <summary>Field number for the "provider_code" field.</summary> public const int ProviderCodeFieldNumber = 1; private string providerCode_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ProviderCode { get { return providerCode_; } set { providerCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OTAChannelProviderSvcQuery); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OTAChannelProviderSvcQuery other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ProviderCode != other.ProviderCode) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ProviderCode.Length != 0) hash ^= ProviderCode.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 (ProviderCode.Length != 0) { output.WriteRawTag(10); output.WriteString(ProviderCode); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ProviderCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ProviderCode); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OTAChannelProviderSvcQuery other) { if (other == null) { return; } if (other.ProviderCode.Length != 0) { ProviderCode = other.ProviderCode; } } [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: { ProviderCode = input.ReadString(); break; } } } } } public sealed partial class OTAChannelProviderAllResponse : pb::IMessage<OTAChannelProviderAllResponse> { private static readonly pb::MessageParser<OTAChannelProviderAllResponse> _parser = new pb::MessageParser<OTAChannelProviderAllResponse>(() => new OTAChannelProviderAllResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OTAChannelProviderAllResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.OtaChannelProviderSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderAllResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderAllResponse(OTAChannelProviderAllResponse other) : this() { result_ = other.result_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderAllResponse Clone() { return new OTAChannelProviderAllResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Channels.OTAChannelProvider> _repeated_result_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.Channels.OTAChannelProvider.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Channels.OTAChannelProvider> result_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Channels.OTAChannelProvider>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Booking.Channels.OTAChannelProvider> Result { get { return result_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OTAChannelProviderAllResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OTAChannelProviderAllResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!result_.Equals(other.result_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= result_.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) { result_.WriteTo(output, _repeated_result_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += result_.CalculateSize(_repeated_result_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OTAChannelProviderAllResponse other) { if (other == null) { return; } result_.Add(other.result_); } [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: { result_.AddEntriesFrom(input, _repeated_result_codec); break; } } } } } public sealed partial class OTAChannelProviderSvcResponse : pb::IMessage<OTAChannelProviderSvcResponse> { private static readonly pb::MessageParser<OTAChannelProviderSvcResponse> _parser = new pb::MessageParser<OTAChannelProviderSvcResponse>(() => new OTAChannelProviderSvcResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OTAChannelProviderSvcResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.OtaChannelProviderSvcReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderSvcResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderSvcResponse(OTAChannelProviderSvcResponse other) : this() { result_ = other.result_; Provider = other.provider_ != null ? other.Provider.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProviderSvcResponse Clone() { return new OTAChannelProviderSvcResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcCRUDResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcCRUDResult Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "provider" field.</summary> public const int ProviderFieldNumber = 2; private global::HOLMS.Types.Booking.Channels.OTAChannelProvider provider_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Channels.OTAChannelProvider Provider { get { return provider_; } set { provider_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OTAChannelProviderSvcResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OTAChannelProviderSvcResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (!object.Equals(Provider, other.Provider)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (provider_ != null) hash ^= Provider.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 (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (provider_ != null) { output.WriteRawTag(18); output.WriteMessage(Provider); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (provider_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Provider); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OTAChannelProviderSvcResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.provider_ != null) { if (provider_ == null) { provider_ = new global::HOLMS.Types.Booking.Channels.OTAChannelProvider(); } Provider.MergeFrom(other.Provider); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Booking.RPC.OTAChannelProviderSvcCRUDResult) input.ReadEnum(); break; } case 18: { if (provider_ == null) { provider_ = new global::HOLMS.Types.Booking.Channels.OTAChannelProvider(); } input.ReadMessage(provider_); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ContainerInstance.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ContainerInstance.Fluent.Models; using Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroup.Definition; using Microsoft.Azure.Management.ContainerInstance.Fluent.ContainerGroup.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Storage.Fluent; using System.Collections.Generic; internal partial class ContainerGroupImpl { /// <summary> /// Specifies the private container image registry server login for the container group. /// </summary> /// <param name="server">Docker image registry server, without protocol such as "http" and "https".</param> /// <param name="username">The username for the private registry.</param> /// <param name="password">The password for the private registry.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithPrivateImageRegistryOrVolume ContainerGroup.Definition.IWithPrivateImageRegistry.WithPrivateImageRegistry(string server, string username, string password) { return this.WithPrivateImageRegistry(server, username, password); } /// <summary> /// Specifies the restart policy for all the container instances within the container group. /// </summary> /// <param name="restartPolicy">The restart policy for all the container instances within the container group.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithCreate ContainerGroup.Definition.IWithRestartPolicyBeta.WithRestartPolicy(ContainerGroupRestartPolicy restartPolicy) { return this.WithRestartPolicy(restartPolicy); } /// <summary> /// Skips the definition of volumes to be shared by the container instances. /// An IllegalArgumentException will be thrown if a container instance attempts to define a volume mounting. /// </summary> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithFirstContainerInstance ContainerGroup.Definition.IWithPrivateImageRegistryOrVolume.WithoutVolume() { return this.WithoutVolume(); } /// <summary> /// Specifies a new Azure file share name to be created. /// </summary> /// <param name="volumeName">The name of the volume.</param> /// <param name="shareName">The Azure file share name to be created.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithFirstContainerInstance ContainerGroup.Definition.IWithPrivateImageRegistryOrVolume.WithNewAzureFileShareVolume(string volumeName, string shareName) { return this.WithNewAzureFileShareVolume(volumeName, shareName); } /// <summary> /// Specifies an empty directory volume that can be shared by the container instances in the container group. /// </summary> /// <param name="name">The name of the empty directory volume.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithFirstContainerInstance ContainerGroup.Definition.IWithPrivateImageRegistryOrVolumeBeta.WithEmptyDirectoryVolume(string name) { return this.WithEmptyDirectoryVolume(name); } /// <summary> /// Begins the definition of a volume that can be shared by the container instances in the container group. /// The definition must be completed with a call to VolumeDefinitionStages.WithVolumeAttach.attach(). /// </summary> /// <param name="name">The name of the volume.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IVolumeDefinitionBlank<ContainerGroup.Definition.IWithVolume> ContainerGroup.Definition.IWithPrivateImageRegistryOrVolume.DefineVolume(string name) { return this.DefineVolume(name); } /// <summary> /// Begins the definition of a volume that can be shared by the container instances in the container group. /// The definition must be completed with a call to VolumeDefinitionStages.WithVolumeAttach.attach(). /// </summary> /// <param name="name">The name of the volume.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IVolumeDefinitionBlank<ContainerGroup.Definition.IWithVolume> ContainerGroup.Definition.IWithVolume.DefineVolume(string name) { return this.DefineVolume(name); } /// <summary> /// <summary> /// Restarts all containers in a container group in place. If container image has updates, new image will be downloaded. /// </summary> void Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.Restart() { this.Restart(); } /// <summary> /// Restarts all containers in a container group in place asynchronously. If container image has updates, new image will be downloaded. /// </summary> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.RestartAsync(CancellationToken cancellationToken) { await this.RestartAsync(cancellationToken); } /// <summary> /// Stops all containers in a container group. Compute resources will be de-allocated and billing will stop. /// </summary> void Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.Stop() { this.Stop(); } /// <summary> /// Stops all containers in a container group asynchronously. Compute resources will be de-allocated and billing will stop. /// </summary> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.StopAsync(CancellationToken cancellationToken) { await this.StopAsync(cancellationToken); } /// Defines one container instance for the specified image with one CPU count and 1.5 GB memory, with TCP port 80 opened externally. /// </summary> /// <param name="imageName">The name of the container image.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithCreate ContainerGroup.Definition.IWithFirstContainerInstance.WithContainerInstance(string imageName) { return this.WithContainerInstance(imageName); } /// <summary> /// Defines one container instance for the specified image with one CPU count and 1.5 GB memory, with a custom TCP port opened externally. /// </summary> /// <param name="imageName">The name of the container image.</param> /// <param name="port">The external port to be opened.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithCreate ContainerGroup.Definition.IWithFirstContainerInstance.WithContainerInstance(string imageName, int port) { return this.WithContainerInstance(imageName, port); } /// <summary> /// Begins the definition of a container instance. /// </summary> /// <param name="name">The name of the container instance.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IContainerInstanceDefinitionBlank<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithFirstContainerInstance.DefineContainerInstance(string name) { return this.DefineContainerInstance(name); } /// <summary> /// Specifies the DNS prefix to be used to create the FQDN for the container group. /// </summary> /// <param name="dnsPrefix">The DNS prefix to be used to create the FQDN for the container group.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithCreate ContainerGroup.Definition.IWithDnsPrefix.WithDnsPrefix(string dnsPrefix) { return this.WithDnsPrefix(dnsPrefix); } /// <summary> /// Only public container image repository will be used to create the container instances in the container group. /// </summary> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithPrivateImageRegistryOrVolume ContainerGroup.Definition.IWithPublicImageRegistryOnly.WithPublicImageRegistryOnly() { return this.WithPublicImageRegistryOnly(); } /// <summary> /// Gets true if IP address is public. /// </summary> bool Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.IsIPAddressPublic { get { return this.IsIPAddressPublic(); } } /// <summary> /// Gets the container instances in this container group. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string,Models.Container> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.Containers { get { return this.Containers(); } } /// <summary> /// Get the log content for the specified container instance within the container group. /// </summary> /// <param name="containerName">The container instance name.</param> /// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws> /// <return>A representation of the future computation of this call.</return> async Task<string> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.GetLogContentAsync(string containerName, CancellationToken cancellationToken) { return await this.GetLogContentAsync(containerName, cancellationToken); } /// <summary> /// Get the log content for the specified container instance within the container group. /// </summary> /// <param name="containerName">The container instance name.</param> /// <param name="tailLineCount">Only get the last log lines up to this.</param> /// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws> /// <return>A representation of the future computation of this call.</return> async Task<string> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.GetLogContentAsync(string containerName, int tailLineCount, CancellationToken cancellationToken) { return await this.GetLogContentAsync(containerName, tailLineCount, cancellationToken); } /// <summary> /// Gets the IP address. /// </summary> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.IPAddress { get { return this.IPAddress(); } } /// <summary> /// Gets the volumes for this container group. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string,Models.Volume> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.Volumes { get { return this.Volumes(); } } /// <summary> /// Gets the Docker image registry servers by which the container group is created from. /// </summary> System.Collections.Generic.IReadOnlyCollection<string> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ImageRegistryServers { get { return this.ImageRegistryServers(); } } /// <summary> /// Gets the TCP ports publicly exposed for this container group. /// </summary> int[] Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ExternalTcpPorts { get { return this.ExternalTcpPorts(); } } /// <summary> /// Gets the container group events. /// </summary> System.Collections.Generic.IReadOnlyCollection<Models.EventModel> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.Events { get { return this.Events(); } } /// <summary> /// Gets the provisioningState of the container group. /// </summary> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ProvisioningState { get { return this.ProvisioningState(); } } /// <summary> /// Get the log content for the specified container instance within the container group. /// </summary> /// <param name="containerName">The container instance name.</param> /// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws> /// <return>All available log lines.</return> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.GetLogContent(string containerName) { return this.GetLogContent(containerName); } /// <summary> /// Get the log content for the specified container instance within the container group. /// </summary> /// <param name="containerName">The container instance name.</param> /// <param name="tailLineCount">Only get the last log lines up to this.</param> /// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws> /// <return>The log lines from the end, up to the number specified.</return> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.GetLogContent(string containerName, int tailLineCount) { return this.GetLogContent(containerName, tailLineCount); } /// <summary> /// Gets the UDP ports publicly exposed for this container group. /// </summary> int[] Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ExternalUdpPorts { get { return this.ExternalUdpPorts(); } } /// <summary> /// Starts the exec command for a specific container instance. /// </summary> /// <param name="containerName">The container instance name.</param> /// <param name="command">The command to be executed.</param> /// <param name="row">The row size of the terminal.</param> /// <param name="column">The column size of the terminal.</param> /// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws> /// <return>The log lines from the end, up to the number specified.</return> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerExecResponse Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ExecuteCommand(string containerName, string command, int row, int column) { return this.ExecuteCommand(containerName, command, row, column); } /// <summary> /// Starts the exec command for a specific container instance within the container group. /// </summary> /// <param name="containerName">The container instance name.</param> /// <param name="command">The command to be executed.</param> /// <param name="row">The row size of the terminal.</param> /// <param name="column">The column size of the terminal.</param> /// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws> /// <return>A representation of the future computation of this call.</return> async Task<Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerExecResponse> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ExecuteCommandAsync(string containerName, string command, int row, int column, CancellationToken cancellationToken) { return await this.ExecuteCommandAsync(containerName, command, row, column, cancellationToken); } /// <summary> /// Gets all the ports publicly exposed for this container group. /// </summary> System.Collections.Generic.IReadOnlyCollection<Models.Port> Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.ExternalPorts { get { return this.ExternalPorts(); } } /// <summary> /// Gets the base level OS type required by the containers in the group. /// </summary> OSTypeName Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.OSType { get { return this.OSType(); } } /// <summary> /// Gets the container group restart policy. /// </summary> Models.ContainerGroupRestartPolicy Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.RestartPolicy { get { return this.RestartPolicy(); } } /// <summary> /// Gets the DNS prefix which was specified at creation time. /// </summary> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.DnsPrefix { get { return this.DnsPrefix(); } } /// <summary> /// Gets the state of the container group; only valid in response. /// </summary> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.State { get { return this.State(); } } /// <summary> /// Gets the FQDN for the container group. /// </summary> string Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup.Fqdn { get { return this.Fqdn(); } } /// <summary> /// Begins the definition of a container instance. /// </summary> /// <param name="name">The name of the volume.</param> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IContainerInstanceDefinitionBlank<ContainerGroup.Definition.IWithNextContainerInstance> ContainerGroup.Definition.IWithNextContainerInstance.DefineContainerInstance(string name) { return this.DefineContainerInstance(name); } /// <summary> /// Specifies this is a Linux container group. /// </summary> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithPublicOrPrivateImageRegistry ContainerGroup.Definition.IWithOsType.WithLinux() { return this.WithLinux(); } /// <summary> /// Specifies this is a Windows container group. /// </summary> /// <return>The next stage of the definition.</return> ContainerGroup.Definition.IWithPublicOrPrivateImageRegistry ContainerGroup.Definition.IWithOsType.WithWindows() { return this.WithWindows(); } /// <summary> /// Refreshes the resource to sync with Azure. /// </summary> /// <return>The Observable to refreshed resource.</return> async Task<Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IRefreshable<Microsoft.Azure.Management.ContainerInstance.Fluent.IContainerGroup>.RefreshAsync(CancellationToken cancellationToken) { return await this.RefreshAsync(cancellationToken); } } }
using System; using System.IO; using System.Text; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Crypto.Parameters; namespace AllAuth.Lib.Crypto { public class EncryptedData { private enum EncryptionMethods { Aes256CbcPkcs7 } private static EncryptionMethods DefaultEncryptionMethod = EncryptionMethods.Aes256CbcPkcs7; private EncryptionMethods Method { get; set; } public string Key { get { return Convert.ToBase64String (_key); } } /// <summary> /// Encryption key /// </summary> private byte[] _key; /// <summary> /// Initialization vector if required for the encryption method. /// </summary> private byte[] _iv; /// <summary> /// Base64-encoded representation of the encrypted data. /// </summary> private byte[] _data; /// <summary> /// Encrypts the given data with the default encryption method. /// </summary> /// <param name="dataToEncrypt"></param> public EncryptedData(string dataToEncrypt) { EncryptData(dataToEncrypt); } /// <summary> /// Encrypts the given byte data with the default encryption method. /// </summary> /// <param name="dataToEncrypt"></param> public EncryptedData(byte[] dataToEncrypt) { EncryptData(dataToEncrypt); } /// <summary> /// Encrypts the data with the given key. The key must be appropiate for the encryption method. /// </summary> /// <param name="dataToEncrypt"></param> /// <param name="encryptionKey"></param> internal EncryptedData(string dataToEncrypt, byte[] encryptionKey) { _key = encryptionKey; EncryptData(dataToEncrypt); } internal EncryptedData(byte[] dataToEncrypt, byte[] encryptionKey) { _key = encryptionKey; EncryptData(dataToEncrypt); } private void EncryptData(string dataToEncrypt) { EncryptData(Encoding.UTF8.GetBytes(dataToEncrypt)); } private void EncryptData(byte[] dataToEncrypt) { Method = DefaultEncryptionMethod; switch (Method) { case EncryptionMethods.Aes256CbcPkcs7: EncryptDataAes256CbcPkcs7(dataToEncrypt); break; default: throw new NotImplementedException("Encryption method has not been implemented"); } } private void EncryptDataAes256CbcPkcs7(byte[] dataToEncrypt) { if (_key != null && _key.Length != 32) throw new Exception("Explicit data encryption key is not of required length for encryption method"); if (_key == null) { // No explicit key was provided, we're going to generate our own. _key = new byte[32]; RandomUtil.SecureRandomBc.NextBytes(_key); } _iv = new byte[16]; RandomUtil.SecureRandomBc.NextBytes(_iv); var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()), new Pkcs7Padding()); cipher.Init(true, new ParametersWithIV(new KeyParameter(_key), _iv)); _data = cipher.DoFinal(dataToEncrypt); } /// <summary> /// Raw byte array of the encrypted data. /// </summary> /// <returns></returns> internal byte[] ToBytes() { using (var memStream = new MemoryStream()) { memStream.WriteByte((byte)(int)Method); memStream.Write(_iv, 0, _iv.Length); memStream.Write(_data, 0, _data.Length); return memStream.ToArray(); } } /// <summary> /// Serializes the encrypted data into a base64 encoded string. /// </summary> /// <returns></returns> public override string ToString() { return Convert.ToBase64String(ToBytes()); } public static string DecryptData(string encryptionKey, string serializedEncryptedData) { return Encoding.UTF8.GetString(DecryptDataAsBytes(encryptionKey, serializedEncryptedData)); } public static byte[] DecryptDataAsBytes(string encryptionKey, string serializedEncryptedData) { var encryptionKeyBytes = Convert.FromBase64String(encryptionKey); var encryptedData = Convert.FromBase64String(serializedEncryptedData); return DecryptDataAsBytes(encryptionKeyBytes, encryptedData); } internal static byte[] DecryptDataAsBytes(byte[] encryptionKey, byte[] encryptedData) { using (var outputStream = new MemoryStream()) using (var encryptedDataStream = new MemoryStream(encryptedData)) { var methodByte = encryptedDataStream.ReadByte(); if (methodByte < 0) throw new Exception("Unexpected end of encrypted data"); var method = (EncryptionMethods)methodByte; switch (method) { case EncryptionMethods.Aes256CbcPkcs7: DecryptDataAes256CbcPkcs7(encryptionKey, encryptedDataStream, outputStream); break; default: throw new Exception("Unexpected data encryption method"); } return outputStream.ToArray(); } } /// <summary> /// Decrypt AES256-CBC with PKCS7 padding data /// </summary> /// <param name="encryptionKey"></param> /// <param name="encryptedDataStream"></param> /// <param name="outputStream"></param> private static void DecryptDataAes256CbcPkcs7( byte[] encryptionKey, Stream encryptedDataStream, Stream outputStream) { if (encryptionKey.Length != 32) throw new Exception("AES256 encryption key not of expected length"); var iv = new byte[16]; var ivBytesRead = encryptedDataStream.Read(iv, 0, 16); if (ivBytesRead != 16) throw new Exception("Unexpected IV"); // The rest of the data stream is the encrypted data itself. var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()), new Pkcs7Padding()); cipher.Init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv)); while (true) { var buffer = new byte[4096]; var dataBytesRead = encryptedDataStream.Read(buffer, 0, 4096); if (dataBytesRead == 0) break; var processedBytes = cipher.ProcessBytes(buffer, 0, dataBytesRead); if (processedBytes != null) outputStream.Write(processedBytes, 0, processedBytes.Length); } var finalBytes = cipher.DoFinal(); outputStream.Write(finalBytes, 0, finalBytes.Length); } } }
// 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 wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Internal.Runtime.CompilerServices; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Single : IComparable, IConvertible, IFormattable, IComparable<Single>, IEquatable<Single>, ISpanFormattable { private float m_value; // Do not rename (binary serialization) // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; // We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal const float NegativeZero = (float)-0.0; /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) < 0x7F800000; } /// <summary>Determines whether the specified value is infinite.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) == 0x7F800000; } /// <summary>Determines whether the specified value is NaN.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) > 0x7F800000; } /// <summary>Determines whether the specified value is negative.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(float f) { var bits = unchecked((uint)BitConverter.SingleToInt32Bits(f)); return (bits & 0x80000000) == 0x80000000; } /// <summary>Determines whether the specified value is negative infinity.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegativeInfinity(float f) { return (f == float.NegativeInfinity); } /// <summary>Determines whether the specified value is normal.</summary> [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0); } /// <summary>Determines whether the specified value is positive infinity.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsPositiveInfinity(float f) { return (f == float.PositiveInfinity); } /// <summary>Determines whether the specified value is subnormal.</summary> [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0); } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (m_value < f) return -1; if (m_value > f) return 1; if (m_value == f) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } [NonVersionable] public static bool operator ==(Single left, Single right) { return left == right; } [NonVersionable] public static bool operator !=(Single left, Single right) { return left != right; } [NonVersionable] public static bool operator <(Single left, Single right) { return left < right; } [NonVersionable] public static bool operator >(Single left, Single right) { return left > right; } [NonVersionable] public static bool operator <=(Single left, Single right) { return left <= right; } [NonVersionable] public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj).m_value; if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } public bool Equals(Single obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } public override int GetHashCode() { var bits = Unsafe.As<float, int>(ref m_value); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000) { // Ensure that all NaNs and both zeros have the same hash code bits &= 0x7F800000; } return bits; } public override String ToString() { return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static Boolean TryParse(String s, out Single result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out float result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out float result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static Boolean TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Single result) { bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { ReadOnlySpan<char> sTrim = s.Trim(); if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (sTrim.EqualsOrdinal(info.NaNSymbol)) { result = NaN; } else { return false; // We really failed } } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return m_value; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// -- FILE ------------------------------------------------------------------ // name : QuarterTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class QuarterTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void InitValuesTest() { DateTime now = ClockProxy.Clock.Now; DateTime firstQuarter = new DateTime( now.Year, 1, 1 ); DateTime secondQuarter = firstQuarter.AddMonths( TimeSpec.MonthsPerQuarter ); Quarter quarter = new Quarter( now.Year, YearQuarter.First, TimeCalendar.NewEmptyOffset() ); Assert.Equal( quarter.Start.Year, firstQuarter.Year ); Assert.Equal( quarter.Start.Month, firstQuarter.Month ); Assert.Equal( quarter.Start.Day, firstQuarter.Day ); Assert.Equal(0, quarter.Start.Hour); Assert.Equal(0, quarter.Start.Minute); Assert.Equal(0, quarter.Start.Second); Assert.Equal(0, quarter.Start.Millisecond); Assert.Equal( quarter.End.Year, secondQuarter.Year ); Assert.Equal( quarter.End.Month, secondQuarter.Month ); Assert.Equal( quarter.End.Day, secondQuarter.Day ); Assert.Equal(0, quarter.End.Hour); Assert.Equal(0, quarter.End.Minute); Assert.Equal(0, quarter.End.Second); Assert.Equal(0, quarter.End.Millisecond); } // InitValuesTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void DefaultCalendarTest() { DateTime yearStart = new DateTime( ClockProxy.Clock.Now.Year, 1, 1 ); foreach ( YearQuarter yearQuarter in Enum.GetValues( typeof( YearQuarter ) ) ) { int offset = (int)yearQuarter - 1; Quarter quarter = new Quarter( yearStart.AddMonths( TimeSpec.MonthsPerQuarter * offset ) ); Assert.Equal(YearMonth.January, quarter.YearBaseMonth); Assert.Equal( quarter.BaseYear, yearStart.Year ); Assert.Equal( quarter.Start, yearStart.AddMonths( TimeSpec.MonthsPerQuarter * offset ).Add( quarter.Calendar.StartOffset ) ); Assert.Equal( quarter.End, yearStart.AddMonths( TimeSpec.MonthsPerQuarter * ( offset + 1 ) ).Add( quarter.Calendar.EndOffset ) ); } } // DefaultCalendarTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void MomentTest() { DateTime now = ClockProxy.Clock.Now; TimeCalendar calendar = TimeCalendar.New( YearMonth.April ); Assert.Equal(YearQuarter.First, new Quarter( new DateTime( now.Year, 1, 1 ) ).YearQuarter); Assert.Equal(YearQuarter.First, new Quarter( new DateTime( now.Year, 3, 30 ) ).YearQuarter); Assert.Equal(YearQuarter.Second, new Quarter( new DateTime( now.Year, 4, 1 ) ).YearQuarter); Assert.Equal(YearQuarter.Second, new Quarter( new DateTime( now.Year, 6, 30 ) ).YearQuarter); Assert.Equal(YearQuarter.Third, new Quarter( new DateTime( now.Year, 7, 1 ) ).YearQuarter); Assert.Equal(YearQuarter.Third, new Quarter( new DateTime( now.Year, 9, 30 ) ).YearQuarter); Assert.Equal(YearQuarter.Fourth, new Quarter( new DateTime( now.Year, 10, 1 ) ).YearQuarter); Assert.Equal(YearQuarter.Fourth, new Quarter( new DateTime( now.Year, 12, 31 ) ).YearQuarter); Assert.Equal(YearQuarter.First, new Quarter( new DateTime( now.Year, 4, 1 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.First, new Quarter( new DateTime( now.Year, 6, 30 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.Second, new Quarter( new DateTime( now.Year, 7, 1 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.Second, new Quarter( new DateTime( now.Year, 9, 30 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.Third, new Quarter( new DateTime( now.Year, 10, 1 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.Third, new Quarter( new DateTime( now.Year, 12, 31 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.Fourth, new Quarter( new DateTime( now.Year, 1, 1 ), calendar ).YearQuarter); Assert.Equal(YearQuarter.Fourth, new Quarter( new DateTime( now.Year, 3, 30 ), calendar ).YearQuarter); } // MomentTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void YearTest() { int currentYear = ClockProxy.Clock.Now.Year; Assert.Equal( new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.April ) ).BaseYear, currentYear ); Assert.Equal(2006, new Quarter( 2006, YearQuarter.Fourth ).BaseYear); } // YearTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void YearQuarterTest() { int currentYear = ClockProxy.Clock.Now.Year; Assert.Equal(YearQuarter.Third, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.April ) ).YearQuarter); Assert.Equal(YearQuarter.Third, new Quarter( currentYear, YearQuarter.Third ).YearQuarter); } // YearQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void CurrentQuarterTest() { int currentYear = ClockProxy.Clock.Now.Year; Quarter quarter = new Quarter( currentYear, YearQuarter.First ); Assert.Equal( quarter.BaseYear, currentYear ); } // CurrentQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void StartMonthTest() { int currentYear = ClockProxy.Clock.Now.Year; Assert.Equal(YearMonth.January, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.January ) ).StartMonth); Assert.Equal(YearMonth.February, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.February ) ).StartMonth); Assert.Equal(YearMonth.March, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.March ) ).StartMonth); Assert.Equal(YearMonth.April, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.April ) ).StartMonth); Assert.Equal(YearMonth.May, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.May ) ).StartMonth); Assert.Equal(YearMonth.June, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.June ) ).StartMonth); Assert.Equal(YearMonth.July, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.July ) ).StartMonth); Assert.Equal(YearMonth.August, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.August ) ).StartMonth); Assert.Equal(YearMonth.September, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.September ) ).StartMonth); Assert.Equal(YearMonth.October, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.October ) ).StartMonth); Assert.Equal(YearMonth.November, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.November ) ).StartMonth); Assert.Equal(YearMonth.December, new Quarter( currentYear, YearQuarter.First, TimeCalendar.New( YearMonth.December ) ).StartMonth); Assert.Equal(YearMonth.April, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.January ) ).StartMonth); Assert.Equal(YearMonth.May, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.February ) ).StartMonth); Assert.Equal(YearMonth.June, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.March ) ).StartMonth); Assert.Equal(YearMonth.July, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.April ) ).StartMonth); Assert.Equal(YearMonth.August, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.May ) ).StartMonth); Assert.Equal(YearMonth.September, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.June ) ).StartMonth); Assert.Equal(YearMonth.October, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.July ) ).StartMonth); Assert.Equal(YearMonth.November, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.August ) ).StartMonth); Assert.Equal(YearMonth.December, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.September ) ).StartMonth); Assert.Equal(YearMonth.January, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.October ) ).StartMonth); Assert.Equal(YearMonth.February, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.November ) ).StartMonth); Assert.Equal(YearMonth.March, new Quarter( currentYear, YearQuarter.Second, TimeCalendar.New( YearMonth.December ) ).StartMonth); Assert.Equal(YearMonth.July, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.January ) ).StartMonth); Assert.Equal(YearMonth.August, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.February ) ).StartMonth); Assert.Equal(YearMonth.September, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.March ) ).StartMonth); Assert.Equal(YearMonth.October, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.April ) ).StartMonth); Assert.Equal(YearMonth.November, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.May ) ).StartMonth); Assert.Equal(YearMonth.December, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.June ) ).StartMonth); Assert.Equal(YearMonth.January, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.July ) ).StartMonth); Assert.Equal(YearMonth.February, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.August ) ).StartMonth); Assert.Equal(YearMonth.March, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.September ) ).StartMonth); Assert.Equal(YearMonth.April, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.October ) ).StartMonth); Assert.Equal(YearMonth.May, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.November ) ).StartMonth); Assert.Equal(YearMonth.June, new Quarter( currentYear, YearQuarter.Third, TimeCalendar.New( YearMonth.December ) ).StartMonth); Assert.Equal(YearMonth.October, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.January ) ).StartMonth); Assert.Equal(YearMonth.November, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.February ) ).StartMonth); Assert.Equal(YearMonth.December, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.March ) ).StartMonth); Assert.Equal(YearMonth.January, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.April ) ).StartMonth); Assert.Equal(YearMonth.February, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.May ) ).StartMonth); Assert.Equal(YearMonth.March, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.June ) ).StartMonth); Assert.Equal(YearMonth.April, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.July ) ).StartMonth); Assert.Equal(YearMonth.May, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.August ) ).StartMonth); Assert.Equal(YearMonth.June, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.September ) ).StartMonth); Assert.Equal(YearMonth.July, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.October ) ).StartMonth); Assert.Equal(YearMonth.August, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.November ) ).StartMonth); Assert.Equal(YearMonth.September, new Quarter( currentYear, YearQuarter.Fourth, TimeCalendar.New( YearMonth.December ) ).StartMonth); } // StartMonthTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void CalendarYearQuarterTest() { int currentYear = ClockProxy.Clock.Now.Year; TimeCalendar calendar = TimeCalendar.New( TimeSpan.Zero, TimeSpan.Zero ); Quarter current = new Quarter( currentYear, YearQuarter.First ); Assert.Equal( current.GetNextQuarter().GetNextQuarter().GetNextQuarter().GetNextQuarter().YearQuarter, current.YearQuarter ); Assert.Equal( current.GetPreviousQuarter().GetPreviousQuarter().GetPreviousQuarter().GetPreviousQuarter().YearQuarter, current.YearQuarter ); Quarter q1 = new Quarter( currentYear, YearQuarter.First, calendar ); Assert.True( q1.IsReadOnly ); Assert.Equal(YearQuarter.First, q1.YearQuarter); Assert.Equal( q1.Start, new DateTime( currentYear, TimeSpec.FirstQuarterMonthIndex, 1 ) ); Assert.Equal( q1.End, new DateTime( currentYear, TimeSpec.SecondQuarterMonthIndex, 1 ) ); Quarter q2 = new Quarter( currentYear, YearQuarter.Second, calendar ); Assert.True( q2.IsReadOnly ); Assert.Equal(YearQuarter.Second, q2.YearQuarter); Assert.Equal( q2.Start, new DateTime( currentYear, TimeSpec.SecondQuarterMonthIndex, 1 ) ); Assert.Equal( q2.End, new DateTime( currentYear, TimeSpec.ThirdQuarterMonthIndex, 1 ) ); Quarter q3 = new Quarter( currentYear, YearQuarter.Third, calendar ); Assert.True( q3.IsReadOnly ); Assert.Equal(YearQuarter.Third, q3.YearQuarter); Assert.Equal( q3.Start, new DateTime( currentYear, TimeSpec.ThirdQuarterMonthIndex, 1 ) ); Assert.Equal( q3.End, new DateTime( currentYear, TimeSpec.FourthQuarterMonthIndex, 1 ) ); Quarter q4 = new Quarter( currentYear, YearQuarter.Fourth, calendar ); Assert.True( q4.IsReadOnly ); Assert.Equal(YearQuarter.Fourth, q4.YearQuarter); Assert.Equal( q4.Start, new DateTime( currentYear, TimeSpec.FourthQuarterMonthIndex, 1 ) ); Assert.Equal( q4.End, new DateTime( currentYear + 1, TimeSpec.FirstQuarterMonthIndex, 1 ) ); } // CalendarYearQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void QuarterMomentTest() { Quarter quarter = new Quarter( 2008, YearQuarter.First, TimeCalendar.New( TimeSpan.Zero, TimeSpan.Zero ) ); Assert.True( quarter.IsReadOnly ); Assert.Equal(2008, quarter.BaseYear); Assert.Equal(YearQuarter.First, quarter.YearQuarter); Assert.Equal( quarter.Start, new DateTime( 2008, TimeSpec.FirstQuarterMonthIndex, 1 ) ); Assert.Equal( quarter.End, new DateTime( 2008, TimeSpec.SecondQuarterMonthIndex, 1 ) ); Quarter previous = quarter.GetPreviousQuarter(); Assert.Equal(2007, previous.BaseYear); Assert.Equal(YearQuarter.Fourth, previous.YearQuarter); Assert.Equal( previous.Start, new DateTime( 2007, TimeSpec.FourthQuarterMonthIndex, 1 ) ); Assert.Equal( previous.End, new DateTime( 2008, TimeSpec.FirstQuarterMonthIndex, 1 ) ); Quarter next = quarter.GetNextQuarter(); Assert.Equal(2008, next.BaseYear); Assert.Equal(YearQuarter.Second, next.YearQuarter); Assert.Equal( next.Start, new DateTime( 2008, TimeSpec.SecondQuarterMonthIndex, 1 ) ); Assert.Equal( next.End, new DateTime( 2008, TimeSpec.ThirdQuarterMonthIndex, 1 ) ); } // QuarterMomentTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void IsCalendarQuarterTest() { int currentYear = ClockProxy.Clock.Now.Year; foreach ( YearQuarter yearQuarter in Enum.GetValues( typeof( YearQuarter ) ) ) { Assert.True( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.January ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.February ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.March ) ).IsCalendarQuarter ); Assert.True( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.April ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.May ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.June ) ).IsCalendarQuarter ); Assert.True( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.July ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.August ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.September ) ).IsCalendarQuarter ); Assert.True( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.October ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.November ) ).IsCalendarQuarter ); Assert.False( new Quarter( currentYear, yearQuarter, TimeCalendar.New( YearMonth.December ) ).IsCalendarQuarter ); } } // IsCalendarQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void MultipleCalendarYearsTest() { DateTime now = ClockProxy.Clock.Now; Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.January ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.February ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.March ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.April ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.May ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.June ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.July ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.August ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.September ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.October ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.November ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.December ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.January ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.February ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.March ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.April ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.May ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.June ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.July ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.August ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.September ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.October ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.November ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Second, TimeCalendar.New( YearMonth.December ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.January ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.February ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.March ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.April ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.May ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.June ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.July ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.August ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.September ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.October ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.November ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Third, TimeCalendar.New( YearMonth.December ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.January ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.February ) ).MultipleCalendarYears ); Assert.True( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.March ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.April ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.May ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.June ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.July ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.August ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.September ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.October ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.November ) ).MultipleCalendarYears ); Assert.False( new Quarter( now.Year, YearQuarter.Fourth, TimeCalendar.New( YearMonth.December ) ).MultipleCalendarYears ); } // MultipleCalendarYearsTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void DefaultQuarterTest() { int currentYear = ClockProxy.Clock.Now.Year; const YearMonth yearStartMonth = YearMonth.April; TimeCalendar calendar = TimeCalendar.New( TimeSpan.Zero, TimeSpan.Zero, yearStartMonth ); Quarter q1 = new Quarter( currentYear, YearQuarter.First, calendar ); Assert.True( q1.IsReadOnly ); Assert.Equal( q1.YearBaseMonth, yearStartMonth ); Assert.Equal(YearQuarter.First, q1.YearQuarter); Assert.Equal( q1.BaseYear, currentYear ); Assert.Equal( q1.Start, new DateTime( currentYear, 4, 1 ) ); Assert.Equal( q1.End, new DateTime( currentYear, 7, 1 ) ); Quarter q2 = new Quarter( currentYear, YearQuarter.Second, calendar ); Assert.True( q2.IsReadOnly ); Assert.Equal( q2.YearBaseMonth, yearStartMonth ); Assert.Equal(YearQuarter.Second, q2.YearQuarter); Assert.Equal( q2.BaseYear, currentYear ); Assert.Equal( q2.Start, new DateTime( currentYear, 7, 1 ) ); Assert.Equal( q2.End, new DateTime( currentYear, 10, 1 ) ); Quarter q3 = new Quarter( currentYear, YearQuarter.Third, calendar ); Assert.True( q3.IsReadOnly ); Assert.Equal( q3.YearBaseMonth, yearStartMonth ); Assert.Equal(YearQuarter.Third, q3.YearQuarter); Assert.Equal( q3.BaseYear, currentYear ); Assert.Equal( q3.Start, new DateTime( currentYear, 10, 1 ) ); Assert.Equal( q3.End, new DateTime( currentYear + 1, 1, 1 ) ); Quarter q4 = new Quarter( currentYear, YearQuarter.Fourth, calendar ); Assert.True( q4.IsReadOnly ); Assert.Equal( q4.YearBaseMonth, yearStartMonth ); Assert.Equal(YearQuarter.Fourth, q4.YearQuarter); Assert.Equal( q4.BaseYear, currentYear ); Assert.Equal( q4.Start, new DateTime( currentYear + 1, 1, 1 ) ); Assert.Equal( q4.End, new DateTime( currentYear + 1, 4, 1 ) ); } // DefaultQuarterTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void GetMonthsTest() { Quarter quarter = new Quarter( ClockProxy.Clock.Now.Year, YearQuarter.First, TimeCalendar.New( YearMonth.October ) ); ITimePeriodCollection months = quarter.GetMonths(); Assert.NotNull(months); int index = 0; foreach ( Month month in months ) { Assert.Equal( month.Start, quarter.Start.AddMonths( index ) ); Assert.Equal( month.End, month.Calendar.MapEnd( month.Start.AddMonths( 1 ) ) ); index++; } Assert.Equal( index, TimeSpec.MonthsPerQuarter ); } // GetMonthsTest // ---------------------------------------------------------------------- [Trait("Category", "Quarter")] [Fact] public void AddQuartersTest() { int currentYear = ClockProxy.Clock.Now.Year; const YearMonth yearStartMonth = YearMonth.April; TimeCalendar calendar = TimeCalendar.New( TimeSpan.Zero, TimeSpan.Zero, yearStartMonth ); DateTime calendarStartDate = new DateTime( currentYear, 4, 1 ); Quarter calendarQuarter = new Quarter( currentYear, YearQuarter.First, calendar ); Assert.Equal( calendarQuarter.AddQuarters( 0 ), calendarQuarter ); Quarter prevQ1 = calendarQuarter.AddQuarters( -1 ); Assert.Equal(YearQuarter.Fourth, prevQ1.YearQuarter); Assert.Equal( prevQ1.BaseYear, currentYear - 1 ); Assert.Equal( prevQ1.Start, calendarStartDate.AddMonths( -3 ) ); Assert.Equal( prevQ1.End, calendarStartDate ); Quarter prevQ2 = calendarQuarter.AddQuarters( -2 ); Assert.Equal(YearQuarter.Third, prevQ2.YearQuarter); Assert.Equal( prevQ2.BaseYear, currentYear - 1 ); Assert.Equal( prevQ2.Start, calendarStartDate.AddMonths( -6 ) ); Assert.Equal( prevQ2.End, calendarStartDate.AddMonths( -3 ) ); Quarter prevQ3 = calendarQuarter.AddQuarters( -3 ); Assert.Equal(YearQuarter.Second, prevQ3.YearQuarter); Assert.Equal( prevQ3.BaseYear, currentYear - 1 ); Assert.Equal( prevQ3.Start, calendarStartDate.AddMonths( -9 ) ); Assert.Equal( prevQ3.End, calendarStartDate.AddMonths( -6 ) ); Quarter prevQ4 = calendarQuarter.AddQuarters( -4 ); Assert.Equal(YearQuarter.First, prevQ4.YearQuarter); Assert.Equal( prevQ4.BaseYear, currentYear - 1 ); Assert.Equal( prevQ4.Start, calendarStartDate.AddMonths( -12 ) ); Assert.Equal( prevQ4.End, calendarStartDate.AddMonths( -9 ) ); Quarter prevQ5 = calendarQuarter.AddQuarters( -5 ); Assert.Equal(YearQuarter.Fourth, prevQ5.YearQuarter); Assert.Equal( prevQ5.BaseYear, currentYear - 2 ); Assert.Equal( prevQ5.Start, calendarStartDate.AddMonths( -15 ) ); Assert.Equal( prevQ5.End, calendarStartDate.AddMonths( -12 ) ); Quarter futureQ1 = calendarQuarter.AddQuarters( 1 ); Assert.Equal(YearQuarter.Second, futureQ1.YearQuarter); Assert.Equal( futureQ1.BaseYear, currentYear ); Assert.Equal( futureQ1.Start, calendarStartDate.AddMonths( 3 ) ); Assert.Equal( futureQ1.End, calendarStartDate.AddMonths( 6 ) ); Quarter futureQ2 = calendarQuarter.AddQuarters( 2 ); Assert.Equal(YearQuarter.Third, futureQ2.YearQuarter); Assert.Equal( futureQ2.BaseYear, currentYear ); Assert.Equal( futureQ2.Start, calendarStartDate.AddMonths( 6 ) ); Assert.Equal( futureQ2.End, calendarStartDate.AddMonths( 9 ) ); Quarter futureQ3 = calendarQuarter.AddQuarters( 3 ); Assert.Equal(YearQuarter.Fourth, futureQ3.YearQuarter); Assert.Equal( futureQ3.BaseYear, currentYear ); Assert.Equal( futureQ3.Start, calendarStartDate.AddMonths( 9 ) ); Assert.Equal( futureQ3.End, calendarStartDate.AddMonths( 12 ) ); Quarter futureQ4 = calendarQuarter.AddQuarters( 4 ); Assert.Equal(YearQuarter.First, futureQ4.YearQuarter); Assert.Equal( futureQ4.BaseYear, currentYear + 1 ); Assert.Equal( futureQ4.Start, calendarStartDate.AddMonths( 12 ) ); Assert.Equal( futureQ4.End, calendarStartDate.AddMonths( 15 ) ); Quarter futureQ5 = calendarQuarter.AddQuarters( 5 ); Assert.Equal(YearQuarter.Second, futureQ5.YearQuarter); Assert.Equal( futureQ5.BaseYear, currentYear + 1 ); Assert.Equal( futureQ5.Start, calendarStartDate.AddMonths( 15 ) ); Assert.Equal( futureQ5.End, calendarStartDate.AddMonths( 18 ) ); } // AddQuartersTest // ---------------------------------------------------------------------- private ITimeCalendar GetFiscalYearCalendar( FiscalYearAlignment yearAlignment ) { return new TimeCalendar( new TimeCalendarConfig { YearType = YearType.FiscalYear, YearBaseMonth = YearMonth.September, FiscalFirstDayOfYear = DayOfWeek.Sunday, FiscalYearAlignment = yearAlignment, FiscalQuarterGrouping = FiscalQuarterGrouping.FourFourFiveWeeks } ); } // GetFiscalYearCalendar // ---------------------------------------------------------------------- // http://en.wikipedia.org/wiki/4-4-5_Calendar [Trait("Category", "Quarter")] [Fact] public void FiscalYearGetMonthsTest() { Quarter quarter = new Quarter( 2006, YearQuarter.First, GetFiscalYearCalendar( FiscalYearAlignment.LastDay ) ); ITimePeriodCollection months = quarter.GetMonths(); Assert.NotNull(months); Assert.Equal( months.Count, TimeSpec.MonthsPerQuarter ); Assert.Equal( months[ 0 ].Start, new DateTime( 2006, 8, 27 ) ); for ( int i = 0; i < months.Count; i++ ) { Assert.Equal( months[ i ].Duration.Subtract( TimeCalendar.DefaultEndOffset ).Days, ( i + 1 ) % 3 == 0 ? TimeSpec.FiscalDaysPerLongMonth : TimeSpec.FiscalDaysPerShortMonth ); } Assert.Equal( months[ TimeSpec.MonthsPerQuarter - 1 ].End, quarter.End ); } // FiscalYearGetMonthsTest } // class QuarterTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
//Persistance Manager tests new PersistenceManager(TestPManager); function runPManTest(%test) { if (!isObject(TestPManager)) return; if (%test $= "") %test = 100; switch(%test) { case 0: TestPManager.testFieldUpdates(); case 1: TestPManager.testObjectRename(); case 2: TestPManager.testNewObject(); case 3: TestPManager.testNewGroup(); case 4: TestPManager.testMoveObject(); case 5: TestPManager.testObjectRemove(); case 100: TestPManager.testFieldUpdates(); TestPManager.testObjectRename(); TestPManager.testNewObject(); TestPManager.testNewGroup(); TestPManager.testMoveObject(); TestPManager.testObjectRemove(); } } function TestPManager::testFieldUpdates(%doNotSave) { // Set some objects as dirty TestPManager.setDirty(AudioGui); TestPManager.setDirty(AudioSim); TestPManager.setDirty(AudioMessage); // Alter some of the existing fields AudioEffect.isLooping = true; AudioMessage.isLooping = true; AudioEffect.is3D = true; // Test removing a field TestPManager.removeField(AudioGui, "isLooping"); // Alter some of the persistent fields AudioGui.referenceDistance = 0.8; AudioMessage.referenceDistance = 0.8; // Add some new dynamic fields AudioGui.foo = "bar"; AudioEffect.foo = "bar"; // Remove an object from the dirty list // It shouldn't get updated in the file TestPManager.removeDirty(AudioEffect); // Dirty an object in another file as well TestPManager.setDirty(WarningMaterial); // Update a field that doesn't exist WarningMaterial.glow[0] = true; // Drity another object to test for crashes // when a dirty object is deleted TestPManager.setDirty(SFXPausedSet); // Delete the object SFXPausedSet.delete(); // Unless %doNotSave is set (by a batch/combo test) // then go ahead and save now if (!%doNotSave) TestPManager.saveDirty(); } function TestPManager::testObjectRename(%doNotSave) { // Flag an object as dirty if (isObject(AudioGui)) TestPManager.setDirty(AudioGui); else if (isObject(AudioGuiFoo)) TestPManager.setDirty(AudioGuiFoo); // Rename it if (isObject(AudioGui)) AudioGui.setName(AudioGuiFoo); else if (isObject(AudioGuiFoo)) AudioGuiFoo.setName(AudioGui); // Unless %doNotSave is set (by a batch/combo test) // then go ahead and save now if (!%doNotSave) TestPManager.saveDirty(); } function TestPManager::testNewObject(%doNotSave) { // Test adding a new named object new SFXDescription(AudioNew) { volume = 0.5; isLooping = true; channel = $GuiAudioType; foo = 2; }; // Flag it as dirty TestPManager.setDirty(AudioNew, "core/scripts/client/audio.cs"); // Test adding a new unnamed object %obj = new SFXDescription() { volume = 0.75; isLooping = true; bar = 3; }; // Flag it as dirty TestPManager.setDirty(%obj, "core/scripts/client/audio.cs"); // Test adding an "empty" object new SFXDescription(AudioEmpty); TestPManager.setDirty(AudioEmpty, "core/scripts/client/audio.cs"); // Unless %doNotSave is set (by a batch/combo test) // then go ahead and save now if (!%doNotSave) TestPManager.saveDirty(); } function TestPManager::testNewGroup(%doNotSave) { // Test adding a new named SimGroup new SimGroup(TestGroup) { foo = "bar"; new SFXDescription(TestObject) { volume = 0.5; isLooping = true; channel = $GuiAudioType; foo = 1; }; new SimGroup(SubGroup) { foo = 2; new SFXDescription(SubObject) { volume = 0.5; isLooping = true; channel = $GuiAudioType; foo = 3; }; }; }; // Flag this as dirty TestPManager.setDirty(TestGroup, "core/scripts/client/audio.cs"); // Test adding a new unnamed SimGroup %group = new SimGroup() { foo = "bar"; new SFXDescription() { volume = 0.75; channel = $GuiAudioType; foo = 4; }; new SimGroup() { foo = 5; new SFXDescription() { volume = 0.75; isLooping = true; channel = $GuiAudioType; foo = 6; }; }; }; // Flag this as dirty TestPManager.setDirty(%group, "core/scripts/client/audio.cs"); // Test adding a new unnamed SimSet %set = new SimSet() { foo = "bar"; new SFXDescription() { volume = 0.75; channel = $GuiAudioType; foo = 7; }; new SimGroup() { foo = 8; new SFXDescription() { volume = 0.75; isLooping = true; channel = $GuiAudioType; foo = 9; }; }; }; // Flag this as dirty TestPManager.setDirty(%set, "core/scripts/client/audio.cs"); // Unless %doNotSave is set (by a batch/combo test) // then go ahead and save now if (!%doNotSave) TestPManager.saveDirty(); } function TestPManager::testMoveObject(%doNotSave) { // First add a couple of groups to the file new SimGroup(MoveGroup1) { foo = "bar"; new SFXDescription(MoveObject1) { volume = 0.5; isLooping = true; channel = $GuiAudioType; foo = 1; }; new SimSet(SubGroup1) { new SFXDescription(SubObject1) { volume = 0.75; isLooping = true; channel = $GuiAudioType; foo = 2; }; }; }; // Flag this as dirty TestPManager.setDirty(MoveGroup1, "core/scripts/client/audio.cs"); new SimGroup(MoveGroup2) { foo = "bar"; new SFXDescription(MoveObject2) { volume = 0.5; isLooping = true; channel = $GuiAudioType; foo = 3; }; }; // Flag this as dirty TestPManager.setDirty(MoveGroup2, "core/scripts/client/audio.cs"); // Unless %doNotSave is set (by a batch/combo test) // then go ahead and save now if (!%doNotSave) TestPManager.saveDirty(); // Set them as dirty again TestPManager.setDirty(MoveGroup1); TestPManager.setDirty(MoveGroup2); // Give the subobject an new value MoveObject1.foo = 4; // Move it into the other group MoveGroup1.add(MoveObject2); // Switch the other subobject MoveGroup2.add(MoveObject1); // Also add a new unnamed object to one of the groups %obj = new SFXDescription() { volume = 0.75; isLooping = true; bar = 5; }; MoveGroup1.add(%obj); // Unless %doNotSave is set (by a batch/combo test) // then go ahead and save now if (!%doNotSave) TestPManager.saveDirty(); } function TestPManager::testObjectRemove(%doNotSave) { TestPManager.removeObjectFromFile(AudioSim); }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using SmashForge.Filetypes.Melee; using SmashForge.Gui.Menus; using WeifenLuo.WinFormsUI.Docking; namespace SmashForge { public partial class MeshList : DockContent { public static ImageList iconList = new ImageList(); private ContextMenu mainContextMenu; public MeshList() { InitializeComponent(); RefreshNodes(); iconList.ImageSize = new Size(24, 24); iconList.Images.Add("group", Properties.Resources.icon_group); iconList.Images.Add("polygon", Properties.Resources.icon_polygon); iconList.Images.Add("mesh", Properties.Resources.icon_mesh); iconList.Images.Add("model", Properties.Resources.icon_model); iconList.Images.Add("texture", Properties.Resources.icon_image); iconList.Images.Add("folder", Properties.Resources.icon_group); iconList.Images.Add("anim", Properties.Resources.icon_anim); iconList.Images.Add("bone", Properties.Resources.icon_bone); iconList.Images.Add("frame", Properties.Resources.icon_model); iconList.Images.Add("image", Properties.Resources.icon_image); iconList.Images.Add("skeleton", Properties.Resources.icon_skeleton); iconList.Images.Add("info", Properties.Resources.icon_info); iconList.Images.Add("number", Properties.Resources.icon_number); iconList.Images.Add("nut", Properties.Resources.UVPattern); iconList.Images.Add("bfres", Properties.Resources.icon_bfres); iconList.Images.Add("dat", Properties.Resources.icon_dat); iconList.Images.Add("script", Properties.Resources.node_file); filesTreeView.ImageList = iconList; mainContextMenu = new ContextMenu(); MenuItem newMc = new MenuItem("Create Blank Model"); newMc.Click += delegate (object sender, EventArgs e) { Console.WriteLine("Adding"); filesTreeView.Nodes.Add(new ModelContainer() { Text = "Model_" + filesTreeView.Nodes.Count }); RefreshNodes(); }; mainContextMenu.MenuItems.Add(newMc); } bool changingValue = false; public ContextMenuStrip PolyContextMenu { get { return polyContextMenu; } } public ContextMenuStrip MeshContextMenu { get { return meshContextMenu; } } public void RefreshNodes() { Queue<TreeNode> nodes = new Queue<TreeNode>(); foreach (TreeNode n in filesTreeView.Nodes) nodes.Enqueue(n); while(nodes.Count > 0) { TreeNode node = nodes.Dequeue(); if(node is Nud.Polygon) { if (node.Parent != null) ((Nud.Polygon)node).Text = "Polygon_" + ((Nud.Mesh)node.Parent).Nodes.IndexOf(node); } foreach (TreeNode n in node.Nodes) nodes.Enqueue(n); } } private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { if (e.Node is Nud) { foreach (TreeNode n in e.Node.Nodes) n.Checked = e.Node.Checked; } if (e.Node is BFRES) { foreach (TreeNode n in e.Node.Nodes) { n.Checked = e.Node.Checked; foreach (TreeNode m in n.Nodes) { m.Checked = e.Node.Checked; } } } if (e.Node is BFRES.FMDL_Model) foreach (TreeNode n in e.Node.Nodes) n.Checked = e.Node.Checked; if (e.Node is BFRES.Mesh) foreach (TreeNode n in e.Node.Nodes) n.Checked = e.Node.Checked; // Update viewport after hiding/showing meshes. MainForm.Instance.GetActiveModelViewport()?.glViewport?.Invalidate(); } private void PolySelected(Nud.Polygon poly, string name) { MainForm.Instance.OpenMats(poly,name); } private void BfresShapeSelected(BFRES.Mesh poly, string name) { MainForm.Instance.OpenBfresMats(poly, name); } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { numericUpDown1.Visible = false; label1.Visible = false; matchToNudButton.Visible = false; //Runtime.TargetVBN = null; if (e.Node is Nud.Mesh) { //Since we are changing value but we don't want the entire model order to swap, // we are disabling the event for on change value temporarily changingValue = true; numericUpDown1.Maximum = ((Nud)e.Node.Parent).Nodes.Count - 1; numericUpDown1.Value = ((Nud)e.Node.Parent).Nodes.IndexOf((Nud.Mesh)e.Node); numericUpDown1.Visible = true; label1.Visible = true; } else if (e.Node is Nud) { matchToNudButton.Visible = true; } else if (e.Node is ModelContainer) { Runtime.TargetVbn = ((ModelContainer)e.Node).VBN; } else if (filesTreeView.SelectedNode is VBN) { Runtime.TargetVbn = ((VBN)e.Node); } else if (filesTreeView.SelectedNode is BCH_Model) { Runtime.TargetVbn = ((BCH_Model)e.Node).skeleton; } else if (filesTreeView.SelectedNode is BchTexture) { MainForm.Instance.GetActiveModelViewport()?.glViewport?.Invalidate(); } else if (filesTreeView.SelectedNode is NutTexture) { MainForm.Instance.GetActiveModelViewport()?.glViewport?.Invalidate(); } if (filesTreeView.SelectedNode is BRTI) { MainForm.Instance.GetActiveModelViewport()?.glViewport?.Invalidate(); } else if (filesTreeView.SelectedNode is FTEX) { MainForm.Instance.GetActiveModelViewport()?.glViewport?.Invalidate(); } else if (filesTreeView.SelectedNode is MeleeRootNode) { Runtime.TargetVbn = ((MeleeRootNode)e.Node).RenderBones; } else if (filesTreeView.SelectedNode is MeleeJointAnimationNode) { ((ModelViewport)Parent).CurrentAnimation = ((MeleeJointAnimationNode)filesTreeView.SelectedNode).GetAnimation(); } else if (filesTreeView.SelectedNode is MeleeJointNode) { ((MeleeJointNode)e.Node).RenderBone.Selected = true; } // Update selection render. MainForm.Instance.GetActiveModelViewport()?.glViewport?.Invalidate(); } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { if(filesTreeView.SelectedNode is Nud.Mesh && !changingValue) { int pos = (int)numericUpDown1.Value; TreeNode node = filesTreeView.SelectedNode; TreeNode parent = node.Parent; Nud.Mesh m = (Nud.Mesh)node; Nud n = (Nud)parent; n.Nodes.Remove(m); n.Nodes.Insert(pos, m); parent.Nodes.Remove(node); parent.Nodes.Insert(pos, node); filesTreeView.SelectedNode = node; n.UpdateRenderMeshes(); } changingValue = false;//Set the value back so the user can change values } private void treeView1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == '=') { if (filesTreeView.SelectedNode is Nud.Mesh) { TreeNode node = filesTreeView.SelectedNode; TreeNode parent = node.Parent; Nud.Mesh m = (Nud.Mesh)node; Nud n = (Nud)parent; int pos = n.Nodes.IndexOf(m) + 1; if (pos >= n.Nodes.Count) pos = n.Nodes.Count - 1; n.Nodes.Remove(m); n.Nodes.Insert(pos, m); parent.Nodes.Remove(node); parent.Nodes.Insert(pos, node); filesTreeView.SelectedNode = node; n.UpdateRenderMeshes(); } } if (e.KeyChar == '-') { if (filesTreeView.SelectedNode is Nud.Mesh) { TreeNode node = filesTreeView.SelectedNode; TreeNode parent = node.Parent; Nud.Mesh m = (Nud.Mesh)node; Nud n = (Nud)parent; int pos = n.Nodes.IndexOf(m) - 1; if (pos < 0) pos = 0; n.Nodes.Remove(m); n.Nodes.Insert(pos, m); parent.Nodes.Remove(node); parent.Nodes.Insert(pos, node); filesTreeView.SelectedNode = node; n.UpdateRenderMeshes(); } } } private void matchToNudButton_Click(object sender, EventArgs e) { using (var ofd = new OpenFileDialog()) { ofd.Filter = "Namco Model (.nud)|*.nud"; if (ofd.ShowDialog() == DialogResult.OK) { Nud sourceNud = new Nud(ofd.FileName); Nud targetNud = (Nud)filesTreeView.SelectedNode; //Gonna reorder some NUDs, nud-in to it // Don't remove any meshes. int meshCount = Math.Max(sourceNud.Nodes.Count, targetNud.Nodes.Count); Nud.Mesh[] newMeshes = new Nud.Mesh[meshCount]; // Fill in matching meshes foreach (Nud.Mesh sourceMesh in sourceNud.Nodes) { foreach (Nud.Mesh targetMesh in targetNud.Nodes) { if (targetMesh.Text.Equals(sourceMesh.Text)) { newMeshes[sourceNud.Nodes.IndexOf((sourceMesh))] = targetMesh; break; } } } // Fill in mismatched meshes foreach (Nud.Mesh targetMesh in targetNud.Nodes) { if (!newMeshes.Contains(targetMesh)) { for (int i = 0; i < newMeshes.Length; i++) { if (newMeshes[i] == null) { newMeshes[i] = targetMesh; break; } } } } // Dummies for the dummies that don't make enough meshes for (int i = 0; i < newMeshes.Length; i++) { if (newMeshes[i] == null) { newMeshes[i] = new Nud.Mesh(); newMeshes[i].Text = "dummy"; } } // Apply the changes. targetNud.Nodes.Clear(); targetNud.Nodes.AddRange(newMeshes); RefreshNodes(); } } } private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { //if (e.Node is NUD.Mesh) // ((NUD.Mesh) e.Node).Text = e.Label; } private void treeView1_KeyDown(object sender, KeyEventArgs e) { e.Handled = false; if (e.KeyCode == Keys.Delete) { e.Handled = true; DeleteNode(); } } public void DeleteNode() { DialogResult dialogResult = MessageBox.Show("Are you sure? (This cannot be undone)", "Delete Polygon/Mesh", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { if (filesTreeView.SelectedNode is Nud.Polygon) { Nud.Mesh parent = ((Nud.Mesh)filesTreeView.SelectedNode.Parent); parent.Nodes.Remove((Nud.Polygon)filesTreeView.SelectedNode); Nud parentNud = ((Nud)parent.Parent); parentNud.UpdateRenderMeshes(); } else if (filesTreeView.SelectedNode is Nud.Mesh) { Nud parent = ((Nud)filesTreeView.SelectedNode.Parent); filesTreeView.SelectedNode.Parent.Nodes.Remove(filesTreeView.SelectedNode); parent.UpdateRenderMeshes(); } else if (filesTreeView.SelectedNode is Nud) { Nud model = (Nud)filesTreeView.SelectedNode; filesTreeView.Nodes.Remove(filesTreeView.SelectedNode); } } } public void MergeModel() { if (filesTreeView.SelectedNode is Nud) { using (var ofd = new OpenFileDialog()) { ofd.Filter = "Namco Model (.nud)|*.nud"; if (ofd.ShowDialog() == DialogResult.OK) { string filename = ofd.FileName; Nud nud = new Nud(filename); foreach (Nud.Mesh mesh in nud.Nodes) ((Nud)filesTreeView.SelectedNode).Nodes.Add((mesh)); ((Nud)filesTreeView.SelectedNode).UpdateRenderMeshes(); RefreshNodes(); } } } } private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { } private void treeView1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { filesTreeView.SelectedNode = filesTreeView.GetNodeAt(e.Location); // Check for null first to avoid exceptions. if (filesTreeView.SelectedNode == null) { mainContextMenu.Show(this, new System.Drawing.Point(e.X, e.Y)); } else if (filesTreeView.SelectedNode is Nud.Mesh) { meshContextMenu.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is Nud.Polygon) { polyContextMenu.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is Nud) { nudContextMenu.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode.Tag is SALT.Graphics.XMBFile) { xmbContextMenu.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is BFRES.Mesh) { bfresMeshContextMenu.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is BFRES) { bfresToolStripMenu.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is BFRES.FMDL_Model) { bfresFmdlcontextMenuStrip1.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is KCL) { kclContextMenuStrip1.Show(this, e.X, e.Y); } else if (filesTreeView.SelectedNode is ModelContainer) { ModelContainerContextMenu.Show(this, e.X, e.Y); } } } private void flipUVsToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud.Polygon) { Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; foreach (Nud.Vertex v in p.vertices) { for(int i = 0; i < v.uv.Count; i++) v.uv[i] = new OpenTK.Vector2(v.uv[i].X, 1 - v.uv[i].Y); } foreach (TreeNode con in filesTreeView.Nodes) { if(con is ModelContainer) { if (((ModelContainer)con).NUD != null) ((ModelContainer)con).NUD.UpdateRenderMeshes(); } } } } private void editMaterialToolStripMenuItem_Click(object sender, EventArgs e) { PolySelected((Nud.Polygon)filesTreeView.SelectedNode, $"{filesTreeView.SelectedNode.Parent.Text} {filesTreeView.SelectedNode.Text}"); } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { DeleteNode(); } private void deleteToolStripMenuItem1_Click(object sender, EventArgs e) { DeleteNode(); } private void singleBindToBoneToolStripMenuItem_Click(object sender, EventArgs e) { Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; //The ModelContainer that contains the NUD that contains this mesh (SelectedNode) ModelContainer parentModel = (ModelContainer)filesTreeView.SelectedNode.Parent.Parent; short boneIndex = -1; if (mesh.singlebind < parentModel.VBN.bones.Count) boneIndex = mesh.singlebind; BoneRiggingSelector brs = new BoneRiggingSelector(boneIndex); brs.ModelContainers.Add(parentModel); brs.ShowDialog(); if (!brs.Cancelled) { if (brs.SelectedNone) mesh.boneflag = (int)Nud.Mesh.BoneFlags.NotRigged; else mesh.boneflag = (int)Nud.Mesh.BoneFlags.SingleBind; mesh.singlebind = brs.boneIndex; foreach (Nud.Polygon poly in mesh.Nodes) { poly.polflag = 0; poly.vertSize = poly.vertSize & 0x0F; foreach (Nud.Vertex vi in poly.vertices) { vi.boneIds.Clear(); vi.boneIds.Add(mesh.singlebind); vi.boneWeights.Clear(); vi.boneWeights.Add(1); } } ((Nud)filesTreeView.SelectedNode.Parent).UpdateRenderMeshes(); } } private void duplicateToolStripMenuItem_Click(object sender, EventArgs e) { /*nud.Polygon p = (nud.Polygon)treeView1.SelectedNode; nud.Polygon np = new nud.Polygon(); np.faces.AddRange(p.faces); np.displayFaceSize = p.displayFaceSize; np.polflag = p.polflag; np.strip = p.strip; np.UVSize = p.UVSize; np.vertSize = p.vertSize;*/ } private void makeMetalToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; MakeMetal makeMetal = new MakeMetal(((Nud)filesTreeView.SelectedNode)); makeMetal.Show(); } private void Merge(TreeNode n) { ModelContainer originalModelContainer = (ModelContainer)filesTreeView.SelectedNode; ModelContainer newModelContainer = (ModelContainer)n; // Remove nodes from original and add to the new model container. int count = originalModelContainer.NUD.Nodes.Count; for (int i = 0; i < count; i++) { TreeNode node = originalModelContainer.NUD.Nodes[0]; originalModelContainer.NUD.Nodes.Remove(node); // TODO: Account for merging single bound meshes. newModelContainer.NUD.Nodes.Add(node); } // Remove the original nodes. originalModelContainer.NUD.Nodes.Clear(); newModelContainer.NUD.UpdateRenderMeshes(); filesTreeView.Nodes.Remove(filesTreeView.SelectedNode); filesTreeView.SelectedNode = n; RefreshNodes(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { string filename = ""; SaveFileDialog save = new SaveFileDialog(); save.Filter = "Namco Universal Data|*.nud|All files(*.*)|*.*"; DialogResult result = save.ShowDialog(); if (result == DialogResult.OK) { filename = save.FileName; if (filename.EndsWith(".nud")) { ((Nud)filesTreeView.SelectedNode).Save(filename); } } } private void toolStripMenuItem1_Click(object sender, EventArgs e) { MeshMover mm = new MeshMover(); if(filesTreeView.SelectedNode!=null) if(filesTreeView.SelectedNode is Nud.Mesh) mm.mesh = (Nud.Mesh)filesTreeView.SelectedNode; mm.Show(); } public List<ModelContainer> GetModelContainers() { List<ModelContainer> models = new List<ModelContainer>(); foreach (TreeNode n in filesTreeView.Nodes) { if (n is ModelContainer) models.Add((ModelContainer)n); } return models; } private void copyMaterialToolStripMenuItem_Click(object sender, EventArgs e) { List<Nud.Polygon> polys = PolygonSelector.Popup(GetModelContainers()); foreach (Nud.Polygon poly in polys) { // link materials. don't link a material to itself if (((Nud.Polygon)filesTreeView.SelectedNode) != poly) { poly.materials.Clear(); foreach (Nud.Material m in ((Nud.Polygon)filesTreeView.SelectedNode).materials) poly.materials.Add(m.Clone()); } } } private void openEditToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud) { Nud org = (Nud)filesTreeView.SelectedNode; foreach (TreeNode node in filesTreeView.Nodes) { if(node is ModelContainer) { ModelContainer con = (ModelContainer)node; if (con.NUD == org) { ModelViewport v = new ModelViewport(); v.draw.Add(con); MainForm.Instance.AddDockedControl(v); break; } } } } } private void detachToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud.Polygon) { Nud.Polygon p = ((Nud.Polygon)filesTreeView.SelectedNode); Nud.Mesh parent = (Nud.Mesh)p.Parent; p.Parent.Nodes.Remove(p); Nud.Mesh m = new Nud.Mesh(); ((Nud)parent.Parent).Nodes.Add(m); m.Text = parent.Text + "_" + p.Text; m.Nodes.Add(p); if (parent.Nodes.Count == 0) ((Nud)parent.Parent).Nodes.Remove(parent); RefreshNodes(); } } private void aboveToolStripMenuItem1_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud.Mesh) { Nud.Mesh sourceMesh = (Nud.Mesh)filesTreeView.SelectedNode; Nud nud = (Nud)(sourceMesh.Parent); int index = nud.Nodes.IndexOf(sourceMesh) - 1; MergeMeshes(sourceMesh, index); } } private void belowToolStripMenuItem1_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud.Mesh) { Nud.Mesh sourceMesh = (Nud.Mesh)filesTreeView.SelectedNode; Nud nud = (Nud)(sourceMesh.Parent); int index = nud.Nodes.IndexOf(sourceMesh) + 1; MergeMeshes(sourceMesh, index); } } private void MergeMeshes(Nud.Mesh sourceMesh, int targetMeshIndex) { Nud nud = (Nud)(sourceMesh.Parent); if (targetMeshIndex >= nud.Nodes.Count || targetMeshIndex < 0) return; // Merge the selected mesh onto the next mesh. Nud.Mesh targetMesh = (Nud.Mesh)nud.Nodes[targetMeshIndex]; nud.Nodes.Remove(sourceMesh); TransferMeshPolygons(sourceMesh, targetMesh); RefreshNodes(); } private static void TransferMeshPolygons(Nud.Mesh sourceMesh, Nud.Mesh targetMesh) { List<TreeNode> sourcePolygons = new List<TreeNode>(); foreach (Nud.Polygon p in sourceMesh.Nodes) sourcePolygons.Add(p); foreach (Nud.Polygon p in sourcePolygons) { sourceMesh.Nodes.Remove(p); targetMesh.Nodes.Add(p); } // Check single bind. if (sourceMesh.singlebind != targetMesh.singlebind) { // Change bone flag and generate weights. } } private void flipUVsHorizontalToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud.Polygon) { Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; foreach (Nud.Vertex v in p.vertices) { for (int i = 0; i < v.uv.Count; i++) v.uv[i] = new OpenTK.Vector2(1 - v.uv[i].X, v.uv[i].Y); } foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).NUD != null) ((ModelContainer)con).NUD.UpdateRenderMeshes(); } } } } private void exportAsXMLToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud) { Nud nud = (Nud)filesTreeView.SelectedNode; string filename = ""; SaveFileDialog save = new SaveFileDialog(); save.Filter = "XML Material|*.xml"; DialogResult result = save.ShowDialog(); if (result == DialogResult.OK) { filename = save.FileName; if (filename.EndsWith(".xml")) { MaterialXML.ExportMaterialAsXml(nud, filename); } } } } private void importFromXMLToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud) { Nud nud = (Nud)filesTreeView.SelectedNode; string filename = ""; OpenFileDialog save = new OpenFileDialog(); save.Filter = "XML Material|*.xml"; DialogResult result = save.ShowDialog(); if (result == DialogResult.OK) { filename = save.FileName; if (filename.EndsWith(".xml")) { try { MaterialXML.ImportMaterialAsXml(nud, filename); } catch (MaterialXML.ParamArrayLengthException ex) { MessageBox.Show(ex.errorMessage); } catch (Exception ex) { MessageBox.Show("An error occurred reading the XML file. \n" + ex.Message); } } } } } private void addBlankMeshToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud) { Nud nud = (Nud)filesTreeView.SelectedNode; Nud.Mesh m = new Nud.Mesh(); int i = 0; bool foundName = false; while (!foundName) { m.Text = $"Blank Mesh {i++}"; foundName = true; foreach (Nud.Mesh mesh in nud.Nodes) if (mesh.Text.Equals(m.Text)) foundName = false; } nud.Nodes.Add(m); RefreshNodes(); } } private void generateTanBitanToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; var messageBox = MessageBox.Show("If the vertex type does not support tangents/bitangents, \n" + "the vertex type will be changed to Normals, Tan, Bi-Tan (Float). \n" + "This will increase the file size.", filesTreeView.SelectedNode.Text, MessageBoxButtons.OKCancel); if (messageBox == DialogResult.OK) { Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh mesh in n.Nodes) { foreach (Nud.Polygon poly in mesh.Nodes) { GenerateTanBitanAndFixVertType(poly); } } // Update the data for rendering. n.UpdateRenderMeshes(); } } private void generateTanBitanToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon poly = ((Nud.Polygon)filesTreeView.SelectedNode); GenerateTanBitanAndFixVertType(poly); // Update the data for rendering. Nud n = (Nud)poly.Parent.Parent; n.UpdateRenderMeshes(); } private void useAOAsSpecToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud) { foreach (Nud.Mesh mesh in ((Nud)filesTreeView.SelectedNode).Nodes) { foreach (Nud.Polygon poly in mesh.Nodes) { poly.AOSpecRefBlend(); } } } } private void useAOAsSpecToolStripMenuItem1_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is Nud.Polygon) ((Nud.Polygon)filesTreeView.SelectedNode).AOSpecRefBlend(); } private void belowToolStripMenuItem_Click_1(object sender, EventArgs e) { TreeNode n = filesTreeView.SelectedNode.NextNode; if (n != null) { Merge(n); } } private void aboveToolStripMenuItem_Click_1(object sender, EventArgs e) { TreeNode n = filesTreeView.SelectedNode.PrevNode; if (n != null) { Merge(n); } } private void exportAsDAEToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog(); save.Filter = "Supported Filetypes (DAE)|*.dae;*.obj;|All files(*.*)|*.*"; DialogResult result = save.ShowDialog(); if (result == DialogResult.OK && filesTreeView.SelectedNode is ModelContainer) { if (save.FileName.EndsWith(".dae")) Collada.Save(save.FileName, (ModelContainer)filesTreeView.SelectedNode); if (save.FileName.EndsWith(".obj")) OBJ.Save(save.FileName, (ModelContainer)filesTreeView.SelectedNode); } } private void importFromDAEToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is ModelContainer)) return; using (OpenFileDialog ofd = new OpenFileDialog()) { if (ofd.ShowDialog() == DialogResult.OK) { ModelContainer con = (ModelContainer)filesTreeView.SelectedNode; if (con.Bfres != null) { for (int p = 0; p < con.Bfres.models.Count; p++) { Collada.DaetoBfresReplace(ofd.FileName, con, p, false); } } else { DAEImportSettings daeImport = new DAEImportSettings(); daeImport.ShowDialog(); if (daeImport.exitStatus == DAEImportSettings.ExitStatus.Opened) { con.VBN = daeImport.getVBN(); Collada.DaetoNud(ofd.FileName, con, daeImport.importTexCB.Checked); // apply settings if (con.NUD != null) daeImport.Apply(con.NUD); } } } } } private void generateBoundingSpheresToolStripMenuItem_Click(object sender, EventArgs e) { ((Nud)filesTreeView.SelectedNode).GenerateBoundingSpheres(); } private void recalculateToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { poly.CalculateNormals(); } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void smoothToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { poly.SmoothNormals(); } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void recalculateToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; p.CalculateNormals(); // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void smoothToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; p.SmoothNormals(); // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void smoothToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh mesh in ((Nud)filesTreeView.SelectedNode).Nodes) { foreach (Nud.Polygon poly in mesh.Nodes) { poly.SmoothNormals(); } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void generateTanBitanToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; string meshName = filesTreeView.SelectedNode.Text; var messageBox = MessageBox.Show("If the vertex type does not support tangents/bitangents, \n" + "the vertex type will be changed to Normals, Tan, Bi-Tan (Float). \n" + "This will increase the file size.", meshName, MessageBoxButtons.OKCancel); if (messageBox == DialogResult.OK) { Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { GenerateTanBitanAndFixVertType(poly); } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } } private static void GenerateTanBitanAndFixVertType(Nud.Polygon poly) { int vertType = poly.vertSize & 0xF; if (!(vertType == 3 || vertType == 7)) { // Change the vert type to normals, tan, bitan (float) poly.vertSize = (poly.vertSize & 0xF0); poly.vertSize |= 7; } // This already checks for the appropriate vertex type. poly.CalculateTangentBitangent(); } private void setToWhiteToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; p.SetVertexColor(new OpenTK.Vector4(127, 127, 127, 127)); // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void selectColorUtilstripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; // Use a dialog so the color isn't set until the color editor is closed. ColorEditor colorEditor = new ColorEditor(new OpenTK.Vector3(1)); colorEditor.ShowDialog(); // Remap the color from 1.0 being white to 127 being white. OpenTK.Vector3 newVertColor = colorEditor.GetColor() * 127; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; p.SetVertexColor(new OpenTK.Vector4(newVertColor, 127)); // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void tangentsToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; foreach (Nud.Vertex v in p.vertices) { OpenTK.Vector3 newTan = v.tan.Xyz * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newTan * 127, 127); } // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void bitangentsToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; foreach (Nud.Vertex v in p.vertices) { OpenTK.Vector3 newBitan = v.bitan.Xyz * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newBitan * 127, 127); } // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void normalsToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; foreach (Nud.Vertex v in p.vertices) { OpenTK.Vector3 newNrm = v.nrm * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newNrm * 127, 127); } // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void uVsToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon p = (Nud.Polygon)filesTreeView.SelectedNode; foreach (Nud.Vertex v in p.vertices) { v.color = new OpenTK.Vector4(v.uv[0].X * 127, v.uv[0].Y * 127, 127, 127); } // Update the data for rendering. Nud n = (Nud)p.Parent.Parent; n.UpdateRenderMeshes(); } private void polyFormatToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon poly = (Nud.Polygon)filesTreeView.SelectedNode; PolygonFormatEditor pfe = new PolygonFormatEditor(poly); pfe.ShowDialog(); ((Nud)poly.Parent.Parent).UpdateRenderMeshes(); } private void setToWhiteToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { poly.SetVertexColor(new OpenTK.Vector4(127, 127, 127, 127)); } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void selectColorUtilstripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; // Use a dialog so the color isn't set until the color editor is closed. ColorEditor colorEditor = new ColorEditor(new OpenTK.Vector3(1)); colorEditor.ShowDialog(); // Remap the color from 1.0 being white to 127 being white. OpenTK.Vector3 newVertColor = colorEditor.GetColor() * 127; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { poly.SetVertexColor(new OpenTK.Vector4(newVertColor, 127)); } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void tangentsToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { foreach (Nud.Vertex v in poly.vertices) { OpenTK.Vector3 newTan = v.tan.Xyz * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newTan * 127, 127); } } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void bitangentsToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { foreach (Nud.Vertex v in poly.vertices) { OpenTK.Vector3 newBitan = v.bitan.Xyz * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newBitan * 127, 127); } } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void normalsToolStripMenuItem1_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { foreach (Nud.Vertex v in poly.vertices) { OpenTK.Vector3 newNrm = v.nrm * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newNrm * 127, 127); } } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void uVsToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Mesh)) return; Nud.Mesh mesh = (Nud.Mesh)filesTreeView.SelectedNode; foreach (Nud.Polygon poly in mesh.Nodes) { foreach (Nud.Vertex v in poly.vertices) { v.color = new OpenTK.Vector4(v.uv[0].X * 127, v.uv[0].Y * 127, 127, 127); } } // Update the data for rendering. Nud n = (Nud)mesh.Parent; n.UpdateRenderMeshes(); } private void tangentsToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh m in n.Nodes) { foreach (Nud.Polygon p in m.Nodes) { foreach (Nud.Vertex v in p.vertices) { OpenTK.Vector3 newTan = v.tan.Xyz * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newTan * 127, 127); } } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void bitangentsToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh m in n.Nodes) { foreach (Nud.Polygon p in m.Nodes) { foreach (Nud.Vertex v in p.vertices) { OpenTK.Vector3 newBitan = v.bitan.Xyz * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newBitan * 127, 127); } } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void setToWhiteToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh m in n.Nodes) { foreach (Nud.Polygon p in m.Nodes) { p.SetVertexColor(new OpenTK.Vector4(127, 127, 127, 127)); } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void normalsToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh m in n.Nodes) { foreach (Nud.Polygon p in m.Nodes) { foreach (Nud.Vertex v in p.vertices) { OpenTK.Vector3 newNrm = v.nrm * 0.5f + new OpenTK.Vector3(0.5f); v.color = new OpenTK.Vector4(newNrm * 127, 127); } } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void uVsToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; foreach (Nud.Mesh m in n.Nodes) { foreach (Nud.Polygon p in m.Nodes) { foreach (Nud.Vertex v in p.vertices) { v.color = new OpenTK.Vector4(v.uv[0].X * 127, v.uv[0].Y * 127, 127, 127); } } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void selectColorUtilstripMenuItem2_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; // Use a dialog so the color isn't set until the color editor is closed. ColorEditor colorEditor = new ColorEditor(new OpenTK.Vector3(1)); colorEditor.ShowDialog(); // Remap the color from 1.0 being white to 127 being white. OpenTK.Vector3 newVertColor = colorEditor.GetColor() * 127; foreach (Nud.Mesh m in n.Nodes) { foreach (Nud.Polygon p in m.Nodes) { p.SetVertexColor(new OpenTK.Vector4(newVertColor, 127)); } } // Update the data for rendering. n.UpdateRenderMeshes(); } private void texIDToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud)) return; Nud n = (Nud)filesTreeView.SelectedNode; using (var texIdSelector = new TexIdSelector()) { texIdSelector.Set(n.GetFirstTexId()); texIdSelector.ShowDialog(); if (texIdSelector.exitStatus == TexIdSelector.ExitStatus.Opened) { n.ChangeTextureIds(texIdSelector.getNewTexId()); } } } private void texIDNUDNUTToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is ModelContainer)) return; ModelContainer modelContainer = (ModelContainer)filesTreeView.SelectedNode; if (modelContainer.NUT.Nodes.Count == 0) return; using (var texIdSelector = new TexIdSelector()) { // Match the texture IDs. Assume the NUT is the correct one to initialize the gui. texIdSelector.Set(((NutTexture)modelContainer.NUT.Nodes[0]).HashId); texIdSelector.ShowDialog(); if (texIdSelector.exitStatus == TexIdSelector.ExitStatus.Opened) { modelContainer.NUD.ChangeTextureIds(texIdSelector.getNewTexId()); modelContainer.NUT.ChangeTextureIds(texIdSelector.getNewTexId()); } } } #region BFRES Menus private void openMaterialEditorToolStripMenuItem_Click(object sender, EventArgs e) { BfresShapeSelected((BFRES.Mesh)filesTreeView.SelectedNode, $""); } private void openPolygonEditorToolStripMenuItem_Click(object sender, EventArgs e) { MainForm.Instance.BfresOpenMeshEditor((BFRES.Mesh)filesTreeView.SelectedNode, (BFRES.FMDL_Model)filesTreeView.SelectedNode.Parent, (BFRES)filesTreeView.SelectedNode.Parent.Parent.Parent, $""); } private void bfresSaveToolStripMenuItem_Click(object sender, EventArgs e) { string filename = ""; SaveFileDialog save = new SaveFileDialog(); save.Filter = "Binary caFe RESource|*.bfres|All files(*.*)|*.*"; DialogResult result = save.ShowDialog(); if (result == DialogResult.OK) { filename = save.FileName; if (filename.EndsWith(".bfres")) { if (((BFRES)filesTreeView.SelectedNode).TargetSwitchBFRES != null) { ((BFRES)filesTreeView.SelectedNode).InjectToFile(filename); } else { ((BFRES)filesTreeView.SelectedNode).InjectToWiiUBFRES(filename); } } } } private void flipUVsVerticalToolStripMenuItem_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is BFRES.Mesh) { BFRES.Mesh msh = (BFRES.Mesh)filesTreeView.SelectedNode; foreach (BFRES.Vertex v in msh.vertices) { v.uv0 = new OpenTK.Vector2(v.uv0.X, 1 - v.uv0.Y); } foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } } private void flipUVsHorizontalToolStripMenuItem1_Click(object sender, EventArgs e) { if (filesTreeView.SelectedNode is BFRES.Mesh) { BFRES.Mesh msh = (BFRES.Mesh)filesTreeView.SelectedNode; foreach (BFRES.Vertex v in msh.vertices) { v.uv0 = new OpenTK.Vector2(1 - v.uv0.X, v.uv0.Y); } foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } } private void bfresGenerateTanBitanToolStripMenuItem3_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh mesh = (BFRES.Mesh)filesTreeView.SelectedNode; BfresGenerateTanBitanAndFixVertType(mesh); // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } private static void BfresGenerateTanBitanAndFixVertType(BFRES.Mesh mesh) { // This already checks for the appropriate vertex type. mesh.CalculateTangentBitangent(); } private void smoothNormalsToolStripMenuItem_Click(object sender, EventArgs e) { } private void bfresRecalculateToolStripMenuItem3_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh mesh = (BFRES.Mesh)filesTreeView.SelectedNode; mesh.CalculateNormals(); // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } private void bfresSmoothToolStripMenuItem3_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh mesh = (BFRES.Mesh)filesTreeView.SelectedNode; mesh.SmoothNormals(); // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } private void bfresNormalsToolStripMenuItem3_Click(object sender, EventArgs e) { } private void bfresSetVertexColors_Click(object sender, EventArgs e) { } private void setColorUtilstripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh mesh = (BFRES.Mesh)filesTreeView.SelectedNode; ColorDialog colorDialog1 = new ColorDialog(); if (colorDialog1.ShowDialog() == DialogResult.OK) { mesh.SetVertexColor(new OpenTK.Vector4( colorDialog1.Color.R / 255.0f, colorDialog1.Color.G / 255.0f, colorDialog1.Color.B / 255.0f, colorDialog1.Color.A / 255.0f)); } // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } private void bfresMeshContextMenu_Opening(object sender, CancelEventArgs e) { } private void bfresSetWhiteToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh mesh = (BFRES.Mesh)filesTreeView.SelectedNode; mesh.SetVertexColor(new OpenTK.Vector4( 127.0f / 255.0f, 127.0f / 255.0f, 127.0f / 255.0f, 127.0f / 255.0f)); // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } public void UpdateBfresMeshList() { // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) { foreach (BFRES.FMDL_Model mdl in ((ModelContainer)con).Bfres.models) { foreach (BFRES.Mesh m in mdl.poly) { ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } } } } private void exportMaterialsXMLToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh msh = (BFRES.Mesh)filesTreeView.SelectedNode; msh.ExportMaterials2XML(); } private void bfresConvertWiiU2SwitchToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES)) return; // Update the data for rendering. foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Supported Formats|*.bfres;|" + "All files(*.*)|*.*"; if (ofd.ShowDialog() == DialogResult.OK) { if (ofd.FileName.EndsWith(".bfres")) { BFRES.WiiU2Switch(ofd.FileName, filesTreeView.SelectedNode.Index, ((ModelContainer)con).Bfres); } } } } } } private void generateTanBitanToolStripMenuItem3_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.FMDL_Model)) return; BFRES.FMDL_Model mdl = (BFRES.FMDL_Model)filesTreeView.SelectedNode; mdl.GenerateTansBitansEachMesh(); UpdateBfresMeshList(); } private void recalculateToolStripMenuItem3_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.FMDL_Model)) return; BFRES.FMDL_Model mdl = (BFRES.FMDL_Model)filesTreeView.SelectedNode; mdl.GenerateNormalEachMesh(); UpdateBfresMeshList(); } private void smoothToolStripMenuItem3_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.FMDL_Model)) return; BFRES.FMDL_Model mdl = (BFRES.FMDL_Model)filesTreeView.SelectedNode; mdl.SmoothNormalEachMesh(); UpdateBfresMeshList(); } private void copyChannel1To2ToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh m = (BFRES.Mesh)filesTreeView.SelectedNode; m.CopyUVChannel2(); UpdateBfresMeshList(); } private void singleBindToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is BFRES.Mesh)) return; BFRES.Mesh m = (BFRES.Mesh)filesTreeView.SelectedNode; foreach (TreeNode con in filesTreeView.Nodes) { if (con is ModelContainer) { if (((ModelContainer)con).Bfres != null) { m.SingleBindMesh(); //Add BFRES instance so we can use the fmdl and skeleton classes ((ModelContainer)con).Bfres.UpdateRenderMeshes(); } } } } #endregion private void KCLtoolStripMenuItem2_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog(); save.Filter = "Supported Filetypes (OBJ)|*.obj;|All files(*.*)|*.*"; DialogResult result = save.ShowDialog(); if (result == DialogResult.OK && filesTreeView.SelectedNode is KCL) { OBJ.KCL2OBJ(save.FileName, (KCL)filesTreeView.SelectedNode); } } private void uvViewerMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode is Nud.Polygon)) return; Nud.Polygon poly = (Nud.Polygon)filesTreeView.SelectedNode; Nud nud = (Nud)poly.Parent.Parent; UvViewer uvViewer = new UvViewer(nud, poly); uvViewer.Show(); } private void openViewerToolStripMenuItem_Click(object sender, EventArgs e) { if (!(filesTreeView.SelectedNode.Tag is SALT.Graphics.XMBFile)) return; try { SALT.Graphics.XMBFile xmb = (SALT.Graphics.XMBFile)filesTreeView.SelectedNode.Tag; XmbViewer xmbViewer = new XmbViewer(xmb); xmbViewer.Show(); } catch (Exception) { // Something broke. Let's just pretend it didn't happen. } } private void renameToolStripMenuItem_Click(object sender, EventArgs e) { filesTreeView.SelectedNode?.BeginEdit(); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class CommitPositionDecoder { public const ushort BLOCK_LENGTH = 20; public const ushort TEMPLATE_ID = 55; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private CommitPositionDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public CommitPositionDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public CommitPositionDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LeadershipTermIdId() { return 1; } public static int LeadershipTermIdSinceVersion() { return 0; } public static int LeadershipTermIdEncodingOffset() { return 0; } public static int LeadershipTermIdEncodingLength() { return 8; } public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LeadershipTermId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int LogPositionId() { return 2; } public static int LogPositionSinceVersion() { return 0; } public static int LogPositionEncodingOffset() { return 8; } public static int LogPositionEncodingLength() { return 8; } public static string LogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public long LogPosition() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int LeaderMemberIdId() { return 3; } public static int LeaderMemberIdSinceVersion() { return 0; } public static int LeaderMemberIdEncodingOffset() { return 16; } public static int LeaderMemberIdEncodingLength() { return 4; } public static string LeaderMemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int LeaderMemberIdNullValue() { return -2147483648; } public static int LeaderMemberIdMinValue() { return -2147483647; } public static int LeaderMemberIdMaxValue() { return 2147483647; } public int LeaderMemberId() { return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[CommitPosition](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeadershipTermId="); builder.Append(LeadershipTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogPosition="); builder.Append(LogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='leaderMemberId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeaderMemberId="); builder.Append(LeaderMemberId()); Limit(originalLimit); return builder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml { public enum XmlNodeOrder { After = 1, Before = 0, Same = 2, Unknown = 3, } } namespace System.Xml.XPath { public partial interface IXPathNavigable { System.Xml.XPath.XPathNavigator CreateNavigator(); } public enum XmlCaseOrder { LowerFirst = 2, None = 0, UpperFirst = 1, } public enum XmlDataType { Number = 2, Text = 1, } public enum XmlSortOrder { Ascending = 1, Descending = 2, } public partial class XPathDocument : System.Xml.XPath.IXPathNavigable { public XPathDocument(System.IO.Stream stream) { } public XPathDocument(System.IO.TextReader textReader) { } public XPathDocument(string uri) { } public XPathDocument(string uri, System.Xml.XmlSpace space) { } public XPathDocument(System.Xml.XmlReader reader) { } public XPathDocument(System.Xml.XmlReader reader, System.Xml.XmlSpace space) { } public System.Xml.XPath.XPathNavigator CreateNavigator() { return default(System.Xml.XPath.XPathNavigator); } } public partial class XPathException : System.Exception { public XPathException() { } public XPathException(string message) { } public XPathException(string message, System.Exception innerException) { } } public abstract partial class XPathExpression { internal XPathExpression() { } public abstract string Expression { get; } public abstract System.Xml.XPath.XPathResultType ReturnType { get; } public abstract void AddSort(object expr, System.Collections.IComparer comparer); public abstract void AddSort(object expr, System.Xml.XPath.XmlSortOrder order, System.Xml.XPath.XmlCaseOrder caseOrder, string lang, System.Xml.XPath.XmlDataType dataType); public abstract System.Xml.XPath.XPathExpression Clone(); public static System.Xml.XPath.XPathExpression Compile(string xpath) { return default(System.Xml.XPath.XPathExpression); } public static System.Xml.XPath.XPathExpression Compile(string xpath, System.Xml.IXmlNamespaceResolver nsResolver) { return default(System.Xml.XPath.XPathExpression); } public abstract void SetContext(System.Xml.IXmlNamespaceResolver nsResolver); public abstract void SetContext(System.Xml.XmlNamespaceManager nsManager); } public abstract partial class XPathItem { internal XPathItem() { } public abstract bool IsNode { get; } public abstract object TypedValue { get; } public abstract string Value { get; } public abstract bool ValueAsBoolean { get; } public abstract System.DateTime ValueAsDateTime { get; } public abstract double ValueAsDouble { get; } public abstract int ValueAsInt { get; } public abstract long ValueAsLong { get; } public abstract System.Type ValueType { get; } public virtual object ValueAs(System.Type returnType) { return default(object); } public abstract object ValueAs(System.Type returnType, System.Xml.IXmlNamespaceResolver nsResolver); } public enum XPathNamespaceScope { All = 0, ExcludeXml = 1, Local = 2, } public abstract partial class XPathNavigator : System.Xml.XPath.XPathItem, System.Xml.IXmlNamespaceResolver, System.Xml.XPath.IXPathNavigable { protected XPathNavigator() { } public abstract string BaseURI { get; } public virtual bool CanEdit { get { return default(bool); } } public virtual bool HasAttributes { get { return default(bool); } } public virtual bool HasChildren { get { return default(bool); } } public virtual string InnerXml { get { return default(string); } set { } } public abstract bool IsEmptyElement { get; } public sealed override bool IsNode { get { return default(bool); } } public abstract string LocalName { get; } public abstract string Name { get; } public abstract string NamespaceURI { get; } public abstract System.Xml.XmlNameTable NameTable { get; } public static System.Collections.IEqualityComparer NavigatorComparer { get { return default(System.Collections.IEqualityComparer); } } public abstract System.Xml.XPath.XPathNodeType NodeType { get; } public virtual string OuterXml { get { return default(string); } set { } } public abstract string Prefix { get; } public override object TypedValue { get { return default(object); } } public virtual object UnderlyingObject { get { return default(object); } } public override bool ValueAsBoolean { get { return default(bool); } } public override System.DateTime ValueAsDateTime { get { return default(System.DateTime); } } public override double ValueAsDouble { get { return default(double); } } public override int ValueAsInt { get { return default(int); } } public override long ValueAsLong { get { return default(long); } } public override System.Type ValueType { get { return default(System.Type); } } public virtual string XmlLang { get { return default(string); } } public virtual System.Xml.XmlWriter AppendChild() { return default(System.Xml.XmlWriter); } public virtual void AppendChild(string newChild) { } public virtual void AppendChild(System.Xml.XmlReader newChild) { } public virtual void AppendChild(System.Xml.XPath.XPathNavigator newChild) { } public virtual void AppendChildElement(string prefix, string localName, string namespaceURI, string value) { } public abstract System.Xml.XPath.XPathNavigator Clone(); public virtual System.Xml.XmlNodeOrder ComparePosition(System.Xml.XPath.XPathNavigator nav) { return default(System.Xml.XmlNodeOrder); } public virtual System.Xml.XPath.XPathExpression Compile(string xpath) { return default(System.Xml.XPath.XPathExpression); } public virtual void CreateAttribute(string prefix, string localName, string namespaceURI, string value) { } public virtual System.Xml.XmlWriter CreateAttributes() { return default(System.Xml.XmlWriter); } public virtual System.Xml.XPath.XPathNavigator CreateNavigator() { return default(System.Xml.XPath.XPathNavigator); } public virtual void DeleteRange(System.Xml.XPath.XPathNavigator lastSiblingToDelete) { } public virtual void DeleteSelf() { } public virtual object Evaluate(string xpath) { return default(object); } public virtual object Evaluate(string xpath, System.Xml.IXmlNamespaceResolver resolver) { return default(object); } public virtual object Evaluate(System.Xml.XPath.XPathExpression expr) { return default(object); } public virtual object Evaluate(System.Xml.XPath.XPathExpression expr, System.Xml.XPath.XPathNodeIterator context) { return default(object); } public virtual string GetAttribute(string localName, string namespaceURI) { return default(string); } public virtual string GetNamespace(string name) { return default(string); } public virtual System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope) { return default(System.Collections.Generic.IDictionary<string, string>); } public virtual System.Xml.XmlWriter InsertAfter() { return default(System.Xml.XmlWriter); } public virtual void InsertAfter(string newSibling) { } public virtual void InsertAfter(System.Xml.XmlReader newSibling) { } public virtual void InsertAfter(System.Xml.XPath.XPathNavigator newSibling) { } public virtual System.Xml.XmlWriter InsertBefore() { return default(System.Xml.XmlWriter); } public virtual void InsertBefore(string newSibling) { } public virtual void InsertBefore(System.Xml.XmlReader newSibling) { } public virtual void InsertBefore(System.Xml.XPath.XPathNavigator newSibling) { } public virtual void InsertElementAfter(string prefix, string localName, string namespaceURI, string value) { } public virtual void InsertElementBefore(string prefix, string localName, string namespaceURI, string value) { } public virtual bool IsDescendant(System.Xml.XPath.XPathNavigator nav) { return default(bool); } public abstract bool IsSamePosition(System.Xml.XPath.XPathNavigator other); public virtual string LookupNamespace(string prefix) { return default(string); } public virtual string LookupPrefix(string namespaceURI) { return default(string); } public virtual bool Matches(string xpath) { return default(bool); } public virtual bool Matches(System.Xml.XPath.XPathExpression expr) { return default(bool); } public abstract bool MoveTo(System.Xml.XPath.XPathNavigator other); public virtual bool MoveToAttribute(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToChild(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToChild(System.Xml.XPath.XPathNodeType type) { return default(bool); } public virtual bool MoveToFirst() { return default(bool); } public abstract bool MoveToFirstAttribute(); public abstract bool MoveToFirstChild(); public bool MoveToFirstNamespace() { return default(bool); } public abstract bool MoveToFirstNamespace(System.Xml.XPath.XPathNamespaceScope namespaceScope); public virtual bool MoveToFollowing(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToFollowing(string localName, string namespaceURI, System.Xml.XPath.XPathNavigator end) { return default(bool); } public virtual bool MoveToFollowing(System.Xml.XPath.XPathNodeType type) { return default(bool); } public virtual bool MoveToFollowing(System.Xml.XPath.XPathNodeType type, System.Xml.XPath.XPathNavigator end) { return default(bool); } public abstract bool MoveToId(string id); public virtual bool MoveToNamespace(string name) { return default(bool); } public abstract bool MoveToNext(); public virtual bool MoveToNext(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToNext(System.Xml.XPath.XPathNodeType type) { return default(bool); } public abstract bool MoveToNextAttribute(); public bool MoveToNextNamespace() { return default(bool); } public abstract bool MoveToNextNamespace(System.Xml.XPath.XPathNamespaceScope namespaceScope); public abstract bool MoveToParent(); public abstract bool MoveToPrevious(); public virtual void MoveToRoot() { } public virtual System.Xml.XmlWriter PrependChild() { return default(System.Xml.XmlWriter); } public virtual void PrependChild(string newChild) { } public virtual void PrependChild(System.Xml.XmlReader newChild) { } public virtual void PrependChild(System.Xml.XPath.XPathNavigator newChild) { } public virtual void PrependChildElement(string prefix, string localName, string namespaceURI, string value) { } public virtual System.Xml.XmlReader ReadSubtree() { return default(System.Xml.XmlReader); } public virtual System.Xml.XmlWriter ReplaceRange(System.Xml.XPath.XPathNavigator lastSiblingToReplace) { return default(System.Xml.XmlWriter); } public virtual void ReplaceSelf(string newNode) { } public virtual void ReplaceSelf(System.Xml.XmlReader newNode) { } public virtual void ReplaceSelf(System.Xml.XPath.XPathNavigator newNode) { } public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath, System.Xml.IXmlNamespaceResolver resolver) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator Select(System.Xml.XPath.XPathExpression expr) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectAncestors(string name, string namespaceURI, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectAncestors(System.Xml.XPath.XPathNodeType type, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectChildren(string name, string namespaceURI) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectChildren(System.Xml.XPath.XPathNodeType type) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectDescendants(System.Xml.XPath.XPathNodeType type, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNavigator SelectSingleNode(string xpath) { return default(System.Xml.XPath.XPathNavigator); } public virtual System.Xml.XPath.XPathNavigator SelectSingleNode(string xpath, System.Xml.IXmlNamespaceResolver resolver) { return default(System.Xml.XPath.XPathNavigator); } public virtual System.Xml.XPath.XPathNavigator SelectSingleNode(System.Xml.XPath.XPathExpression expression) { return default(System.Xml.XPath.XPathNavigator); } public virtual void SetTypedValue(object typedValue) { } public virtual void SetValue(string value) { } public override string ToString() { return default(string); } public override object ValueAs(System.Type returnType, System.Xml.IXmlNamespaceResolver nsResolver) { return default(object); } public virtual void WriteSubtree(System.Xml.XmlWriter writer) { } } public abstract partial class XPathNodeIterator : System.Collections.IEnumerable { protected XPathNodeIterator() { } public virtual int Count { get { return default(int); } } public abstract System.Xml.XPath.XPathNavigator Current { get; } public abstract int CurrentPosition { get; } public abstract System.Xml.XPath.XPathNodeIterator Clone(); public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public abstract bool MoveNext(); } public enum XPathNodeType { All = 9, Attribute = 2, Comment = 8, Element = 1, Namespace = 3, ProcessingInstruction = 7, Root = 0, SignificantWhitespace = 5, Text = 4, Whitespace = 6, } public enum XPathResultType { Any = 5, Boolean = 2, Error = 6, Navigator = 1, NodeSet = 3, Number = 0, String = 1, } }
using System; using System.Runtime.InteropServices; class TestHelper { public static void Assert(bool exp,string msg="") { CoreFXTestLibrary.Assert.IsTrue(exp, msg); } } [StructLayout(LayoutKind.Sequential)] public struct S_INTArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_UINTArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_SHORTArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_WORDArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_LONG64Array_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public long[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_ULONG64Array_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_DOUBLEArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_FLOATArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_BYTEArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_CHARArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_INTPTRArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public IntPtr[] arr; } //struct array in a struct [StructLayout(LayoutKind.Sequential)] public struct TestStruct { public int x; public double d; public long l; public string str; } [StructLayout(LayoutKind.Sequential)] public struct S_StructArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Sequential)] public struct S_BOOLArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_INTArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_UINTArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_SHORTArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_WORDArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_LONG64Array_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public long[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_ULONG64Array_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_DOUBLEArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_FLOATArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_BYTEArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_CHARArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_LPSTRArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_LPCSTRArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } //struct array in a class [StructLayout(LayoutKind.Sequential)] public class C_StructArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Sequential)] public class C_BOOLArray_Seq { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_INTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_UINTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_SHORTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_WORDArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_LONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE, ArraySubType = UnmanagedType.I8)] public long[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_ULONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_DOUBLEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_FLOATArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_BYTEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_CHARArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_LPSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_LPCSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } //struct array in a struct [StructLayout(LayoutKind.Explicit)] public struct S_StructArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Explicit)] public struct S_BOOLArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_INTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public int[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_UINTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public uint[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_SHORTArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public short[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_WORDArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ushort[] arr; } [StructLayout(LayoutKind.Explicit, Pack = 8)] public class C_LONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public long[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_ULONG64Array_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public ulong[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_DOUBLEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public double[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_FLOATArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public float[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_BYTEArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public byte[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_CHARArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public char[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_LPSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_LPCSTRArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public string[] arr; } //struct array in a class [StructLayout(LayoutKind.Explicit)] public class C_StructArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public TestStruct[] arr; } [StructLayout(LayoutKind.Explicit)] public class C_BOOLArray_Exp { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Test.ARRAY_SIZE)] public bool[] arr; } class Test { //for RunTest1 [DllImport("MarshalArrayByValNative")] static extern bool TakeIntArraySeqStructByVal([In]S_INTArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeUIntArraySeqStructByVal([In]S_UINTArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeShortArraySeqStructByVal([In]S_SHORTArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeWordArraySeqStructByVal([In]S_WORDArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLong64ArraySeqStructByVal([In]S_LONG64Array_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeULong64ArraySeqStructByVal([In]S_ULONG64Array_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeDoubleArraySeqStructByVal([In]S_DOUBLEArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeFloatArraySeqStructByVal([In]S_FLOATArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeByteArraySeqStructByVal([In]S_BYTEArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeCharArraySeqStructByVal([In]S_CHARArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeIntPtrArraySeqStructByVal([In]S_INTPTRArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeStructArraySeqStructByVal([In]S_StructArray_Seq s, int size); //for RunTest2 [DllImport("MarshalArrayByValNative")] static extern bool TakeIntArraySeqClassByVal([In]C_INTArray_Seq c, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeUIntArraySeqClassByVal([In]C_UINTArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeShortArraySeqClassByVal([In]C_SHORTArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeWordArraySeqClassByVal([In]C_WORDArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLong64ArraySeqClassByVal([In]C_LONG64Array_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeULong64ArraySeqClassByVal([In]C_ULONG64Array_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeDoubleArraySeqClassByVal([In]C_DOUBLEArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeFloatArraySeqClassByVal([In]C_FLOATArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeByteArraySeqClassByVal([In]C_BYTEArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeCharArraySeqClassByVal([In]C_CHARArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLPSTRArraySeqClassByVal([In]C_LPSTRArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLPCSTRArraySeqClassByVal([In]C_LPCSTRArray_Seq s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeStructArraySeqClassByVal([In]C_StructArray_Seq s, int size); //for RunTest3 [DllImport("MarshalArrayByValNative")] static extern bool TakeIntArrayExpStructByVal([In]S_INTArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeUIntArrayExpStructByVal([In]S_UINTArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeShortArrayExpStructByVal([In]S_SHORTArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeWordArrayExpStructByVal([In]S_WORDArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLong64ArrayExpStructByVal([In]S_LONG64Array_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeULong64ArrayExpStructByVal([In]S_ULONG64Array_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeDoubleArrayExpStructByVal([In]S_DOUBLEArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeFloatArrayExpStructByVal([In]S_FLOATArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeByteArrayExpStructByVal([In]S_BYTEArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeCharArrayExpStructByVal([In]S_CHARArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLPSTRArrayExpStructByVal([In]S_LPSTRArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLPCSTRArrayExpStructByVal([In]S_LPCSTRArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeStructArrayExpStructByVal([In]S_StructArray_Exp s, int size); //for RunTest4 [DllImport("MarshalArrayByValNative")] static extern bool TakeIntArrayExpClassByVal([In]C_INTArray_Exp c, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeUIntArrayExpClassByVal([In]C_UINTArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeShortArrayExpClassByVal([In]C_SHORTArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeWordArrayExpClassByVal([In]C_WORDArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLong64ArrayExpClassByVal([In]C_LONG64Array_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeULong64ArrayExpClassByVal([In]C_ULONG64Array_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeDoubleArrayExpClassByVal([In]C_DOUBLEArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeFloatArrayExpClassByVal([In]C_FLOATArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeByteArrayExpClassByVal([In]C_BYTEArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeCharArrayExpClassByVal([In]C_CHARArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLPSTRArrayExpClassByVal([In]C_LPSTRArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeLPCSTRArrayExpClassByVal([In]C_LPCSTRArray_Exp s, int size); [DllImport("MarshalArrayByValNative")] static extern bool TakeStructArrayExpClassByVal([In]C_StructArray_Exp s, int size); //for RunTest5 //get struct on C++ side as sequential class [DllImport("MarshalArrayByValNative")] static extern C_INTArray_Seq S_INTArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_UINTArray_Seq S_UINTArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_SHORTArray_Seq S_SHORTArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_WORDArray_Seq S_WORDArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_LONG64Array_Seq S_LONG64Array_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_ULONG64Array_Seq S_ULONG64Array_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_DOUBLEArray_Seq S_DOUBLEArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_FLOATArray_Seq S_FLOATArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_BYTEArray_Seq S_BYTEArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_CHARArray_Seq S_CHARArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_LPSTRArray_Seq S_LPSTRArray_Ret(); [DllImport("MarshalArrayByValNative")] static extern C_StructArray_Seq S_StructArray_Ret(); //for RunTest6 //get struct on C++ side as explicit class [DllImport("MarshalArrayByValNative", EntryPoint = "S_INTArray_Ret")] static extern C_INTArray_Exp S_INTArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_UINTArray_Ret")] static extern C_UINTArray_Exp S_UINTArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_SHORTArray_Ret")] static extern C_SHORTArray_Exp S_SHORTArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_WORDArray_Ret")] static extern C_WORDArray_Exp S_WORDArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_LONG64Array_Ret")] static extern C_LONG64Array_Exp S_LONG64Array_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_ULONG64Array_Ret")] static extern C_ULONG64Array_Exp S_ULONG64Array_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_DOUBLEArray_Ret")] static extern C_DOUBLEArray_Exp S_DOUBLEArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_FLOATArray_Ret")] static extern C_FLOATArray_Exp S_FLOATArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_BYTEArray_Ret")] static extern C_BYTEArray_Exp S_BYTEArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_CHARArray_Ret")] static extern C_CHARArray_Exp S_CHARArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_LPSTRArray_Ret")] static extern C_LPSTRArray_Exp S_LPSTRArray_Ret2(); [DllImport("MarshalArrayByValNative", EntryPoint = "S_StructArray_Ret")] static extern C_StructArray_Exp S_StructArray_Ret2(); internal const int ARRAY_SIZE = 100; static T[] InitArray<T>(int size) { T[] array = new T[size]; for (int i = 0; i < array.Length; i++) array[i] = (T)Convert.ChangeType(i, typeof(T)); return array; } static TestStruct[] InitStructArray(int size) { TestStruct[] array = new TestStruct[size]; for (int i = 0; i < array.Length; i++) { array[i].x = i; array[i].d = i; array[i].l = i; array[i].str = i.ToString(); } return array; } static bool[] InitBoolArray(int size) { bool[] array = new bool[size]; for (int i = 0; i < array.Length; i++) { if (i % 2 == 0) array[i] = true; else array[i] = false; } return array; } static IntPtr[] InitIntPtrArray(int size) { IntPtr[] array = new IntPtr[size]; for (int i = 0; i < array.Length; i++) array[i] = new IntPtr(i); return array; } static bool Equals<T>(T[] arr1, T[] arr2) { if (arr1 == null && arr2 == null) return true; else if (arr1 == null && arr2 != null) return false; else if (arr1 != null && arr2 == null) return false; else if (arr1.Length != arr2.Length) return false; for (int i = 0; i < arr2.Length; ++i) { if (!Object.Equals(arr1[i], arr2[i])) { Console.WriteLine("Array marshaling error, when type is {0}", typeof(T)); Console.WriteLine("Expected: {0}, Actual: {1}", arr1[i], arr2[i]); return false; } } return true; } static bool TestStructEquals(TestStruct[] tsArr1, TestStruct[] tsArr2) { if (tsArr1 == null && tsArr2 == null) return true; else if (tsArr1 == null && tsArr2 != null) return false; else if (tsArr1 != null && tsArr2 == null) return false; else if (tsArr1.Length != tsArr2.Length) return false; bool result = true; for (int i = 0; i < tsArr2.Length; i++) { result = (tsArr1[i].x == tsArr2[i].x && tsArr1[i].d == tsArr2[i].d && tsArr1[i].l == tsArr2[i].l && tsArr1[i].str == tsArr2[i].str) && result; } return result; } static bool RunTest1(string report) { Console.WriteLine(report); S_INTArray_Seq s1 = new S_INTArray_Seq(); s1.arr = InitArray<int>(ARRAY_SIZE); TestHelper.Assert(TakeIntArraySeqStructByVal(s1, s1.arr.Length), "TakeIntArraySeqStructByVal"); S_UINTArray_Seq s2 = new S_UINTArray_Seq(); s2.arr = InitArray<uint>(ARRAY_SIZE); TestHelper.Assert(TakeUIntArraySeqStructByVal(s2, s2.arr.Length), "TakeUIntArraySeqStructByVal"); S_SHORTArray_Seq s3 = new S_SHORTArray_Seq(); s3.arr = InitArray<short>(ARRAY_SIZE); TestHelper.Assert(TakeShortArraySeqStructByVal(s3, s3.arr.Length), "TakeShortArraySeqStructByVal"); S_WORDArray_Seq s4 = new S_WORDArray_Seq(); s4.arr = InitArray<ushort>(ARRAY_SIZE); TestHelper.Assert(TakeWordArraySeqStructByVal(s4, s4.arr.Length), "TakeWordArraySeqStructByVal"); S_LONG64Array_Seq s5 = new S_LONG64Array_Seq(); s5.arr = InitArray<long>(ARRAY_SIZE); TestHelper.Assert(TakeLong64ArraySeqStructByVal(s5, s5.arr.Length), "TakeLong64ArraySeqStructByVal"); S_ULONG64Array_Seq s6 = new S_ULONG64Array_Seq(); s6.arr = InitArray<ulong>(ARRAY_SIZE); TestHelper.Assert(TakeULong64ArraySeqStructByVal(s6, s6.arr.Length), "TakeULong64ArraySeqStructByVal"); S_DOUBLEArray_Seq s7 = new S_DOUBLEArray_Seq(); s7.arr = InitArray<double>(ARRAY_SIZE); TestHelper.Assert(TakeDoubleArraySeqStructByVal(s7, s7.arr.Length), "TakeDoubleArraySeqStructByVal"); S_FLOATArray_Seq s8 = new S_FLOATArray_Seq(); s8.arr = InitArray<float>(ARRAY_SIZE); TestHelper.Assert(TakeFloatArraySeqStructByVal(s8, s8.arr.Length), "TakeFloatArraySeqStructByVal"); S_BYTEArray_Seq s9 = new S_BYTEArray_Seq(); s9.arr = InitArray<byte>(ARRAY_SIZE); TestHelper.Assert(TakeByteArraySeqStructByVal(s9, s9.arr.Length), "TakeByteArraySeqStructByVal"); S_CHARArray_Seq s10 = new S_CHARArray_Seq(); s10.arr = InitArray<char>(ARRAY_SIZE); TestHelper.Assert(TakeCharArraySeqStructByVal(s10, s10.arr.Length), "TakeCharArraySeqStructByVal"); S_INTPTRArray_Seq s11 = new S_INTPTRArray_Seq(); s11.arr = InitIntPtrArray(ARRAY_SIZE); TestHelper.Assert(TakeIntPtrArraySeqStructByVal(s11, s11.arr.Length), "TakeIntPtrArraySeqStructByVal"); S_StructArray_Seq s14 = new S_StructArray_Seq(); s14.arr = InitStructArray(ARRAY_SIZE); TestHelper.Assert(TakeStructArraySeqStructByVal(s14, s14.arr.Length),"TakeStructArraySeqStructByVal"); return true; } static bool RunTest2(string report) { C_INTArray_Seq c1 = new C_INTArray_Seq(); c1.arr = InitArray<int>(ARRAY_SIZE); TestHelper.Assert(TakeIntArraySeqClassByVal(c1, c1.arr.Length)); C_UINTArray_Seq c2 = new C_UINTArray_Seq(); c2.arr = InitArray<uint>(ARRAY_SIZE); TestHelper.Assert(TakeUIntArraySeqClassByVal(c2, c2.arr.Length)); C_SHORTArray_Seq c3 = new C_SHORTArray_Seq(); c3.arr = InitArray<short>(ARRAY_SIZE); TestHelper.Assert(TakeShortArraySeqClassByVal(c3, c3.arr.Length)); C_WORDArray_Seq c4 = new C_WORDArray_Seq(); c4.arr = InitArray<ushort>(ARRAY_SIZE); TestHelper.Assert(TakeWordArraySeqClassByVal(c4, c4.arr.Length)); C_LONG64Array_Seq c5 = new C_LONG64Array_Seq(); c5.arr = InitArray<long>(ARRAY_SIZE); TestHelper.Assert(TakeLong64ArraySeqClassByVal(c5, c5.arr.Length)); C_ULONG64Array_Seq c6 = new C_ULONG64Array_Seq(); c6.arr = InitArray<ulong>(ARRAY_SIZE); TestHelper.Assert(TakeULong64ArraySeqClassByVal(c6, c6.arr.Length)); C_DOUBLEArray_Seq c7 = new C_DOUBLEArray_Seq(); c7.arr = InitArray<double>(ARRAY_SIZE); TestHelper.Assert(TakeDoubleArraySeqClassByVal(c7, c7.arr.Length)); C_FLOATArray_Seq c8 = new C_FLOATArray_Seq(); c8.arr = InitArray<float>(ARRAY_SIZE); TestHelper.Assert(TakeFloatArraySeqClassByVal(c8, c8.arr.Length)); C_BYTEArray_Seq c9 = new C_BYTEArray_Seq(); c9.arr = InitArray<byte>(ARRAY_SIZE); TestHelper.Assert(TakeByteArraySeqClassByVal(c9, c9.arr.Length)); C_CHARArray_Seq c10 = new C_CHARArray_Seq(); c10.arr = InitArray<char>(ARRAY_SIZE); TestHelper.Assert(TakeCharArraySeqClassByVal(c10, c10.arr.Length)); C_LPSTRArray_Seq c11 = new C_LPSTRArray_Seq(); c11.arr = InitArray<string>(ARRAY_SIZE); TestHelper.Assert(TakeLPSTRArraySeqClassByVal(c11, c11.arr.Length)); C_LPCSTRArray_Seq c12 = new C_LPCSTRArray_Seq(); c12.arr = InitArray<string>(ARRAY_SIZE); TestHelper.Assert(TakeLPCSTRArraySeqClassByVal(c12, c12.arr.Length)); C_StructArray_Seq c14 = new C_StructArray_Seq(); c14.arr = InitStructArray(ARRAY_SIZE); TestHelper.Assert(TakeStructArraySeqClassByVal(c14, c14.arr.Length)); return true; } static bool RunTest3(string report) { Console.WriteLine(report); S_INTArray_Exp s1 = new S_INTArray_Exp(); s1.arr = InitArray<int>(ARRAY_SIZE); TestHelper.Assert(TakeIntArrayExpStructByVal(s1, s1.arr.Length), "TakeIntArrayExpStructByVal"); S_UINTArray_Exp s2 = new S_UINTArray_Exp(); s2.arr = InitArray<uint>(ARRAY_SIZE); TestHelper.Assert(TakeUIntArrayExpStructByVal(s2, s2.arr.Length), "TakeUIntArrayExpStructByVal"); S_SHORTArray_Exp s3 = new S_SHORTArray_Exp(); s3.arr = InitArray<short>(ARRAY_SIZE); TestHelper.Assert(TakeShortArrayExpStructByVal(s3, s3.arr.Length), "TakeShortArrayExpStructByVal"); S_WORDArray_Exp s4 = new S_WORDArray_Exp(); s4.arr = InitArray<ushort>(ARRAY_SIZE); TestHelper.Assert(TakeWordArrayExpStructByVal(s4, s4.arr.Length), "TakeWordArrayExpStructByVal"); S_LONG64Array_Exp s5 = new S_LONG64Array_Exp(); s5.arr = InitArray<long>(ARRAY_SIZE); TestHelper.Assert(TakeLong64ArrayExpStructByVal(s5, s5.arr.Length), "TakeLong64ArrayExpStructByVal"); S_ULONG64Array_Exp s6 = new S_ULONG64Array_Exp(); s6.arr = InitArray<ulong>(ARRAY_SIZE); TestHelper.Assert(TakeULong64ArrayExpStructByVal(s6, s6.arr.Length), "TakeULong64ArrayExpStructByVal"); S_DOUBLEArray_Exp s7 = new S_DOUBLEArray_Exp(); s7.arr = InitArray<double>(ARRAY_SIZE); TestHelper.Assert(TakeDoubleArrayExpStructByVal(s7, s7.arr.Length), "TakeDoubleArrayExpStructByVal"); S_FLOATArray_Exp s8 = new S_FLOATArray_Exp(); s8.arr = InitArray<float>(ARRAY_SIZE); TestHelper.Assert(TakeFloatArrayExpStructByVal(s8, s8.arr.Length), "TakeFloatArrayExpStructByVal"); S_BYTEArray_Exp s9 = new S_BYTEArray_Exp(); s9.arr = InitArray<byte>(ARRAY_SIZE); TestHelper.Assert(TakeByteArrayExpStructByVal(s9, s9.arr.Length), "TakeByteArrayExpStructByVal"); S_CHARArray_Exp s10 = new S_CHARArray_Exp(); s10.arr = InitArray<char>(ARRAY_SIZE); TestHelper.Assert(TakeCharArrayExpStructByVal(s10, s10.arr.Length), "TakeCharArrayExpStructByVal"); S_LPSTRArray_Exp s11 = new S_LPSTRArray_Exp(); s11.arr = InitArray<string>(ARRAY_SIZE); TestHelper.Assert(TakeLPSTRArrayExpStructByVal(s11, s11.arr.Length)); S_LPCSTRArray_Exp s12 = new S_LPCSTRArray_Exp(); s12.arr = InitArray<string>(ARRAY_SIZE); TestHelper.Assert(TakeLPCSTRArrayExpStructByVal(s12, s12.arr.Length)); S_StructArray_Exp s14 = new S_StructArray_Exp(); s14.arr = InitStructArray(ARRAY_SIZE); TestHelper.Assert(TakeStructArrayExpStructByVal(s14, s14.arr.Length)); return true; } static bool RunTest4(string report) { Console.WriteLine(report); C_INTArray_Exp c1 = new C_INTArray_Exp(); c1.arr = InitArray<int>(ARRAY_SIZE); TestHelper.Assert(TakeIntArrayExpClassByVal(c1, c1.arr.Length)); C_UINTArray_Exp c2 = new C_UINTArray_Exp(); c2.arr = InitArray<uint>(ARRAY_SIZE); TestHelper.Assert(TakeUIntArrayExpClassByVal(c2, c2.arr.Length)); C_SHORTArray_Exp c3 = new C_SHORTArray_Exp(); c3.arr = InitArray<short>(ARRAY_SIZE); TestHelper.Assert(TakeShortArrayExpClassByVal(c3, c3.arr.Length)); C_WORDArray_Exp c4 = new C_WORDArray_Exp(); c4.arr = InitArray<ushort>(ARRAY_SIZE); TestHelper.Assert(TakeWordArrayExpClassByVal(c4, c4.arr.Length)); C_LONG64Array_Exp c5 = new C_LONG64Array_Exp(); c5.arr = InitArray<long>(ARRAY_SIZE); TestHelper.Assert(TakeLong64ArrayExpClassByVal(c5, c5.arr.Length)); C_ULONG64Array_Exp c6 = new C_ULONG64Array_Exp(); c6.arr = InitArray<ulong>(ARRAY_SIZE); TestHelper.Assert(TakeULong64ArrayExpClassByVal(c6, c6.arr.Length)); C_DOUBLEArray_Exp c7 = new C_DOUBLEArray_Exp(); c7.arr = InitArray<double>(ARRAY_SIZE); TestHelper.Assert(TakeDoubleArrayExpClassByVal(c7, c7.arr.Length)); C_FLOATArray_Exp c8 = new C_FLOATArray_Exp(); c8.arr = InitArray<float>(ARRAY_SIZE); TestHelper.Assert(TakeFloatArrayExpClassByVal(c8, c8.arr.Length)); C_BYTEArray_Exp c9 = new C_BYTEArray_Exp(); c9.arr = InitArray<byte>(ARRAY_SIZE); TestHelper.Assert(TakeByteArrayExpClassByVal(c9, c9.arr.Length)); C_CHARArray_Exp c10 = new C_CHARArray_Exp(); c10.arr = InitArray<char>(ARRAY_SIZE); TestHelper.Assert(TakeCharArrayExpClassByVal(c10, c10.arr.Length)); C_LPSTRArray_Exp c11 = new C_LPSTRArray_Exp(); c11.arr = InitArray<string>(ARRAY_SIZE); TestHelper.Assert(TakeLPSTRArrayExpClassByVal(c11, c11.arr.Length)); C_LPCSTRArray_Exp c12 = new C_LPCSTRArray_Exp(); c12.arr = InitArray<string>(ARRAY_SIZE); TestHelper.Assert(TakeLPCSTRArrayExpClassByVal(c12, c12.arr.Length)); C_StructArray_Exp c14 = new C_StructArray_Exp(); c14.arr = InitStructArray(ARRAY_SIZE); TestHelper.Assert(TakeStructArrayExpClassByVal(c14, c14.arr.Length)); return true; } static bool RunTest5(string report) { C_INTArray_Seq retval1 = S_INTArray_Ret(); TestHelper.Assert(Equals(InitArray<int>(ARRAY_SIZE), retval1.arr)); C_UINTArray_Seq retval2 = S_UINTArray_Ret(); TestHelper.Assert(Equals(InitArray<uint>(ARRAY_SIZE), retval2.arr)); C_SHORTArray_Seq retval3 = S_SHORTArray_Ret(); TestHelper.Assert(Equals(InitArray<short>(ARRAY_SIZE), retval3.arr)); C_WORDArray_Seq retval4 = S_WORDArray_Ret(); TestHelper.Assert(Equals(InitArray<ushort>(ARRAY_SIZE), retval4.arr)); C_LONG64Array_Seq retval5 = S_LONG64Array_Ret(); TestHelper.Assert(Equals(InitArray<long>(ARRAY_SIZE), retval5.arr)); C_ULONG64Array_Seq retval6 = S_ULONG64Array_Ret(); TestHelper.Assert(Equals(InitArray<ulong>(ARRAY_SIZE), retval6.arr)); C_DOUBLEArray_Seq retval7 = S_DOUBLEArray_Ret(); TestHelper.Assert(Equals(InitArray<double>(ARRAY_SIZE), retval7.arr)); C_FLOATArray_Seq retval8 = S_FLOATArray_Ret(); TestHelper.Assert(Equals(InitArray<float>(ARRAY_SIZE), retval8.arr)); C_BYTEArray_Seq retval9 = S_BYTEArray_Ret(); TestHelper.Assert(Equals(InitArray<byte>(ARRAY_SIZE), retval9.arr)); C_CHARArray_Seq retval10 = S_CHARArray_Ret(); TestHelper.Assert(Equals(InitArray<char>(ARRAY_SIZE), retval10.arr)); C_LPSTRArray_Seq retval11 = S_LPSTRArray_Ret(); TestHelper.Assert(Equals(InitArray<string>(ARRAY_SIZE), retval11.arr)); C_StructArray_Seq retval13 = S_StructArray_Ret(); TestHelper.Assert(TestStructEquals(InitStructArray(ARRAY_SIZE), retval13.arr)); return true; } static bool RunTest6(string report) { C_INTArray_Exp retval1 = S_INTArray_Ret2(); TestHelper.Assert(Equals(InitArray<int>(ARRAY_SIZE), retval1.arr)); C_UINTArray_Exp retval2 = S_UINTArray_Ret2(); TestHelper.Assert(Equals(InitArray<uint>(ARRAY_SIZE), retval2.arr)); C_SHORTArray_Exp retval3 = S_SHORTArray_Ret2(); TestHelper.Assert(Equals(InitArray<short>(ARRAY_SIZE), retval3.arr)); C_WORDArray_Exp retval4 = S_WORDArray_Ret2(); TestHelper.Assert(Equals(InitArray<ushort>(ARRAY_SIZE), retval4.arr)); C_LONG64Array_Exp retval5 = S_LONG64Array_Ret2(); TestHelper.Assert(Equals(InitArray<long>(ARRAY_SIZE), retval5.arr)); C_ULONG64Array_Exp retval6 = S_ULONG64Array_Ret2(); TestHelper.Assert(Equals(InitArray<ulong>(ARRAY_SIZE), retval6.arr)); C_DOUBLEArray_Exp retval7 = S_DOUBLEArray_Ret2(); TestHelper.Assert(Equals(InitArray<double>(ARRAY_SIZE), retval7.arr)); C_FLOATArray_Exp retval8 = S_FLOATArray_Ret2(); TestHelper.Assert(Equals(InitArray<float>(ARRAY_SIZE), retval8.arr)); C_BYTEArray_Exp retval9 = S_BYTEArray_Ret2(); TestHelper.Assert(Equals(InitArray<byte>(ARRAY_SIZE), retval9.arr)); C_CHARArray_Exp retval10 = S_CHARArray_Ret2(); TestHelper.Assert(Equals(InitArray<char>(ARRAY_SIZE), retval10.arr)); C_LPSTRArray_Exp retval11 = S_LPSTRArray_Ret2(); TestHelper.Assert(Equals(InitArray<string>(ARRAY_SIZE), retval11.arr)); C_StructArray_Exp retval13 = S_StructArray_Ret2(); TestHelper.Assert(TestStructEquals(InitStructArray(ARRAY_SIZE), retval13.arr)); return true; } static int Main(string[] args) { RunTest1("RunTest1 : Marshal array as field as ByValArray in sequential struct as parameter."); RunTest3("RunTest3 : Marshal array as field as ByValArray in explicit struct as parameter."); RunTest2("RunTest2 : Marshal array as field as ByValArray in sequential class as parameter."); RunTest4("RunTest4 : Marshal array as field as ByValArray in explicit class as parameter."); RunTest5("RunTest5 : Marshal array as field as ByValArray in sequential class as return type."); RunTest6("RunTest6 : Marshal array as field as ByValArray in explicit class as return type."); return 100; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.HDInsight; using Microsoft.Azure.Management.HDInsight.Models; namespace Microsoft.Azure.Management.HDInsight { /// <summary> /// The HDInsight Management Client. /// </summary> public static partial class ClusterOperationsExtensions { /// <summary> /// Begins configuring the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginConfiguringHttpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginConfiguringHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins configuring the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginConfiguringHttpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return operations.BeginConfiguringHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters, CancellationToken.None); } /// <summary> /// Begins configuring the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginConfiguringRdpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginConfiguringRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins configuring the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginConfiguringRdpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return operations.BeginConfiguringRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters, CancellationToken.None); } /// <summary> /// Begins creating a new HDInsight cluster with the specified /// parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The CreateCluster operation response. /// </returns> public static ClusterCreateResponse BeginCreating(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginCreatingAsync(resourceGroupName, clusterName, clusterCreateParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins creating a new HDInsight cluster with the specified /// parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The CreateCluster operation response. /// </returns> public static Task<ClusterCreateResponse> BeginCreatingAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return operations.BeginCreatingAsync(resourceGroupName, clusterName, clusterCreateParameters, CancellationToken.None); } /// <summary> /// Begins deleting the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginDeleting(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginDeletingAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins deleting the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginDeletingAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.BeginDeletingAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Begins executing script actions on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='executeScriptActionParameters'> /// Required. The parameters for executing script actions. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginExecuteScriptActions(this IClusterOperations operations, string resourceGroupName, string clusterName, ExecuteScriptActionParameters executeScriptActionParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginExecuteScriptActionsAsync(resourceGroupName, clusterName, executeScriptActionParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins executing script actions on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='executeScriptActionParameters'> /// Required. The parameters for executing script actions. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginExecuteScriptActionsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ExecuteScriptActionParameters executeScriptActionParameters) { return operations.BeginExecuteScriptActionsAsync(resourceGroupName, clusterName, executeScriptActionParameters, CancellationToken.None); } /// <summary> /// Begins a resize operation on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginResizing(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginResizingAsync(resourceGroupName, clusterName, resizeParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins a resize operation on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginResizingAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return operations.BeginResizingAsync(resourceGroupName, clusterName, resizeParameters, CancellationToken.None); } /// <summary> /// Configures the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static OperationResource ConfigureHttpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ConfigureHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Configures the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static Task<OperationResource> ConfigureHttpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return operations.ConfigureHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters, CancellationToken.None); } /// <summary> /// Configures the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. Use null to turn RDP off. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static OperationResource ConfigureRdpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ConfigureRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Configures the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. Use null to turn RDP off. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static Task<OperationResource> ConfigureRdpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return operations.ConfigureRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters, CancellationToken.None); } /// <summary> /// Creates a new HDInsight cluster with the specified parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse Create(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).CreateAsync(resourceGroupName, clusterName, clusterCreateParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new HDInsight cluster with the specified parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> CreateAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return operations.CreateAsync(resourceGroupName, clusterName, clusterCreateParameters, CancellationToken.None); } /// <summary> /// Deletes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static OperationResource Delete(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).DeleteAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static Task<OperationResource> DeleteAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.DeleteAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Deletes a given persisted script action of the cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='scriptName'> /// Required. The name of the script. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse DeletePersistedScript(this IClusterOperations operations, string resourceGroupName, string clusterName, string scriptName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).DeletePersistedScriptAsync(resourceGroupName, clusterName, scriptName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a given persisted script action of the cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='scriptName'> /// Required. The name of the script. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeletePersistedScriptAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, string scriptName) { return operations.DeletePersistedScriptAsync(resourceGroupName, clusterName, scriptName, CancellationToken.None); } /// <summary> /// Executes script actions on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='executeScriptActionParameters'> /// Required. The parameters for executing script actions. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static OperationResource ExecuteScriptActions(this IClusterOperations operations, string resourceGroupName, string clusterName, ExecuteScriptActionParameters executeScriptActionParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ExecuteScriptActionsAsync(resourceGroupName, clusterName, executeScriptActionParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Executes script actions on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='executeScriptActionParameters'> /// Required. The parameters for executing script actions. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static Task<OperationResource> ExecuteScriptActionsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ExecuteScriptActionParameters executeScriptActionParameters) { return operations.ExecuteScriptActionsAsync(resourceGroupName, clusterName, executeScriptActionParameters, CancellationToken.None); } /// <summary> /// Gets the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse Get(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> GetAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.GetAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Gets the capabilities for the specified location. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='location'> /// Required. The location to get capabilities for. /// </param> /// <returns> /// The Get Capabilities operation response. /// </returns> public static CapabilitiesResponse GetCapabilities(this IClusterOperations operations, string location) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetCapabilitiesAsync(location); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the capabilities for the specified location. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='location'> /// Required. The location to get capabilities for. /// </param> /// <returns> /// The Get Capabilities operation response. /// </returns> public static Task<CapabilitiesResponse> GetCapabilitiesAsync(this IClusterOperations operations, string location) { return operations.GetCapabilitiesAsync(location, CancellationToken.None); } /// <summary> /// Gets the configuration for the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='configurationName'> /// Required. The type name of the hadoop configuration. /// </param> /// <returns> /// The Cluster Configurations operation response. /// </returns> public static ClusterConfigurationsResponse GetClusterConfigurations(this IClusterOperations operations, string resourceGroupName, string clusterName, string configurationName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetClusterConfigurationsAsync(resourceGroupName, clusterName, configurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the configuration for the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='configurationName'> /// Required. The type name of the hadoop configuration. /// </param> /// <returns> /// The Cluster Configurations operation response. /// </returns> public static Task<ClusterConfigurationsResponse> GetClusterConfigurationsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, string configurationName) { return operations.GetClusterConfigurationsAsync(resourceGroupName, clusterName, configurationName, CancellationToken.None); } /// <summary> /// Gets the connectivity settings for the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The payload for a Configure HTTP settings request. /// </returns> public static HttpConnectivitySettings GetConnectivitySettings(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetConnectivitySettingsAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the connectivity settings for the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The payload for a Configure HTTP settings request. /// </returns> public static Task<HttpConnectivitySettings> GetConnectivitySettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.GetConnectivitySettingsAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Gets the status of the Create operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse GetCreateStatus(this IClusterOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetCreateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of the Create operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> GetCreateStatusAsync(this IClusterOperations operations, string operationStatusLink) { return operations.GetCreateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets the status of the Delete operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static OperationResource GetDeleteStatus(this IClusterOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetDeleteStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of the Delete operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static Task<OperationResource> GetDeleteStatusAsync(this IClusterOperations operations, string operationStatusLink) { return operations.GetDeleteStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets the script execution detail for the given script execution id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='scriptExecutionId'> /// Required. The script execution Id /// </param> /// <returns> /// The GetScriptExecutionDetail operation response. /// </returns> public static ClusterRuntimeScriptActionDetailResponse GetScriptExecutionDetail(this IClusterOperations operations, string resourceGroupName, string clusterName, long scriptExecutionId) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetScriptExecutionDetailAsync(resourceGroupName, clusterName, scriptExecutionId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the script execution detail for the given script execution id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='scriptExecutionId'> /// Required. The script execution Id /// </param> /// <returns> /// The GetScriptExecutionDetail operation response. /// </returns> public static Task<ClusterRuntimeScriptActionDetailResponse> GetScriptExecutionDetailAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, long scriptExecutionId) { return operations.GetScriptExecutionDetailAsync(resourceGroupName, clusterName, scriptExecutionId, CancellationToken.None); } /// <summary> /// Lists HDInsight clusters under the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static ClusterListResponse List(this IClusterOperations operations) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists HDInsight clusters under the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static Task<ClusterListResponse> ListAsync(this IClusterOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// List the HDInsight clusters in a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static ClusterListResponse ListByResourceGroup(this IClusterOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ListByResourceGroupAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List the HDInsight clusters in a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static Task<ClusterListResponse> ListByResourceGroupAsync(this IClusterOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Lists all persisted script actions for the given cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// List PersistedScriptActions operations response. /// </returns> public static ClusterListPersistedScriptActionsResponse ListPersistedScripts(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ListPersistedScriptsAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all persisted script actions for the given cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// List PersistedScriptActions operations response. /// </returns> public static Task<ClusterListPersistedScriptActionsResponse> ListPersistedScriptsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.ListPersistedScriptsAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Lists all scripts execution history for the given cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The ListScriptExecutionHistory response. /// </returns> public static ClusterListRuntimeScriptActionDetailResponse ListScriptExecutionHistory(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ListScriptExecutionHistoryAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all scripts execution history for the given cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The ListScriptExecutionHistory response. /// </returns> public static Task<ClusterListRuntimeScriptActionDetailResponse> ListScriptExecutionHistoryAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.ListScriptExecutionHistoryAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Promote ad-hoc script execution to a persisted script. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='scriptExecutionId'> /// Required. The script execution Id /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse PromoteScript(this IClusterOperations operations, string resourceGroupName, string clusterName, long scriptExecutionId) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).PromoteScriptAsync(resourceGroupName, clusterName, scriptExecutionId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Promote ad-hoc script execution to a persisted script. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='scriptExecutionId'> /// Required. The script execution Id /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> PromoteScriptAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, long scriptExecutionId) { return operations.PromoteScriptAsync(resourceGroupName, clusterName, scriptExecutionId, CancellationToken.None); } /// <summary> /// Resizes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static OperationResource Resize(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ResizeAsync(resourceGroupName, clusterName, resizeParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Resizes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The azure async operation response. /// </returns> public static Task<OperationResource> ResizeAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return operations.ResizeAsync(resourceGroupName, clusterName, resizeParameters, CancellationToken.None); } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Microedition.Khronos.Egl.cs // // 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. #pragma warning disable 1717 namespace Javax.Microedition.Khronos.Egl { /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL11Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_CONTEXT_LOST /// </java-name> [Dot42.DexImport("EGL_CONTEXT_LOST", "I", AccessFlags = 25)] public const int EGL_CONTEXT_LOST = 12302; } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537)] public partial interface IEGL11 : global::Javax.Microedition.Khronos.Egl.IEGL10 /* scope: __dot42__ */ { } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL10Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_SUCCESS /// </java-name> [Dot42.DexImport("EGL_SUCCESS", "I", AccessFlags = 25)] public const int EGL_SUCCESS = 12288; /// <java-name> /// EGL_NOT_INITIALIZED /// </java-name> [Dot42.DexImport("EGL_NOT_INITIALIZED", "I", AccessFlags = 25)] public const int EGL_NOT_INITIALIZED = 12289; /// <java-name> /// EGL_BAD_ACCESS /// </java-name> [Dot42.DexImport("EGL_BAD_ACCESS", "I", AccessFlags = 25)] public const int EGL_BAD_ACCESS = 12290; /// <java-name> /// EGL_BAD_ALLOC /// </java-name> [Dot42.DexImport("EGL_BAD_ALLOC", "I", AccessFlags = 25)] public const int EGL_BAD_ALLOC = 12291; /// <java-name> /// EGL_BAD_ATTRIBUTE /// </java-name> [Dot42.DexImport("EGL_BAD_ATTRIBUTE", "I", AccessFlags = 25)] public const int EGL_BAD_ATTRIBUTE = 12292; /// <java-name> /// EGL_BAD_CONFIG /// </java-name> [Dot42.DexImport("EGL_BAD_CONFIG", "I", AccessFlags = 25)] public const int EGL_BAD_CONFIG = 12293; /// <java-name> /// EGL_BAD_CONTEXT /// </java-name> [Dot42.DexImport("EGL_BAD_CONTEXT", "I", AccessFlags = 25)] public const int EGL_BAD_CONTEXT = 12294; /// <java-name> /// EGL_BAD_CURRENT_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_CURRENT_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_CURRENT_SURFACE = 12295; /// <java-name> /// EGL_BAD_DISPLAY /// </java-name> [Dot42.DexImport("EGL_BAD_DISPLAY", "I", AccessFlags = 25)] public const int EGL_BAD_DISPLAY = 12296; /// <java-name> /// EGL_BAD_MATCH /// </java-name> [Dot42.DexImport("EGL_BAD_MATCH", "I", AccessFlags = 25)] public const int EGL_BAD_MATCH = 12297; /// <java-name> /// EGL_BAD_NATIVE_PIXMAP /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_PIXMAP", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_PIXMAP = 12298; /// <java-name> /// EGL_BAD_NATIVE_WINDOW /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_WINDOW", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_WINDOW = 12299; /// <java-name> /// EGL_BAD_PARAMETER /// </java-name> [Dot42.DexImport("EGL_BAD_PARAMETER", "I", AccessFlags = 25)] public const int EGL_BAD_PARAMETER = 12300; /// <java-name> /// EGL_BAD_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_SURFACE = 12301; /// <java-name> /// EGL_BUFFER_SIZE /// </java-name> [Dot42.DexImport("EGL_BUFFER_SIZE", "I", AccessFlags = 25)] public const int EGL_BUFFER_SIZE = 12320; /// <java-name> /// EGL_ALPHA_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_SIZE = 12321; /// <java-name> /// EGL_BLUE_SIZE /// </java-name> [Dot42.DexImport("EGL_BLUE_SIZE", "I", AccessFlags = 25)] public const int EGL_BLUE_SIZE = 12322; /// <java-name> /// EGL_GREEN_SIZE /// </java-name> [Dot42.DexImport("EGL_GREEN_SIZE", "I", AccessFlags = 25)] public const int EGL_GREEN_SIZE = 12323; /// <java-name> /// EGL_RED_SIZE /// </java-name> [Dot42.DexImport("EGL_RED_SIZE", "I", AccessFlags = 25)] public const int EGL_RED_SIZE = 12324; /// <java-name> /// EGL_DEPTH_SIZE /// </java-name> [Dot42.DexImport("EGL_DEPTH_SIZE", "I", AccessFlags = 25)] public const int EGL_DEPTH_SIZE = 12325; /// <java-name> /// EGL_STENCIL_SIZE /// </java-name> [Dot42.DexImport("EGL_STENCIL_SIZE", "I", AccessFlags = 25)] public const int EGL_STENCIL_SIZE = 12326; /// <java-name> /// EGL_CONFIG_CAVEAT /// </java-name> [Dot42.DexImport("EGL_CONFIG_CAVEAT", "I", AccessFlags = 25)] public const int EGL_CONFIG_CAVEAT = 12327; /// <java-name> /// EGL_CONFIG_ID /// </java-name> [Dot42.DexImport("EGL_CONFIG_ID", "I", AccessFlags = 25)] public const int EGL_CONFIG_ID = 12328; /// <java-name> /// EGL_LEVEL /// </java-name> [Dot42.DexImport("EGL_LEVEL", "I", AccessFlags = 25)] public const int EGL_LEVEL = 12329; /// <java-name> /// EGL_MAX_PBUFFER_HEIGHT /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_HEIGHT", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_HEIGHT = 12330; /// <java-name> /// EGL_MAX_PBUFFER_PIXELS /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_PIXELS", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_PIXELS = 12331; /// <java-name> /// EGL_MAX_PBUFFER_WIDTH /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_WIDTH", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_WIDTH = 12332; /// <java-name> /// EGL_NATIVE_RENDERABLE /// </java-name> [Dot42.DexImport("EGL_NATIVE_RENDERABLE", "I", AccessFlags = 25)] public const int EGL_NATIVE_RENDERABLE = 12333; /// <java-name> /// EGL_NATIVE_VISUAL_ID /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_ID", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_ID = 12334; /// <java-name> /// EGL_NATIVE_VISUAL_TYPE /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_TYPE", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_TYPE = 12335; /// <java-name> /// EGL_SAMPLES /// </java-name> [Dot42.DexImport("EGL_SAMPLES", "I", AccessFlags = 25)] public const int EGL_SAMPLES = 12337; /// <java-name> /// EGL_SAMPLE_BUFFERS /// </java-name> [Dot42.DexImport("EGL_SAMPLE_BUFFERS", "I", AccessFlags = 25)] public const int EGL_SAMPLE_BUFFERS = 12338; /// <java-name> /// EGL_SURFACE_TYPE /// </java-name> [Dot42.DexImport("EGL_SURFACE_TYPE", "I", AccessFlags = 25)] public const int EGL_SURFACE_TYPE = 12339; /// <java-name> /// EGL_TRANSPARENT_TYPE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_TYPE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_TYPE = 12340; /// <java-name> /// EGL_TRANSPARENT_BLUE_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_BLUE_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_BLUE_VALUE = 12341; /// <java-name> /// EGL_TRANSPARENT_GREEN_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_GREEN_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_GREEN_VALUE = 12342; /// <java-name> /// EGL_TRANSPARENT_RED_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RED_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RED_VALUE = 12343; /// <java-name> /// EGL_NONE /// </java-name> [Dot42.DexImport("EGL_NONE", "I", AccessFlags = 25)] public const int EGL_NONE = 12344; /// <java-name> /// EGL_LUMINANCE_SIZE /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_SIZE", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_SIZE = 12349; /// <java-name> /// EGL_ALPHA_MASK_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_MASK_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_MASK_SIZE = 12350; /// <java-name> /// EGL_COLOR_BUFFER_TYPE /// </java-name> [Dot42.DexImport("EGL_COLOR_BUFFER_TYPE", "I", AccessFlags = 25)] public const int EGL_COLOR_BUFFER_TYPE = 12351; /// <java-name> /// EGL_RENDERABLE_TYPE /// </java-name> [Dot42.DexImport("EGL_RENDERABLE_TYPE", "I", AccessFlags = 25)] public const int EGL_RENDERABLE_TYPE = 12352; /// <java-name> /// EGL_SLOW_CONFIG /// </java-name> [Dot42.DexImport("EGL_SLOW_CONFIG", "I", AccessFlags = 25)] public const int EGL_SLOW_CONFIG = 12368; /// <java-name> /// EGL_NON_CONFORMANT_CONFIG /// </java-name> [Dot42.DexImport("EGL_NON_CONFORMANT_CONFIG", "I", AccessFlags = 25)] public const int EGL_NON_CONFORMANT_CONFIG = 12369; /// <java-name> /// EGL_TRANSPARENT_RGB /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RGB", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RGB = 12370; /// <java-name> /// EGL_RGB_BUFFER /// </java-name> [Dot42.DexImport("EGL_RGB_BUFFER", "I", AccessFlags = 25)] public const int EGL_RGB_BUFFER = 12430; /// <java-name> /// EGL_LUMINANCE_BUFFER /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_BUFFER", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_BUFFER = 12431; /// <java-name> /// EGL_VENDOR /// </java-name> [Dot42.DexImport("EGL_VENDOR", "I", AccessFlags = 25)] public const int EGL_VENDOR = 12371; /// <java-name> /// EGL_VERSION /// </java-name> [Dot42.DexImport("EGL_VERSION", "I", AccessFlags = 25)] public const int EGL_VERSION = 12372; /// <java-name> /// EGL_EXTENSIONS /// </java-name> [Dot42.DexImport("EGL_EXTENSIONS", "I", AccessFlags = 25)] public const int EGL_EXTENSIONS = 12373; /// <java-name> /// EGL_HEIGHT /// </java-name> [Dot42.DexImport("EGL_HEIGHT", "I", AccessFlags = 25)] public const int EGL_HEIGHT = 12374; /// <java-name> /// EGL_WIDTH /// </java-name> [Dot42.DexImport("EGL_WIDTH", "I", AccessFlags = 25)] public const int EGL_WIDTH = 12375; /// <java-name> /// EGL_LARGEST_PBUFFER /// </java-name> [Dot42.DexImport("EGL_LARGEST_PBUFFER", "I", AccessFlags = 25)] public const int EGL_LARGEST_PBUFFER = 12376; /// <java-name> /// EGL_RENDER_BUFFER /// </java-name> [Dot42.DexImport("EGL_RENDER_BUFFER", "I", AccessFlags = 25)] public const int EGL_RENDER_BUFFER = 12422; /// <java-name> /// EGL_COLORSPACE /// </java-name> [Dot42.DexImport("EGL_COLORSPACE", "I", AccessFlags = 25)] public const int EGL_COLORSPACE = 12423; /// <java-name> /// EGL_ALPHA_FORMAT /// </java-name> [Dot42.DexImport("EGL_ALPHA_FORMAT", "I", AccessFlags = 25)] public const int EGL_ALPHA_FORMAT = 12424; /// <java-name> /// EGL_HORIZONTAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_HORIZONTAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_HORIZONTAL_RESOLUTION = 12432; /// <java-name> /// EGL_VERTICAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_VERTICAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_VERTICAL_RESOLUTION = 12433; /// <java-name> /// EGL_PIXEL_ASPECT_RATIO /// </java-name> [Dot42.DexImport("EGL_PIXEL_ASPECT_RATIO", "I", AccessFlags = 25)] public const int EGL_PIXEL_ASPECT_RATIO = 12434; /// <java-name> /// EGL_SINGLE_BUFFER /// </java-name> [Dot42.DexImport("EGL_SINGLE_BUFFER", "I", AccessFlags = 25)] public const int EGL_SINGLE_BUFFER = 12421; /// <java-name> /// EGL_CORE_NATIVE_ENGINE /// </java-name> [Dot42.DexImport("EGL_CORE_NATIVE_ENGINE", "I", AccessFlags = 25)] public const int EGL_CORE_NATIVE_ENGINE = 12379; /// <java-name> /// EGL_DRAW /// </java-name> [Dot42.DexImport("EGL_DRAW", "I", AccessFlags = 25)] public const int EGL_DRAW = 12377; /// <java-name> /// EGL_READ /// </java-name> [Dot42.DexImport("EGL_READ", "I", AccessFlags = 25)] public const int EGL_READ = 12378; /// <java-name> /// EGL_DONT_CARE /// </java-name> [Dot42.DexImport("EGL_DONT_CARE", "I", AccessFlags = 25)] public const int EGL_DONT_CARE = -1; /// <java-name> /// EGL_PBUFFER_BIT /// </java-name> [Dot42.DexImport("EGL_PBUFFER_BIT", "I", AccessFlags = 25)] public const int EGL_PBUFFER_BIT = 1; /// <java-name> /// EGL_PIXMAP_BIT /// </java-name> [Dot42.DexImport("EGL_PIXMAP_BIT", "I", AccessFlags = 25)] public const int EGL_PIXMAP_BIT = 2; /// <java-name> /// EGL_WINDOW_BIT /// </java-name> [Dot42.DexImport("EGL_WINDOW_BIT", "I", AccessFlags = 25)] public const int EGL_WINDOW_BIT = 4; /// <java-name> /// EGL_DEFAULT_DISPLAY /// </java-name> [Dot42.DexImport("EGL_DEFAULT_DISPLAY", "Ljava/lang/Object;", AccessFlags = 25)] public static readonly object EGL_DEFAULT_DISPLAY; /// <java-name> /// EGL_NO_DISPLAY /// </java-name> [Dot42.DexImport("EGL_NO_DISPLAY", "Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLDisplay EGL_NO_DISPLAY; /// <java-name> /// EGL_NO_CONTEXT /// </java-name> [Dot42.DexImport("EGL_NO_CONTEXT", "Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLContext EGL_NO_CONTEXT; /// <java-name> /// EGL_NO_SURFACE /// </java-name> [Dot42.DexImport("EGL_NO_SURFACE", "Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLSurface EGL_NO_SURFACE; } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537)] public partial interface IEGL10 : global::Javax.Microedition.Khronos.Egl.IEGL /* scope: __dot42__ */ { /// <java-name> /// eglChooseConfig /// </java-name> [Dot42.DexImport("eglChooseConfig", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I[Ljavax/microedition/khronos/egl/EG" + "LConfig;I[I)Z", AccessFlags = 1025)] bool EglChooseConfig(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] attrib_list, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglCopyBuffers /// </java-name> [Dot42.DexImport("eglCopyBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljava/lang/Object;)Z", AccessFlags = 1025)] bool EglCopyBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, object native_pixmap) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateContext /// </java-name> [Dot42.DexImport("eglCreateContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljavax/microedition/khronos/egl/EGLContext;[I)Ljavax/microedition/khronos/e" + "gl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglCreateContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, global::Javax.Microedition.Khronos.Egl.EGLContext share_context, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePbufferSurface /// </java-name> [Dot42.DexImport("eglCreatePbufferSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePbufferSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePixmapSurface /// </java-name> [Dot42.DexImport("eglCreatePixmapSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePixmapSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_pixmap, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateWindowSurface /// </java-name> [Dot42.DexImport("eglCreateWindowSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreateWindowSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_window, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroyContext /// </java-name> [Dot42.DexImport("eglDestroyContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;)Z", AccessFlags = 1025)] bool EglDestroyContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroySurface /// </java-name> [Dot42.DexImport("eglDestroySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglDestroySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigAttrib /// </java-name> [Dot42.DexImport("eglGetConfigAttrib", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigAttrib(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigs /// </java-name> [Dot42.DexImport("eglGetConfigs", "(Ljavax/microedition/khronos/egl/EGLDisplay;[Ljavax/microedition/khronos/egl/EGLC" + "onfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigs(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentContext /// </java-name> [Dot42.DexImport("eglGetCurrentContext", "()Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglGetCurrentContext() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentDisplay /// </java-name> [Dot42.DexImport("eglGetCurrentDisplay", "()Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetCurrentDisplay() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentSurface /// </java-name> [Dot42.DexImport("eglGetCurrentSurface", "(I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglGetCurrentSurface(int readdraw) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetDisplay /// </java-name> [Dot42.DexImport("eglGetDisplay", "(Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetDisplay(object native_display) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetError /// </java-name> [Dot42.DexImport("eglGetError", "()I", AccessFlags = 1025)] int EglGetError() /* MethodBuilder.Create */ ; /// <java-name> /// eglInitialize /// </java-name> [Dot42.DexImport("eglInitialize", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I)Z", AccessFlags = 1025)] bool EglInitialize(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] major_minor) /* MethodBuilder.Create */ ; /// <java-name> /// eglMakeCurrent /// </java-name> [Dot42.DexImport("eglMakeCurrent", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljavax/microedition/khronos/egl/EGLSurface;Ljavax/microedition/khronos/egl" + "/EGLContext;)Z", AccessFlags = 1025)] bool EglMakeCurrent(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface draw, global::Javax.Microedition.Khronos.Egl.EGLSurface read, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryContext /// </java-name> [Dot42.DexImport("eglQueryContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;I[I)Z", AccessFlags = 1025)] bool EglQueryContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryString /// </java-name> [Dot42.DexImport("eglQueryString", "(Ljavax/microedition/khronos/egl/EGLDisplay;I)Ljava/lang/String;", AccessFlags = 1025)] string EglQueryString(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int name) /* MethodBuilder.Create */ ; /// <java-name> /// eglQuerySurface /// </java-name> [Dot42.DexImport("eglQuerySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;I[I)Z", AccessFlags = 1025)] bool EglQuerySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglSwapBuffers /// </java-name> [Dot42.DexImport("eglSwapBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglSwapBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglTerminate /// </java-name> [Dot42.DexImport("eglTerminate", "(Ljavax/microedition/khronos/egl/EGLDisplay;)Z", AccessFlags = 1025)] bool EglTerminate(global::Javax.Microedition.Khronos.Egl.EGLDisplay display) /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitGL /// </java-name> [Dot42.DexImport("eglWaitGL", "()Z", AccessFlags = 1025)] bool EglWaitGL() /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitNative /// </java-name> [Dot42.DexImport("eglWaitNative", "(ILjava/lang/Object;)Z", AccessFlags = 1025)] bool EglWaitNative(int engine, object bindTarget) /* MethodBuilder.Create */ ; } /// <java-name> /// javax/microedition/khronos/egl/EGLDisplay /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLDisplay", AccessFlags = 1057)] public abstract partial class EGLDisplay /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLDisplay() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGLSurface /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLSurface", AccessFlags = 1057)] public abstract partial class EGLSurface /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLSurface() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGLConfig /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLConfig", AccessFlags = 1057)] public abstract partial class EGLConfig /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLConfig() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGL /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL", AccessFlags = 1537)] public partial interface IEGL /* scope: __dot42__ */ { } /// <java-name> /// javax/microedition/khronos/egl/EGLContext /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLContext", AccessFlags = 1057)] public abstract partial class EGLContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLContext() /* MethodBuilder.Create */ { } /// <java-name> /// getEGL /// </java-name> [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] public static global::Javax.Microedition.Khronos.Egl.IEGL GetEGL() /* MethodBuilder.Create */ { return default(global::Javax.Microedition.Khronos.Egl.IEGL); } /// <java-name> /// getGL /// </java-name> [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] public abstract global::Javax.Microedition.Khronos.Opengles.IGL GetGL() /* MethodBuilder.Create */ ; /// <java-name> /// getEGL /// </java-name> public static global::Javax.Microedition.Khronos.Egl.IEGL EGL { [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] get{ return GetEGL(); } } /// <java-name> /// getGL /// </java-name> public global::Javax.Microedition.Khronos.Opengles.IGL GL { [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] get{ return GetGL(); } } } }
using System; using System.Linq; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using System.IO; using Moscrif.IDE.Editors; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; using Moscrif.IDE.Tool; using Moscrif.IDE.Controls; using Moscrif.IDE.Iface.Entities; using System.Threading; using System.Diagnostics; using Moscrif.IDE.Iface; namespace Moscrif.IDE.Workspace { public class Workspace { #region Public Property private string filePath; [XmlIgnore] public string FilePath { get { return filePath; } set { filePath = value; if (!String.IsNullOrEmpty(filePath)) RootDirectory = System.IO.Path.GetDirectoryName(filePath); } } [XmlIgnore] public List<Project> Projects; [XmlIgnore] public string RootDirectory; [XmlIgnore] public Project ActualProject { get; set; } [XmlArray("projects")] [XmlArrayItem("project")] public List<string> ProjectsFile; [XmlArray("opened")] [XmlArrayItem("file")] public List<string> OpenFiles; //public List<string> PublishDevices; [XmlAttribute("fileExplorerPath")] public string FileExplorerPath; [XmlAttribute("vertBodyHeight")] public int VpBodyHeight; [XmlAttribute("horzMiddleBodyHeight")] public int HpBodyMiddleWidth; [XmlAttribute("horzRightBodyWidth")] public int HpBodyRightWidth; [XmlAttribute("vertOutputWidth")] public int HpOutputWidth; [XmlAttribute("name")] public string Name; [XmlAttribute("outputDir")] public string OutputDirectory; [XmlAttribute("tag")] public int Tag; [XmlAttribute("signapp")] public bool SignApp; [XmlAttribute("showLeftPane")] public bool ShowLeftPane = true; [XmlAttribute("showRightPane")] public bool ShowRightPane = true; [XmlAttribute("showBottomPane")] public bool ShowBottomPane = true; [XmlAttribute("selectedProject")] public String ActualProjectPath { get; set; } [XmlAttribute("showalllibs")] public bool ShowAllLibs { get; set; } [XmlAttribute("selectedResolution")] public string ActualResolution { get; set; } [XmlAttribute("selectedDevices")] public int ActualDevice { get; set; } public void SetActualProject(string projectFile) { ActualProject = FindProject(projectFile); if(ActualProject!=null) ActualProjectPath = ActualProject.FilePath; } [XmlIgnore] public string OutputMaskToFullPath{ get{ return ConvertOutputMaskToFullPath(OutputDirectory); } } // nazovprojektu.msp.nazovPc-Username.user private WorkspaceUserFile workspaceUserSetting; [XmlIgnore] public WorkspaceUserFile WorkspaceUserSetting{ get{ if(workspaceUserSetting == null){ if (string.IsNullOrEmpty(FilePath)){ workspaceUserSetting =new WorkspaceUserFile(); return workspaceUserSetting; } string mspPath = System.IO.Path.GetDirectoryName(FilePath); string userName = String.Format("{0}.{1}-{2}.user",Name,Environment.MachineName,Environment.UserName); string userPath = System.IO.Path.Combine(mspPath,userName); if(System.IO.File.Exists(userPath)){ workspaceUserSetting = WorkspaceUserFile.OpenWorkspaceUserFile(userPath); } else { workspaceUserSetting =new WorkspaceUserFile(userPath); } } return workspaceUserSetting; } } public string ConvertOutputMaskToFullPath(string mask){ if(String.IsNullOrEmpty(mask)) return ""; mask = mask.Replace('/',Path.DirectorySeparatorChar); mask = mask.Replace('\\',Path.DirectorySeparatorChar); string path = mask.Replace("$(workspace_dir)", RootDirectory); path = path.Replace("$(workspace_work)", MainClass.Paths.WorkDir); return path; } #endregion //private Tools tools = new Tools(); public Workspace() { FilePath = String.Empty; //System.IO.Path.Combine(tools.ConfingDir, "workspace.wsp"); Projects = new List<Project>(); ProjectsFile = new List<string>(); OpenFiles = new List<string>(); } /* public Workspace(string filePath) { FilePath = filePath; Projects = new List<Project>(); ProjectsFile = new List<string>(); OpenFiles = new List<string>(); }*/ public void SaveWorkspace(List<string> openFile, int vpBodyHeight, int hpBodyMiddleWidth,int hpBodyRightWidth, int hpOutputWidth) { foreach (Project project in Projects) SaveProject(project); HpOutputWidth = hpOutputWidth; VpBodyHeight = vpBodyHeight; HpBodyMiddleWidth = hpBodyMiddleWidth; HpBodyRightWidth = hpBodyRightWidth; OpenFiles = openFile; SaveWorkspace(); } public void SaveWorkspace() { if (String.IsNullOrEmpty(FilePath)) return; XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.NewLineChars = "\n";//Environment.NewLine; xmlSettings.Indent = true; xmlSettings.CloseOutput = true; XmlSerializer x_serial = new XmlSerializer( typeof( Workspace ) ); using (XmlWriter wr = XmlWriter.Create( FilePath, xmlSettings )) { x_serial.Serialize( wr, this ); } XmlSerializer x_serial_WU = new XmlSerializer( typeof( WorkspaceUserFile ) ); using (XmlWriter wr = XmlWriter.Create( this.WorkspaceUserSetting.FilePath, xmlSettings )) { x_serial_WU.Serialize( wr, this.WorkspaceUserSetting ); } /*using (FileStream fs = new FileStream(FilePath, FileMode.Create)) { XmlSerializer serializer = new XmlSerializer(typeof(Workspace)); serializer.Serialize(fs, this); }*/ } public void SaveUserWorkspaceFile(){ if (String.IsNullOrEmpty(FilePath)) return; XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.NewLineChars = "\n";//Environment.NewLine; xmlSettings.Indent = true; xmlSettings.CloseOutput = true; XmlSerializer x_serial_WU = new XmlSerializer( typeof( WorkspaceUserFile ) ); using (XmlWriter wr = XmlWriter.Create( this.WorkspaceUserSetting.FilePath, xmlSettings )) { x_serial_WU.Serialize( wr, this.WorkspaceUserSetting ); } } static void OnExited(object sender, EventArgs e) { //Console.WriteLine("exit "); try{ //System.IO.File.Delete(path); }catch{ } } static internal Workspace CreateWorkspace(string filePath, string workspaceName, string workspaceOutput, string workspaceRoot, bool copyLibs) { Workspace workspace = new Workspace(); workspace.FilePath = filePath; workspace.RootDirectory = workspaceRoot; workspace.OutputDirectory = workspaceOutput; workspace.Name = workspaceName; if (!Directory.Exists(workspace.RootDirectory)){ try { Directory.CreateDirectory(workspace.RootDirectory); }catch(Exception ex){ throw new Exception(MainClass.Languages.Translate("cannot_create_root",workspace.RootDirectory) + "\n"+ ex.Message); /*MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_create_root",workspace.RootDirectory), ex.Message, Gtk.MessageType.Error); md.ShowDialog(); return null;*/ } } if (!Directory.Exists(workspace.OutputMaskToFullPath)){ try { Directory.CreateDirectory(workspace.OutputMaskToFullPath); }catch{ } } //Console.WriteLine("MainClass.Settings.LibDirectory -> {0}",MainClass.Settings.LibDirectory); if (!Directory.Exists(MainClass.Settings.LibDirectory)){ throw new Exception(MainClass.Languages.Translate("invalid_lids_dir",MainClass.Settings.LibDirectory) ); /*MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("invalid_lids_dir",MainClass.Settings.LibDirectory),"", Gtk.MessageType.Error); md.ShowDialog(); return null;*/ } if (copyLibs) MainClass.Tools.CopyDirectory(MainClass.Settings.LibDirectory, workspace.RootDirectory, true, true); else { MainClass.Tools.CreateLinks(MainClass.Settings.LibDirectory, workspace.RootDirectory, true, false); } workspace.SaveWorkspace(); return workspace; } static internal Workspace OpenWorkspace(string filePath){ if (System.IO.File.Exists(filePath)) try { using (FileStream fs = File.OpenRead(filePath)) { XmlSerializer serializer = new XmlSerializer(typeof(Workspace)); Workspace w = (Workspace)serializer.Deserialize(fs); w.FilePath = filePath; return w; } } catch (Exception ex) { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("workspace_is_corrupted"), ex.Message, Gtk.MessageType.Error,null); md.ShowDialog(); return null; } else { //throw new FileNotFoundException(); MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "", MainClass.Languages.Translate("workspace_is_corrupted"), Gtk.MessageType.Error,null); md.ShowDialog(); return null; } } private static string ShellExec(string cmd,string path,string parms,out int exit_code){ System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(path + cmd, parms); psi.RedirectStandardOutput = true; psi.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi); string tool_output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); exit_code = p.ExitCode; return tool_output; } #region Project public string GetFullPath(string path) { if (String.IsNullOrEmpty(path)) return ""; return FileUtility.RelativeToAbsolutePath(RootDirectory, path); } public string GetRelativePath(string path) { if (String.IsNullOrEmpty(path)) return ""; return FileUtility.AbsoluteToRelativePath(RootDirectory, path); } public Project CreateProject(Project prj, AppFile appFile,string skin, string theme,string[] fonts){ string projectLocation = this.RootDirectory; string projectDir = System.IO.Path.GetFileNameWithoutExtension(prj.FilePath); Project p = FindProject(prj.FilePath); if (p == null) { p = new Project(); if (!System.IO.File.Exists(prj.FilePath)) { string projectWorkingDir = System.IO.Path.Combine(projectLocation, projectDir); if (!System.IO.File.Exists(appFile.ApplicationFile)) { try{ appFile.Save(); } catch(Exception ex){ MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file", appFile.ApplicationFile), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); return null; } } string mainFile = System.IO.Path.Combine(projectWorkingDir,"main.ms"); try { Directory.CreateDirectory(projectWorkingDir); using (StreamWriter file = new StreamWriter(mainFile)) { file.Write("// TODO: Add your code here."); file.Close(); file.Dispose(); } //Directory.CreateDirectory(System.IO.Path.Combine(projectWorkingDir, "core")); //Directory.CreateDirectory(System.IO.Path.Combine(projectWorkingDir, "ui")); } catch { } //p = new Project(prj.FilePath); prj.NewSkin=true; //p = new Project(filename); //p.ProjectDir = GetRelativePath(projectWorkingDir); //p.ProjectName = projectName; prj.AppFilePath = GetRelativePath(appFile.ApplicationFile); prj.StartFile = GetRelativePath(mainFile); prj.GenerateDevices(skin,theme,fonts); SaveProject(prj); Projects.Add(prj); ProjectsFile.Add(GetRelativePath(prj.FilePath)); return prj; } else { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_exist",prj.FilePath), "", Gtk.MessageType.Error); md.ShowDialog(); return null; } } else { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_opened",p.ProjectName), null, Gtk.MessageType.Error); md.ShowDialog(); return null; } } public Project CreateProject(string filename, string projectName, string projectLocation, string projectDir, string aplicationFile,string skin, string theme) { Project p = FindProject(filename); if (p == null) { p = new Project(); if (!System.IO.File.Exists(filename)) { string projectWorkingDir = System.IO.Path.Combine(projectLocation, projectDir); if (!System.IO.File.Exists(aplicationFile)) { AppFile appFile = new AppFile(aplicationFile, projectName);//, projectDir); appFile.Uses = "core ui uix uix-skin media sqlite net game2d crypto box2d graphics sensor"; appFile.Main = "main.ms"; appFile.Author = "Generated by Moscrif-Ide"; appFile.Title = projectName; appFile.Copyright = " "; appFile.Version = "1.0"; appFile.Orientation = "portrait"; try{ appFile.Save(); } catch(Exception ex){ throw new Exception(MainClass.Languages.Translate("cannot_save_file", appFile.ApplicationFile)+"\n"+ ex.Message); /*MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file", appFile.ApplicationFile), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); return null;*/ } } string mainFile = System.IO.Path.Combine(projectWorkingDir,"main.ms"); try { Directory.CreateDirectory(projectWorkingDir); using (StreamWriter file = new StreamWriter(mainFile)) { file.Write("// TODO: Add your code here."); file.Close(); file.Dispose(); } //Directory.CreateDirectory(System.IO.Path.Combine(projectWorkingDir, "core")); //Directory.CreateDirectory(System.IO.Path.Combine(projectWorkingDir, "ui")); } catch { } p = new Project(filename); //p.ProjectDir = GetRelativePath(projectWorkingDir); //p.ProjectName = projectName; p.AppFilePath = GetRelativePath(aplicationFile); p.StartFile = GetRelativePath(mainFile); p.NewSkin=true; p.GenerateDevices(skin,theme); SaveProject(p); Projects.Add(p); ProjectsFile.Add(GetRelativePath(filename)); LoggingInfo log = new LoggingInfo(); log.LoggWebThread(LoggingInfo.ActionId.IDENewProject,p.ProjectName); return p; } else { throw new Exception(MainClass.Languages.Translate("project_is_exist",filename)); /*MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_exist",filename), "", Gtk.MessageType.Error); md.ShowDialog(); return null;*/ } } else { throw new Exception(MainClass.Languages.Translate("project_is_opened",p.ProjectName)); /*MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_opened",p.ProjectName), null, Gtk.MessageType.Error); md.ShowDialog(); return null;*/ } } public Project ConvertAppToProject(AppFile aplicationFile) { string mspDir = System.IO.Path.GetDirectoryName(aplicationFile.ApplicationFile); string filename = System.IO.Path.Combine(mspDir, aplicationFile.Name + ".msp"); Project p = FindProject(filename); if (p == null) { p = new Project(); if (!System.IO.File.Exists(filename)) { p = new Project(filename); //p.ProjectDir = GetRelativePath(projectDir); //p.ProjectName = aplicationFile.Name; p.AppFilePath = GetRelativePath(aplicationFile.ApplicationFile); p.NewSkin=true; p.GenerateDevices("",""); SaveProject(p); Projects.Add(p); ProjectsFile.Add(GetRelativePath(p.FilePath)); return p; } else { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_exist",filename), "", Gtk.MessageType.Error); md.ShowDialog(); return null; } } else { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_opened", p.ProjectName), null, Gtk.MessageType.Error); md.ShowDialog(); return null; } } public Project OpenProject(string filename) { return OpenProject(filename,true,false); } public Project OpenProject(string filename,bool showError,bool throwError) { Project p = FindProject(filename); if (p == null) { p = Project.OpenProject(filename,showError,throwError); if (p != null) { Projects.Add(p); ProjectsFile.Add(GetRelativePath(p.FilePath)); return p; } } else { if(showError){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_is_opened", p.ProjectName), null, Gtk.MessageType.Error,null); md.ShowDialog(); } else if (throwError){ throw new Exception(MainClass.Languages.Translate("project_is_opened", p.ProjectName)); } return null; } return null; } public Project CloseProject(string appFile) { Project p = FindProject_byApp(appFile, true); if (p != null) { Projects.Remove(p); ProjectsFile.Remove(GetRelativePath(p.FilePath)); SaveProject(p); return p; } else { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("project_not_exit"), null, Gtk.MessageType.Error); md.ShowDialog(); return null; } } internal Project FindProject(string filename) { return Projects.Find(x => x.FilePath == filename); } internal Project FindProject_byApp(string appname, bool fullpath) { if (fullpath){ //Console.WriteLine("GetRelativePath appname 1->{0}",appname); appname = GetRelativePath(appname); //Console.WriteLine("GetRelativePath appname 2->{0}",appname); } return Projects.Find(x => x.RelativeAppFilePath == appname);//AppFilePath } internal void SaveProject(Project p) { try { /*XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.NewLineChars = "\n";//Environment.NewLine; xmlSettings.Indent = true; xmlSettings.CloseOutput = true; XmlSerializer x_serial = new XmlSerializer( typeof( Project ) ); using (XmlWriter wr = XmlWriter.Create( p.FilePath, xmlSettings )) { x_serial.Serialize( wr, p ); } XmlSerializer x_serial_PU = new XmlSerializer( typeof( ProjectUserFile ) ); using (XmlWriter wr = XmlWriter.Create( p.ProjectUserSetting.FilePath, xmlSettings )) { x_serial_PU.Serialize( wr, p.ProjectUserSetting ); }*/ p.Save(); } catch (Exception ex) { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_saving"), ex.Message, Gtk.MessageType.Error); md.ShowDialog(); } } public bool RenameProject(Project prj, string newName){ string newDir = System.IO.Path.Combine(MainClass.Workspace.RootDirectory,newName); string newApp = System.IO.Path.Combine(MainClass.Workspace.RootDirectory,newName+".app"); string newPrj = System.IO.Path.Combine(MainClass.Workspace.RootDirectory,newName+".msp"); string oldPrjName =prj.ProjectName; if(File.Exists(newApp) || File.Exists(newPrj) || Directory.Exists(newDir)){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_rename_project",prj.ProjectName),MainClass.Languages.Translate("project_exist"), Gtk.MessageType.Error); md.ShowDialog(); return false; } string oldPrjFile =prj.FilePath; System.IO.File.Move(prj.AbsolutAppFilePath, newApp); System.IO.File.Move(prj.FilePath ,newPrj); System.IO.Directory.Move(prj.AbsolutProjectDir,newDir); prj.AppFilePath = GetRelativePath(newApp); prj.FilePath =newPrj; foreach(FileItem fi in prj.FilesProperty){ fi.FilePath = fi.FilePath.Replace("./"+oldPrjName+"/","./"+newName+"/"); fi.FilePath = fi.FilePath.Replace(".\\"+oldPrjName+"\\",".\\"+newName+"\\"); //MainClass.Workspace.GetRelativePath(d.FullName); } SaveProject(prj); ProjectsFile.Remove(GetRelativePath(oldPrjFile)); ProjectsFile.Add(GetRelativePath(prj.FilePath)); Devices.Device dev = prj.DevicesSettings.Find(x=>x.Devicetype == DeviceType.iOS_5_0); if(dev != null){ Devices.PublishProperty pp = dev.PublishPropertisMask.Find(x=>x.PublishName == Project.KEY_BUNDLEIDENTIFIER); if(pp != null) pp.PublishValue.Replace(oldPrjName,newName); } return true; } #endregion #region File/Directory public TypeFile? ToggleExcludeFile(string filename, string appFile) { if (String.IsNullOrEmpty(appFile)) return null; Project prj = FindProject_byApp(appFile, true); if (prj == null) return null; string relativeFile = GetRelativePath(filename); FileItem fi = prj.ToggleExcludeFile(relativeFile); if (fi.IsExcluded) return TypeFile.ExcludetFile; else return TypeFile.SourceFile; /* FileItem fi = prj.ExcludesFiles.Find(x => x.FilePath == relativeFile); if (fi == null) { prj.ExcludesFiles.Add(new FileItem(relativeFile, true)); return TypeFile.ExcludetFile; } else { prj.ExcludesFiles.Remove(fi); return TypeFile.SourceFile; }*/ } public void SetAsStartup(string filename, string appFilePath) { if (String.IsNullOrEmpty(appFilePath)) return; Project prj = FindProject_byApp(appFilePath, true); if (prj == null) return; if (!String.IsNullOrEmpty(filename)) { if (!String.IsNullOrEmpty(prj.StartFile)) { // change old file Gtk.TreeIter tiOld = MainClass.MainWindow.WorkspaceTree.GetStartUpIter(GetFullPath(prj.StartFile)); MainClass.MainWindow.WorkspaceTree.UpdateIter(tiOld, String.Empty, String.Empty, (int)TypeFile.SourceFile); } AppFile appFile = prj.AppFile; appFile.Main = System.IO.Path.GetFileName(filename); try{ appFile.Save(); } catch(Exception ex){ MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file", appFile.ApplicationFile), ex.Message, Gtk.MessageType.Error); ms.ShowDialog(); } //prj.AppFile.Main = System.IO.Path.GetFileName(filename); //prj.AppFile.Save(); } prj.StartFile = GetRelativePath(filename); SaveProject(prj); } public string AddDirectory(string dirPath, string selectedDir, int selectedTyp) { //string filename = System.IO.Path.GetFileName(Filename); string dirName = System.IO.Path.GetFileName(dirPath); string newPath = ""; if (selectedTyp == (int)TypeFile.AppFile) { Project prj = FindProject_byApp(selectedDir, true); if (prj == null) return String.Empty; selectedDir = prj.AbsolutProjectDir; newPath = System.IO.Path.Combine(prj.AbsolutProjectDir, dirName); } else newPath = System.IO.Path.Combine(selectedDir, dirName); if (System.IO.File.Exists(newPath)) newPath = System.IO.Path.Combine(selectedDir, "Copy_" + dirName); try { MainClass.Tools.CopyDirectory(dirPath, newPath, true, true); } catch { return String.Empty; } return newPath; } public string AddTheme(string selectedProj, int selectedTyp) { string themeName = null; if (selectedTyp != (int)TypeFile.AppFile) return null; Project prj = FindProject_byApp(selectedProj, true); if (prj == null) return String.Empty; CreateThemeDialog ctd = new CreateThemeDialog(prj); int result = ctd.Run(); if (result == (int)Gtk.ResponseType.Ok) { themeName = ctd.ThemePath; string skinName = ctd.SkinPath; try { MainClass.Tools.CopyDirectory(skinName, themeName, true, true); } catch { themeName = null; } } ctd.Destroy(); return themeName; } public string AddFile(string filePath, string selectedDir, int selectedTyp) { string filename = System.IO.Path.GetFileName(filePath); string newFile = ""; if (selectedTyp == (int)TypeFile.AppFile) { Project prj = FindProject_byApp(selectedDir, true); if (prj == null) return String.Empty; newFile = System.IO.Path.Combine(prj.AbsolutProjectDir, filename); selectedDir = prj.AbsolutProjectDir; } else newFile = System.IO.Path.Combine(selectedDir, filename); if (System.IO.File.Exists(newFile)) newFile = System.IO.Path.Combine(selectedDir, "Copy_" + filename); try { System.IO.File.Copy(filePath, newFile); } catch { return String.Empty; } return newFile; } public string CreateFile(string filename, string selectedDir, int selectedTyp,string content) { //string filename = System.IO.Path.GetFileName(Filename); string newFile = ""; if (selectedTyp == (int)TypeFile.AppFile) { Project prj = FindProject_byApp(selectedDir, true); if (prj == null) return String.Empty; selectedDir = prj.AbsolutProjectDir; } if(Directory.Exists(selectedDir)) newFile = System.IO.Path.Combine(selectedDir, filename); else return String.Empty; try { FileUtility.CreateFile(newFile,content); //CreateDirectory(newFile); } catch { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_creating_file"), filename, Gtk.MessageType.Error); md.ShowDialog(); return String.Empty; } return newFile; } public string CreateDirectory(string Filename, string selectedDir, int selectedTyp) { string filename = System.IO.Path.GetFileName(Filename); string newFile = ""; if (selectedTyp == (int)TypeFile.AppFile) { Project prj = FindProject_byApp(selectedDir, true); if (prj == null) return String.Empty; newFile = System.IO.Path.Combine(prj.AbsolutProjectDir, filename); selectedDir = prj.AbsolutProjectDir; } else newFile = System.IO.Path.Combine(selectedDir, filename); try { FileUtility.CreateDirectory(newFile); } catch { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_creating_dir"), filename, Gtk.MessageType.Error); md.ShowDialog(); return String.Empty; } return newFile; } /*public void DeleteFile() { string filename = ""; int typ = -1; Gtk.TreeIter ti = new Gtk.TreeIter(); MainClass.MainWindow.WorkspaceTree.GetSelectedFile(out filename, out typ, out ti); if (typ == (int)TypeFile.Directory) { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, string.Format("Are you sure you want to permanently delete folder {0} ?", filename), "", Gtk.MessageType.Question); int result = md.ShowDialog(); if (result != (int)Gtk.ResponseType.Yes) return; if (!System.IO.Directory.Exists(filename)) return; try { System.IO.Directory.Delete(filename, true); } catch { MessageDialogs mdd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Cannot delete File.",filename, Gtk.MessageType.Error); mdd.ShowDialog(); } } else { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, string.Format("Are you sure you want to permanent delete file {0} ?", filename), "", Gtk.MessageType.Question); int result = md.ShowDialog(); if (result != (int)Gtk.ResponseType.Yes) return; if (!System.IO.File.Exists(filename)) return; try { System.IO.File.Delete(filename); } catch { MessageDialogs mdd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Cannot rename File.", filename, Gtk.MessageType.Error); mdd.ShowDialog(); } } if (typ == (int)TypeFile.StartFile) { string appFile = MainClass.MainWindow.WorkspaceTree.GetSelectedProjectApp(); if (String.IsNullOrEmpty(appFile)) return; Project prj = FindProject_byApp(appFile, true); if (prj != null) prj.StartFile = String.Empty; } MainClass.MainWindow.WorkspaceTree.RemoveTree(ti); } */ #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions.Compiler { /// <summary> /// Determines if variables are closed over in nested lambdas and need to /// be hoisted. /// </summary> internal sealed class VariableBinder : ExpressionVisitor { private readonly AnalyzedTree _tree = new AnalyzedTree(); private readonly Stack<CompilerScope> _scopes = new Stack<CompilerScope>(); private readonly Stack<BoundConstants> _constants = new Stack<BoundConstants>(); private bool _inQuote; internal static AnalyzedTree Bind(LambdaExpression lambda) { var binder = new VariableBinder(); binder.Visit(lambda); return binder._tree; } private VariableBinder() { } protected internal override Expression VisitConstant(ConstantExpression node) { // If we're in Quote, we can ignore constants completely if (_inQuote) { return node; } // Constants that can be emitted into IL don't need to be stored on // the delegate if (ILGen.CanEmitConstant(node.Value, node.Type)) { return node; } _constants.Peek().AddReference(node.Value, node.Type); return node; } protected internal override Expression VisitUnary(UnaryExpression node) { if (node.NodeType == ExpressionType.Quote) { bool savedInQuote = _inQuote; _inQuote = true; Visit(node.Operand); _inQuote = savedInQuote; } else { Visit(node.Operand); } return node; } protected internal override Expression VisitLambda<T>(Expression<T> node) { _scopes.Push(_tree.Scopes[node] = new CompilerScope(node, true)); _constants.Push(_tree.Constants[node] = new BoundConstants()); Visit(MergeScopes(node)); _constants.Pop(); _scopes.Pop(); return node; } protected internal override Expression VisitInvocation(InvocationExpression node) { LambdaExpression lambda = node.LambdaOperand; // optimization: inline code for literal lambda's directly if (lambda != null) { // visit the lambda, but treat it like a scope associated with invocation _scopes.Push(_tree.Scopes[node] = new CompilerScope(lambda, false)); Visit(MergeScopes(lambda)); _scopes.Pop(); // visit the invoke's arguments Visit(node.Arguments); return node; } return base.VisitInvocation(node); } protected internal override Expression VisitBlock(BlockExpression node) { if (node.Variables.Count == 0) { Visit(node.Expressions); return node; } _scopes.Push(_tree.Scopes[node] = new CompilerScope(node, false)); Visit(MergeScopes(node)); _scopes.Pop(); return node; } protected override CatchBlock VisitCatchBlock(CatchBlock node) { if (node.Variable == null) { Visit(node.Body); return node; } _scopes.Push(_tree.Scopes[node] = new CompilerScope(node, false)); Visit(node.Body); _scopes.Pop(); return node; } // If the immediate child is another scope, merge it into this one // This is an optimization to save environment allocations and // array accesses. private ReadOnlyCollection<Expression> MergeScopes(Expression node) { ReadOnlyCollection<Expression> body; var lambda = node as LambdaExpression; if (lambda != null) { body = new ReadOnlyCollection<Expression>(new[] { lambda.Body }); } else { body = ((BlockExpression)node).Expressions; } var currentScope = _scopes.Peek(); // A block body is mergeable if the body only contains one single block node containing variables, // and the child block has the same type as the parent block. while (body.Count == 1 && body[0].NodeType == ExpressionType.Block) { var block = (BlockExpression)body[0]; if (block.Variables.Count > 0) { // Make sure none of the variables are shadowed. If any // are, we can't merge it. foreach (var v in block.Variables) { if (currentScope.Definitions.ContainsKey(v)) { return body; } } // Otherwise, merge it if (currentScope.MergedScopes == null) { currentScope.MergedScopes = new Set<object>(ReferenceEqualityComparer<object>.Instance); } currentScope.MergedScopes.Add(block); foreach (var v in block.Variables) { currentScope.Definitions.Add(v, VariableStorageKind.Local); } } node = block; body = block.Expressions; } return body; } protected internal override Expression VisitParameter(ParameterExpression node) { Reference(node, VariableStorageKind.Local); // // Track reference count so we can emit it in a more optimal way if // it is used a lot. // CompilerScope referenceScope = null; foreach (CompilerScope scope in _scopes) { // // There are two times we care about references: // 1. When we enter a lambda, we want to cache frequently // used variables // 2. When we enter a scope with closed-over variables, we // want to cache it immediately when we allocate the // closure slot for it // if (scope.IsMethod || scope.Definitions.ContainsKey(node)) { referenceScope = scope; break; } } Debug.Assert(referenceScope != null); if (referenceScope.ReferenceCount == null) { referenceScope.ReferenceCount = new Dictionary<ParameterExpression, int>(); } Helpers.IncrementCount(node, referenceScope.ReferenceCount); return node; } protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { foreach (var v in node.Variables) { // Force hoisting of these variables Reference(v, VariableStorageKind.Hoisted); } return node; } private void Reference(ParameterExpression node, VariableStorageKind storage) { CompilerScope definition = null; foreach (CompilerScope scope in _scopes) { if (scope.Definitions.ContainsKey(node)) { definition = scope; break; } scope.NeedsClosure = true; if (scope.IsMethod) { storage = VariableStorageKind.Hoisted; } } if (definition == null) { throw Error.UndefinedVariable(node.Name, node.Type, CurrentLambdaName); } if (storage == VariableStorageKind.Hoisted) { if (node.IsByRef) { throw Error.CannotCloseOverByRef(node.Name, CurrentLambdaName); } definition.Definitions[node] = VariableStorageKind.Hoisted; } } private string CurrentLambdaName { get { foreach (var scope in _scopes) { var lambda = scope.Node as LambdaExpression; if (lambda != null) { return lambda.Name; } } throw ContractUtils.Unreachable; } } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Xml.Transform.Sax.cs // // 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. #pragma warning disable 1717 namespace Javax.Xml.Transform.Sax { /// <summary> /// <para>Acts as an holder for SAX-style Source.</para><para>Note that XSLT requires namespace support. Attempting to transform an input source that is not generated with a namespace-aware parser may result in errors. Parsers can be made namespace aware by calling the javax.xml.parsers.SAXParserFactory#setNamespaceAware(boolean awareness) method.</para><para><para> </para><para></para><title>Revision:</title><para>446598 </para>, <title>Date:</title><para>2006-09-15 05:55:40 -0700 (Fri, 15 Sep 2006) </para></para> /// </summary> /// <java-name> /// javax/xml/transform/sax/SAXSource /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/SAXSource", AccessFlags = 33)] public partial class SAXSource : global::Javax.Xml.Transform.ISource /* scope: __dot42__ */ { /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Source input of this type. </para> /// </summary> /// <java-name> /// FEATURE /// </java-name> [Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE = "http://javax.xml.transform.sax.SAXSource/feature"; /// <summary> /// <para>Zero-argument default constructor. If this constructor is used, and no SAX source is set using setInputSource(InputSource inputSource) , then the <code>Transformer</code> will create an empty source org.xml.sax.InputSource using new InputSource().</para><para><para>javax.xml.transform.Transformer::transform(Source xmlSource, Result outputTarget) </para></para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SAXSource() /* MethodBuilder.Create */ { } /// <summary> /// <para>Create a <code>SAXSource</code>, using an org.xml.sax.XMLReader and a SAX InputSource. The javax.xml.transform.Transformer or javax.xml.transform.sax.SAXTransformerFactory will set itself to be the reader's org.xml.sax.ContentHandler, and then will call reader.parse(inputSource).</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Lorg/xml/sax/XMLReader;Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] public SAXSource(global::Org.Xml.Sax.IXMLReader reader, global::Org.Xml.Sax.InputSource inputSource) /* MethodBuilder.Create */ { } /// <summary> /// <para>Create a <code>SAXSource</code>, using a SAX <code>InputSource</code>. The javax.xml.transform.Transformer or javax.xml.transform.sax.SAXTransformerFactory creates a reader via org.xml.sax.helpers.XMLReaderFactory (if setXMLReader is not used), sets itself as the reader's org.xml.sax.ContentHandler, and calls reader.parse(inputSource).</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] public SAXSource(global::Org.Xml.Sax.InputSource inputSource) /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the XMLReader to be used for the Source.</para><para></para> /// </summary> /// <java-name> /// setXMLReader /// </java-name> [Dot42.DexImport("setXMLReader", "(Lorg/xml/sax/XMLReader;)V", AccessFlags = 1)] public virtual void SetXMLReader(global::Org.Xml.Sax.IXMLReader reader) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the XMLReader to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid XMLReader or XMLFilter reference, or null. </para> /// </returns> /// <java-name> /// getXMLReader /// </java-name> [Dot42.DexImport("getXMLReader", "()Lorg/xml/sax/XMLReader;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.IXMLReader GetXMLReader() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.IXMLReader); } /// <summary> /// <para>Set the SAX InputSource to be used for the Source.</para><para></para> /// </summary> /// <java-name> /// setInputSource /// </java-name> [Dot42.DexImport("setInputSource", "(Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] public virtual void SetInputSource(global::Org.Xml.Sax.InputSource inputSource) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the SAX InputSource to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid InputSource reference, or null. </para> /// </returns> /// <java-name> /// getInputSource /// </java-name> [Dot42.DexImport("getInputSource", "()Lorg/xml/sax/InputSource;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.InputSource GetInputSource() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.InputSource); } /// <summary> /// <para>Set the system identifier for this Source. If an input source has already been set, it will set the system ID or that input source, otherwise it will create a new input source.</para><para>The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if no byte stream or character stream is specified).</para><para></para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSystemId(string systemId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the base ID (URI or system ID) from where URIs will be resolved.</para><para></para> /// </summary> /// <returns> /// <para>Base URL for the <code>Source</code>, or <code>null</code>. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSystemId() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Attempt to obtain a SAX InputSource object from a Source object.</para><para></para> /// </summary> /// <returns> /// <para>An InputSource, or null if Source can not be converted. </para> /// </returns> /// <java-name> /// sourceToInputSource /// </java-name> [Dot42.DexImport("sourceToInputSource", "(Ljavax/xml/transform/Source;)Lorg/xml/sax/InputSource;", AccessFlags = 9)] public static global::Org.Xml.Sax.InputSource SourceToInputSource(global::Javax.Xml.Transform.ISource source) /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.InputSource); } /// <summary> /// <para>Get the XMLReader to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid XMLReader or XMLFilter reference, or null. </para> /// </returns> /// <java-name> /// getXMLReader /// </java-name> public global::Org.Xml.Sax.IXMLReader XMLReader { [Dot42.DexImport("getXMLReader", "()Lorg/xml/sax/XMLReader;", AccessFlags = 1)] get{ return GetXMLReader(); } [Dot42.DexImport("setXMLReader", "(Lorg/xml/sax/XMLReader;)V", AccessFlags = 1)] set{ SetXMLReader(value); } } /// <summary> /// <para>Get the SAX InputSource to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid InputSource reference, or null. </para> /// </returns> /// <java-name> /// getInputSource /// </java-name> public global::Org.Xml.Sax.InputSource InputSource { [Dot42.DexImport("getInputSource", "()Lorg/xml/sax/InputSource;", AccessFlags = 1)] get{ return GetInputSource(); } [Dot42.DexImport("setInputSource", "(Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] set{ SetInputSource(value); } } /// <summary> /// <para>Get the base ID (URI or system ID) from where URIs will be resolved.</para><para></para> /// </summary> /// <returns> /// <para>Base URL for the <code>Source</code>, or <code>null</code>. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> public string SystemId { [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSystemId(); } [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSystemId(value); } } } /// <summary> /// <para>A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.</para><para>Note that TemplatesHandler does not need to implement LexicalHandler.</para> /// </summary> /// <java-name> /// javax/xml/transform/sax/TemplatesHandler /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/TemplatesHandler", AccessFlags = 1537)] public partial interface ITemplatesHandler : global::Org.Xml.Sax.IContentHandler /* scope: __dot42__ */ { /// <summary> /// <para>When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.</para><para></para> /// </summary> /// <returns> /// <para>The Templates object that was created during the SAX event process, or null if no Templates object has been created. </para> /// </returns> /// <java-name> /// getTemplates /// </java-name> [Dot42.DexImport("getTemplates", "()Ljavax/xml/transform/Templates;", AccessFlags = 1025)] global::Javax.Xml.Transform.ITemplates GetTemplates() /* MethodBuilder.Create */ ; /// <summary> /// <para>Set the base ID (URI or system ID) for the Templates object created by this builder. This must be set in order to resolve relative URIs in the stylesheet. This must be called before the startDocument event.</para><para></para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetSystemId(string systemID) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the base ID (URI or system ID) from where relative URLs will be resolved. </para> /// </summary> /// <returns> /// <para>The systemID that was set with setSystemId. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1025)] string GetSystemId() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Acts as an holder for a transformation Result.</para><para><para> </para></para> /// </summary> /// <java-name> /// javax/xml/transform/sax/SAXResult /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/SAXResult", AccessFlags = 33)] public partial class SAXResult : global::Javax.Xml.Transform.IResult /* scope: __dot42__ */ { /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Result output of this type. </para> /// </summary> /// <java-name> /// FEATURE /// </java-name> [Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE = "http://javax.xml.transform.sax.SAXResult/feature"; /// <summary> /// <para>Zero-argument default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SAXResult() /* MethodBuilder.Create */ { } /// <summary> /// <para>Create a SAXResult that targets a SAX2 org.xml.sax.ContentHandler.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Lorg/xml/sax/ContentHandler;)V", AccessFlags = 1)] public SAXResult(global::Org.Xml.Sax.IContentHandler handler) /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the target to be a SAX2 org.xml.sax.ContentHandler.</para><para></para> /// </summary> /// <java-name> /// setHandler /// </java-name> [Dot42.DexImport("setHandler", "(Lorg/xml/sax/ContentHandler;)V", AccessFlags = 1)] public virtual void SetHandler(global::Org.Xml.Sax.IContentHandler handler) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the org.xml.sax.ContentHandler that is the Result.</para><para></para> /// </summary> /// <returns> /// <para>The ContentHandler that is to be transformation output. </para> /// </returns> /// <java-name> /// getHandler /// </java-name> [Dot42.DexImport("getHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.IContentHandler GetHandler() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.IContentHandler); } /// <summary> /// <para>Set the SAX2 org.xml.sax.ext.LexicalHandler for the output.</para><para>This is needed to handle XML comments and the like. If the lexical handler is not set, an attempt should be made by the transformer to cast the org.xml.sax.ContentHandler to a <code>LexicalHandler</code>.</para><para></para> /// </summary> /// <java-name> /// setLexicalHandler /// </java-name> [Dot42.DexImport("setLexicalHandler", "(Lorg/xml/sax/ext/LexicalHandler;)V", AccessFlags = 1)] public virtual void SetLexicalHandler(global::Org.Xml.Sax.Ext.ILexicalHandler handler) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get a SAX2 org.xml.sax.ext.LexicalHandler for the output.</para><para></para> /// </summary> /// <returns> /// <para>A <code>LexicalHandler</code>, or null. </para> /// </returns> /// <java-name> /// getLexicalHandler /// </java-name> [Dot42.DexImport("getLexicalHandler", "()Lorg/xml/sax/ext/LexicalHandler;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.Ext.ILexicalHandler GetLexicalHandler() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.Ext.ILexicalHandler); } /// <summary> /// <para>Method setSystemId Set the systemID that may be used in association with the org.xml.sax.ContentHandler.</para><para></para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSystemId(string systemId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the system identifier that was set with setSystemId.</para><para></para> /// </summary> /// <returns> /// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSystemId() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Get the org.xml.sax.ContentHandler that is the Result.</para><para></para> /// </summary> /// <returns> /// <para>The ContentHandler that is to be transformation output. </para> /// </returns> /// <java-name> /// getHandler /// </java-name> public global::Org.Xml.Sax.IContentHandler Handler { [Dot42.DexImport("getHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] get{ return GetHandler(); } [Dot42.DexImport("setHandler", "(Lorg/xml/sax/ContentHandler;)V", AccessFlags = 1)] set{ SetHandler(value); } } /// <summary> /// <para>Get a SAX2 org.xml.sax.ext.LexicalHandler for the output.</para><para></para> /// </summary> /// <returns> /// <para>A <code>LexicalHandler</code>, or null. </para> /// </returns> /// <java-name> /// getLexicalHandler /// </java-name> public global::Org.Xml.Sax.Ext.ILexicalHandler LexicalHandler { [Dot42.DexImport("getLexicalHandler", "()Lorg/xml/sax/ext/LexicalHandler;", AccessFlags = 1)] get{ return GetLexicalHandler(); } [Dot42.DexImport("setLexicalHandler", "(Lorg/xml/sax/ext/LexicalHandler;)V", AccessFlags = 1)] set{ SetLexicalHandler(value); } } /// <summary> /// <para>Get the system identifier that was set with setSystemId.</para><para></para> /// </summary> /// <returns> /// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> public string SystemId { [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSystemId(); } [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSystemId(value); } } } /// <summary> /// <para>This class extends TransformerFactory to provide SAX-specific factory methods. It provides two types of ContentHandlers, one for creating Transformers, the other for creating Templates objects.</para><para>If an application wants to set the ErrorHandler or EntityResolver for an XMLReader used during a transformation, it should use a URIResolver to return the SAXSource which provides (with getXMLReader) a reference to the XMLReader.</para> /// </summary> /// <java-name> /// javax/xml/transform/sax/SAXTransformerFactory /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/SAXTransformerFactory", AccessFlags = 1057)] public abstract partial class SAXTransformerFactory : global::Javax.Xml.Transform.TransformerFactory /* scope: __dot42__ */ { /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the TransformerFactory returned from javax.xml.transform.TransformerFactory#newInstance may be safely cast to a SAXTransformerFactory. </para> /// </summary> /// <java-name> /// FEATURE /// </java-name> [Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE = "http://javax.xml.transform.sax.SAXTransformerFactory/feature"; /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the newXMLFilter(Source src) and newXMLFilter(Templates templates) methods are supported. </para> /// </summary> /// <java-name> /// FEATURE_XMLFILTER /// </java-name> [Dot42.DexImport("FEATURE_XMLFILTER", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE_XMLFILTER = "http://javax.xml.transform.sax.SAXTransformerFactory/feature/xmlfilter"; /// <summary> /// <para>The default constructor is protected on purpose. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal SAXTransformerFactory() /* MethodBuilder.Create */ { } /// <summary> /// <para>Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.</para><para></para> /// </summary> /// <returns> /// <para>TransformerHandler ready to transform SAX events.</para> /// </returns> /// <java-name> /// newTransformerHandler /// </java-name> [Dot42.DexImport("newTransformerHandler", "(Ljavax/xml/transform/Source;)Ljavax/xml/transform/sax/TransformerHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITransformerHandler NewTransformerHandler(global::Javax.Xml.Transform.ISource src) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.</para><para></para> /// </summary> /// <returns> /// <para>TransformerHandler ready to transform SAX events.</para> /// </returns> /// <java-name> /// newTransformerHandler /// </java-name> [Dot42.DexImport("newTransformerHandler", "(Ljavax/xml/transform/Templates;)Ljavax/xml/transform/sax/TransformerHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITransformerHandler NewTransformerHandler(global::Javax.Xml.Transform.ITemplates src) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get a TransformerHandler object that can process SAX ContentHandler events into a Result. The transformation is defined as an identity (or copy) transformation, for example to copy a series of SAX parse events into a DOM tree.</para><para></para> /// </summary> /// <returns> /// <para>A non-null reference to a TransformerHandler, that may be used as a ContentHandler for SAX parse events.</para> /// </returns> /// <java-name> /// newTransformerHandler /// </java-name> [Dot42.DexImport("newTransformerHandler", "()Ljavax/xml/transform/sax/TransformerHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITransformerHandler NewTransformerHandler() /* MethodBuilder.Create */ ; /// <summary> /// <para>Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.</para><para></para> /// </summary> /// <returns> /// <para>A non-null reference to a TransformerHandler, that may be used as a ContentHandler for SAX parse events.</para> /// </returns> /// <java-name> /// newTemplatesHandler /// </java-name> [Dot42.DexImport("newTemplatesHandler", "()Ljavax/xml/transform/sax/TemplatesHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITemplatesHandler NewTemplatesHandler() /* MethodBuilder.Create */ ; /// <summary> /// <para>Create an XMLFilter that uses the given Source as the transformation instructions.</para><para></para> /// </summary> /// <returns> /// <para>An XMLFilter object, or null if this feature is not supported.</para> /// </returns> /// <java-name> /// newXMLFilter /// </java-name> [Dot42.DexImport("newXMLFilter", "(Ljavax/xml/transform/Source;)Lorg/xml/sax/XMLFilter;", AccessFlags = 1025)] public abstract global::Org.Xml.Sax.IXMLFilter NewXMLFilter(global::Javax.Xml.Transform.ISource src) /* MethodBuilder.Create */ ; /// <summary> /// <para>Create an XMLFilter that uses the given Source as the transformation instructions.</para><para></para> /// </summary> /// <returns> /// <para>An XMLFilter object, or null if this feature is not supported.</para> /// </returns> /// <java-name> /// newXMLFilter /// </java-name> [Dot42.DexImport("newXMLFilter", "(Ljavax/xml/transform/Templates;)Lorg/xml/sax/XMLFilter;", AccessFlags = 1025)] public abstract global::Org.Xml.Sax.IXMLFilter NewXMLFilter(global::Javax.Xml.Transform.ITemplates src) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result. </para> /// </summary> /// <java-name> /// javax/xml/transform/sax/TransformerHandler /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/TransformerHandler", AccessFlags = 1537)] public partial interface ITransformerHandler : global::Org.Xml.Sax.IContentHandler, global::Org.Xml.Sax.Ext.ILexicalHandler, global::Org.Xml.Sax.IDTDHandler /* scope: __dot42__ */ { /// <summary> /// <para>Set the <code>Result</code> associated with this <code>TransformerHandler</code> to be used for the transformation.</para><para></para> /// </summary> /// <java-name> /// setResult /// </java-name> [Dot42.DexImport("setResult", "(Ljavax/xml/transform/Result;)V", AccessFlags = 1025)] void SetResult(global::Javax.Xml.Transform.IResult result) /* MethodBuilder.Create */ ; /// <summary> /// <para>Set the base ID (URI or system ID) from where relative URLs will be resolved. </para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetSystemId(string systemID) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the base ID (URI or system ID) from where relative URLs will be resolved. </para> /// </summary> /// <returns> /// <para>The systemID that was set with setSystemId. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1025)] string GetSystemId() /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the <code>Transformer</code> associated with this handler, which is needed in order to set parameters and output properties.</para><para></para> /// </summary> /// <returns> /// <para><code>Transformer</code> associated with this <code>TransformerHandler</code>. </para> /// </returns> /// <java-name> /// getTransformer /// </java-name> [Dot42.DexImport("getTransformer", "()Ljavax/xml/transform/Transformer;", AccessFlags = 1025)] global::Javax.Xml.Transform.Transformer GetTransformer() /* MethodBuilder.Create */ ; } }
using OpenKh.Common; using OpenKh.Imaging; using OpenKh.Kh2; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; namespace OpenKh.Tests.kh2 { public class ModelTextureTests { private const string FileName1 = "kh2/res/model_texture1.tex"; private const string FileName2 = "kh2/res/model_texture2.tex"; [Fact] public void IsValidReturnsTrueWhenStreamContainsValidData() => File.OpenRead(FileName1).Using(stream => { Assert.True(ModelTexture.IsValid(stream)); }); [Theory] [InlineData(FileName1, 1)] [InlineData(FileName2, 3)] public void ReadCorrectAmountOfTextures(string fileName, int expectedCount) => File.OpenRead(fileName).Using(stream => { var modelTexture = ModelTexture.Read(stream); Assert.Equal(expectedCount, modelTexture.Images.Count); }); [Fact] public void CreateImagesWithTheCorrectInformation() => File.OpenRead(FileName2).Using(stream => { var modelTexture = ModelTexture.Read(stream); var image0 = modelTexture.Images[0]; Assert.Equal(256, image0.Size.Width); Assert.Equal(256, image0.Size.Height); Assert.Equal(PixelFormat.Indexed8, image0.PixelFormat); Assert.Equal(256 * 256, image0.GetData().Length); var image1 = modelTexture.Images[1]; Assert.Equal(256, image1.Size.Width); Assert.Equal(256, image1.Size.Height); Assert.Equal(PixelFormat.Indexed8, image1.PixelFormat); Assert.Equal(256 * 256, image1.GetData().Length); var image2 = modelTexture.Images[2]; Assert.Equal(128, image2.Size.Width); Assert.Equal(64, image2.Size.Height); Assert.Equal(PixelFormat.Indexed8, image2.PixelFormat); Assert.Equal(128 * 64, image2.GetData().Length); }); [Theory] [InlineData(FileName1)] [InlineData(FileName2)] public void WriteBackTheSameFile(string fileName) => File.OpenRead(fileName).Using(stream => Helpers.AssertStream(stream, inStream => { var outStream = new MemoryStream(); ModelTexture.Read(inStream).Write(outStream); return outStream; })); [Fact] public void Read4bitPaletteCorrectly() => File.OpenRead(FileName1).Using(stream => { var clut = ModelTexture.Read(stream).Images.First().GetClut(); Assert.Equal(87, clut[0]); Assert.Equal(98, clut[1]); Assert.Equal(106, clut[2]); Assert.Equal(255, clut[3]); Assert.Equal(95, clut[4]); Assert.Equal(105, clut[5]); Assert.Equal(114, clut[6]); Assert.Equal(255, clut[7]); Assert.Equal(108, clut[16]); Assert.Equal(118, clut[17]); Assert.Equal(128, clut[18]); Assert.Equal(255, clut[19]); Assert.Equal(134, clut[32]); Assert.Equal(147, clut[33]); Assert.Equal(158, clut[34]); Assert.Equal(255, clut[35]); }); [Fact] public void Read8bitPaletteCorrectly() => File.OpenRead(FileName2).Using(stream => { var images = ModelTexture.Read(stream).Images; AssertPalette(images, 0, 0, 0, 0, 0); AssertPalette(images, 0, 4, 10, 10, 10); AssertPalette(images, 0, 8, 11, 15, 23); AssertPalette(images, 0, 16, 23, 19, 29); AssertPalette(images, 0, 32, 23, 35, 56); AssertPalette(images, 0, 64, 57, 51, 71); AssertPalette(images, 0, 128, 153, 96, 7); AssertPalette(images, 1, 3, 22, 18, 27); }); [Theory] [InlineData(0, 0, 0, 0x0)] [InlineData(1, 0, 0, 0x4)] [InlineData(2, 0, 0, 0x8)] [InlineData(4, 0, 0, 0x10)] [InlineData(7, 0, 0, 0x1c)] [InlineData(8, 0, 0, 0x100)] [InlineData(16, 0, 0, 0x20)] [InlineData(32, 0, 0, 0x200)] [InlineData(64, 0, 0, 0x400)] [InlineData(0, 4, 0, 0x40)] [InlineData(8, 4, 0, 0x140)] [InlineData(16, 4, 0, 0x60)] [InlineData(32, 4, 0, 0x240)] [InlineData(0, 0x08, 0, 0x1000)] [InlineData(0, 0x08, 1, 0x1020)] [InlineData(0, 0x08, 2, 0x1200)] [InlineData(0, 0x08, 3, 0x1220)] [InlineData(0, 0x08, 4, 0x1400)] [InlineData(0, 0x08, 8, 0x1800)] [InlineData(0, 0x0c, 0, 0x1040)] [InlineData(0, 0x10, 0, 0x80)] [InlineData(0, 0x20, 0, 0x2000)] public void PointerTest(int index, int cbp, int csa, int expectedPointer) { Assert.Equal(expectedPointer / 4, ModelTexture.GetClutPointer(index, cbp, csa)); } private void AssertPalette(List<ModelTexture.Texture> textures, int imageIndex, int colorIndex, byte r, byte g, byte b) { var texture = textures[imageIndex]; var clut = texture.GetClut(); try { Assert.Equal(r, clut[colorIndex * 4 + 0]); Assert.Equal(g, clut[colorIndex * 4 + 1]); Assert.Equal(b, clut[colorIndex * 4 + 2]); } catch { Console.WriteLine($"Error for texture {imageIndex}"); throw; } } [Theory] [InlineData("4bit-128-128")] [InlineData("4bit-256-128")] [InlineData("4bit-256-512")] [InlineData("4bit-512-128")] [InlineData("4bit-512-512")] [InlineData("8bit-128-128")] [InlineData("8bit-128-64")] [InlineData("8bit-256-128")] [InlineData("8bit-256-256")] [InlineData("8bit-512-256")] [InlineData("8bit-512-512")] public void CreateAndRead(string baseName) { var image = File.OpenRead($"kh2/res/image-{baseName}.imd").Using(s => Imgd.Read(s)); { var outStream = new MemoryStream(); { var textures = new ModelTexture(new Imgd[] { image }); textures.Write(outStream); } { outStream.Position = 0; var textures = ModelTexture.Read(outStream); Assert.Single(textures.Images); var converted = textures.Images.Single(); Assert.Equal(image.PixelFormat, converted.PixelFormat); Assert.Equal(image.Size, converted.Size); Assert.Equal(image.GetClut(), converted.GetClut()); Assert.Equal(image.GetData(), converted.GetData()); } } { var outStream = new MemoryStream(); { var textures = new ModelTexture(new Imgd[] { image, image }); textures.Write(outStream); } { outStream.Position = 0; var textures = ModelTexture.Read(outStream); Assert.Equal(2, textures.Images.Count); foreach (var converted in textures.Images) { Assert.Equal(image.PixelFormat, converted.PixelFormat); Assert.Equal(image.Size, converted.Size); Assert.Equal(image.GetClut(), converted.GetClut()); Assert.Equal(image.GetData(), converted.GetData()); } } } { var outStream = new MemoryStream(); { var textures = new ModelTexture(new Imgd[] { image, image, image, image }); textures.Write(outStream); } { outStream.Position = 0; var textures = ModelTexture.Read(outStream); Assert.Equal(4, textures.Images.Count); foreach (var converted in textures.Images) { Assert.Equal(image.PixelFormat, converted.PixelFormat); Assert.Equal(image.Size, converted.Size); Assert.Equal(image.GetClut(), converted.GetClut()); Assert.Equal(image.GetData(), converted.GetData()); } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using NUnit.Framework; using Palaso.UI.WindowsForms.HotSpot; namespace PalasoUIWindowsForms.Tests.Hotspot { [TestFixture] public class HotSpotProviderTests { private HotSpotProvider _hotSpotProvider; [SetUp] public void Setup() { _hotSpotProvider = new HotSpotProvider(); } [TearDown] public void Teardown() { _hotSpotProvider.Dispose(); } [Test] public void Construct() { using (HotSpotProvider hotSpotProvider = new HotSpotProvider()) { Assert.IsNotNull(hotSpotProvider); } } [Test] public void CanExtend_TextBox_True() { using (TextBox textBox = new TextBox()) { Assert.IsTrue(((IExtenderProvider) _hotSpotProvider).CanExtend(textBox)); } } [Test] public void CanExtend_RichTextBox_True() { using (RichTextBox textBox = new RichTextBox()) { Assert.IsTrue(((IExtenderProvider) _hotSpotProvider).CanExtend(textBox)); } } [Test] public void CanExtend_ComboBox_False() { using (ComboBox comboBox = new ComboBox()) { Assert.IsFalse(((IExtenderProvider) _hotSpotProvider).CanExtend(comboBox)); } } [Test] public void CanExtend_Null_False() { Assert.IsFalse(((IExtenderProvider) _hotSpotProvider).CanExtend(null)); } [Test] public void CanExtend_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); using (TextBox textBox = new TextBox()) { Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.CanExtend(textBox)); } } [Test] public void GetEnableHotSpots_Null_Throws() { Assert.Throws<ArgumentNullException>(() => _hotSpotProvider.GetEnableHotSpots(null)); } [Test] public void GetEnableHotSpots_ComboBox_Throws() { using (ComboBox comboBox = new ComboBox()) { Assert.Throws<ArgumentException>(() => _hotSpotProvider.GetEnableHotSpots(comboBox)); } } [Test] public void GetEnableHotSpots_NeverSet_False() { using (TextBox textBox = new TextBox()) { Assert.IsFalse(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void GetEnableHotSpots_SetTrue_True() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); Assert.IsTrue(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void GetEnableHotSpots_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); using (TextBox textBox = new TextBox()) { Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void GetEnableHotSpots_SetFalse_False() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, false); Assert.IsFalse(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void SetEnableHotSpots_NullControl_EmptyString() { Assert.Throws<ArgumentNullException>(() => _hotSpotProvider.SetEnableHotSpots(null, true)); } [Test] public void SetEnableHotSpots_ComboBox_Throws() { using (ComboBox comboBox = new ComboBox()) { Assert.Throws<ArgumentException>(() => _hotSpotProvider.SetEnableHotSpots(comboBox, true)); } } [Test] public void SetEnableHotSpots_SetTwice_GetSecond() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.SetEnableHotSpots(textBox, false); Assert.IsFalse(_hotSpotProvider.GetEnableHotSpots(textBox)); } } [Test] public void SetEnableHotSpots_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); using (TextBox textBox = new TextBox()) { Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.SetEnableHotSpots(textBox, false)); } } [Test] public void Dispose_HasDisposedEventHandler_CallsHandler() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); bool disposedCalled = false; hotSpotProvider.Disposed += delegate { disposedCalled = true; }; Assert.IsFalse(disposedCalled); hotSpotProvider.Dispose(); Assert.IsTrue(disposedCalled); } [Test] public void Dispose_CalledTwice_CallsHandlerOnce() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); int disposedCalledCount = 0; hotSpotProvider.Disposed += delegate { ++disposedCalledCount; }; Assert.AreEqual(0, disposedCalledCount); hotSpotProvider.Dispose(); Assert.AreEqual(1, disposedCalledCount); hotSpotProvider.Dispose(); Assert.AreEqual(1, disposedCalledCount); } [Test] public void GetSite_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); ISite x; Assert.Throws<ObjectDisposedException>(() => x = hotSpotProvider.Site); } [Test] public void SetSite_CalledAfterDisposed_Throws() { HotSpotProvider hotSpotProvider = new HotSpotProvider(); hotSpotProvider.Dispose(); Assert.Throws<ObjectDisposedException>(() => hotSpotProvider.Site = null); } [Test] public void Refresh_HotSpotsAreNotEnabledOnControl_DoNothing() { using (TextBox textBox = new TextBox()) { bool retrieveHotSpotsCalled = false; _hotSpotProvider.RetrieveHotSpots += delegate { retrieveHotSpotsCalled = true; }; Assert.IsFalse(retrieveHotSpotsCalled); _hotSpotProvider.Refresh(textBox); Assert.IsFalse(retrieveHotSpotsCalled); } } [Test] public void Refresh_HotSpotsAreEnabled_TriggersRetrieveHotSpotEvent() { using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); bool retrieveHotSpotsCalled = false; _hotSpotProvider.RetrieveHotSpots += delegate { retrieveHotSpotsCalled = true; }; // reset since installing the handler causes it to fire. retrieveHotSpotsCalled = false; _hotSpotProvider.Refresh(textBox); Assert.IsTrue(retrieveHotSpotsCalled); } } [Test] public void RetrieveHotSpots_AddingAHandler_CausesHotSpotsToBeRetrieved() { bool handlerCalled = false; using (TextBox textBox = new TextBox()) { _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate { handlerCalled = true; }; } Assert.IsTrue(handlerCalled); } [Test] public void RefreshAll_TriggersRetrieveHotSpotEventForAllEnabled() { TextBox textBox1 = new TextBox(); TextBox textBox2 = new TextBox(); TextBox textBox3 = new TextBox(); TextBox textBox4 = new TextBox(); _hotSpotProvider.SetEnableHotSpots(textBox1, true); _hotSpotProvider.SetEnableHotSpots(textBox2, false); _hotSpotProvider.SetEnableHotSpots(textBox3, false); _hotSpotProvider.SetEnableHotSpots(textBox4, true); bool retrieveHotSpots1Called = false; bool retrieveHotSpots2Called = false; bool retrieveHotSpots3Called = false; bool retrieveHotSpots4Called = false; _hotSpotProvider.RetrieveHotSpots += delegate(object sender, RetrieveHotSpotsEventArgs e) { if (e.Control == textBox1) { retrieveHotSpots1Called = true; return; } if (e.Control == textBox2) { retrieveHotSpots2Called = true; return; } if (e.Control == textBox3) { retrieveHotSpots3Called = true; return; } if (e.Control == textBox4) { retrieveHotSpots4Called = true; return; } throw new InvalidOperationException(); }; // reset since installing the handler causes it to fire. retrieveHotSpots1Called = false; retrieveHotSpots2Called = false; retrieveHotSpots3Called = false; retrieveHotSpots4Called = false; // force hotSpotProvider to retrieve HotSpots _hotSpotProvider.RefreshAll(); Assert.IsTrue(retrieveHotSpots1Called); Assert.IsFalse(retrieveHotSpots2Called); Assert.IsFalse(retrieveHotSpots3Called); Assert.IsTrue(retrieveHotSpots4Called); textBox1.Dispose(); textBox2.Dispose(); textBox3.Dispose(); textBox4.Dispose(); } [Test] [NUnit.Framework.Category("KnownMonoIssue")] // review: WS-???? public void RetrieveHotSpots_GiveSomeHotspots_HotSpotsVisible() { using (TextBox textBox = new TextBox()) { textBox.Text = "Now is the time for all good men to come to the aid..."; _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate(object sender, RetrieveHotSpotsEventArgs e) { e.AddHotSpot(new HotSpot(e.Control, 7, 3)); e.AddHotSpot(new HotSpot(e.Control, 16, 3)); }; Point position = textBox.GetPositionFromCharIndex(8); List<HotSpot> hotSpots = new List<HotSpot>( _hotSpotProvider.GetHotSpotsFromPosition(textBox, position)); Assert.AreEqual(1, hotSpots.Count); Assert.AreEqual(7, hotSpots[0].Offset); Assert.AreEqual("the", hotSpots[0].Text); position = textBox.GetPositionFromCharIndex(16); hotSpots = new List<HotSpot>( _hotSpotProvider.GetHotSpotsFromPosition(textBox, position)); Assert.AreEqual(1, hotSpots.Count); Assert.AreEqual(16, hotSpots[0].Offset); Assert.AreEqual("for", hotSpots[0].Text); } } [Test] public void RetrieveHotSpots_NoHotspotsReturned_NoHotSpotsVisible() { using (TextBox textBox = new TextBox()) { textBox.Text = "Now is the time."; _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate { // give back no hot spots }; //if we scan the entire text for hot spots we shouldn't find any for (int i = 0;i != textBox.Text.Length;++i) { Point position = textBox.GetPositionFromCharIndex(i); List<HotSpot> hotSpots = new List<HotSpot>( _hotSpotProvider.GetHotSpotsFromPosition(textBox, position)); Assert.AreEqual(0, hotSpots.Count); } } } [Test] public void RetrieveHotSpots_CalledWhenTheTextChanges() { using (TextBox textBox = new TextBox()) { bool hotSpotsWereRetrieved; textBox.Text = "Now is the time."; _hotSpotProvider.SetEnableHotSpots(textBox, true); _hotSpotProvider.RetrieveHotSpots += delegate { hotSpotsWereRetrieved = true; }; hotSpotsWereRetrieved = false; textBox.Text = "For all Good Men..."; Assert.IsTrue(hotSpotsWereRetrieved); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim 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.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenSim.Framework; using OpenMetaverse; using System; using OpenSim.Region.Interfaces; namespace OpenSim.Region.Physics.Manager { public delegate void physicsCrash(); public abstract class PhysicsScene { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); [Flags] public enum AddPrimShapeFlags { None = 0, Physical = (1 << 0), FromSceneStartup = (1 << 1), Phantom = (1 << 2), WantsCollisionNotification = (1 << 3), StartSuspended = (1 << 4), Interpolate = (1 << 5), FromCrossing = (1 << 6) } public event physicsCrash OnPhysicsCrash; public static PhysicsScene Null { get { return null; } } public abstract float SimulationFPS { get; } public abstract int SimulationFrameTimeAvg { get; } public abstract bool Simulating { get; set; } public abstract IMesher Mesher { get; } public virtual void TriggerPhysicsBasedRestart() { physicsCrash handler = OnPhysicsCrash; if (handler != null) { OnPhysicsCrash(); } } public abstract void Initialize(IMesher meshmerizer, IConfigSource config, UUID regionId); public abstract PhysicsActor AddAvatar(string avName, OpenMetaverse.Vector3 position, OpenMetaverse.Quaternion rotation, OpenMetaverse.Vector3 size, bool isFlying, OpenMetaverse.Vector3 initialVelocity); public abstract void RemoveAvatar(PhysicsActor actor); public abstract void RemovePrim(PhysicsActor prim); public abstract PhysicsActor AddPrimShape(string primName, AddPrimShapeFlags flags, BulkShapeData shapeData); /// <summary> /// Adds all the shapes for a prim and its children /// </summary> /// <param name="parent"></param> /// <param name="primName"></param> /// <param name="shapeData"></param> /// <param name="flags"></param> /// <returns></returns> public abstract void BulkAddPrimShapes(ICollection<BulkShapeData> shapeData, AddPrimShapeFlags flags); public virtual bool SupportsNINJAJoints { get { return false; } } public virtual PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, OpenMetaverse.Vector3 position, Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation) { return null; } public virtual void RequestJointDeletion(string objectNameInScene) { return; } public virtual void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor) { return; } public virtual void DumpJointInfo() { return; } public event JointMoved OnJointMoved; protected virtual void DoJointMoved(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointMoved != null) { OnJointMoved(joint); } } public event JointDeactivated OnJointDeactivated; protected virtual void DoJointDeactivated(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointDeactivated != null) { OnJointDeactivated(joint); } } public event JointErrorMessage OnJointErrorMessage; protected virtual void DoJointErrorMessage(PhysicsJoint joint, string message) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointErrorMessage != null) { OnJointErrorMessage(joint, message); } } public virtual OpenMetaverse.Vector3 GetJointAnchor(PhysicsJoint joint) { return OpenMetaverse.Vector3.Zero; } public virtual OpenMetaverse.Vector3 GetJointAxis(PhysicsJoint joint) { return OpenMetaverse.Vector3.Zero; } //public abstract ITerrainChannel public abstract void AddPhysicsActorTaint(PhysicsActor prim); public abstract void AddPhysicsActorTaint(PhysicsActor prim, TaintType taint); public abstract float Simulate(float timeStep, uint ticksSinceLastSimulate, uint frameNum, bool dilated); public abstract void GetResults(); public abstract void SetTerrain(float[] heightMap, int revision); public virtual void SetStartupTerrain(float[] heightMap, int revision) { } public abstract void SetWaterLevel(float baseheight); public abstract void DeleteTerrain(); public abstract void Dispose(); public abstract Dictionary<uint, float> GetTopColliders(); public abstract bool IsThreaded { get; } public abstract IMaterial FindMaterialImpl(Material materialEnum); public abstract ITerrainChannel TerrainChannel { get; set; } public abstract RegionSettings RegionSettings { get; set; } public abstract void DumpCollisionInfo(); public abstract void SendPhysicsWindData(OpenMetaverse.Vector2[] sea, OpenMetaverse.Vector2[] gnd, OpenMetaverse.Vector2[] air, float[] ranges, float[] maxheights); public abstract void RayCastWorld(OpenMetaverse.Vector3 start, OpenMetaverse.Vector3 direction, float distance, int hitAmounts, Action<List<ContactResult>> result); public abstract List<ContactResult> RayCastWorld(OpenMetaverse.Vector3 start, OpenMetaverse.Vector3 direction, float distance, int hitAmounts); } public struct ContactResult { public PhysicsActor CollisionActor; public Vector3 Normal; public Vector3 Position; public float Distance; public int FaceIndex; } public delegate void JointMoved(PhysicsJoint joint); public delegate void JointDeactivated(PhysicsJoint joint); public delegate void JointErrorMessage(PhysicsJoint joint, string message); // this refers to an "error message due to a problem", not "amount of joint constraint violation" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System.IO; using System; using System.Security; using System.Collections; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Schema; using System.ComponentModel; using System.Globalization; using System.CodeDom.Compiler; using System.Diagnostics; using System.Threading; using System.Collections.Generic; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants; using XmlDeserializationEvents = System.Object; ///<internalonly/> public abstract class XmlSerializationReader : XmlSerializationGeneratedCode { private XmlReader _r; private XmlDocument _d; private XmlDeserializationEvents _events; private bool _soap12; private bool _isReturnValue; private bool _decodeName = true; private string _schemaNsID; private string _schemaNs1999ID; private string _schemaNs2000ID; private string _schemaNonXsdTypesNsID; private string _instanceNsID; private string _instanceNs2000ID; private string _instanceNs1999ID; private string _soapNsID; private string _soap12NsID; private string _schemaID; private string _wsdlNsID; private string _wsdlArrayTypeID; private string _nullID; private string _nilID; private string _typeID; private string _arrayTypeID; private string _itemTypeID; private string _arraySizeID; private string _arrayID; private string _urTypeID; private string _stringID; private string _intID; private string _booleanID; private string _shortID; private string _longID; private string _floatID; private string _doubleID; private string _decimalID; private string _dateTimeID; private string _qnameID; private string _dateID; private string _timeID; private string _hexBinaryID; private string _base64BinaryID; private string _base64ID; private string _unsignedByteID; private string _byteID; private string _unsignedShortID; private string _unsignedIntID; private string _unsignedLongID; private string _oldDecimalID; private string _oldTimeInstantID; private string _anyURIID; private string _durationID; private string _ENTITYID; private string _ENTITIESID; private string _gDayID; private string _gMonthID; private string _gMonthDayID; private string _gYearID; private string _gYearMonthID; private string _IDID; private string _IDREFID; private string _IDREFSID; private string _integerID; private string _languageID; private string _nameID; private string _NCNameID; private string _NMTOKENID; private string _NMTOKENSID; private string _negativeIntegerID; private string _nonPositiveIntegerID; private string _nonNegativeIntegerID; private string _normalizedStringID; private string _NOTATIONID; private string _positiveIntegerID; private string _tokenID; private string _charID; private string _guidID; private string _timeSpanID; protected abstract void InitIDs(); // this method must be called before any generated deserialization methods are called internal void Init(XmlReader r, string encodingStyle) { _r = r; _soap12 = (encodingStyle == Soap12.Encoding); _schemaNsID = r.NameTable.Add(XmlSchema.Namespace); _schemaNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema"); _schemaNs1999ID = r.NameTable.Add("http://www.w3.org/1999/XMLSchema"); _schemaNonXsdTypesNsID = r.NameTable.Add(UrtTypes.Namespace); _instanceNsID = r.NameTable.Add(XmlSchema.InstanceNamespace); _instanceNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema-instance"); _instanceNs1999ID = r.NameTable.Add("http://www.w3.org/1999/XMLSchema-instance"); _soapNsID = r.NameTable.Add(Soap.Encoding); _soap12NsID = r.NameTable.Add(Soap12.Encoding); _schemaID = r.NameTable.Add("schema"); _wsdlNsID = r.NameTable.Add(Wsdl.Namespace); _wsdlArrayTypeID = r.NameTable.Add(Wsdl.ArrayType); _nullID = r.NameTable.Add("null"); _nilID = r.NameTable.Add("nil"); _typeID = r.NameTable.Add("type"); _arrayTypeID = r.NameTable.Add("arrayType"); _itemTypeID = r.NameTable.Add("itemType"); _arraySizeID = r.NameTable.Add("arraySize"); _arrayID = r.NameTable.Add("Array"); _urTypeID = r.NameTable.Add(Soap.UrType); InitIDs(); } // this method must be called before any generated deserialization methods are called internal void Init(XmlReader r, XmlDeserializationEvents events, string encodingStyle, TempAssembly tempAssembly) { _events = events; Init(tempAssembly); Init(r, encodingStyle); } protected bool DecodeName { get { return _decodeName; } set { _decodeName = value; } } protected XmlReader Reader { get { return _r; } } protected XmlDocument Document { get { if (_d == null) { _d = new XmlDocument(_r.NameTable); } return _d; } } protected int ReaderCount { get { return 0; } } private void InitPrimitiveIDs() { if (_tokenID != null) return; object ns = _r.NameTable.Add(XmlSchema.Namespace); object ns2 = _r.NameTable.Add(UrtTypes.Namespace); _stringID = _r.NameTable.Add("string"); _intID = _r.NameTable.Add("int"); _booleanID = _r.NameTable.Add("boolean"); _shortID = _r.NameTable.Add("short"); _longID = _r.NameTable.Add("long"); _floatID = _r.NameTable.Add("float"); _doubleID = _r.NameTable.Add("double"); _decimalID = _r.NameTable.Add("decimal"); _dateTimeID = _r.NameTable.Add("dateTime"); _qnameID = _r.NameTable.Add("QName"); _dateID = _r.NameTable.Add("date"); _timeID = _r.NameTable.Add("time"); _hexBinaryID = _r.NameTable.Add("hexBinary"); _base64BinaryID = _r.NameTable.Add("base64Binary"); _unsignedByteID = _r.NameTable.Add("unsignedByte"); _byteID = _r.NameTable.Add("byte"); _unsignedShortID = _r.NameTable.Add("unsignedShort"); _unsignedIntID = _r.NameTable.Add("unsignedInt"); _unsignedLongID = _r.NameTable.Add("unsignedLong"); _oldDecimalID = _r.NameTable.Add("decimal"); _oldTimeInstantID = _r.NameTable.Add("timeInstant"); _charID = _r.NameTable.Add("char"); _guidID = _r.NameTable.Add("guid"); _timeSpanID = _r.NameTable.Add("TimeSpan"); _base64ID = _r.NameTable.Add("base64"); _anyURIID = _r.NameTable.Add("anyURI"); _durationID = _r.NameTable.Add("duration"); _ENTITYID = _r.NameTable.Add("ENTITY"); _ENTITIESID = _r.NameTable.Add("ENTITIES"); _gDayID = _r.NameTable.Add("gDay"); _gMonthID = _r.NameTable.Add("gMonth"); _gMonthDayID = _r.NameTable.Add("gMonthDay"); _gYearID = _r.NameTable.Add("gYear"); _gYearMonthID = _r.NameTable.Add("gYearMonth"); _IDID = _r.NameTable.Add("ID"); _IDREFID = _r.NameTable.Add("IDREF"); _IDREFSID = _r.NameTable.Add("IDREFS"); _integerID = _r.NameTable.Add("integer"); _languageID = _r.NameTable.Add("language"); _nameID = _r.NameTable.Add("Name"); _NCNameID = _r.NameTable.Add("NCName"); _NMTOKENID = _r.NameTable.Add("NMTOKEN"); _NMTOKENSID = _r.NameTable.Add("NMTOKENS"); _negativeIntegerID = _r.NameTable.Add("negativeInteger"); _nonNegativeIntegerID = _r.NameTable.Add("nonNegativeInteger"); _nonPositiveIntegerID = _r.NameTable.Add("nonPositiveInteger"); _normalizedStringID = _r.NameTable.Add("normalizedString"); _NOTATIONID = _r.NameTable.Add("NOTATION"); _positiveIntegerID = _r.NameTable.Add("positiveInteger"); _tokenID = _r.NameTable.Add("token"); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected XmlQualifiedName GetXsiType() { string type = _r.GetAttribute(_typeID, _instanceNsID); if (type == null) { type = _r.GetAttribute(_typeID, _instanceNs2000ID); if (type == null) { type = _r.GetAttribute(_typeID, _instanceNs1999ID); if (type == null) return null; } } return ToXmlQualifiedName(type, false); } private bool IsPrimitiveNamespace(string ns) { return (object)ns == (object)_schemaNsID || (object)ns == (object)_schemaNonXsdTypesNsID || (object)ns == (object)_soapNsID || (object)ns == (object)_soap12NsID || (object)ns == (object)_schemaNs2000ID || (object)ns == (object)_schemaNs1999ID; } private string ReadStringValue() { if (_r.IsEmptyElement) { _r.Skip(); return string.Empty; } _r.ReadStartElement(); string retVal = _r.ReadString(); ReadEndElement(); return retVal; } private XmlQualifiedName ReadXmlQualifiedName(bool collapseWhitespace = false) { string s; bool isEmpty = false; if (_r.IsEmptyElement) { s = string.Empty; isEmpty = true; } else { _r.ReadStartElement(); s = _r.ReadString(); } if (collapseWhitespace) { s = CollapseWhitespace(s); } XmlQualifiedName retVal = ToXmlQualifiedName(s); if (isEmpty) _r.Skip(); else ReadEndElement(); return retVal; } private byte[] ReadByteArray(bool isBase64) { var list = new List<byte[]>(); const int MAX_ALLOC_SIZE = 64 * 1024; int currentSize = 1024; byte[] buffer; int bytes = -1; int offset = 0; int total = 0; buffer = new byte[currentSize]; list.Add(buffer); while (bytes != 0) { if (offset == buffer.Length) { currentSize = Math.Min(currentSize * 2, MAX_ALLOC_SIZE); buffer = new byte[currentSize]; offset = 0; list.Add(buffer); } if (isBase64) { bytes = _r.ReadElementContentAsBase64(buffer, offset, buffer.Length - offset); } else { bytes = _r.ReadElementContentAsBinHex(buffer, offset, buffer.Length - offset); } offset += bytes; total += bytes; } byte[] result = new byte[total]; offset = 0; foreach (byte[] block in list) { currentSize = Math.Min(block.Length, total); if (currentSize > 0) { Buffer.BlockCopy(block, 0, result, offset, currentSize); offset += currentSize; total -= currentSize; } } list.Clear(); return result; } protected object ReadTypedPrimitive(XmlQualifiedName type) { return ReadTypedPrimitive(type, false); } private object ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) { InitPrimitiveIDs(); object value = null; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) return ReadXmlNodes(elementCanBeType); if ((object)type.Namespace == (object)_schemaNsID || (object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID) { if ((object)type.Name == (object)_stringID || (object)type.Name == (object)_normalizedStringID) value = ReadStringValue(); else if ((object)type.Name == (object)_anyURIID || (object)type.Name == (object)_durationID || (object)type.Name == (object)_ENTITYID || (object)type.Name == (object)_ENTITIESID || (object)type.Name == (object)_gDayID || (object)type.Name == (object)_gMonthID || (object)type.Name == (object)_gMonthDayID || (object)type.Name == (object)_gYearID || (object)type.Name == (object)_gYearMonthID || (object)type.Name == (object)_IDID || (object)type.Name == (object)_IDREFID || (object)type.Name == (object)_IDREFSID || (object)type.Name == (object)_integerID || (object)type.Name == (object)_languageID || (object)type.Name == (object)_nameID || (object)type.Name == (object)_NCNameID || (object)type.Name == (object)_NMTOKENID || (object)type.Name == (object)_NMTOKENSID || (object)type.Name == (object)_negativeIntegerID || (object)type.Name == (object)_nonPositiveIntegerID || (object)type.Name == (object)_nonNegativeIntegerID || (object)type.Name == (object)_NOTATIONID || (object)type.Name == (object)_positiveIntegerID || (object)type.Name == (object)_tokenID) value = CollapseWhitespace(ReadStringValue()); else if ((object)type.Name == (object)_intID) value = XmlConvert.ToInt32(ReadStringValue()); else if ((object)type.Name == (object)_booleanID) value = XmlConvert.ToBoolean(ReadStringValue()); else if ((object)type.Name == (object)_shortID) value = XmlConvert.ToInt16(ReadStringValue()); else if ((object)type.Name == (object)_longID) value = XmlConvert.ToInt64(ReadStringValue()); else if ((object)type.Name == (object)_floatID) value = XmlConvert.ToSingle(ReadStringValue()); else if ((object)type.Name == (object)_doubleID) value = XmlConvert.ToDouble(ReadStringValue()); else if ((object)type.Name == (object)_decimalID) value = XmlConvert.ToDecimal(ReadStringValue()); else if ((object)type.Name == (object)_dateTimeID) value = ToDateTime(ReadStringValue()); else if ((object)type.Name == (object)_qnameID) value = ReadXmlQualifiedName(); else if ((object)type.Name == (object)_dateID) value = ToDate(ReadStringValue()); else if ((object)type.Name == (object)_timeID) value = ToTime(ReadStringValue()); else if ((object)type.Name == (object)_unsignedByteID) value = XmlConvert.ToByte(ReadStringValue()); else if ((object)type.Name == (object)_byteID) value = XmlConvert.ToSByte(ReadStringValue()); else if ((object)type.Name == (object)_unsignedShortID) value = XmlConvert.ToUInt16(ReadStringValue()); else if ((object)type.Name == (object)_unsignedIntID) value = XmlConvert.ToUInt32(ReadStringValue()); else if ((object)type.Name == (object)_unsignedLongID) value = XmlConvert.ToUInt64(ReadStringValue()); else if ((object)type.Name == (object)_hexBinaryID) value = ToByteArrayHex(false); else if ((object)type.Name == (object)_base64BinaryID) value = ToByteArrayBase64(false); else if ((object)type.Name == (object)_base64ID && ((object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID)) value = ToByteArrayBase64(false); else value = ReadXmlNodes(elementCanBeType); } else if ((object)type.Namespace == (object)_schemaNs2000ID || (object)type.Namespace == (object)_schemaNs1999ID) { if ((object)type.Name == (object)_stringID || (object)type.Name == (object)_normalizedStringID) value = ReadStringValue(); else if ((object)type.Name == (object)_anyURIID || (object)type.Name == (object)_anyURIID || (object)type.Name == (object)_durationID || (object)type.Name == (object)_ENTITYID || (object)type.Name == (object)_ENTITIESID || (object)type.Name == (object)_gDayID || (object)type.Name == (object)_gMonthID || (object)type.Name == (object)_gMonthDayID || (object)type.Name == (object)_gYearID || (object)type.Name == (object)_gYearMonthID || (object)type.Name == (object)_IDID || (object)type.Name == (object)_IDREFID || (object)type.Name == (object)_IDREFSID || (object)type.Name == (object)_integerID || (object)type.Name == (object)_languageID || (object)type.Name == (object)_nameID || (object)type.Name == (object)_NCNameID || (object)type.Name == (object)_NMTOKENID || (object)type.Name == (object)_NMTOKENSID || (object)type.Name == (object)_negativeIntegerID || (object)type.Name == (object)_nonPositiveIntegerID || (object)type.Name == (object)_nonNegativeIntegerID || (object)type.Name == (object)_NOTATIONID || (object)type.Name == (object)_positiveIntegerID || (object)type.Name == (object)_tokenID) value = CollapseWhitespace(ReadStringValue()); else if ((object)type.Name == (object)_intID) value = XmlConvert.ToInt32(ReadStringValue()); else if ((object)type.Name == (object)_booleanID) value = XmlConvert.ToBoolean(ReadStringValue()); else if ((object)type.Name == (object)_shortID) value = XmlConvert.ToInt16(ReadStringValue()); else if ((object)type.Name == (object)_longID) value = XmlConvert.ToInt64(ReadStringValue()); else if ((object)type.Name == (object)_floatID) value = XmlConvert.ToSingle(ReadStringValue()); else if ((object)type.Name == (object)_doubleID) value = XmlConvert.ToDouble(ReadStringValue()); else if ((object)type.Name == (object)_oldDecimalID) value = XmlConvert.ToDecimal(ReadStringValue()); else if ((object)type.Name == (object)_oldTimeInstantID) value = ToDateTime(ReadStringValue()); else if ((object)type.Name == (object)_qnameID) value = ReadXmlQualifiedName(); else if ((object)type.Name == (object)_dateID) value = ToDate(ReadStringValue()); else if ((object)type.Name == (object)_timeID) value = ToTime(ReadStringValue()); else if ((object)type.Name == (object)_unsignedByteID) value = XmlConvert.ToByte(ReadStringValue()); else if ((object)type.Name == (object)_byteID) value = XmlConvert.ToSByte(ReadStringValue()); else if ((object)type.Name == (object)_unsignedShortID) value = XmlConvert.ToUInt16(ReadStringValue()); else if ((object)type.Name == (object)_unsignedIntID) value = XmlConvert.ToUInt32(ReadStringValue()); else if ((object)type.Name == (object)_unsignedLongID) value = XmlConvert.ToUInt64(ReadStringValue()); else value = ReadXmlNodes(elementCanBeType); } else if ((object)type.Namespace == (object)_schemaNonXsdTypesNsID) { if ((object)type.Name == (object)_charID) value = ToChar(ReadStringValue()); else if ((object)type.Name == (object)_guidID) value = new Guid(CollapseWhitespace(ReadStringValue())); else if ((object)type.Name == (object)_timeSpanID) value = XmlConvert.ToTimeSpan(ReadStringValue()); else value = ReadXmlNodes(elementCanBeType); } else value = ReadXmlNodes(elementCanBeType); return value; } protected object ReadTypedNull(XmlQualifiedName type) { InitPrimitiveIDs(); object value = null; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) { return null; } if ((object)type.Namespace == (object)_schemaNsID || (object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID) { if ((object)type.Name == (object)_stringID || (object)type.Name == (object)_anyURIID || (object)type.Name == (object)_durationID || (object)type.Name == (object)_ENTITYID || (object)type.Name == (object)_ENTITIESID || (object)type.Name == (object)_gDayID || (object)type.Name == (object)_gMonthID || (object)type.Name == (object)_gMonthDayID || (object)type.Name == (object)_gYearID || (object)type.Name == (object)_gYearMonthID || (object)type.Name == (object)_IDID || (object)type.Name == (object)_IDREFID || (object)type.Name == (object)_IDREFSID || (object)type.Name == (object)_integerID || (object)type.Name == (object)_languageID || (object)type.Name == (object)_nameID || (object)type.Name == (object)_NCNameID || (object)type.Name == (object)_NMTOKENID || (object)type.Name == (object)_NMTOKENSID || (object)type.Name == (object)_negativeIntegerID || (object)type.Name == (object)_nonPositiveIntegerID || (object)type.Name == (object)_nonNegativeIntegerID || (object)type.Name == (object)_normalizedStringID || (object)type.Name == (object)_NOTATIONID || (object)type.Name == (object)_positiveIntegerID || (object)type.Name == (object)_tokenID) value = null; else if ((object)type.Name == (object)_intID) { value = default(Nullable<int>); } else if ((object)type.Name == (object)_booleanID) value = default(Nullable<bool>); else if ((object)type.Name == (object)_shortID) value = default(Nullable<Int16>); else if ((object)type.Name == (object)_longID) value = default(Nullable<long>); else if ((object)type.Name == (object)_floatID) value = default(Nullable<float>); else if ((object)type.Name == (object)_doubleID) value = default(Nullable<double>); else if ((object)type.Name == (object)_decimalID) value = default(Nullable<decimal>); else if ((object)type.Name == (object)_dateTimeID) value = default(Nullable<DateTime>); else if ((object)type.Name == (object)_qnameID) value = null; else if ((object)type.Name == (object)_dateID) value = default(Nullable<DateTime>); else if ((object)type.Name == (object)_timeID) value = default(Nullable<DateTime>); else if ((object)type.Name == (object)_unsignedByteID) value = default(Nullable<byte>); else if ((object)type.Name == (object)_byteID) value = default(Nullable<SByte>); else if ((object)type.Name == (object)_unsignedShortID) value = default(Nullable<UInt16>); else if ((object)type.Name == (object)_unsignedIntID) value = default(Nullable<UInt32>); else if ((object)type.Name == (object)_unsignedLongID) value = default(Nullable<UInt64>); else if ((object)type.Name == (object)_hexBinaryID) value = null; else if ((object)type.Name == (object)_base64BinaryID) value = null; else if ((object)type.Name == (object)_base64ID && ((object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID)) value = null; else value = null; } else if ((object)type.Namespace == (object)_schemaNonXsdTypesNsID) { if ((object)type.Name == (object)_charID) value = default(Nullable<char>); else if ((object)type.Name == (object)_guidID) value = default(Nullable<Guid>); else if ((object) type.Name == (object) _timeSpanID) value = default(Nullable<TimeSpan>); else value = null; } else value = null; return value; } protected bool IsXmlnsAttribute(string name) { if (!name.StartsWith("xmlns", StringComparison.Ordinal)) return false; if (name.Length == 5) return true; return name[5] == ':'; } protected void ParseWsdlArrayType(XmlAttribute attr) { if ((object)attr.LocalName == (object)_wsdlArrayTypeID && (object)attr.NamespaceURI == (object)_wsdlNsID) { int colon = attr.Value.LastIndexOf(':'); if (colon < 0) { attr.Value = _r.LookupNamespace("") + ":" + attr.Value; } else { attr.Value = _r.LookupNamespace(attr.Value.Substring(0, colon)) + ":" + attr.Value.Substring(colon + 1); } } return; } protected bool IsReturnValue { // value only valid for soap 1.1 get { return _isReturnValue && !_soap12; } set { _isReturnValue = value; } } protected bool ReadNull() { if (!GetNullAttr()) return false; if (_r.IsEmptyElement) { _r.Skip(); return true; } _r.ReadStartElement(); int whileIterations = 0; int readerCount = ReaderCount; while (_r.NodeType != XmlNodeType.EndElement) { UnknownNode(null); CheckReaderCount(ref whileIterations, ref readerCount); } ReadEndElement(); return true; } protected bool GetNullAttr() { string isNull = _r.GetAttribute(_nilID, _instanceNsID); if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNsID); if (isNull == null) { isNull = _r.GetAttribute(_nullID, _instanceNs2000ID); if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNs1999ID); } if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false; return true; } protected string ReadNullableString() { if (ReadNull()) return null; return _r.ReadElementString(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected XmlQualifiedName ReadNullableQualifiedName() { if (ReadNull()) return null; return ReadElementQualifiedName(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected XmlQualifiedName ReadElementQualifiedName() { if (_r.IsEmptyElement) { XmlQualifiedName empty = new XmlQualifiedName(string.Empty, _r.LookupNamespace("")); _r.Skip(); return empty; } XmlQualifiedName qname = ReadXmlQualifiedName(collapseWhitespace: true); return qname; } protected XmlDocument ReadXmlDocument(bool wrapped) { XmlNode n = ReadXmlNode(wrapped); if (n == null) return null; XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.ImportNode(n, true)); return doc; } protected string CollapseWhitespace(string value) { if (value == null) return null; return value.Trim(); } protected XmlNode ReadXmlNode(bool wrapped) { XmlNode node = null; if (wrapped) { if (ReadNull()) return null; _r.ReadStartElement(); _r.MoveToContent(); if (_r.NodeType != XmlNodeType.EndElement) node = Document.ReadNode(_r); int whileIterations = 0; int readerCount = ReaderCount; while (_r.NodeType != XmlNodeType.EndElement) { UnknownNode(null); CheckReaderCount(ref whileIterations, ref readerCount); } _r.ReadEndElement(); } else { node = Document.ReadNode(_r); } return node; } protected static byte[] ToByteArrayBase64(string value) { return XmlCustomFormatter.ToByteArrayBase64(value); } protected byte[] ToByteArrayBase64(bool isNull) { if (isNull) { return null; } return ReadByteArray(true); //means use Base64 } protected static byte[] ToByteArrayHex(string value) { return XmlCustomFormatter.ToByteArrayHex(value); } protected byte[] ToByteArrayHex(bool isNull) { if (isNull) { return null; } return ReadByteArray(false); //means use BinHex } protected static DateTime ToDateTime(string value) { return XmlCustomFormatter.ToDateTime(value); } protected static DateTime ToDate(string value) { return XmlCustomFormatter.ToDate(value); } protected static DateTime ToTime(string value) { return XmlCustomFormatter.ToTime(value); } protected static char ToChar(string value) { return XmlCustomFormatter.ToChar(value); } protected static long ToEnum(string value, IDictionary h, string typeName) { return XmlCustomFormatter.ToEnum(value, h, typeName, true); } protected static string ToXmlName(string value) { return XmlCustomFormatter.ToXmlName(value); } protected static string ToXmlNCName(string value) { return XmlCustomFormatter.ToXmlNCName(value); } protected static string ToXmlNmToken(string value) { return XmlCustomFormatter.ToXmlNmToken(value); } protected static string ToXmlNmTokens(string value) { return XmlCustomFormatter.ToXmlNmTokens(value); } protected XmlQualifiedName ToXmlQualifiedName(string value) { return ToXmlQualifiedName(value, DecodeName); } internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) { int colon = value == null ? -1 : value.LastIndexOf(':'); string prefix = colon < 0 ? null : value.Substring(0, colon); string localName = value.Substring(colon + 1); if (decodeName) { prefix = XmlConvert.DecodeName(prefix); localName = XmlConvert.DecodeName(localName); } if (prefix == null || prefix.Length == 0) { return new XmlQualifiedName(_r.NameTable.Add(value), _r.LookupNamespace(String.Empty)); } else { string ns = _r.LookupNamespace(prefix); if (ns == null) { // Namespace prefix '{0}' is not defined. throw new InvalidOperationException(SR.Format(SR.XmlUndefinedAlias, prefix)); } return new XmlQualifiedName(_r.NameTable.Add(localName), ns); } } protected void UnknownNode(object o) { UnknownNode(o, null); } protected void UnknownNode(object o, string qnames) { if (_r.NodeType == XmlNodeType.None || _r.NodeType == XmlNodeType.Whitespace) { _r.Read(); return; } if (_r.NodeType == XmlNodeType.EndElement) return; if (_r.NodeType == XmlNodeType.Attribute) { return; } if (_r.NodeType == XmlNodeType.Element) { _r.Skip(); return; } UnknownNode(Document.ReadNode(_r), o, qnames); } private void UnknownNode(XmlNode unknownNode, object o, string qnames) { if (unknownNode == null) return; } private void GetCurrentPosition(out int lineNumber, out int linePosition) { if (Reader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)Reader; lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else lineNumber = linePosition = -1; } private string CurrentTag() { switch (_r.NodeType) { case XmlNodeType.Element: return "<" + _r.LocalName + " xmlns='" + _r.NamespaceURI + "'>"; case XmlNodeType.EndElement: return ">"; case XmlNodeType.Text: return _r.Value; case XmlNodeType.CDATA: return "CDATA"; case XmlNodeType.Comment: return "<--"; case XmlNodeType.ProcessingInstruction: return "<?"; default: return "(unknown)"; } } protected Exception CreateUnknownTypeException(XmlQualifiedName type) { return new InvalidOperationException(SR.Format(SR.XmlUnknownType, type.Name, type.Namespace, CurrentTag())); } protected Exception CreateReadOnlyCollectionException(string name) { return new InvalidOperationException(SR.Format(SR.XmlReadOnlyCollection, name)); } protected Exception CreateAbstractTypeException(string name, string ns) { return new InvalidOperationException(SR.Format(SR.XmlAbstractType, name, ns, CurrentTag())); } protected Exception CreateInaccessibleConstructorException(string typeName) { return new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, typeName)); } protected Exception CreateCtorHasSecurityException(string typeName) { return new InvalidOperationException(SR.Format(SR.XmlConstructorHasSecurityAttributes, typeName)); } protected Exception CreateUnknownNodeException() { return new InvalidOperationException(SR.Format(SR.XmlUnknownNode, CurrentTag())); } protected Exception CreateUnknownConstantException(string value, Type enumType) { return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, enumType.Name)); } protected Exception CreateInvalidCastException(Type type, object value) { return CreateInvalidCastException(type, value, null); } protected Exception CreateInvalidCastException(Type type, object value, string id) { if (value == null) return new InvalidCastException(SR.Format(SR.XmlInvalidNullCast, type.FullName)); else if (id == null) return new InvalidCastException(SR.Format(SR.XmlInvalidCast, value.GetType().FullName, type.FullName)); else return new InvalidCastException(SR.Format(SR.XmlInvalidCastWithId, value.GetType().FullName, type.FullName, id)); } protected Exception CreateBadDerivationException(string xsdDerived, string nsDerived, string xsdBase, string nsBase, string clrDerived, string clrBase) { return new InvalidOperationException(SR.Format(SR.XmlSerializableBadDerivation, xsdDerived, nsDerived, xsdBase, nsBase, clrDerived, clrBase)); } protected Exception CreateMissingIXmlSerializableType(string name, string ns, string clrType) { return new InvalidOperationException(SR.Format(SR.XmlSerializableMissingClrType, name, ns, typeof(XmlIncludeAttribute).Name, clrType)); //XmlSerializableMissingClrType= Type '{0}' from namespace '{1}' doesnot have corresponding IXmlSerializable type. Please consider adding {2} to '{3}'. } protected Array EnsureArrayIndex(Array a, int index, Type elementType) { if (a == null) return Array.CreateInstance(elementType, 32); if (index < a.Length) return a; Array b = Array.CreateInstance(elementType, a.Length * 2); Array.Copy(a, b, index); return b; } protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable) { if (a == null) { if (isNullable) return null; return Array.CreateInstance(elementType, 0); } if (a.Length == length) return a; Array b = Array.CreateInstance(elementType, length); Array.Copy(a, b, length); return b; } // This is copied from Core's XmlReader.ReadString, as it is not exposed in the Contract. protected virtual string ReadString() { if (Reader.ReadState != ReadState.Interactive) { return string.Empty; } Reader.MoveToElement(); if (Reader.NodeType == XmlNodeType.Element) { if (Reader.IsEmptyElement) { return string.Empty; } else if (!Reader.Read()) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } if (Reader.NodeType == XmlNodeType.EndElement) { return string.Empty; } } string result = string.Empty; while (IsTextualNode(Reader.NodeType)) { result += Reader.Value; if (!Reader.Read()) { break; } } return result; } // 0x6018 private static uint s_isTextualNodeBitmap = (1 << (int)XmlNodeType.Text) | (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Whitespace) | (1 << (int)XmlNodeType.SignificantWhitespace); private static bool IsTextualNode(XmlNodeType nodeType) { return 0 != (s_isTextualNodeBitmap & (1 << (int)nodeType)); } protected string ReadString(string value) { return ReadString(value, false); } protected string ReadString(string value, bool trim) { string str = _r.ReadString(); if (str != null && trim) str = str.Trim(); if (value == null || value.Length == 0) return str; return value + str; } protected IXmlSerializable ReadSerializable(IXmlSerializable serializable) { return ReadSerializable(serializable, false); } protected IXmlSerializable ReadSerializable(IXmlSerializable serializable, bool wrappedAny) { string name = null; string ns = null; if (wrappedAny) { name = _r.LocalName; ns = _r.NamespaceURI; _r.Read(); _r.MoveToContent(); } serializable.ReadXml(_r); if (wrappedAny) { while (_r.NodeType == XmlNodeType.Whitespace) _r.Skip(); if (_r.NodeType == XmlNodeType.None) _r.Skip(); if (_r.NodeType == XmlNodeType.EndElement && _r.LocalName == name && _r.NamespaceURI == ns) { Reader.Read(); } } return serializable; } protected abstract void InitCallbacks(); protected void ReadEndElement() { while (_r.NodeType == XmlNodeType.Whitespace) _r.Skip(); if (_r.NodeType == XmlNodeType.None) _r.Skip(); else _r.ReadEndElement(); } private object ReadXmlNodes(bool elementCanBeType) { var xmlNodeList = new List<XmlNode>(); string elemLocalName = Reader.LocalName; string elemNs = Reader.NamespaceURI; string elemName = Reader.Name; string xsiTypeName = null; string xsiTypeNs = null; int skippableNodeCount = 0; int lineNumber = -1, linePosition = -1; XmlNode unknownNode = null; if (Reader.NodeType == XmlNodeType.Attribute) { XmlAttribute attr = Document.CreateAttribute(elemName, elemNs); attr.Value = Reader.Value; unknownNode = attr; } else unknownNode = Document.CreateElement(elemName, elemNs); GetCurrentPosition(out lineNumber, out linePosition); XmlElement unknownElement = unknownNode as XmlElement; while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute(Reader.Name) || (Reader.Name == "id" && (!_soap12 || Reader.NamespaceURI == Soap12.Encoding))) skippableNodeCount++; if ((object)Reader.LocalName == (object)_typeID && ((object)Reader.NamespaceURI == (object)_instanceNsID || (object)Reader.NamespaceURI == (object)_instanceNs2000ID || (object)Reader.NamespaceURI == (object)_instanceNs1999ID ) ) { string value = Reader.Value; int colon = value.LastIndexOf(':'); xsiTypeName = (colon >= 0) ? value.Substring(colon + 1) : value; xsiTypeNs = Reader.LookupNamespace((colon >= 0) ? value.Substring(0, colon) : ""); } XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r); xmlNodeList.Add(xmlAttribute); if (unknownElement != null) unknownElement.SetAttributeNode(xmlAttribute); } // If the node is referenced (or in case of paramStyle = bare) and if xsi:type is not // specified then the element name is used as the type name. Reveal this to the user // by adding an extra attribute node "xsi:type" with value as the element name. if (elementCanBeType && xsiTypeName == null) { xsiTypeName = elemLocalName; xsiTypeNs = elemNs; XmlAttribute xsiTypeAttribute = Document.CreateAttribute(_typeID, _instanceNsID); xsiTypeAttribute.Value = elemName; xmlNodeList.Add(xsiTypeAttribute); } if (xsiTypeName == Soap.UrType && ((object)xsiTypeNs == (object)_schemaNsID || (object)xsiTypeNs == (object)_schemaNs1999ID || (object)xsiTypeNs == (object)_schemaNs2000ID ) ) skippableNodeCount++; Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); } else { Reader.ReadStartElement(); Reader.MoveToContent(); int whileIterations = 0; int readerCount = ReaderCount; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { XmlNode xmlNode = Document.ReadNode(_r); xmlNodeList.Add(xmlNode); if (unknownElement != null) unknownElement.AppendChild(xmlNode); Reader.MoveToContent(); CheckReaderCount(ref whileIterations, ref readerCount); } ReadEndElement(); } if (xmlNodeList.Count <= skippableNodeCount) return new object(); XmlNode[] childNodes = xmlNodeList.ToArray(); UnknownNode(unknownNode, null, null); return childNodes; } protected void CheckReaderCount(ref int whileIterations, ref int readerCount) { } } }
using System; using System.Xml; using System.Reflection; using System.Collections; namespace Platform.Xml.Serialization { /// <summary> /// Describes the types of the items in a list to be serialized. /// </summary> /// <remarks> /// <p> /// You need to mark any IList field or property to be serialized with this attribute /// at least once. The attribute is used to map an element name to the type /// of object contained in the list. /// </p> /// </remarks> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = true)] public class XmlListElementAttribute : XmlElementAttribute { /// <summary> /// /// </summary> public string Alias { get { return this.Name; } set { this.Name = value; } } /// <summary> /// /// </summary> public Type ItemType { get { return this.Type; } set { this.Type = value; } } /// <summary> /// Specifies a list item's type. /// </summary> /// <remarks> /// The type's name will be used as the alias for all elements with the type. /// If the type has been attributed with an XmlElement attribute then the alias /// specified in that attribute will be used. /// </remarks> /// <param name="itemType">The type of element the list can contain.</param> public XmlListElementAttribute(Type itemType) : this(itemType, itemType.Name) { } /// <summary> /// Specifies a list item's type. /// </summary> /// <remarks> /// The supplied alias will be used to map the actual element <c>Type</c> with /// an XML element. /// </remarks> /// <param name="itemType"></param> /// <param name="alias"></param> public XmlListElementAttribute(Type itemType, string alias) : base(alias, itemType) { } } /// <summary> /// /// </summary> public class ListTypeSerializer : TypeSerializer { public override bool MemberBound { get { return true; } } public override Type SupportedType { get { return typeof(IList); } } private IDictionary m_TypeToItemMap; private IDictionary m_AliasToItemMap; private Type m_ListType; public class ListItem { public string Alias; public XmlListElementAttribute Attribute; public TypeSerializer Serializer; } public ListTypeSerializer(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options) { m_TypeToItemMap = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); m_AliasToItemMap = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); Scan(memberInfo, cache, options); } /// <summary> /// /// </summary> /// <param name="memberInfo"></param> /// <param name="cache"></param> /// <param name="options"></param> private void Scan(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options) { IList attributes; SerializationMemberInfo smi; XmlSerializationAttribute[] attribs; attributes = new ArrayList(10); // Get the ElementType attributes specified on the type itself as long // as we're not the type itself! if (memberInfo.MemberInfo != memberInfo.LogicalType) { smi = new SerializationMemberInfo(memberInfo.LogicalType, options, cache); attribs = smi.GetApplicableAttributes(typeof(XmlListElementAttribute)); foreach (Attribute a in attribs) { attributes.Add(a); } } // Get the ElementType attributes specified on the member. attribs = memberInfo.GetApplicableAttributes(typeof(XmlListElementAttribute)); foreach (Attribute a in attribs) { attributes.Add(a); } foreach (XmlListElementAttribute attribute in attributes) { SerializationMemberInfo smi2; ListItem listItem = new ListItem(); smi2 = new SerializationMemberInfo(attribute.ItemType, options, cache); if (attribute.Alias == null) { attribute.Alias = smi2.SerializedName; } listItem.Attribute = attribute; listItem.Alias = attribute.Alias; // Check if a specific type of serializer is specified. if (attribute.SerializerType == null) { // Figure out the serializer based on the type of the element. listItem.Serializer = cache.GetTypeSerializerBySupportedType(attribute.ItemType, smi2); } else { // Get the type of serializer they specify. listItem.Serializer = cache.GetTypeSerializerBySerializerType(attribute.SerializerType, smi2); } m_TypeToItemMap[attribute.ItemType] = listItem; m_AliasToItemMap[attribute.Alias] = listItem; } if (m_TypeToItemMap.Count == 0) { if (memberInfo.LogicalType.IsArray) { ListItem listItem; Type elementType; listItem = new ListItem(); elementType = memberInfo.LogicalType.GetElementType(); listItem.Alias = elementType.Name; listItem.Serializer = cache.GetTypeSerializerBySupportedType(elementType, new SerializationMemberInfo(elementType, options, cache)); m_TypeToItemMap[elementType] = listItem; m_AliasToItemMap[listItem.Alias] = listItem; } } if (m_TypeToItemMap.Count == 0) { throw new InvalidOperationException("Must specify at least one XmlListElementype."); } m_ListType = memberInfo.LogicalType; if (m_ListType.IsAbstract) { m_ListType = typeof(ArrayList); } } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="writer"></param> /// <param name="state"></param> public override void Serialize(object obj, XmlWriter writer, SerializationState state) { foreach (object item in (IList)obj) { ListItem listItem; listItem = (ListItem)m_TypeToItemMap[item.GetType()]; writer.WriteStartElement(listItem.Alias); if (listItem.Attribute != null && listItem.Attribute.SerializeAsValueNode && listItem.Attribute.ValueNodeAttributeName != null && listItem.Serializer is TypeSerializerWithSimpleTextSupport) { writer.WriteAttributeString(listItem.Attribute.ValueNodeAttributeName, ((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Serialize(item, state)); } else { listItem.Serializer.Serialize(item, writer, state); } writer.WriteEndElement(); } } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="state"></param> /// <returns></returns> public override object Deserialize(XmlReader reader, SerializationState state) { IList retval = null; if (m_ListType.IsArray) { retval = new ArrayList(); } else { retval = (IList)Activator.CreateInstance(m_ListType); state.DeserializationStart(retval); } // Go thru all elements and deserialize each one. if (reader.IsEmptyElement) { reader.ReadStartElement(); } else { reader.ReadStartElement(); for (;;) { ListItem listItem; XmlReaderHelper.ReadUntilAnyTypesReached(reader, XmlReaderHelper.ElementOrEndElement); if (reader.NodeType == XmlNodeType.Element) { listItem = (ListItem)m_AliasToItemMap[reader.Name]; if (listItem.Attribute != null && listItem.Attribute.SerializeAsValueNode && listItem.Attribute.ValueNodeAttributeName != null && listItem.Serializer is TypeSerializerWithSimpleTextSupport) { string s; s = reader.GetAttribute(listItem.Attribute.ValueNodeAttributeName); retval.Add(((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Deserialize(s, state)); XmlReaderHelper.ReadAndConsumeMatchingEndElement(reader); } else { retval.Add(listItem.Serializer.Deserialize(reader, state)); } } else { if (reader.NodeType == XmlNodeType.EndElement) { reader.ReadEndElement(); } break; } } } if (m_ListType.IsArray) { Array array = Array.CreateInstance(m_ListType.GetElementType(), retval.Count); state.DeserializationStart(retval); retval.CopyTo(array, 0); retval = array; } state.DeserializationEnd(retval); return retval; } } }
//----------------------------------------------------------------------- // <copyright file="SplineRouterTests.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; #if GDI_DEBUG_VIEWER using Microsoft.Msagl.GraphViewerGdi; #endif using Microsoft.Msagl.Core; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.Routing; using Microsoft.Msagl.DebugHelpers.Persistence; using Microsoft.Msagl.Layout.Incremental; using Microsoft.Msagl.Layout.Initial; using Microsoft.Msagl.Routing; using Microsoft.Msagl.Routing.Rectilinear; using Microsoft.Msagl.Routing.Spline.Bundling; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Msagl.UnitTests { /// <summary> /// Test class for methods inside EdgeRouterHelper /// </summary> [TestClass] [DeploymentItem(@"Resources\MSAGLGeometryGraphs")] public class SplineRouterTests : MsaglTestBase { [TestMethod] [Description("Verifies that RouteEdges calls progress changed.")] public void RouteEdges_CallsProgress() { //DisplayGeometryGraph.SetShowFunctions(); GeometryGraph graph = GraphGenerator.GenerateTree(10); double ratioComplete = 0; EventHandler<ProgressChangedEventArgs> handler = (s, e) => ratioComplete = e.RatioComplete; SplineRouter splineRouter = null; try { splineRouter = new SplineRouter(graph, 10, 1, Math.PI / 6, null); splineRouter.ProgressChanged += handler; splineRouter.Run(); // DisplayGeometryGraph.ShowGraph(graph); } finally { splineRouter.ProgressChanged -= handler; } Assert.AreEqual(1, ratioComplete, "RouteEdges did not complete"); } [TestMethod] [WorkItem(571435)] [Description("Runs spline routing on a relatively small graph that has caused problems in the past.")] public void RouteEdges_SplineRoutingRegressionBug20110127() { double tightPadding = 1; double loosePadding = 20; double coneAngle = Math.PI / 6; GeometryGraph graph = LoadGraph("RoutingRegressionBug20110127.msagl.geom"); SplineRouter splineRouter = new SplineRouter(graph, tightPadding, loosePadding, coneAngle, null); splineRouter.Run(); //DisplayGeometryGraph.ShowGraph(graph); CheckEdgesForOverlapWithNodes(tightPadding, graph); } [TestMethod] [WorkItem(446802)] [TestCategory("LayoutPerfTest")] [TestCategory("NonRollingBuildTest")] [Timeout(30 * 1000)] [Description("Simple timed test of routing with 20 degree cones over a large graph")] public void RouteEdges_SplineRouting1138Bus() { var g = LoadGraph("GeometryGraph_1138bus.msagl.geom"); var sw = new Stopwatch(); sw.Start(); var loosePadding = SplineRouter.ComputeLooseSplinePadding(10, 2); SplineRouter splineRouter = new SplineRouter(g, 2, loosePadding, Math.PI / 6, null); splineRouter.Run(); sw.Stop(); System.Console.WriteLine("Edge routing took: {0} seconds.", sw.ElapsedMilliseconds / 1000.0); } [TestMethod] [WorkItem(448382)] [WorkItem(446802)] [TestCategory("LayoutPerfTest")] [TestCategory("NonRollingBuildTest")] // [Timeout(30 * 1000)] [Description("Simple timed test of routing with 20 degree cones over a large graph")] public void RouteEdges_Nodes50() { var g = LoadGraph("nodes50.msagl.geom"); var sw = new Stopwatch(); sw.Start(); const double TightPadding = 2.0; var loosePadding = SplineRouter.ComputeLooseSplinePadding(10, TightPadding); SplineRouter splineRouter = new SplineRouter(g, TightPadding, loosePadding, Math.PI / 6, null); splineRouter.Run(); sw.Stop(); Console.WriteLine("Edge routing took: {0} seconds.", sw.ElapsedMilliseconds / 1000.0); CheckEdgesForOverlapWithNodes(TightPadding, g); } private static void CheckEdgesForOverlapWithNodes(double tightPadding, GeometryGraph graph) { #if GDI_DEBUG_VIEWER if (!DontShowTheDebugViewer()) { DisplayGeometryGraph.SetShowFunctions(); } #endif foreach (var e in graph.Edges.Where(e=>!MultiEdge(e)))//avoid checking multi-edges since they routed as bundles and can slightly go over the nodes { Assert.IsNotNull(e.EdgeGeometry, "EdgeGeometry is null"); Assert.IsNotNull(e.EdgeGeometry.Curve, "EdgeGeometry.Curve is null"); foreach (var v in graph.Nodes) { if (v == e.Source || v == e.Target) { continue; } var box = v.BoundingBox; var poly = InteractiveObstacleCalculator.CreatePaddedPolyline(Curve.PolylineAroundClosedCurve(v.BoundaryCurve), tightPadding / 2); bool overlaps = CurveOverlapsBox(e.EdgeGeometry.Curve, ref box, poly); #if GDI_DEBUG_VIEWER //uncomment to see the graph and the overlaps if (overlaps && !DontShowTheDebugViewer()) { LayoutAlgorithmSettings.ShowGraph(graph); LayoutAlgorithmSettings.Show(poly, e.Curve); } #endif Assert.IsFalse(overlaps); } } } static bool CurveOverlapsBox(ICurve curve, ref Rectangle box, Polyline boxPolyline) { // if the curve bounding box doesn't intersect the invalidated region then no overlap! if (!box.Intersects(curve.BoundingBox)) { return false; } // if either end of the curve is inside the box then there is definitely overlap! if (box.Contains(curve.Start) || box.Contains(curve.End)) { return true; } // we have already determined that the curve is close but not fully contained so now we // need to check for a more expensive intersection return Curve.CurveCurveIntersectionOne(boxPolyline, curve, false) != null; } private static bool MultiEdge(Edge edge) { return edge.Source.OutEdges.Where(e => e.Target == edge.Target && e != edge).Any() || edge.Source.InEdges.Where(e => e.Source == edge.Target && e != edge).Any(); } [TestMethod] [WorkItem(446802)] [TestCategory("LayoutPerfTest")] [TestCategory("NonRollingBuildTest")] [Timeout(20000000)] [Description("Simple timed test of routing with 20 degree cones over a small complete graph")] public void SplineRoutingSmallCompleteGraph() { //DisplayGeometryGraph.SetShowFunctions(); var g = LoadGraph("K20.msagl.geom"); var sw = new Stopwatch(); sw.Start(); var loosePadding = SplineRouter.ComputeLooseSplinePadding(10, 2); SplineRouter splineRouter = new SplineRouter(g, 2, loosePadding, Math.PI / 6, null); splineRouter.Run(); sw.Stop(); TestContext.WriteLine("Edge routing took: {0} seconds.", sw.ElapsedMilliseconds / 1000.0); } [TestMethod] [Description("the run does not stop")] public void BundlingBug1GeomGraph() { #if DEBUG && TEST_MSAGL DisplayGeometryGraph.SetShowFunctions(); #endif var graph = GeometryGraphReader.CreateFromFile(GetGeomGraphFileName("bug1.msagl.geom")); var settings = new BundlingSettings(); var router = new SplineRouter(graph, 0.1, 0.75, Math.PI / 6, settings); router.Run(); } [TestMethod] [Description("the run does not stop")] public void ComplexGeomGraph() { var graph = GeometryGraphReader.CreateFromFile(GetGeomGraphFileName("complex.msagl.geom")); var settings = new BundlingSettings(); var br = new SplineRouter(graph, 1, 1.5, Math.PI / 6, settings); br.Run(); } [TestMethod] [Description("bundling with groups")] public void BundlingWithGroups() { var graph = GeometryGraphReader.CreateFromFile(GetGeomGraphFileName("graphWithGroups.msagl.geom")); var settings = new BundlingSettings(); var router = new SplineRouter(graph, 3, 1, Math.PI / 6, settings); router.Run(); } string GetGeomGraphFileName(string graphName) { var dirName = (null != this.TestContext) ? this.TestContext.DeploymentDirectory : Path.GetTempPath(); return Path.Combine(dirName, graphName); } [TestMethod] [Description("Simple test of rectilinear routing between two nodes, one inside a cluster")] public void SimpleClusterGraphRectilinear() { var g = new GeometryGraph(); var node0 = new Node(CurveFactory.CreateRectangle(10, 10, new Point()), 0); var node1 = new Node(CurveFactory.CreateRectangle(10, 10, new Point()), 1); var cluster = new Cluster(new[] { node1 }); cluster.UserData = 2; cluster.BoundaryCurve = CurveFactory.CreateRectangle(10, 10, new Point()); var edge = new Edge(node0, node1) { Length = 100 }; g.Nodes.Add(node0); g.Nodes.Add(node1); g.Edges.Add(edge); var cluster2 = new Cluster(new[] { node0 }, new[] { cluster }); cluster2.UserData = 3; cluster2.BoundaryCurve = CurveFactory.CreateRectangle(10, 10, new Point()); g.RootCluster = cluster2; InitialLayout initialLayout = new InitialLayout(g, new FastIncrementalLayoutSettings() { AvoidOverlaps = true }); initialLayout.Run(); RectilinearEdgeRouter router = new RectilinearEdgeRouter(g, 1, 1, false); router.Run(); EnableDebugViewer(); ShowGraphInDebugViewer(g); var bb0 = node0.BoundingBox; bb0.Pad(1); Assert.IsTrue(bb0.Contains(edge.EdgeGeometry.Curve.Start)); var bb1 = node1.BoundingBox; bb1.Pad(1); Assert.IsTrue(bb1.Contains(edge.EdgeGeometry.Curve.End)); } [Ignore, WorkItem(535708)] [TestMethod] [TestCategory("Rectilinear routing")] [TestCategory("NonRollingBuildTest")] [Timeout(5000)] [Description("Create three groups, a couple of embedded and see if the routing succeeds")] public void RoutingWithThreeGroups() { var graph = LoadGraph("abstract.msagl.geom"); var root = graph.RootCluster; var a = new Cluster { UserData = "a" }; foreach (string id in new[] { "17", "39", "13", "19", "28", "12" }) a.AddChild(graph.FindNodeByUserData(id)); var b = new Cluster { UserData = "b" }; b.AddChild(a); b.AddChild(graph.FindNodeByUserData("18")); root.AddChild(b); var c = new Cluster { UserData = "c" }; foreach (string id in new[] { "30", "5", "6", "7", "8" }) c.AddChild(graph.FindNodeByUserData(id)); root.AddChild(c); var clusterNodes = new Set<Node>(root.AllClustersDepthFirst().SelectMany(cl => cl.Nodes)); foreach (var node in graph.Nodes.Where(n => clusterNodes.Contains(n) == false)) root.AddChild(node); FixClusterBoundariesWithNoRectBoundaries(root, 5); var defaultSettings = new FastIncrementalLayoutSettings(); var rootSettings = new FastIncrementalLayoutSettings() { AvoidOverlaps = true }; var initialLayout = new InitialLayoutByCluster(graph, new[] { graph.RootCluster }, cl => cl == root ? rootSettings : defaultSettings); initialLayout.Run(); const double Padding = 5; SplineRouter splineRouter = new SplineRouter(graph, Padding/3, Padding, Math.PI / 6); splineRouter.Run(); #if TEST_MSAGL if (!DontShowTheDebugViewer()) { graph.UpdateBoundingBox(); DisplayGeometryGraph.ShowGraph(graph); } #endif } static void FixClusterBoundariesWithNoRectBoundaries(Cluster cluster, double padding) { foreach (Cluster cl in cluster.Clusters) FixClusterBoundariesWithNoRectBoundaries(cl, padding); var box = Rectangle.CreateAnEmptyBox(); var clusterPoints = cluster.Clusters.SelectMany(c => ClusterPoints(c)).Concat( cluster.Nodes.SelectMany(n => NodePerimeterPoints(n))); foreach (var clusterPoint in clusterPoints) box.Add(clusterPoint); box.Pad(padding); cluster.BoundaryCurve = box.Perimeter(); cluster.RectangularBoundary = new RectangularClusterBoundary(); } static IEnumerable<Point> NodePerimeterPoints(Node node) { return new[] { node.BoundingBox.RightTop, node.BoundingBox.LeftBottom, node.BoundingBox.LeftTop, node.BoundingBox.RightBottom }; } static IEnumerable<Point> ClusterPoints(Cluster cluster) { return cluster.BoundaryCurve as Polyline; } } }
/* * 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.Threading; using System.Collections.Generic; using System.Collections; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Scripting.LSLHttp { /// <summary> /// Data describing an external URL set up by a script. /// </summary> public class UrlData { /// <summary> /// Scene object part hosting the script /// </summary> public UUID hostID; /// <summary> /// The item ID of the script that requested the URL. /// </summary> public UUID itemID; /// <summary> /// The script engine that runs the script. /// </summary> public IScriptModule engine; /// <summary> /// The generated URL. /// </summary> public string url; /// <summary> /// The random UUID component of the generated URL. /// </summary> public UUID urlcode; /// <summary> /// The external requests currently being processed or awaiting retrieval for this URL. /// </summary> public Dictionary<UUID, RequestData> requests; } public class RequestData { public UUID requestID; public Dictionary<string, string> headers; public string body; public int responseCode; public string responseBody; public string responseType = "text/plain"; //public ManualResetEvent ev; public bool requestDone; public int startTime; public string uri; } /// <summary> /// This module provides external URLs for in-world scripts. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UrlModule")] public class UrlModule : ISharedRegionModule, IUrlModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the request ID /// randomly generated when a request is received for this URL. /// </summary> /// <remarks> /// Manipulation or retrieval from this dictionary must be locked on m_UrlMap to preserve consistency with /// m_UrlMap /// </remarks> private Dictionary<UUID, UrlData> m_RequestMap = new Dictionary<UUID, UrlData>(); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the full URL /// </summary> private Dictionary<string, UrlData> m_UrlMap = new Dictionary<string, UrlData>(); private uint m_HttpsPort = 0; private IHttpServer m_HttpServer = null; private IHttpServer m_HttpsServer = null; public string ExternalHostNameForLSL { get; private set; } /// <summary> /// The default maximum number of urls /// </summary> public const int DefaultTotalUrls = 100; /// <summary> /// Maximum number of external urls that can be set up by this module. /// </summary> public int TotalUrls { get; set; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "UrlModule"; } } public void Initialise(IConfigSource config) { IConfig networkConfig = config.Configs["Network"]; if (networkConfig != null) { ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", null); bool ssl_enabled = config.Configs["Network"].GetBoolean("https_listener", false); if (ssl_enabled) m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort); } if (ExternalHostNameForLSL == null) ExternalHostNameForLSL = System.Environment.MachineName; IConfig llFunctionsConfig = config.Configs["LL-Functions"]; if (llFunctionsConfig != null) TotalUrls = llFunctionsConfig.GetInt("max_external_urls_per_simulator", DefaultTotalUrls); else TotalUrls = DefaultTotalUrls; } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_HttpServer == null) { // There can only be one // m_HttpServer = MainServer.Instance; // // We can use the https if it is enabled if (m_HttpsPort > 0) { m_HttpsServer = MainServer.GetHttpServer(m_HttpsPort); } } scene.RegisterModuleInterface<IUrlModule>(this); scene.EventManager.OnScriptReset += OnScriptReset; } public void RegionLoaded(Scene scene) { IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule scriptModule in scriptModules) { scriptModule.OnScriptRemoved += ScriptRemoved; scriptModule.OnObjectRemoved += ObjectRemoved; } } public void RemoveRegion(Scene scene) { } public void Close() { } public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); lock (m_UrlMap) { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new Dictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttp/" + urlcode.ToString() + "/"; m_HttpServer.AddPollServiceHTTPHandler( uri, new PollServiceEventArgs(HttpRequestHandler, HasEvents, GetEvents, NoEvents, urlcode)); m_log.DebugFormat( "[URL MODULE]: Set up incoming request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); if (m_HttpsServer == null) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } lock (m_UrlMap) { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new Dictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttps/" + urlcode.ToString() + "/"; m_HttpsServer.AddPollServiceHTTPHandler( uri, new PollServiceEventArgs(HttpRequestHandler, HasEvents, GetEvents, NoEvents, urlcode)); m_log.DebugFormat( "[URL MODULE]: Set up incoming secure request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public void ReleaseURL(string url) { lock (m_UrlMap) { UrlData data; if (!m_UrlMap.TryGetValue(url, out data)) { return; } foreach (UUID req in data.requests.Keys) m_RequestMap.Remove(req); m_log.DebugFormat( "[URL MODULE]: Releasing url {0} for {1} in {2}", url, data.itemID, data.hostID); RemoveUrl(data); m_UrlMap.Remove(url); } } public void HttpContentType(UUID request, string type) { lock (m_UrlMap) { if (m_RequestMap.ContainsKey(request)) { UrlData urlData = m_RequestMap[request]; urlData.requests[request].responseType = type; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } } public void HttpResponse(UUID request, int status, string body) { lock (m_UrlMap) { if (m_RequestMap.ContainsKey(request)) { UrlData urlData = m_RequestMap[request]; string responseBody = body; if (urlData.requests[request].responseType.Equals("text/plain")) { string value; if (urlData.requests[request].headers.TryGetValue("user-agent", out value)) { if (value != null && value.IndexOf("MSIE") >= 0) { // wrap the html escaped response if the target client is IE // It ignores "text/plain" if the body is html responseBody = "<html>" + System.Web.HttpUtility.HtmlEncode(body) + "</html>"; } } } urlData.requests[request].responseCode = status; urlData.requests[request].responseBody = responseBody; //urlData.requests[request].ev.Set(); urlData.requests[request].requestDone =true; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } } public string GetHttpHeader(UUID requestId, string header) { lock (m_UrlMap) { if (m_RequestMap.ContainsKey(requestId)) { UrlData urlData = m_RequestMap[requestId]; string value; if (urlData.requests[requestId].headers.TryGetValue(header, out value)) return value; } else { m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId); } } return String.Empty; } public int GetFreeUrls() { lock (m_UrlMap) return TotalUrls - m_UrlMap.Count; } public void ScriptRemoved(UUID itemID) { // m_log.DebugFormat("[URL MODULE]: Removing script {0}", itemID); lock (m_UrlMap) { List<string> removeURLs = new List<string>(); foreach (KeyValuePair<string, UrlData> url in m_UrlMap) { if (url.Value.itemID == itemID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } } foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } } public void ObjectRemoved(UUID objectID) { lock (m_UrlMap) { List<string> removeURLs = new List<string>(); foreach (KeyValuePair<string, UrlData> url in m_UrlMap) { if (url.Value.hostID == objectID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } } foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } } private void RemoveUrl(UrlData data) { m_HttpServer.RemoveHTTPHandler("", "/lslhttp/" + data.urlcode.ToString() + "/"); } private Hashtable NoEvents(UUID requestID, UUID sessionID) { Hashtable response = new Hashtable(); UrlData urlData; lock (m_UrlMap) { // We need to return a 404 here in case the request URL was removed at exactly the same time that a // request was made. In this case, the request thread can outrace llRemoveURL() and still be polling // for the request ID. if (!m_RequestMap.ContainsKey(requestID)) { response["int_response_code"] = 404; response["str_response_string"] = ""; response["keepalive"] = false; response["reusecontext"] = false; return response; } urlData = m_RequestMap[requestID]; if (System.Environment.TickCount - urlData.requests[requestID].startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map urlData.requests.Remove(requestID); m_RequestMap.Remove(requestID); return response; } } return response; } private bool HasEvents(UUID requestID, UUID sessionID) { lock (m_UrlMap) { // We return true here because an external URL request that happened at the same time as an llRemoveURL() // can still make it through to HttpRequestHandler(). That will return without setting up a request // when it detects that the URL has been removed. The poller, however, will continue to ask for // events for that request, so here we will signal that there are events and in GetEvents we will // return a 404. if (!m_RequestMap.ContainsKey(requestID)) { return true; } UrlData urlData = m_RequestMap[requestID]; if (!urlData.requests.ContainsKey(requestID)) { return true; } // Trigger return of timeout response. if (System.Environment.TickCount - urlData.requests[requestID].startTime > 25000) { return true; } return urlData.requests[requestID].requestDone; } } private Hashtable GetEvents(UUID requestID, UUID sessionID, string request) { Hashtable response; lock (m_UrlMap) { UrlData url = null; RequestData requestData = null; if (!m_RequestMap.ContainsKey(requestID)) return NoEvents(requestID, sessionID); url = m_RequestMap[requestID]; requestData = url.requests[requestID]; if (!requestData.requestDone) return NoEvents(requestID, sessionID); response = new Hashtable(); if (System.Environment.TickCount - requestData.startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; } //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = requestData.responseType; // response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map url.requests.Remove(requestID); m_RequestMap.Remove(requestID); } return response; } public void HttpRequestHandler(UUID requestID, Hashtable request) { string uri = request["uri"].ToString(); bool is_ssl = uri.Contains("lslhttps"); try { Hashtable headers = (Hashtable)request["headers"]; // string uri_full = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/"; int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string uri_tmp = uri.Substring(0, pos3 + 1); //HTTP server code doesn't provide us with QueryStrings string pathInfo; string queryString; queryString = ""; pathInfo = uri.Substring(pos3); UrlData urlData = null; lock (m_UrlMap) { string url; if (is_ssl) url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + uri_tmp; else url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp; // Avoid a race - the request URL may have been released via llRequestUrl() whilst this // request was being processed. if (!m_UrlMap.TryGetValue(url, out urlData)) return; //for llGetHttpHeader support we need to store original URI here //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader RequestData requestData = new RequestData(); requestData.requestID = requestID; requestData.requestDone = false; requestData.startTime = System.Environment.TickCount; requestData.uri = uri; if (requestData.headers == null) requestData.headers = new Dictionary<string, string>(); foreach (DictionaryEntry header in headers) { string key = (string)header.Key; string value = (string)header.Value; requestData.headers.Add(key, value); } foreach (DictionaryEntry de in request) { if (de.Key.ToString() == "querystringkeys") { System.String[] keys = (System.String[])de.Value; foreach (String key in keys) { if (request.ContainsKey(key)) { string val = (String)request[key]; queryString = queryString + key + "=" + val + "&"; } } if (queryString.Length > 1) queryString = queryString.Substring(0, queryString.Length - 1); } } //if this machine is behind DNAT/port forwarding, currently this is being //set to address of port forwarding router requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"]; requestData.headers["x-path-info"] = pathInfo; requestData.headers["x-query-string"] = queryString; requestData.headers["x-script-url"] = urlData.url; urlData.requests.Add(requestID, requestData); m_RequestMap.Add(requestID, urlData); } urlData.engine.PostScriptEvent( urlData.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() }); } catch (Exception we) { //Hashtable response = new Hashtable(); m_log.Warn("[HttpRequestHandler]: http-in request failed"); m_log.Warn(we.Message); m_log.Warn(we.StackTrace); } } private void OnScriptReset(uint localID, UUID itemID) { ScriptRemoved(itemID); } } }
using Tweetinvi.Models; using Tweetinvi.Parameters; using Tweetinvi.Parameters.TrendsClient; namespace Tweetinvi.Core.Client.Validators { public interface IParametersValidator : IAccountActivityClientParametersValidator, IAccountSettingsClientParametersValidator, IAuthClientParametersValidator, IHelpClientParametersValidator, IMessagesClientParametersValidator, ISearchClientParametersValidator, ITwitterListsClientParametersValidator, ITimelineClientParametersValidator, ITrendsClientParametersValidator, ITweetsClientParametersValidator, IUploadClientParametersValidator, IUsersClientParametersValidator { } public class ParametersValidator : IParametersValidator { private readonly IAccountActivityClientParametersValidator _accountActivityClientParametersValidator; private readonly IAccountSettingsClientParametersValidator _accountSettingsClientParametersValidator; private readonly IAuthClientParametersValidator _authClientParametersValidator; private readonly IHelpClientParametersValidator _helpClientParametersValidator; private readonly IMessagesClientParametersValidator _messagesClientParametersValidator; private readonly ISearchClientParametersValidator _searchClientParametersValidator; private readonly ITwitterListsClientParametersValidator _twitterListsClientParametersValidator; private readonly ITrendsClientParametersValidator _trendsClientParametersValidator; private readonly ITimelineClientParametersValidator _timelineClientParametersValidator; private readonly ITweetsClientParametersValidator _tweetsClientParametersValidator; private readonly IUploadClientParametersValidator _uploadClientParametersValidator; private readonly IUsersClientParametersValidator _usersClientParametersValidator; public ParametersValidator( IAccountActivityClientParametersValidator accountActivityClientParametersValidator, IAccountSettingsClientParametersValidator accountSettingsClientParametersValidator, IAuthClientParametersValidator authClientParametersValidator, IHelpClientParametersValidator helpClientParametersValidator, IMessagesClientParametersValidator messagesClientParametersValidator, ISearchClientParametersValidator searchClientParametersValidator, ITwitterListsClientParametersValidator twitterListsClientParametersValidator, ITrendsClientParametersValidator trendsClientParametersValidator, ITimelineClientParametersValidator timelineClientParametersValidator, ITweetsClientParametersValidator tweetsClientParametersValidator, IUploadClientParametersValidator uploadClientParametersValidator, IUsersClientParametersValidator usersClientParametersValidator) { _accountActivityClientParametersValidator = accountActivityClientParametersValidator; _accountSettingsClientParametersValidator = accountSettingsClientParametersValidator; _authClientParametersValidator = authClientParametersValidator; _helpClientParametersValidator = helpClientParametersValidator; _messagesClientParametersValidator = messagesClientParametersValidator; _searchClientParametersValidator = searchClientParametersValidator; _twitterListsClientParametersValidator = twitterListsClientParametersValidator; _trendsClientParametersValidator = trendsClientParametersValidator; _timelineClientParametersValidator = timelineClientParametersValidator; _tweetsClientParametersValidator = tweetsClientParametersValidator; _uploadClientParametersValidator = uploadClientParametersValidator; _usersClientParametersValidator = usersClientParametersValidator; } public void Validate(ICreateAccountActivityWebhookParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IGetAccountActivityWebhookEnvironmentsParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IGetAccountActivityEnvironmentWebhooksParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IDeleteAccountActivityWebhookParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(ITriggerAccountActivityWebhookCRCParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(ISubscribeToAccountActivityParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(ICountAccountActivitySubscriptionsParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IIsAccountSubscribedToAccountActivityParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IGetAccountActivitySubscriptionsParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IUnsubscribeFromAccountActivityParameters parameters) { _accountActivityClientParametersValidator.Validate(parameters); } public void Validate(IGetAccountSettingsParameters parameters) { _accountSettingsClientParametersValidator.Validate(parameters); } public void Validate(IUpdateAccountSettingsParameters parameters) { _accountSettingsClientParametersValidator.Validate(parameters); } public void Validate(IUpdateProfileParameters parameters) { _accountSettingsClientParametersValidator.Validate(parameters); } public void Validate(IUpdateProfileImageParameters parameters) { _accountSettingsClientParametersValidator.Validate(parameters); } public void Validate(IUpdateProfileBannerParameters parameters) { _accountSettingsClientParametersValidator.Validate(parameters); } public void Validate(IRemoveProfileBannerParameters parameters) { _accountSettingsClientParametersValidator.Validate(parameters); } public void Validate(ICreateBearerTokenParameters parameters, ITwitterRequest request) { _authClientParametersValidator.Validate(parameters, request); } public void Validate(IRequestAuthUrlParameters parameters) { _authClientParametersValidator.Validate(parameters); } public void Validate(IRequestCredentialsParameters parameters) { _authClientParametersValidator.Validate(parameters); } public void Validate(IInvalidateAccessTokenParameters parameters, ITwitterRequest request) { _authClientParametersValidator.Validate(parameters, request); } public void Validate(IInvalidateBearerTokenParameters parameters, ITwitterRequest request) { _authClientParametersValidator.Validate(parameters, request); } public void Validate(IGetRateLimitsParameters parameters) { _helpClientParametersValidator.Validate(parameters); } public void Validate(IGetTwitterConfigurationParameters parameters) { _helpClientParametersValidator.Validate(parameters); } public void Validate(IGetSupportedLanguagesParameters parameters) { _helpClientParametersValidator.Validate(parameters); } public void Validate(IGetPlaceParameters parameters) { _helpClientParametersValidator.Validate(parameters); } public void Validate(IGeoSearchParameters parameters) { _helpClientParametersValidator.Validate(parameters); } public void Validate(IGeoSearchReverseParameters parameters) { _helpClientParametersValidator.Validate(parameters); } public void Validate(IPublishMessageParameters parameters) { _messagesClientParametersValidator.Validate(parameters); } public void Validate(IDeleteMessageParameters parameters) { _messagesClientParametersValidator.Validate(parameters); } public void Validate(IGetMessageParameters parameters) { _messagesClientParametersValidator.Validate(parameters); } public void Validate(IGetMessagesParameters parameters) { _messagesClientParametersValidator.Validate(parameters); } public void Validate(ICreateListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetListsSubscribedByUserParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IUpdateListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IDestroyListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetListsOwnedByAccountParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetListsOwnedByUserParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetTweetsFromListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IAddMemberToListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IAddMembersToListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetUserListMembershipsParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetMembersOfListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(ICheckIfUserIsMemberOfListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IRemoveMemberFromListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IRemoveMembersFromListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetAccountListMembershipsParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(ISubscribeToListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IUnsubscribeFromListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetListSubscribersParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetAccountListSubscriptionsParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(IGetUserListSubscriptionsParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(ICheckIfUserIsSubscriberOfListParameters parameters) { _twitterListsClientParametersValidator.Validate(parameters); } public void Validate(ISearchTweetsParameters parameters) { _searchClientParametersValidator.Validate(parameters); } public void Validate(ISearchUsersParameters parameters) { _searchClientParametersValidator.Validate(parameters); } public void Validate(ICreateSavedSearchParameters parameters) { _searchClientParametersValidator.Validate(parameters); } public void Validate(IGetSavedSearchParameters parameters) { _searchClientParametersValidator.Validate(parameters); } public void Validate(IListSavedSearchesParameters parameters) { _searchClientParametersValidator.Validate(parameters); } public void Validate(IDestroySavedSearchParameters parameters) { _searchClientParametersValidator.Validate(parameters); } public void Validate(IGetHomeTimelineParameters parameters) { _timelineClientParametersValidator.Validate(parameters); } public void Validate(IGetUserTimelineParameters parameters) { _timelineClientParametersValidator.Validate(parameters); } public void Validate(IGetMentionsTimelineParameters parameters) { _timelineClientParametersValidator.Validate(parameters); } public void Validate(IGetRetweetsOfMeTimelineParameters parameters) { _timelineClientParametersValidator.Validate(parameters); } public void Validate(IGetTrendsLocationCloseToParameters parameters) { _trendsClientParametersValidator.Validate(parameters); } public void Validate(IGetTrendsAtParameters parameters) { _trendsClientParametersValidator.Validate(parameters); } public void Validate(IGetTrendsLocationParameters parameters) { _trendsClientParametersValidator.Validate(parameters); } public void Validate(IGetTweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IGetTweetsParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IPublishTweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IDestroyTweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IGetUserFavoriteTweetsParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IGetRetweetsParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IPublishRetweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IDestroyRetweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IGetRetweeterIdsParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IFavoriteTweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IUnfavoriteTweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IGetOEmbedTweetParameters parameters) { _tweetsClientParametersValidator.Validate(parameters); } public void Validate(IUploadParameters parameters) { _uploadClientParametersValidator.Validate(parameters); } public void Validate(IAddMediaMetadataParameters parameters) { _uploadClientParametersValidator.Validate(parameters); } public void Validate(IGetUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetUsersParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetFollowerIdsParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetFollowersParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetFriendIdsParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetFriendsParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetRelationshipBetweenParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetProfileImageParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetAuthenticatedUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IBlockUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IUnblockUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IReportUserForSpamParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetBlockedUserIdsParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetBlockedUsersParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IFollowUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IUnfollowUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetUserIdsRequestingFriendshipParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetUsersRequestingFriendshipParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetUserIdsYouRequestedToFollowParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetUsersYouRequestedToFollowParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IUpdateRelationshipParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetRelationshipsWithParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetUserIdsWhoseRetweetsAreMutedParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetMutedUserIdsParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IGetMutedUsersParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IMuteUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } public void Validate(IUnmuteUserParameters parameters) { _usersClientParametersValidator.Validate(parameters); } } }
using System; using FluentAssertions.Primitives; #if !OLD_MSTEST using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace FluentAssertions.Specs { [TestClass] public class NullableNumericAssertionSpecs { [TestMethod] public void Should_succeed_when_asserting_nullable_numeric_value_with_value_to_have_a_value() { int? nullableInteger = 1; nullableInteger.Should().HaveValue(); } [TestMethod] public void Should_succeed_when_asserting_nullable_numeric_value_with_value_to_not_be_null() { int? nullableInteger = 1; nullableInteger.Should().NotBeNull(); } [TestMethod] public void Should_fail_when_asserting_nullable_numeric_value_without_a_value_to_have_a_value() { int? nullableInteger = null; Action act = () => nullableInteger.Should().HaveValue(); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void Should_fail_when_asserting_nullable_numeric_value_without_a_value_to_not_be_null() { int? nullableInteger = null; Action act = () => nullableInteger.Should().NotBeNull(); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void Should_fail_with_descriptive_message_when_asserting_nullable_numeric_value_without_a_value_to_have_a_value() { int? nullableInteger = null; var assertions = nullableInteger.Should(); assertions.Invoking(x => x.HaveValue("because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage("Expected a value because we want to test the failure message."); } [TestMethod] public void Should_fail_with_descriptive_message_when_asserting_nullable_numeric_value_without_a_value_to_not_be_null() { int? nullableInteger = null; var assertions = nullableInteger.Should(); assertions.Invoking(x => x.NotBeNull("because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage("Expected a value because we want to test the failure message."); } [TestMethod] public void Should_succeed_when_asserting_nullable_numeric_value_without_a_value_to_not_have_a_value() { int? nullableInteger = null; nullableInteger.Should().NotHaveValue(); } [TestMethod] public void Should_succeed_when_asserting_nullable_numeric_value_without_a_value_to_be_null() { int? nullableInteger = null; nullableInteger.Should().BeNull(); } [TestMethod] public void Should_fail_when_asserting_nullable_numeric_value_with_a_value_to_not_have_a_value() { int? nullableInteger = 1; Action act = () => nullableInteger.Should().NotHaveValue(); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void Should_fail_when_asserting_nullable_numeric_value_with_a_value_to_be_null() { int? nullableInteger = 1; Action act = () => nullableInteger.Should().BeNull(); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_nullable_value_with_unexpected_value_is_found_it_should_throw_with_message() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- int? nullableInteger = 1; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableInteger.Should().NotHaveValue("it was {0} expected", "not"); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- action .ShouldThrow<AssertFailedException>() .WithMessage("Did not expect a value because it was not expected, but found 1."); } [TestMethod] public void Should_fail_with_descriptive_message_when_asserting_nullable_numeric_value_with_a_value_to_be_null() { int? nullableInteger = 1; var assertions = nullableInteger.Should(); assertions.Invoking(x => x.BeNull("because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage("Did not expect a value because we want to test the failure message, but found 1."); } [TestMethod] public void Should_succeed_when_asserting_nullable_numeric_value_equals_an_equal_value() { int? nullableIntegerA = 1; int? nullableIntegerB = 1; nullableIntegerA.Should().Be(nullableIntegerB); } [TestMethod] public void Should_succeed_when_asserting_nullable_numeric_null_value_equals_null() { int? nullableIntegerA = null; int? nullableIntegerB = null; nullableIntegerA.Should().Be(nullableIntegerB); } [TestMethod] public void Should_fail_when_asserting_nullable_numeric_value_equals_a_different_value() { int? nullableIntegerA = 1; int? nullableIntegerB = 2; Action act = () => nullableIntegerA.Should().Be(nullableIntegerB); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void Should_fail_with_descriptive_message_when_asserting_nullable_numeric_value_equals_a_different_value() { int? nullableIntegerA = 1; int? nullableIntegerB = 2; var assertions = nullableIntegerA.Should(); assertions.Invoking(x => x.Be(nullableIntegerB, "because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage("Expected*2 because we want to test the failure message, but found 1."); } #region Be Approximately [TestMethod] public void When_nullable_double_is_indeed_approximating_a_value_it_should_not_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- double? value = 3.1415927; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(3.14, 0.1); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_nullable_double_has_no_value_it_should_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- double? value = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(3.14, 0.001); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>().WithMessage(string.Format( "Expected value to approximate {0} +/- {1}, but it was <null>.", 3.14, 0.001)); } [TestMethod] public void When_nullable_double_is_not_approximating_a_value_it_should_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- double? value = 3.1415927F; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(1.0, 0.1); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act .ShouldThrow<AssertFailedException>() .WithMessage(string.Format( "Expected value*to approximate 1.0 +/- {0}, but it differed by*", 0.1)); } [TestMethod] public void When_nullable_float_is_indeed_approximating_a_value_it_should_not_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- float? value = 3.1415927F; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(3.14F, 0.1F); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_nullable_float_is_not_approximating_a_value_it_should_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- float? value = 3.1415927F; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(1.0F, 0.1F); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act .ShouldThrow<AssertFailedException>() .WithMessage(string.Format( "Expected value*to approximate *{0}* +/- *{1}* but it differed by*", 1, 0.1)); } [TestMethod] public void When_nullable_decimal_is_indeed_approximating_a_value_it_should_not_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- decimal? value = 3.1415927m; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(3.14m, 0.1m); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_nullable_decimal_has_no_value_it_should_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- decimal? value = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(3.14m, 0.001m); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>().WithMessage(string.Format( "Expected value to approximate*{0}* +/-*{1}*, but it was <null>.", 3.14m, 0.001m)); } [TestMethod] public void When_nullable_decimal_is_not_approximating_a_value_it_should_throw() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- decimal? value = 3.1415927m; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action act = () => value.Should().BeApproximately(1.0m, 0.1m); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- act .ShouldThrow<AssertFailedException>() .WithMessage(string.Format( "Expected value*to approximate*{0}* +/-*{1}*, but it differed by*", 1.0m, 0.1m)); } #endregion [TestMethod] public void Should_support_chaining_constraints_with_and() { int? nullableInteger = 1; nullableInteger.Should() .HaveValue() .And .BePositive(); } } }
using System; using System.Diagnostics; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC { public abstract class ECFieldElement { public abstract BigInteger ToBigInteger(); public abstract string FieldName { get; } public abstract int FieldSize { get; } public abstract ECFieldElement Add(ECFieldElement b); public abstract ECFieldElement Subtract(ECFieldElement b); public abstract ECFieldElement Multiply(ECFieldElement b); public abstract ECFieldElement Divide(ECFieldElement b); public abstract ECFieldElement Negate(); public abstract ECFieldElement Square(); public abstract ECFieldElement Invert(); public abstract ECFieldElement Sqrt(); public override bool Equals( object obj) { if (obj == this) return true; ECFieldElement other = obj as ECFieldElement; if (other == null) return false; return Equals(other); } protected bool Equals( ECFieldElement other) { return ToBigInteger().Equals(other.ToBigInteger()); } public override int GetHashCode() { return ToBigInteger().GetHashCode(); } public override string ToString() { return this.ToBigInteger().ToString(2); } } public class FpFieldElement : ECFieldElement { private readonly BigInteger q, x; public FpFieldElement( BigInteger q, BigInteger x) { if (x.CompareTo(q) >= 0) throw new ArgumentException("x value too large in field element"); this.q = q; this.x = x; } public override BigInteger ToBigInteger() { return x; } /** * return the field name for this field. * * @return the string "Fp". */ public override string FieldName { get { return "Fp"; } } public override int FieldSize { get { return q.BitLength; } } public BigInteger Q { get { return q; } } public override ECFieldElement Add( ECFieldElement b) { return new FpFieldElement(q, x.Add(b.ToBigInteger()).Mod(q)); } public override ECFieldElement Subtract( ECFieldElement b) { return new FpFieldElement(q, x.Subtract(b.ToBigInteger()).Mod(q)); } public override ECFieldElement Multiply( ECFieldElement b) { return new FpFieldElement(q, x.Multiply(b.ToBigInteger()).Mod(q)); } public override ECFieldElement Divide( ECFieldElement b) { return new FpFieldElement(q, x.Multiply(b.ToBigInteger().ModInverse(q)).Mod(q)); } public override ECFieldElement Negate() { return new FpFieldElement(q, x.Negate().Mod(q)); } public override ECFieldElement Square() { return new FpFieldElement(q, x.Multiply(x).Mod(q)); } public override ECFieldElement Invert() { return new FpFieldElement(q, x.ModInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public override ECFieldElement Sqrt() { if (!q.TestBit(0)) throw Platform.CreateNotImplementedException("even value of q"); // p mod 4 == 3 if (q.TestBit(1)) { // TODO Can this be optimised (inline the Square?) // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new FpFieldElement(q, x.ModPow(q.ShiftRight(2).Add(BigInteger.One), q)); return z.Square().Equals(this) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.Subtract(BigInteger.One); BigInteger legendreExponent = qMinusOne.ShiftRight(1); if (!(x.ModPow(legendreExponent, q).Equals(BigInteger.One))) return null; BigInteger u = qMinusOne.ShiftRight(2); BigInteger k = u.ShiftLeft(1).Add(BigInteger.One); BigInteger Q = this.x; BigInteger fourQ = Q.ShiftLeft(2).Mod(q); BigInteger U, V; do { Random rand = new Random(); BigInteger P; do { P = new BigInteger(q.BitLength, rand); } while (P.CompareTo(q) >= 0 || !(P.Multiply(P).Subtract(fourQ).ModPow(legendreExponent, q).Equals(qMinusOne))); BigInteger[] result = fastLucasSequence(q, P, Q, k); U = result[0]; V = result[1]; if (V.Multiply(V).Mod(q).Equals(fourQ)) { // Integer division by 2, mod q if (V.TestBit(0)) { V = V.Add(q); } V = V.ShiftRight(1); Debug.Assert(V.Multiply(V).Mod(q).Equals(x)); return new FpFieldElement(q, V); } } while (U.Equals(BigInteger.One) || U.Equals(qMinusOne)); return null; // BigInteger qMinusOne = q.Subtract(BigInteger.One); // // BigInteger legendreExponent = qMinusOne.ShiftRight(1); // if (!(x.ModPow(legendreExponent, q).Equals(BigInteger.One))) // return null; // // Random rand = new Random(); // BigInteger fourX = x.ShiftLeft(2); // // BigInteger r; // do // { // r = new BigInteger(q.BitLength, rand); // } // while (r.CompareTo(q) >= 0 // || !(r.Multiply(r).Subtract(fourX).ModPow(legendreExponent, q).Equals(qMinusOne))); // // BigInteger n1 = qMinusOne.ShiftRight(2); // BigInteger n2 = n1.Add(BigInteger.One); // // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).Add(W(n2, wOne, q)).Mod(q); // BigInteger twoR = r.ShiftLeft(1); // // BigInteger root = twoR.ModPow(q.Subtract(BigInteger.Two), q) // .Multiply(x).Mod(q) // .Multiply(wSum).Mod(q); // // return new FpFieldElement(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // { // if (n.Equals(BigInteger.One)) // return wOne; // // bool isEven = !n.TestBit(0); // n = n.ShiftRight(1); // if (isEven) // { // BigInteger w = W(n, wOne, p); // return w.Multiply(w).Subtract(BigInteger.Two).Mod(p); // } // BigInteger w1 = W(n.Add(BigInteger.One), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.Multiply(w2).Subtract(wOne).Mod(p); // } // // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // { // return r.Multiply(r).Multiply(x.ModPow(q.Subtract(BigInteger.Two), q)).Subtract(BigInteger.Two).Mod(p); // } private static BigInteger[] fastLucasSequence( BigInteger p, BigInteger P, BigInteger Q, BigInteger k) { // TODO Research and apply "common-multiplicand multiplication here" int n = k.BitLength; int s = k.GetLowestSetBit(); Debug.Assert(k.TestBit(s)); BigInteger Uh = BigInteger.One; BigInteger Vl = BigInteger.Two; BigInteger Vh = P; BigInteger Ql = BigInteger.One; BigInteger Qh = BigInteger.One; for (int j = n - 1; j >= s + 1; --j) { Ql = Ql.Multiply(Qh).Mod(p); if (k.TestBit(j)) { Qh = Ql.Multiply(Q).Mod(p); Uh = Uh.Multiply(Vh).Mod(p); Vl = Vh.Multiply(Vl).Subtract(P.Multiply(Ql)).Mod(p); Vh = Vh.Multiply(Vh).Subtract(Qh.ShiftLeft(1)).Mod(p); } else { Qh = Ql; Uh = Uh.Multiply(Vl).Subtract(Ql).Mod(p); Vh = Vh.Multiply(Vl).Subtract(P.Multiply(Ql)).Mod(p); Vl = Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)).Mod(p); } } Ql = Ql.Multiply(Qh).Mod(p); Qh = Ql.Multiply(Q).Mod(p); Uh = Uh.Multiply(Vl).Subtract(Ql).Mod(p); Vl = Vh.Multiply(Vl).Subtract(P.Multiply(Ql)).Mod(p); Ql = Ql.Multiply(Qh).Mod(p); for (int j = 1; j <= s; ++j) { Uh = Uh.Multiply(Vl).Mod(p); Vl = Vl.Multiply(Vl).Subtract(Ql.ShiftLeft(1)).Mod(p); Ql = Ql.Multiply(Ql).Mod(p); } return new BigInteger[]{ Uh, Vl }; } // private static BigInteger[] verifyLucasSequence( // BigInteger p, // BigInteger P, // BigInteger Q, // BigInteger k) // { // BigInteger[] actual = fastLucasSequence(p, P, Q, k); // BigInteger[] plus1 = fastLucasSequence(p, P, Q, k.Add(BigInteger.One)); // BigInteger[] plus2 = fastLucasSequence(p, P, Q, k.Add(BigInteger.Two)); // // BigInteger[] check = stepLucasSequence(p, P, Q, actual, plus1); // // Debug.Assert(check[0].Equals(plus2[0])); // Debug.Assert(check[1].Equals(plus2[1])); // // return actual; // } // // private static BigInteger[] stepLucasSequence( // BigInteger p, // BigInteger P, // BigInteger Q, // BigInteger[] backTwo, // BigInteger[] backOne) // { // return new BigInteger[] // { // P.Multiply(backOne[0]).Subtract(Q.Multiply(backTwo[0])).Mod(p), // P.Multiply(backOne[1]).Subtract(Q.Multiply(backTwo[1])).Mod(p) // }; // } public override bool Equals( object obj) { if (obj == this) return true; FpFieldElement other = obj as FpFieldElement; if (other == null) return false; return Equals(other); } protected bool Equals( FpFieldElement other) { return q.Equals(other.q) && base.Equals(other); } public override int GetHashCode() { return q.GetHashCode() ^ base.GetHashCode(); } } // /** // * Class representing the Elements of the finite field // * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) // * representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial // * basis representations are supported. Gaussian normal basis (GNB) // * representation is not supported. // */ // public class F2mFieldElement // : ECFieldElement // { // /** // * Indicates gaussian normal basis representation (GNB). Number chosen // * according to X9.62. GNB is not implemented at present. // */ // public const int Gnb = 1; // // /** // * Indicates trinomial basis representation (Tpb). Number chosen // * according to X9.62. // */ // public const int Tpb = 2; // // /** // * Indicates pentanomial basis representation (Ppb). Number chosen // * according to X9.62. // */ // public const int Ppb = 3; // // /** // * Tpb or Ppb. // */ // private int representation; // // /** // * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. // */ // private int m; // // /** // * Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k1; // // /** // * Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k2; // // /** // * Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // private int k3; // // /** // * Constructor for Ppb. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2mFieldElement( // int m, // int k1, // int k2, // int k3, // BigInteger x) // : base(x) // { // if ((k2 == 0) && (k3 == 0)) // { // this.representation = Tpb; // } // else // { // if (k2 >= k3) // throw new ArgumentException("k2 must be smaller than k3"); // if (k2 <= 0) // throw new ArgumentException("k2 must be larger than 0"); // // this.representation = Ppb; // } // // if (x.SignValue < 0) // throw new ArgumentException("x value cannot be negative"); // // this.m = m; // this.k1 = k1; // this.k2 = k2; // this.k3 = k3; // } // // /** // * Constructor for Tpb. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction // * polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2mFieldElement( // int m, // int k, // BigInteger x) // : this(m, k, 0, 0, x) // { // // Set k1 to k, and set k2 and k3 to 0 // } // // public override string FieldName // { // get { return "F2m"; } // } // // /** // * Checks, if the ECFieldElements <code>a</code> and <code>b</code> // * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> // * (having the same representation). // * @param a field element. // * @param b field element to be compared. // * @throws ArgumentException if <code>a</code> and <code>b</code> // * are not elements of the same field // * <code>F<sub>2<sup>m</sup></sub></code> (having the same // * representation). // */ // public static void CheckFieldElements( // ECFieldElement a, // ECFieldElement b) // { // if (!(a is F2mFieldElement) || !(b is F2mFieldElement)) // { // throw new ArgumentException("Field elements are not " // + "both instances of F2mFieldElement"); // } // // if ((a.x.SignValue < 0) || (b.x.SignValue < 0)) // { // throw new ArgumentException( // "x value may not be negative"); // } // // F2mFieldElement aF2m = (F2mFieldElement)a; // F2mFieldElement bF2m = (F2mFieldElement)b; // // if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) // || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) // { // throw new ArgumentException("Field elements are not " // + "elements of the same field F2m"); // } // // if (aF2m.representation != bF2m.representation) // { // // Should never occur // throw new ArgumentException( // "One of the field " // + "elements are not elements has incorrect representation"); // } // } // // /** // * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is // * the reduction polynomial of <code>this</code>. // * @param a The polynomial <code>a(z)</code> to be multiplied by // * <code>z mod f(z)</code>. // * @return <code>z * a(z) mod f(z)</code> // */ // private BigInteger multZModF( // BigInteger a) // { // // Left-shift of a(z) // BigInteger az = a.ShiftLeft(1); // if (az.TestBit(this.m)) // { // // If the coefficient of z^m in a(z) Equals 1, reduction // // modulo f(z) is performed: Add f(z) to to a(z): // // Step 1: Unset mth coeffient of a(z) // az = az.ClearBit(this.m); // // // Step 2: Add r(z) to a(z), where r(z) is defined as // // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // // the non-zero coefficients in r(z) // az = az.FlipBit(0); // az = az.FlipBit(this.k1); // if (this.representation == Ppb) // { // az = az.FlipBit(this.k2); // az = az.FlipBit(this.k3); // } // } // return az; // } // // public override ECFieldElement Add( // ECFieldElement b) // { // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // if (b.x.SignValue == 0) // return this; // // return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, this.x.Xor(b.x)); // } // // public override ECFieldElement Subtract( // ECFieldElement b) // { // // Addition and subtraction are the same in F2m // return Add(b); // } // // public override ECFieldElement Multiply( // ECFieldElement b) // { // // Left-to-right shift-and-add field multiplication in F2m // // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // // Output: c(z) = a(z) * b(z) mod f(z) // // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // BigInteger az = this.x; // BigInteger bz = b.x; // BigInteger cz; // // // Compute c(z) = a(z) * b(z) mod f(z) // if (az.TestBit(0)) // { // cz = bz; // } // else // { // cz = BigInteger.Zero; // } // // for (int i = 1; i < this.m; i++) // { // // b(z) := z * b(z) mod f(z) // bz = multZModF(bz); // // if (az.TestBit(i)) // { // // If the coefficient of x^i in a(z) Equals 1, b(z) is added // // to c(z) // cz = cz.Xor(bz); // } // } // return new F2mFieldElement(m, this.k1, this.k2, this.k3, cz); // } // // // public override ECFieldElement Divide( // ECFieldElement b) // { // // There may be more efficient implementations // ECFieldElement bInv = b.Invert(); // return Multiply(bInv); // } // // public override ECFieldElement Negate() // { // // -x == x holds for all x in F2m // return this; // } // // public override ECFieldElement Square() // { // // Naive implementation, can probably be speeded up using modular // // reduction // return Multiply(this); // } // // public override ECFieldElement Invert() // { // // Inversion in F2m using the extended Euclidean algorithm // // Input: A nonzero polynomial a(z) of degree at most m-1 // // Output: a(z)^(-1) mod f(z) // // // u(z) := a(z) // BigInteger uz = this.x; // if (uz.SignValue <= 0) // { // throw new ArithmeticException("x is zero or negative, " + // "inversion is impossible"); // } // // // v(z) := f(z) // BigInteger vz = BigInteger.One.ShiftLeft(m); // vz = vz.SetBit(0); // vz = vz.SetBit(this.k1); // if (this.representation == Ppb) // { // vz = vz.SetBit(this.k2); // vz = vz.SetBit(this.k3); // } // // // g1(z) := 1, g2(z) := 0 // BigInteger g1z = BigInteger.One; // BigInteger g2z = BigInteger.Zero; // // // while u != 1 // while (uz.SignValue != 0) // { // // j := deg(u(z)) - deg(v(z)) // int j = uz.BitLength - vz.BitLength; // // // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j // if (j < 0) // { // BigInteger uzCopy = uz; // uz = vz; // vz = uzCopy; // // BigInteger g1zCopy = g1z; // g1z = g2z; // g2z = g1zCopy; // // j = -j; // } // // // u(z) := u(z) + z^j * v(z) // // Note, that no reduction modulo f(z) is required, because // // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // // = deg(u(z)) // uz = uz.Xor(vz.ShiftLeft(j)); // // // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.Xor(g2z.ShiftLeft(j)); // // if (g1z.BitLength() > this.m) { // // throw new ArithmeticException( // // "deg(g1z) >= m, g1z = " + g1z.ToString(2)); // // } // } // return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, g2z); // } // // public override ECFieldElement Sqrt() // { // throw new ArithmeticException("Not implemented"); // } // // /** // * @return the representation of the field // * <code>F<sub>2<sup>m</sup></sub></code>, either of // * {@link F2mFieldElement.Tpb} (trinomial // * basis representation) or // * {@link F2mFieldElement.Ppb} (pentanomial // * basis representation). // */ // public int Representation // { // get { return this.representation; } // } // // /** // * @return the degree <code>m</code> of the reduction polynomial // * <code>f(z)</code>. // */ // public int M // { // get { return this.m; } // } // // /** // * @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K1 // { // get { return this.k1; } // } // // /** // * @return Tpb: Always returns <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K2 // { // get { return this.k2; } // } // // /** // * @return Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ // public int K3 // { // get { return this.k3; } // } // // public override bool Equals( // object obj) // { // if (obj == this) // return true; // // F2mFieldElement other = obj as F2mFieldElement; // // if (other == null) // return false; // // return Equals(other); // } // // protected bool Equals( // F2mFieldElement other) // { // return m == other.m // && k1 == other.k1 // && k2 == other.k2 // && k3 == other.k3 // && representation == other.representation // && base.Equals(other); // } // // public override int GetHashCode() // { // return base.GetHashCode() ^ m ^ k1 ^ k2 ^ k3; // } // } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public class F2mFieldElement : ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public const int Gnb = 1; /** * Indicates trinomial basis representation (Tpb). Number chosen * according to X9.62. */ public const int Tpb = 2; /** * Indicates pentanomial basis representation (Ppb). Number chosen * according to X9.62. */ public const int Ppb = 3; /** * Tpb or Ppb. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br/> * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ private int k1; /** * Tpb: Always set to <code>0</code><br/> * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ private int k2; /** * Tpb: Always set to <code>0</code><br/> * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ private int k3; /** * The <code>IntArray</code> holding the bits. */ private IntArray x; /** * The number of <code>int</code>s required to hold <code>m</code> bits. */ private readonly int t; /** * Constructor for Ppb. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2mFieldElement( int m, int k1, int k2, int k3, BigInteger x) { // t = m / 32 rounded up to the next integer this.t = (m + 31) >> 5; this.x = new IntArray(x, t); if ((k2 == 0) && (k3 == 0)) { this.representation = Tpb; } else { if (k2 >= k3) throw new ArgumentException("k2 must be smaller than k3"); if (k2 <= 0) throw new ArgumentException("k2 must be larger than 0"); this.representation = Ppb; } if (x.SignValue < 0) throw new ArgumentException("x value cannot be negative"); this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; } /** * Constructor for Tpb. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2mFieldElement( int m, int k, BigInteger x) : this(m, k, 0, 0, x) { // Set k1 to k, and set k2 and k3 to 0 } private F2mFieldElement(int m, int k1, int k2, int k3, IntArray x) { t = (m + 31) >> 5; this.x = x; this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; if ((k2 == 0) && (k3 == 0)) { this.representation = Tpb; } else { this.representation = Ppb; } } public override BigInteger ToBigInteger() { return x.ToBigInteger(); } public override string FieldName { get { return "F2m"; } } public override int FieldSize { get { return m; } } /** * Checks, if the ECFieldElements <code>a</code> and <code>b</code> * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> * (having the same representation). * @param a field element. * @param b field element to be compared. * @throws ArgumentException if <code>a</code> and <code>b</code> * are not elements of the same field * <code>F<sub>2<sup>m</sup></sub></code> (having the same * representation). */ public static void CheckFieldElements( ECFieldElement a, ECFieldElement b) { if (!(a is F2mFieldElement) || !(b is F2mFieldElement)) { throw new ArgumentException("Field elements are not " + "both instances of F2mFieldElement"); } F2mFieldElement aF2m = (F2mFieldElement)a; F2mFieldElement bF2m = (F2mFieldElement)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new ArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new ArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } public override ECFieldElement Add( ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); IntArray iarrClone = (IntArray) this.x.Clone(); F2mFieldElement bF2m = (F2mFieldElement) b; iarrClone.AddShifted(bF2m.x, 0); return new F2mFieldElement(m, k1, k2, k3, iarrClone); } public override ECFieldElement Subtract( ECFieldElement b) { // Addition and subtraction are the same in F2m return Add(b); } public override ECFieldElement Multiply( ECFieldElement b) { // Right-to-left comb multiplication in the IntArray // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); F2mFieldElement bF2m = (F2mFieldElement) b; IntArray mult = x.Multiply(bF2m.x, m); mult.Reduce(m, new int[]{k1, k2, k3}); return new F2mFieldElement(m, k1, k2, k3, mult); } public override ECFieldElement Divide( ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.Invert(); return Multiply(bInv); } public override ECFieldElement Negate() { // -x == x holds for all x in F2m return this; } public override ECFieldElement Square() { IntArray squared = x.Square(m); squared.Reduce(m, new int[]{k1, k2, k3}); return new F2mFieldElement(m, k1, k2, k3, squared); } public override ECFieldElement Invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) IntArray uz = (IntArray)this.x.Clone(); // v(z) := f(z) IntArray vz = new IntArray(t); vz.SetBit(m); vz.SetBit(0); vz.SetBit(this.k1); if (this.representation == Ppb) { vz.SetBit(this.k2); vz.SetBit(this.k3); } // g1(z) := 1, g2(z) := 0 IntArray g1z = new IntArray(t); g1z.SetBit(0); IntArray g2z = new IntArray(t); // while u != 0 while (uz.GetUsedLength() > 0) // while (uz.bitLength() > 1) { // j := deg(u(z)) - deg(v(z)) int j = uz.BitLength - vz.BitLength; // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { IntArray uzCopy = uz; uz = vz; vz = uzCopy; IntArray g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) // uz = uz.xor(vz.ShiftLeft(j)); // jInt = n / 32 int jInt = j >> 5; // jInt = n % 32 int jBit = j & 0x1F; IntArray vzShift = vz.ShiftLeft(jBit); uz.AddShifted(vzShift, jInt); // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.ShiftLeft(j)); IntArray g2zShift = g2z.ShiftLeft(jBit); g1z.AddShifted(g2zShift, jInt); } return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, g2z); } public override ECFieldElement Sqrt() { throw new ArithmeticException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * {@link F2mFieldElement.Tpb} (trinomial * basis representation) or * {@link F2mFieldElement.Ppb} (pentanomial * basis representation). */ public int Representation { get { return this.representation; } } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int M { get { return this.m; } } /** * @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br/> * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ public int K1 { get { return this.k1; } } /** * @return Tpb: Always returns <code>0</code><br/> * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ public int K2 { get { return this.k2; } } /** * @return Tpb: Always set to <code>0</code><br/> * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br/> */ public int K3 { get { return this.k3; } } public override bool Equals( object obj) { if (obj == this) return true; F2mFieldElement other = obj as F2mFieldElement; if (other == null) return false; return Equals(other); } protected bool Equals( F2mFieldElement other) { return m == other.m && k1 == other.k1 && k2 == other.k2 && k3 == other.k3 && representation == other.representation && base.Equals(other); } public override int GetHashCode() { return m.GetHashCode() ^ k1.GetHashCode() ^ k2.GetHashCode() ^ k3.GetHashCode() ^ representation.GetHashCode() ^ base.GetHashCode(); } } }
using System; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System.IO; using System.Text; using System.Collections.Generic; using RaptorDB.Common; namespace RaptorDB { internal class StorageData { public byte[] Key; public byte[] Data; public bool isDeleted; } internal class StorageFile<T> { FileStream _datawrite; FileStream _recfilewrite; FileStream _recfileread = null; FileStream _dataread = null; private string _filename = ""; private string _recfilename = ""; private int _lastRecordNum = 0; private long _lastWriteOffset = 6; private object _lock = new object(); private bool _dirty = false; IGetBytes<T> _T = null; public static byte[] _fileheader = { (byte)'M', (byte)'G', (byte)'D', (byte)'B', 0, // 4 -- not used, 0 // 5 -- not used }; public static byte[] _rowheader = { (byte)'M', (byte)'G', (byte)'R' , 0, // 3 [keylen] 0,0,0,0,0,0,0,0, // 4-11 [datetime] 8 bytes = insert time 0,0,0,0, // 12-15 [data length] 4 bytes 0, // 16 -- [flags] = 1 : isDeletd:1 // 2 : isCompressed:1 // // 0 // 17 -- [crc] = header crc check }; private enum HDR_POS { KeyLen = 3, DateTime = 4, DataLength = 12, Flags = 16, CRC = 17 } public bool SkipDateTime = false; public StorageFile(string filename) { Initialize(filename, false); } public StorageFile(string filename, bool SkipChecking) { Initialize(filename, SkipChecking); } private void Initialize(string filename, bool SkipChecking) { _T = RDBDataType<T>.ByteHandler(); _filename = filename; if (File.Exists(filename) == false) _datawrite = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); else _datawrite = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); _dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (SkipChecking == false) { // load rec pointers _recfilename = filename.Substring(0, filename.LastIndexOf('.')) + ".mgrec"; if (File.Exists(_recfilename) == false) _recfilewrite = new FileStream(_recfilename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); else _recfilewrite = new FileStream(_recfilename, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); _recfileread = new FileStream(_recfilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (_datawrite.Length == 0) { // new file _datawrite.Write(_fileheader, 0, _fileheader.Length); _datawrite.Flush(); _lastWriteOffset = _fileheader.Length; } else { _lastWriteOffset = _datawrite.Seek(0L, SeekOrigin.End); } _lastRecordNum = (int)(_recfilewrite.Length / 8); _recfilewrite.Seek(0L, SeekOrigin.End); } } public int Count() { return (int)(_recfilewrite.Length >> 3); } public int WriteData(T key, byte[] data, bool deleted) { lock (_lock) { _dirty = true; byte[] k = _T.GetBytes(key); int kl = k.Length; // seek end of file long offset = _lastWriteOffset; byte[] hdr = CreateRowHeader(kl, (data == null ? 0 : data.Length)); if (deleted) hdr[(int)HDR_POS.Flags] = (byte)1; // write header info _datawrite.Write(hdr, 0, hdr.Length); // write key _datawrite.Write(k, 0, kl); if (data != null) { // write data block _datawrite.Write(data, 0, data.Length); _lastWriteOffset += data.Length; } // update pointer _lastWriteOffset += hdr.Length; _lastWriteOffset += kl; // return starting offset -> recno int recno = _lastRecordNum++; _recfilewrite.Write(Helper.GetBytes(offset, false), 0, 8); if (Global.FlushStorageFileImmetiatley) { _datawrite.Flush(); _recfilewrite.Flush(); } return recno; } } public byte[] ReadData(int recnum) { bool isdel = false; return ReadData(recnum, out isdel); } public void Shutdown() { FlushClose(_dataread); FlushClose(_recfileread); FlushClose(_recfilewrite); FlushClose(_datawrite); _dataread = null; _recfileread = null; _recfilewrite = null; _datawrite = null; } public static StorageFile<int> ReadForward(string filename) { StorageFile<int> sf = new StorageFile<int>(filename, true); return sf; } #region [ private / internal ] private byte[] CreateRowHeader(int keylen, int datalen) { byte[] rh = new byte[_rowheader.Length]; Buffer.BlockCopy(_rowheader, 0, rh, 0, rh.Length); rh[3] = (byte)keylen; if (SkipDateTime == false) Buffer.BlockCopy(Helper.GetBytes(FastDateTime.Now.Ticks, false), 0, rh, 4, 4); Buffer.BlockCopy(Helper.GetBytes(datalen, false), 0, rh, 12, 4); return rh; } internal byte[] ReadData(int recnum, out bool isdeleted) { isdeleted = false; if (recnum >= _lastRecordNum) return null; lock (_lock) { long off = ComputeOffset(recnum); byte[] key; return internalReadData(off, out key, out isdeleted); } } /// <summary> /// internal use for guid keys only /// </summary> /// <param name="recnum"></param> /// <param name="?"></param> /// <param name="isdeleted"></param> /// <returns></returns> internal byte[] ReadData(int recnum, out Guid docid, out bool isdeleted) { isdeleted = false; docid = Guid.Empty; if (recnum >= _lastRecordNum) return null; lock (_lock) { long off = ComputeOffset(recnum); byte[] key; byte[] data= internalReadData(off, out key, out isdeleted); docid = new Guid(key); return data; } } private long ComputeOffset(int recnum) { if (_dirty) { _datawrite.Flush(); _recfilewrite.Flush(); } long off = recnum * 8L; byte[] b = new byte[8]; _recfileread.Seek(off, SeekOrigin.Begin); _recfileread.Read(b, 0, 8); off = Helper.ToInt64(b, 0); if (off == 0)// kludge off = 6; return off; } private byte[] internalReadData(long offset, out byte[] key, out bool isdeleted) { // seek offset in file byte[] hdr = new byte[_rowheader.Length]; _dataread.Seek(offset, System.IO.SeekOrigin.Begin); // read header _dataread.Read(hdr, 0, _rowheader.Length); // check header if (CheckHeader(hdr)) { //isdeleted = false; key = null; byte[] data = null; isdeleted = isDeleted(hdr); //if (isDeleted(hdr) == false) // isdeleted = false; int kl = hdr[(int)HDR_POS.KeyLen]; if (kl > 0) { key = new byte[kl]; _dataread.Read(key, 0, key.Length); } int dl = Helper.ToInt32(hdr, (int)HDR_POS.DataLength); if (dl > 0) { data = new byte[dl]; // read data block _dataread.Read(data, 0, dl); } return data; } else throw new Exception("data header error at offset : " + offset + " data file size = " + _dataread.Length); } private bool CheckHeader(byte[] hdr) { if (hdr[0] == (byte)'M' && hdr[1] == (byte)'G' && hdr[2] == (byte)'R' && hdr[(int)HDR_POS.CRC] == (byte)0) return true; return false; } private void FlushClose(FileStream st) { if (st != null) { st.Flush(true); st.Close(); } } internal T GetKey(int recnum, out bool deleted) { lock (_lock) { deleted = false; long off = recnum * 8L; byte[] b = new byte[8]; _recfileread.Seek(off, SeekOrigin.Begin); _recfileread.Read(b, 0, 8); off = Helper.ToInt64(b, 0); // seek offset in file byte[] hdr = new byte[_rowheader.Length]; _dataread.Seek(off, System.IO.SeekOrigin.Begin); // read header _dataread.Read(hdr, 0, _rowheader.Length); if (CheckHeader(hdr)) { deleted = isDeleted(hdr); byte kl = hdr[3]; byte[] kbyte = new byte[kl]; _dataread.Read(kbyte, 0, kl); return _T.GetObject(kbyte, 0, kl); } return default(T); } } private bool isDeleted(byte[] hdr) { return (hdr[(int)HDR_POS.Flags] & (byte)1) > 0; } internal int CopyTo(StorageFile<int> storageFile, int start) { // copy data here lock (_lock) { long off = ComputeOffset(start); _dataread.Seek(off, SeekOrigin.Begin); Pump(_dataread, storageFile._datawrite); return _lastRecordNum; } } private static void Pump(Stream input, Stream output) { byte[] bytes = new byte[4096 * 2]; int n; while ((n = input.Read(bytes, 0, bytes.Length)) != 0) output.Write(bytes, 0, n); } internal IEnumerable<StorageData> Enumerate() { lock (_lock) { long offset = 6; long size = _dataread.Length; while (offset < size) { // skip header _dataread.Seek(offset, SeekOrigin.Begin); byte[] hdr = new byte[_rowheader.Length]; // read header _dataread.Read(hdr, 0, _rowheader.Length); offset += hdr.Length; if (CheckHeader(hdr)) { StorageData sd = new StorageData(); sd.isDeleted = isDeleted(hdr); byte kl = hdr[3]; byte[] kbyte = new byte[kl]; offset += kl; _dataread.Read(kbyte, 0, kl); sd.Key = kbyte; int dl = Helper.ToInt32(hdr, (int)HDR_POS.DataLength); byte[] data = new byte[dl]; // read data block _dataread.Read(data, 0, dl); sd.Data = data; offset += dl; yield return sd; } else { throw new Exception("Data read failed"); } } } } #endregion } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using Com.Drew.Lang; using Com.Drew.Metadata; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Exif.Makernotes { /// <summary> /// Provides human-readable string representations of tag values stored in a /// <see cref="NikonType2MakernoteDirectory"/> /// . /// Type-2 applies to the E990 and D-series cameras such as the D1, D70 and D100. /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public class NikonType2MakernoteDescriptor : TagDescriptor<NikonType2MakernoteDirectory> { public NikonType2MakernoteDescriptor([NotNull] NikonType2MakernoteDirectory directory) : base(directory) { } [CanBeNull] public override string GetDescription(int tagType) { switch (tagType) { case NikonType2MakernoteDirectory.TagProgramShift: { return GetProgramShiftDescription(); } case NikonType2MakernoteDirectory.TagExposureDifference: { return GetExposureDifferenceDescription(); } case NikonType2MakernoteDirectory.TagLens: { return GetLensDescription(); } case NikonType2MakernoteDirectory.TagCameraHueAdjustment: { return GetHueAdjustmentDescription(); } case NikonType2MakernoteDirectory.TagCameraColorMode: { return GetColorModeDescription(); } case NikonType2MakernoteDirectory.TagAutoFlashCompensation: { return GetAutoFlashCompensationDescription(); } case NikonType2MakernoteDirectory.TagFlashExposureCompensation: { return GetFlashExposureCompensationDescription(); } case NikonType2MakernoteDirectory.TagFlashBracketCompensation: { return GetFlashBracketCompensationDescription(); } case NikonType2MakernoteDirectory.TagExposureTuning: { return GetExposureTuningDescription(); } case NikonType2MakernoteDirectory.TagLensStops: { return GetLensStopsDescription(); } case NikonType2MakernoteDirectory.TagColorSpace: { return GetColorSpaceDescription(); } case NikonType2MakernoteDirectory.TagActiveDLighting: { return GetActiveDLightingDescription(); } case NikonType2MakernoteDirectory.TagVignetteControl: { return GetVignetteControlDescription(); } case NikonType2MakernoteDirectory.TagIso1: { return GetIsoSettingDescription(); } case NikonType2MakernoteDirectory.TagDigitalZoom: { return GetDigitalZoomDescription(); } case NikonType2MakernoteDirectory.TagFlashUsed: { return GetFlashUsedDescription(); } case NikonType2MakernoteDirectory.TagAfFocusPosition: { return GetAutoFocusPositionDescription(); } case NikonType2MakernoteDirectory.TagFirmwareVersion: { return GetFirmwareVersionDescription(); } case NikonType2MakernoteDirectory.TagLensType: { return GetLensTypeDescription(); } case NikonType2MakernoteDirectory.TagShootingMode: { return GetShootingModeDescription(); } case NikonType2MakernoteDirectory.TagNefCompression: { return GetNEFCompressionDescription(); } case NikonType2MakernoteDirectory.TagHighIsoNoiseReduction: { return GetHighISONoiseReductionDescription(); } case NikonType2MakernoteDirectory.TagPowerUpTime: { return GetPowerUpTimeDescription(); } default: { return base.GetDescription(tagType); } } } [CanBeNull] public virtual string GetPowerUpTimeDescription() { return GetEpochTimeDescription(NikonType2MakernoteDirectory.TagPowerUpTime); } [CanBeNull] public virtual string GetHighISONoiseReductionDescription() { return GetIndexedDescription(NikonType2MakernoteDirectory.TagHighIsoNoiseReduction, "Off", "Minimal", "Low", null, "Normal", null, "High"); } [CanBeNull] public virtual string GetFlashUsedDescription() { return GetIndexedDescription(NikonType2MakernoteDirectory.TagFlashUsed, "Flash Not Used", "Manual Flash", null, "Flash Not Ready", null, null, null, "External Flash", "Fired, Commander Mode", "Fired, TTL Mode"); } [CanBeNull] public virtual string GetNEFCompressionDescription() { return GetIndexedDescription(NikonType2MakernoteDirectory.TagNefCompression, 1, "Lossy (Type 1)", null, "Uncompressed", null, null, null, "Lossless", "Lossy (Type 2)"); } [CanBeNull] public virtual string GetShootingModeDescription() { return GetBitFlagDescription(NikonType2MakernoteDirectory.TagShootingMode, new string[] { "Single Frame", "Continuous" }, "Delay", null, "PC Control", "Exposure Bracketing", "Auto ISO", "White-Balance Bracketing", "IR Control"); } // LSB [low label, high label] [CanBeNull] public virtual string GetLensTypeDescription() { return GetBitFlagDescription(NikonType2MakernoteDirectory.TagLensType, new string[] { "AF", "MF" }, "D", "G", "VR"); } // LSB [low label, high label] [CanBeNull] public virtual string GetColorSpaceDescription() { return GetIndexedDescription(NikonType2MakernoteDirectory.TagColorSpace, 1, "sRGB", "Adobe RGB"); } [CanBeNull] public virtual string GetActiveDLightingDescription() { int? value = _directory.GetInteger(NikonType2MakernoteDirectory.TagActiveDLighting); if (value == null) { return null; } switch (value) { case 0: { return "Off"; } case 1: { return "Light"; } case 3: { return "Normal"; } case 5: { return "High"; } case 7: { return "Extra High"; } case 65535: { return "Auto"; } default: { return "Unknown (" + value + ")"; } } } [CanBeNull] public virtual string GetVignetteControlDescription() { int? value = _directory.GetInteger(NikonType2MakernoteDirectory.TagVignetteControl); if (value == null) { return null; } switch (value) { case 0: { return "Off"; } case 1: { return "Low"; } case 3: { return "Normal"; } case 5: { return "High"; } default: { return "Unknown (" + value + ")"; } } } [CanBeNull] public virtual string GetAutoFocusPositionDescription() { int[] values = _directory.GetIntArray(NikonType2MakernoteDirectory.TagAfFocusPosition); if (values == null) { return null; } if (values.Length != 4 || values[0] != 0 || values[2] != 0 || values[3] != 0) { return "Unknown (" + _directory.GetString(NikonType2MakernoteDirectory.TagAfFocusPosition) + ")"; } switch (values[1]) { case 0: { return "Centre"; } case 1: { return "Top"; } case 2: { return "Bottom"; } case 3: { return "Left"; } case 4: { return "Right"; } default: { return "Unknown (" + values[1] + ")"; } } } [CanBeNull] public virtual string GetDigitalZoomDescription() { Rational value = _directory.GetRational(NikonType2MakernoteDirectory.TagDigitalZoom); if (value == null) { return null; } return value.IntValue() == 1 ? "No digital zoom" : value.ToSimpleString(true) + "x digital zoom"; } [CanBeNull] public virtual string GetProgramShiftDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagProgramShift); } [CanBeNull] public virtual string GetExposureDifferenceDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagExposureDifference); } [CanBeNull] public virtual string GetAutoFlashCompensationDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagAutoFlashCompensation); } [CanBeNull] public virtual string GetFlashExposureCompensationDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagFlashExposureCompensation); } [CanBeNull] public virtual string GetFlashBracketCompensationDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagFlashBracketCompensation); } [CanBeNull] public virtual string GetExposureTuningDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagExposureTuning); } [CanBeNull] public virtual string GetLensStopsDescription() { return GetEVDescription(NikonType2MakernoteDirectory.TagLensStops); } [CanBeNull] private string GetEVDescription(int tagType) { int[] values = _directory.GetIntArray(tagType); if (values == null) { return null; } if (values.Length < 3 || values[2] == 0) { return null; } DecimalFormat decimalFormat = new DecimalFormat("0.##"); double ev = values[0] * values[1] / (double)values[2]; return decimalFormat.Format(ev) + " EV"; } [CanBeNull] public virtual string GetIsoSettingDescription() { int[] values = _directory.GetIntArray(NikonType2MakernoteDirectory.TagIso1); if (values == null) { return null; } if (values[0] != 0 || values[1] == 0) { return "Unknown (" + _directory.GetString(NikonType2MakernoteDirectory.TagIso1) + ")"; } return "ISO " + values[1]; } [CanBeNull] public virtual string GetLensDescription() { Rational[] values = _directory.GetRationalArray(NikonType2MakernoteDirectory.TagLens); return values == null ? null : values.Length < 4 ? _directory.GetString(NikonType2MakernoteDirectory.TagLens) : Sharpen.Extensions.StringFormat("%d-%dmm f/%.1f-%.1f", values[0].IntValue(), values[1].IntValue(), values[2].FloatValue(), values [3].FloatValue()); } [CanBeNull] public virtual string GetHueAdjustmentDescription() { return GetFormattedString(NikonType2MakernoteDirectory.TagCameraHueAdjustment, "%s degrees"); } [CanBeNull] public virtual string GetColorModeDescription() { string value = _directory.GetString(NikonType2MakernoteDirectory.TagCameraColorMode); return value == null ? null : value.StartsWith("MODE1") ? "Mode I (sRGB)" : value; } [CanBeNull] public virtual string GetFirmwareVersionDescription() { return GetVersionBytesDescription(NikonType2MakernoteDirectory.TagFirmwareVersion, 2); } } }
// Reference: Oxide.Ext.Unity /* * Many thanks to feramor@computer.org for his HappyHour.cs plugin, which * gave me examples of how to work with dates and timers in a plugin. */ /* * The MIT License (MIT) * Copyright (c) 2015 #db_arcane * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using Oxide.Core; using Oxide.Core.Plugins; using Oxide.Core.Libraries; namespace Oxide.Plugins { [Info("SchedShutdown", "db_arcane", "1.1.2")] public class SchedShutdown : RustPlugin { static List<Oxide.Core.Libraries.Timer.TimerInstance> Timers = new List<Oxide.Core.Libraries.Timer.TimerInstance>(); Oxide.Core.Libraries.Timer MainTimer; string TimeFormat = "HH:mm:ss"; string EnabledStr = "enabled"; string DisabledStr = "disabled"; void Init() { LoadConfig(); CleanupConfig(); MainTimer = Interface.GetMod().GetLibrary<Oxide.Core.Libraries.Timer>("Timer"); } [ConsoleCommand("schedule.shutdown")] private void ScheduleShutdown(ConsoleSystem.Arg arg) { string param = arg.ArgsStr.ToString(); if (param == "") { PrintShutdownStatus(); return; } if (param == "enable") { if (Config["UTC_Time"].ToString() == "") { this.Puts("The shutdown time has not been configured yet. The shutdown timer remains disabled."); return; } Config["Status"] = EnabledStr; SaveConfig(); ResetShutdownTimer(); return; } if (param == DisabledStr) { Config["Status"] = DisabledStr; SaveConfig(); ResetShutdownTimer(); return; } if (!IsTimeValid(param)) { this.Puts("The time entered was unreadable, must be in format like '01:30:00'. No changes have been made. "); PrintShutdownStatus(); return; } Config["Status"] = EnabledStr; Config["UTC_Time"] = param; SaveConfig(); ResetShutdownTimer(); } [HookMethod("OnServerInitialized")] void myOnServerInitialized() { DateTime configTime; DateTime mainTime = DateTime.UtcNow; if (Config["Status"].ToString() == DisabledStr) { PrintShutdownStatus(); return; } // Set up timer for server save and shutdown try { configTime = DateTime.ParseExact(Config["UTC_Time"].ToString(), TimeFormat, null); } catch (Exception e) { PrintShutdownStatus(); return; } DateTime shutdownTime = new DateTime(mainTime.Year, mainTime.Month, mainTime.Day, configTime.Hour, configTime.Minute, configTime.Second, DateTimeKind.Utc); if (mainTime > shutdownTime) { shutdownTime = shutdownTime.AddDays(1); } long shutdownInterval = Convert.ToInt64((shutdownTime - mainTime).TotalSeconds); // schedule the server save command. Oxide.Core.Libraries.Timer.TimerInstance newTimer = MainTimer.Once(shutdownInterval, () => ConsoleSystem.Run.Server.Normal("server.save")); Timers.Add(newTimer); // schedule the restart command. Restart simply shuts down the server after a 60-second countdown newTimer = MainTimer.Once(shutdownInterval, () => ConsoleSystem.Run.Server.Normal("restart")); Timers.Add(newTimer); PrintShutdownStatus(); } [HookMethod("Unload")] void myUnload() { foreach (Oxide.Core.Libraries.Timer.TimerInstance CurrentTimer in Timers) { if (CurrentTimer != null) if (CurrentTimer.Destroyed == false) CurrentTimer.Destroy(); } Timers.Clear(); } [HookMethod("LoadDefaultConfig")] void myLoadDefaultConfig() { Config["Status"] = DisabledStr; Config["UTC_Time"] = ""; SaveConfig(); } private void ResetShutdownTimer() { myUnload(); myOnServerInitialized(); } private void PrintShutdownStatus() { string status = (Config["Status"].ToString() == DisabledStr) ? "DISABLED" : "ENABLED"; string schedTime = Config["UTC_Time"].ToString(); schedTime = (schedTime == "") ? "blank" : schedTime + " UTC" ; this.Puts("Shutdown timer is " + status + ", configured shutdown time is " + schedTime); } private void CleanupConfig() { string status = Config["Status"].ToString().ToLower(); Config["Status"] = ((status != EnabledStr) && (status != DisabledStr)) ? DisabledStr : status; if (!IsTimeValid(Config["UTC_Time"].ToString())) { Config["UTC_Time"] = ""; Config["Status"] = DisabledStr; } SaveConfig(); } private bool IsTimeValid(string timeString) { DateTime temp; try { temp = DateTime.ParseExact(timeString, TimeFormat, null); } catch (Exception e) { return false; } return true; } } }
using System; using System.Reflection; using System.Collections.Generic; using System.Text; namespace FlatRedBall.Content { #region XML Docs /// <summary> /// Delegate representing the method that is to be called for a property to be mapped. /// This can be applied by specific type or by generic type. /// </summary> /// <param name="objectInfo">The member info of the object being mapped.</param> /// <param name="objectValue">The instance being mapped.</param> #endregion public delegate void MemberMapping(MemberInfo objectInfo, object objectValue); public abstract class MappingMethods { #region Fields protected Dictionary<Type, MemberMapping> mMappings = new Dictionary<Type, MemberMapping>(); protected Dictionary<Type, MemberMapping> mMappingsForGenerics = new Dictionary<Type, MemberMapping>(); protected List<Type> mTypesToIgnore = new List<Type>(); //Child classes must fill this or else there will be no members. protected List<MemberTypes> mAcceptedMemberTypes = new List<MemberTypes>(); protected BindingFlags mMemberBitMask = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; protected int mBytesUsed = 0; //If there is a base type, get it's members and append this type's sorted members onto the base type's sorted members. protected bool mAppendOntoBase = false; #endregion #region Properties public BindingFlags MemberBitMask { get { return mMemberBitMask; } } public List<MemberTypes> AcceptedMemberTypes { get { return mAcceptedMemberTypes; } } public bool BreakdownUnknownTypes { get; set; } public bool AppendOntoBase { get { return mAppendOntoBase; } } #endregion #region Methods public MappingMethods() { BreakdownUnknownTypes = false; } public bool IgnoreType(Type typeOfObject) { return mTypesToIgnore.Contains(typeOfObject); } public bool HasMethodForType(Type typeOfObject) { if (typeOfObject.IsEnum) { typeOfObject = typeof(Enum); } if(mMappings.ContainsKey(typeOfObject)) { return true; } else if(typeOfObject.IsGenericType && mMappingsForGenerics.ContainsKey(typeOfObject.GetGenericTypeDefinition())) { return true; } else if (BreakdownUnknownTypes) //If we breakdown types, we must have a breakdown method. { return true; } return false; } public MemberMapping GetMappingForType(Type typeOfObject) { if (typeOfObject.IsEnum) { typeOfObject = typeof(Enum); } if(mMappings.ContainsKey(typeOfObject)) { return mMappings[typeOfObject]; } else if (typeOfObject.IsGenericType && mMappingsForGenerics.ContainsKey(typeOfObject.GetGenericTypeDefinition())) { return mMappingsForGenerics[typeOfObject.GetGenericTypeDefinition()]; } else if (BreakdownUnknownTypes) { if (typeOfObject.GetInterface("ICollection", true) != null) { return BreakdownUnknownTypeList; } return BreakdownUnknownType; } else { throw new Exception("Mapping for object was not provided. You should use HasMethodForType to check before calling this method."); } } public virtual void BreakdownUnknownType(MemberInfo objectInfo, object objectValue) { throw new Exception("If this method is being called, it should have been overriden in it's derived class"); } public virtual void BreakdownUnknownTypeList(MemberInfo objectInfo, object objectValue) { throw new Exception("If this method is being called, it should have been overriden in it's derived class"); } public virtual void Start() { } public virtual void End() { } protected int GetSizeOfListType(PropertyInfo objectInfo) { Type type; if (objectInfo.PropertyType.IsArray) { type = ((PropertyInfo)objectInfo).PropertyType.GetElementType(); } else if (objectInfo.PropertyType.IsGenericType) { Type[] genericTypes = ((PropertyInfo)objectInfo).PropertyType.GetGenericArguments(); type = genericTypes[0]; } else //everything else (such as primitives) { type = ((PropertyInfo)objectInfo).PropertyType; } if (type == typeof(bool) || type == typeof(char)) { return 1; } return System.Runtime.InteropServices.Marshal.SizeOf(type); } protected int GetSizeOfType(Type type) { if (type == typeof(bool) || type == typeof(char)) { return 1; } else if (type.IsValueType == false || type.IsEnum) { //Reference types and enums will be 4bytes. return 4; } return System.Runtime.InteropServices.Marshal.SizeOf(type); } protected static bool IsStruct(Type t) { return t.IsValueType && t.IsPrimitive == false && t.IsEnum == false; } protected void FormatStringReplacement(StringBuilder outputText) { outputText.Replace("System.Single", "float"); //Do this as to not change "Single" in names of members outputText.Replace(" Single", " float"); //For fields that are on a new line following a generated \t outputText.Replace("\tSingle", "\tfloat"); //For casts (__*) outputText.Replace("(Single", "(float"); outputText.Replace("System.Boolean", "bool"); //Do this as to not change "Boolean" in names of members outputText.Replace(" Boolean", " bool"); outputText.Replace("\tBoolean", "\tbool"); outputText.Replace("(Boolean", "(bool"); outputText.Replace("System.Int32", "int"); outputText.Replace("Int32", "int"); outputText.Replace("System.Int16", "short"); outputText.Replace("Int16", "short"); outputText.Replace("System.String", "string"); //Do this as to not change "String" in names of members outputText.Replace(" String", " string"); outputText.Replace("\tString", "\tstring"); outputText.Replace("(String", "(string"); outputText.Replace("System.Double", "double"); //Do this as to not change "Double" in names of members outputText.Replace(" Double", " double"); outputText.Replace("\tDouble", "\tdouble"); outputText.Replace("(Double", "(double"); outputText.Replace("System.Char", "char"); //Do this as to not change "Char" in names of members outputText.Replace(" Char", " char"); outputText.Replace("\tChar", "\tchar"); outputText.Replace("(Char", "(char"); outputText.Replace("Microsoft.Xna.Framework.", ""); } #endregion } }
using System; using SilentOrbit.Code; using System.Collections.Generic; namespace SilentOrbit.ProtocolBuffers { class MessageCode { readonly CodeWriter cw; readonly Options options; public MessageCode(CodeWriter cw, Options options) { this.cw = cw; this.options = options; } public void GenerateClass(ProtoMessage m) { //Do not generate class code for external classes if (m.OptionExternal) { cw.Comment("Written elsewhere"); cw.Comment(m.OptionAccess + " " + m.OptionType + " " + m.CsType + " {}"); return; } //Default class cw.Summary(m.Comments); cw.Bracket(m.OptionAccess + " partial " + m.OptionType + " " + m.CsType); if (options.GenerateDefaultConstructors) GenerateCtorForDefaults(m); GenerateEnums(m); GenerateProperties(m); //if(options.GenerateToString... // ... if (m.OptionPreserveUnknown) { cw.Summary("Values for unknown fields."); cw.WriteLine("public List<global::SilentOrbit.ProtocolBuffers.KeyValue> PreservedFields;"); cw.WriteLine(); } if (m.OptionTriggers) { cw.Comment("protected virtual void BeforeSerialize() {}"); cw.Comment("protected virtual void AfterDeserialize() {}"); cw.WriteLine(); } foreach (ProtoMessage sub in m.Messages.Values) { GenerateClass(sub); cw.WriteLine(); } cw.EndBracket(); return; } void GenerateCtorForDefaults(ProtoMessage m) { // Collect all fields with default values. var fieldsWithDefaults = new List<Field>(); foreach (Field field in m.Fields.Values) { if (field.OptionDefault != null) { fieldsWithDefaults.Add(field); } } if (fieldsWithDefaults.Count > 0) { cw.Bracket("public " + m.CsType + "()"); foreach (var field in fieldsWithDefaults) { string formattedValue = field.FormatForTypeAssignment(); string line = string.Format("{0} = {1};", field.CsName, formattedValue); cw.WriteLine(line); } cw.EndBracket(); } } void GenerateEnums(ProtoMessage m) { foreach (ProtoEnum me in m.Enums.Values) { GenerateEnum(me); } } public void GenerateEnum(ProtoEnum m) { if (m.OptionExternal) { cw.Comment("Written elsewhere"); cw.Comment(m.Comments); cw.Comment(m.OptionAccess + " enum " + m.CsType); cw.Comment("{"); foreach (var epair in m.Enums) { cw.Summary(epair.Comment); cw.Comment(cw.IndentPrefix + epair.Name + " = " + epair.Value + ","); } cw.Comment("}"); return; } cw.Summary(m.Comments); if (m.OptionFlags) cw.Attribute("global::System.FlagsAttribute"); cw.Bracket(m.OptionAccess + " enum " + m.CsType); foreach (var epair in m.Enums) { cw.Summary(epair.Comment); cw.WriteLine(epair.Name + " = " + epair.Value + ","); } cw.EndBracket(); cw.WriteLine(); } /// <summary> /// Generates the properties. /// </summary> /// <param name='template'> /// if true it will generate only properties that are not included by default, because of the [generate=false] option. /// </param> void GenerateProperties(ProtoMessage m) { foreach (Field f in m.Fields.Values) { if (f.Comments != null) cw.Summary(f.Comments); if (f.OptionExternal) { if (f.OptionDeprecated) cw.WriteLine("// [Obsolete]"); cw.WriteLine("//" + GenerateProperty(f) + " // Implemented by user elsewhere"); } else { if (f.OptionDeprecated) cw.WriteLine("[Obsolete]"); cw.WriteLine(GenerateProperty(f)); } cw.WriteLine(); } cw.WriteLine("public string ChangedProp { get; set; }"); //Wire format field ID #if DEBUGx cw.Comment("ProtocolBuffers wire field id"); foreach (Field f in m.Fields.Values) { cw.WriteLine("public const int " + f.CsName + "FieldID = " + f.ID + ";"); } #endif } string GenerateProperty(Field f) { string type = f.ProtoType.FullCsType; if (f.OptionCodeType != null) type = f.OptionCodeType; if (f.Rule == FieldRule.Repeated) type = "List<" + type + ">"; if (f.Rule == FieldRule.Optional && !f.ProtoType.Nullable && options.Nullable) type = type + "?"; if (f.OptionReadOnly) return f.OptionAccess + " readonly " + type + " " + f.CsName + " = new " + type + "();"; else if (f.ProtoType is ProtoMessage && f.ProtoType.OptionType == "struct") return f.OptionAccess + " " + type + " " + f.CsName + ";"; else { string line = "private " + type + " _" + f.CsName; switch (f.ProtoType.ProtoName) { case ProtoBuiltin.Double: line += " = 0.0D"; break; case ProtoBuiltin.Float: line += " = 0.0F"; break; case ProtoBuiltin.Int32: //Wire format is 64 bit varint line += " = 0"; break; case ProtoBuiltin.Int64: line += " = 0l"; break; case ProtoBuiltin.UInt32: line += " = 0u"; break; case ProtoBuiltin.UInt64: line += " = 0ul"; break; case ProtoBuiltin.SInt32: line += " = 0"; break; case ProtoBuiltin.SInt64: line += " = 0"; break; case ProtoBuiltin.Fixed32: line += " = 0"; break; case ProtoBuiltin.Fixed64: line += " = 0"; break; case ProtoBuiltin.SFixed32: line += " = 0"; break; case ProtoBuiltin.SFixed64: line += " = 0"; break; case ProtoBuiltin.Bool: line += " = false"; break; case ProtoBuiltin.String: line += " = null"; break; } line += ";\r\n"; line += f.OptionAccess + " " + type + " " + f.CsName; line += " \r\n{"; line += "\r\n\tget\r\n\t{\r\n\t\treturn _" + f.CsName + ";\r\n\t}"; line += "\r\n\tset\r\n\t{\r\n\t\tChangedProp += \"" + f.CsName + ",\";\r\n\t\t_" + f.CsName + " = value;\r\n\t}\r\n}"; return line; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PhotonHandler.cs" company="Exit Games GmbH"> // Part of: Photon Unity Networking // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections; using System.Diagnostics; using ExitGames.Client.Photon; using UnityEngine; using Debug = UnityEngine.Debug; using Hashtable = ExitGames.Client.Photon.Hashtable; using SupportClassPun = ExitGames.Client.Photon.SupportClass; /// <summary> /// Internal Monobehaviour that allows Photon to run an Update loop. /// </summary> internal class PhotonHandler : Photon.MonoBehaviour { public static PhotonHandler SP; public int updateInterval; // time [ms] between consecutive SendOutgoingCommands calls public int updateIntervalOnSerialize; // time [ms] between consecutive RunViewUpdate calls (sending syncs, etc) private int nextSendTickCount = 0; private int nextSendTickCountOnSerialize = 0; private static bool sendThreadShouldRun; private static Stopwatch timerToStopConnectionInBackground; protected internal static bool AppQuits; protected internal static Type PingImplementation = null; protected void Awake() { if (SP != null && SP != this && SP.gameObject != null) { GameObject.DestroyImmediate(SP.gameObject); } SP = this; DontDestroyOnLoad(this.gameObject); this.updateInterval = 1000 / PhotonNetwork.sendRate; this.updateIntervalOnSerialize = 1000 / PhotonNetwork.sendRateOnSerialize; PhotonHandler.StartFallbackSendAckThread(); } /// <summary>Called by Unity when the application is closed. Disconnects.</summary> protected void OnApplicationQuit() { PhotonHandler.AppQuits = true; PhotonHandler.StopFallbackSendAckThread(); PhotonNetwork.Disconnect(); } /// <summary> /// Called by Unity when the application gets paused (e.g. on Android when in background). /// </summary> /// <remarks> /// Some versions of Unity will give false values for pause on Android (and possibly on other platforms). /// Sets a disconnect timer when PhotonNetwork.BackgroundTimeout > 0.001f. /// </remarks> /// <param name="pause"></param> protected void OnApplicationPause(bool pause) { if (PhotonNetwork.BackgroundTimeout > 0.001f) { if (timerToStopConnectionInBackground == null) { timerToStopConnectionInBackground = new Stopwatch(); } timerToStopConnectionInBackground.Reset(); if (pause) { timerToStopConnectionInBackground.Start(); } else { timerToStopConnectionInBackground.Stop(); } } } /// <summary>Called by Unity when the play mode ends. Used to cleanup.</summary> protected void OnDestroy() { //Debug.Log("OnDestroy on PhotonHandler."); PhotonHandler.StopFallbackSendAckThread(); //PhotonNetwork.Disconnect(); } protected void Update() { if (PhotonNetwork.networkingPeer == null) { Debug.LogError("NetworkPeer broke!"); return; } if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated || PhotonNetwork.connectionStateDetailed == ClientState.Disconnected || PhotonNetwork.offlineMode) { return; } // the messageQueue might be paused. in that case a thread will send acknowledgements only. nothing else to do here. if (!PhotonNetwork.isMessageQueueRunning) { return; } bool doDispatch = true; while (PhotonNetwork.isMessageQueueRunning && doDispatch) { // DispatchIncomingCommands() returns true of it found any command to dispatch (event, result or state change) Profiler.BeginSample("DispatchIncomingCommands"); doDispatch = PhotonNetwork.networkingPeer.DispatchIncomingCommands(); Profiler.EndSample(); } int currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); // avoiding Environment.TickCount, which could be negative on long-running platforms if (PhotonNetwork.isMessageQueueRunning && currentMsSinceStart > this.nextSendTickCountOnSerialize) { PhotonNetwork.networkingPeer.RunViewUpdate(); this.nextSendTickCountOnSerialize = currentMsSinceStart + this.updateIntervalOnSerialize; this.nextSendTickCount = 0; // immediately send when synchronization code was running } currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); if (currentMsSinceStart > this.nextSendTickCount) { bool doSend = true; while (PhotonNetwork.isMessageQueueRunning && doSend) { // Send all outgoing commands Profiler.BeginSample("SendOutgoingCommands"); doSend = PhotonNetwork.networkingPeer.SendOutgoingCommands(); Profiler.EndSample(); } this.nextSendTickCount = currentMsSinceStart + this.updateInterval; } } /// <summary>Called by Unity after a new level was loaded.</summary> protected void OnLevelWasLoaded(int level) { PhotonNetwork.networkingPeer.NewSceneLoaded(); PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); } protected void OnJoinedRoom() { PhotonNetwork.networkingPeer.LoadLevelIfSynced(); } protected void OnCreatedRoom() { PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(SceneManagerHelper.ActiveSceneName); } public static void StartFallbackSendAckThread() { #if !UNITY_WEBGL if (sendThreadShouldRun) { return; } sendThreadShouldRun = true; SupportClassPun.CallInBackground(FallbackSendAckThread); // thread will call this every 100ms until method returns false #endif } public static void StopFallbackSendAckThread() { #if !UNITY_WEBGL sendThreadShouldRun = false; #endif } public static bool FallbackSendAckThread() { if (sendThreadShouldRun && PhotonNetwork.networkingPeer != null) { // check if the client should disconnect after some seconds in background if (timerToStopConnectionInBackground != null && PhotonNetwork.BackgroundTimeout > 0.001f) { if (timerToStopConnectionInBackground.ElapsedMilliseconds > PhotonNetwork.BackgroundTimeout * 1000) { return sendThreadShouldRun; } } PhotonNetwork.networkingPeer.SendAcksOnly(); } return sendThreadShouldRun; } #region Photon Cloud Ping Evaluation private const string PlayerPrefsKey = "PUNCloudBestRegion"; internal static CloudRegionCode BestRegionCodeCurrently = CloudRegionCode.none; // default to none internal static CloudRegionCode BestRegionCodeInPreferences { get { string prefsRegionCode = PlayerPrefs.GetString(PlayerPrefsKey, ""); if (!string.IsNullOrEmpty(prefsRegionCode)) { CloudRegionCode loadedRegion = Region.Parse(prefsRegionCode); return loadedRegion; } return CloudRegionCode.none; } set { if (value == CloudRegionCode.none) { PlayerPrefs.DeleteKey(PlayerPrefsKey); } else { PlayerPrefs.SetString(PlayerPrefsKey, value.ToString()); } } } internal protected static void PingAvailableRegionsAndConnectToBest() { SP.StartCoroutine(SP.PingAvailableRegionsCoroutine(true)); } internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest) { BestRegionCodeCurrently = CloudRegionCode.none; while (PhotonNetwork.networkingPeer.AvailableRegions == null) { if (PhotonNetwork.connectionStateDetailed != ClientState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != ClientState.ConnectedToNameServer) { Debug.LogError("Call ConnectToNameServer to ping available regions."); yield break; // break if we don't connect to the nameserver at all } Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null)); yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping) } if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0) { Debug.LogError("No regions available. Are you sure your appid is valid and setup?"); yield break; // break if we don't get regions at all } PhotonPingManager pingManager = new PhotonPingManager(); foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions) { SP.StartCoroutine(pingManager.PingSocket(region)); } while (!pingManager.Done) { yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping) } Region best = pingManager.BestRegion; PhotonHandler.BestRegionCodeCurrently = best.Code; PhotonHandler.BestRegionCodeInPreferences = best.Code; Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest); if (connectToBest) { PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code); } } #endregion }
using System; using Csla; using Codisa.InterwayDocs.DataAccess; namespace Codisa.InterwayDocs.Business { /// <summary> /// IncomingInfo (read only object).<br/> /// This is a generated <see cref="IncomingInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="IncomingBook"/> collection. /// </remarks> [Serializable] public partial class IncomingInfo : ReadOnlyBase<IncomingInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="RegisterId"/> property. /// </summary> public static readonly PropertyInfo<int> RegisterIdProperty = RegisterProperty<int>(p => p.RegisterId, "Register Id"); /// <summary> /// Gets the Register Id. /// </summary> /// <value>The Register Id.</value> public int RegisterId { get { return GetProperty(RegisterIdProperty); } } /// <summary> /// Maintains metadata about <see cref="RegisterDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> RegisterDateProperty = RegisterProperty<SmartDate>(p => p.RegisterDate, "Register Date"); /// <summary> /// Gets the Register Date. /// </summary> /// <value>The Register Date.</value> public string RegisterDate { get { return GetPropertyConvert<SmartDate, string>(RegisterDateProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentType"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentTypeProperty = RegisterProperty<string>(p => p.DocumentType, "Document Type"); /// <summary> /// Gets the Document Type. /// </summary> /// <value>The Document Type.</value> public string DocumentType { get { return GetProperty(DocumentTypeProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentReference"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentReferenceProperty = RegisterProperty<string>(p => p.DocumentReference, "Document Reference"); /// <summary> /// Gets the Document Reference. /// </summary> /// <value>The Document Reference.</value> public string DocumentReference { get { return GetProperty(DocumentReferenceProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentEntity"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentEntityProperty = RegisterProperty<string>(p => p.DocumentEntity, "Document Entity"); /// <summary> /// Gets the Document Entity. /// </summary> /// <value>The Document Entity.</value> public string DocumentEntity { get { return GetProperty(DocumentEntityProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDept"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentDeptProperty = RegisterProperty<string>(p => p.DocumentDept, "Document Dept"); /// <summary> /// Gets the Document Dept. /// </summary> /// <value>The Document Dept.</value> public string DocumentDept { get { return GetProperty(DocumentDeptProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentClass"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentClassProperty = RegisterProperty<string>(p => p.DocumentClass, "Document Class"); /// <summary> /// Gets the Document Class. /// </summary> /// <value>The Document Class.</value> public string DocumentClass { get { return GetProperty(DocumentClassProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> DocumentDateProperty = RegisterProperty<SmartDate>(p => p.DocumentDate, "Document Date"); /// <summary> /// Gets the Document Date. /// </summary> /// <value>The Document Date.</value> public string DocumentDate { get { return GetPropertyConvert<SmartDate, string>(DocumentDateProperty); } } /// <summary> /// Maintains metadata about <see cref="Subject"/> property. /// </summary> public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject"); /// <summary> /// Gets the Subject. /// </summary> /// <value>The Subject.</value> public string Subject { get { return GetProperty(SubjectProperty); } } /// <summary> /// Maintains metadata about <see cref="SenderName"/> property. /// </summary> public static readonly PropertyInfo<string> SenderNameProperty = RegisterProperty<string>(p => p.SenderName, "Sender Name"); /// <summary> /// Gets the Sender Name. /// </summary> /// <value>The Sender Name.</value> public string SenderName { get { return GetProperty(SenderNameProperty); } } /// <summary> /// Maintains metadata about <see cref="ReceptionDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ReceptionDateProperty = RegisterProperty<SmartDate>(p => p.ReceptionDate, "Reception Date"); /// <summary> /// Gets the Reception Date. /// </summary> /// <value>The Reception Date.</value> public string ReceptionDate { get { return GetPropertyConvert<SmartDate, string>(ReceptionDateProperty); } } /// <summary> /// Maintains metadata about <see cref="RoutedTo"/> property. /// </summary> public static readonly PropertyInfo<string> RoutedToProperty = RegisterProperty<string>(p => p.RoutedTo, "Routed To"); /// <summary> /// Gets the Routed To. /// </summary> /// <value>The Routed To.</value> public string RoutedTo { get { return GetProperty(RoutedToProperty); } } /// <summary> /// Maintains metadata about <see cref="Notes"/> property. /// </summary> public static readonly PropertyInfo<string> NotesProperty = RegisterProperty<string>(p => p.Notes, "Notes"); /// <summary> /// Gets the Notes. /// </summary> /// <value>The Notes.</value> public string Notes { get { return GetProperty(NotesProperty); } } /// <summary> /// Maintains metadata about <see cref="ArchiveLocation"/> property. /// </summary> public static readonly PropertyInfo<string> ArchiveLocationProperty = RegisterProperty<string>(p => p.ArchiveLocation, "Archive Location"); /// <summary> /// Gets the Archive Location. /// </summary> /// <value>The Archive Location.</value> public string ArchiveLocation { get { return GetProperty(ArchiveLocationProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="IncomingInfo"/> object from the given IncomingInfoDto. /// </summary> /// <param name="data">The <see cref="IncomingInfoDto"/>.</param> /// <returns>A reference to the fetched <see cref="IncomingInfo"/> object.</returns> internal static IncomingInfo GetIncomingInfo(IncomingInfoDto data) { IncomingInfo obj = new IncomingInfo(); obj.Fetch(data); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="IncomingInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public IncomingInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="IncomingInfo"/> object from the given <see cref="IncomingInfoDto"/>. /// </summary> /// <param name="data">The IncomingInfoDto to use.</param> private void Fetch(IncomingInfoDto data) { // Value properties LoadProperty(RegisterIdProperty, data.RegisterId); LoadProperty(RegisterDateProperty, data.RegisterDate); LoadProperty(DocumentTypeProperty, data.DocumentType); LoadProperty(DocumentReferenceProperty, data.DocumentReference); LoadProperty(DocumentEntityProperty, data.DocumentEntity); LoadProperty(DocumentDeptProperty, data.DocumentDept); LoadProperty(DocumentClassProperty, data.DocumentClass); LoadProperty(DocumentDateProperty, data.DocumentDate); LoadProperty(SubjectProperty, data.Subject); LoadProperty(SenderNameProperty, data.SenderName); LoadProperty(ReceptionDateProperty, data.ReceptionDate); LoadProperty(RoutedToProperty, data.RoutedTo); LoadProperty(NotesProperty, data.Notes); LoadProperty(ArchiveLocationProperty, data.ArchiveLocation); var args = new DataPortalHookArgs(data); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="KeywordPlanAdGroupServiceClient"/> instances.</summary> public sealed partial class KeywordPlanAdGroupServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="KeywordPlanAdGroupServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="KeywordPlanAdGroupServiceSettings"/>.</returns> public static KeywordPlanAdGroupServiceSettings GetDefault() => new KeywordPlanAdGroupServiceSettings(); /// <summary> /// Constructs a new <see cref="KeywordPlanAdGroupServiceSettings"/> object with default settings. /// </summary> public KeywordPlanAdGroupServiceSettings() { } private KeywordPlanAdGroupServiceSettings(KeywordPlanAdGroupServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateKeywordPlanAdGroupsSettings = existing.MutateKeywordPlanAdGroupsSettings; OnCopy(existing); } partial void OnCopy(KeywordPlanAdGroupServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanAdGroupServiceClient.MutateKeywordPlanAdGroups</c> and /// <c>KeywordPlanAdGroupServiceClient.MutateKeywordPlanAdGroupsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateKeywordPlanAdGroupsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="KeywordPlanAdGroupServiceSettings"/> object.</returns> public KeywordPlanAdGroupServiceSettings Clone() => new KeywordPlanAdGroupServiceSettings(this); } /// <summary> /// Builder class for <see cref="KeywordPlanAdGroupServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class KeywordPlanAdGroupServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanAdGroupServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public KeywordPlanAdGroupServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public KeywordPlanAdGroupServiceClientBuilder() { UseJwtAccessWithScopes = KeywordPlanAdGroupServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref KeywordPlanAdGroupServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanAdGroupServiceClient> task); /// <summary>Builds the resulting client.</summary> public override KeywordPlanAdGroupServiceClient Build() { KeywordPlanAdGroupServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<KeywordPlanAdGroupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<KeywordPlanAdGroupServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private KeywordPlanAdGroupServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return KeywordPlanAdGroupServiceClient.Create(callInvoker, Settings); } private async stt::Task<KeywordPlanAdGroupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return KeywordPlanAdGroupServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => KeywordPlanAdGroupServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanAdGroupServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanAdGroupServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>KeywordPlanAdGroupService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad groups. /// </remarks> public abstract partial class KeywordPlanAdGroupServiceClient { /// <summary> /// The default endpoint for the KeywordPlanAdGroupService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default KeywordPlanAdGroupService scopes.</summary> /// <remarks> /// The default KeywordPlanAdGroupService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="KeywordPlanAdGroupServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns> public static stt::Task<KeywordPlanAdGroupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new KeywordPlanAdGroupServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="KeywordPlanAdGroupServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns> public static KeywordPlanAdGroupServiceClient Create() => new KeywordPlanAdGroupServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="KeywordPlanAdGroupServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="KeywordPlanAdGroupServiceSettings"/>.</param> /// <returns>The created <see cref="KeywordPlanAdGroupServiceClient"/>.</returns> internal static KeywordPlanAdGroupServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanAdGroupServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient = new KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient(callInvoker); return new KeywordPlanAdGroupServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC KeywordPlanAdGroupService client</summary> public virtual KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad groups are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad groups. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroups(new MutateKeywordPlanAdGroupsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad groups are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad groups. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroupsAsync(new MutateKeywordPlanAdGroupsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad groups are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad groups. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupOperation> operations, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>KeywordPlanAdGroupService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad groups. /// </remarks> public sealed partial class KeywordPlanAdGroupServiceClientImpl : KeywordPlanAdGroupServiceClient { private readonly gaxgrpc::ApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse> _callMutateKeywordPlanAdGroups; /// <summary> /// Constructs a client wrapper for the KeywordPlanAdGroupService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="KeywordPlanAdGroupServiceSettings"/> used within this client. /// </param> public KeywordPlanAdGroupServiceClientImpl(KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient, KeywordPlanAdGroupServiceSettings settings) { GrpcClient = grpcClient; KeywordPlanAdGroupServiceSettings effectiveSettings = settings ?? KeywordPlanAdGroupServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateKeywordPlanAdGroups = clientHelper.BuildApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse>(grpcClient.MutateKeywordPlanAdGroupsAsync, grpcClient.MutateKeywordPlanAdGroups, effectiveSettings.MutateKeywordPlanAdGroupsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateKeywordPlanAdGroups); Modify_MutateKeywordPlanAdGroupsApiCall(ref _callMutateKeywordPlanAdGroups); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateKeywordPlanAdGroupsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanAdGroupsRequest, MutateKeywordPlanAdGroupsResponse> call); partial void OnConstruction(KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient grpcClient, KeywordPlanAdGroupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC KeywordPlanAdGroupService client</summary> public override KeywordPlanAdGroupService.KeywordPlanAdGroupServiceClient GrpcClient { get; } partial void Modify_MutateKeywordPlanAdGroupsRequest(ref MutateKeywordPlanAdGroupsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateKeywordPlanAdGroupsResponse MutateKeywordPlanAdGroups(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroups.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad groups. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupError]() /// [KeywordPlanError]() /// [MutateError]() /// [NewResourceCreationError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateKeywordPlanAdGroupsResponse> MutateKeywordPlanAdGroupsAsync(MutateKeywordPlanAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroups.Async(request, callSettings); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Mocks; using TestUtilities.Python; namespace PythonToolsTests { [TestClass] public class ProjectUpgradeTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } [TestMethod, Priority(1)] public void UpgradeCheckToolsVersion() { var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "NoToolsVersion.pyproj", Expected = 1 }, new { Name = "OldToolsVersion.pyproj", Expected = 1 }, new { Name = "CorrectToolsVersion.pyproj", Expected = 0 }, new { Name = "NewerToolsVersion.pyproj", Expected = 0 } }) { int actual; Guid factoryGuid; uint flags; var hr = upgrade.UpgradeProject_CheckOnly( TestData.GetPath(Path.Combine("TestData", "ProjectUpgrade", testCase.Name)), null, out actual, out factoryGuid, out flags ); Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); Assert.AreEqual(Guid.Empty, factoryGuid); } } [TestMethod, Priority(1)] public void UpgradeToolsVersion() { var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "NoToolsVersion.pyproj", Expected = 1 }, new { Name = "OldToolsVersion.pyproj", Expected = 1 }, new { Name = "CorrectToolsVersion.pyproj", Expected = 0 }, new { Name = "NewerToolsVersion.pyproj", Expected = 0 } }) { int actual; Guid factoryGuid; string newLocation; // Use a copy of the project so we don't interfere with other // tests using them. var origProject = Path.Combine("TestData", "ProjectUpgrade", testCase.Name); var tempProject = Path.Combine(TestData.GetTempPath("ProjectUpgrade", true), testCase.Name); File.Copy(origProject, tempProject); var hr = upgrade.UpgradeProject( tempProject, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); Assert.AreEqual(tempProject, newLocation, string.Format("Wrong location for {0}", testCase.Name)); if (testCase.Expected != 0) { Assert.IsTrue( File.ReadAllText(tempProject).Contains("ToolsVersion=\"4.0\""), string.Format("Upgraded {0} did not contain ToolsVersion=\"4.0\"", testCase.Name) ); } else { Assert.IsTrue( File.ReadAllText(tempProject) == File.ReadAllText(origProject), string.Format("Non-upgraded {0} has different content to original", testCase.Name) ); } Assert.AreEqual(Guid.Empty, factoryGuid); } } [TestMethod, Priority(1)] public void UpgradeCheckUserToolsVersion() { var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var projectFile = TestData.GetPath(Path.Combine("TestData", "ProjectUpgrade", "CorrectToolsVersion.pyproj")); var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "12.0", Expected = 0 }, new { Name = "4.0", Expected = 0 } }) { int actual; int hr; Guid factoryGuid; uint flags; var xml = Microsoft.Build.Construction.ProjectRootElement.Create(); xml.ToolsVersion = testCase.Name; xml.Save(projectFile + ".user"); try { hr = upgrade.UpgradeProject_CheckOnly( projectFile, null, out actual, out factoryGuid, out flags ); } finally { File.Delete(projectFile + ".user"); } Assert.AreEqual(0, hr, string.Format("Wrong HR for ToolsVersion={0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for ToolsVersion={0}", testCase.Name)); Assert.AreEqual(Guid.Empty, factoryGuid); } } [TestMethod, Priority(1)] public void OldWebProjectUpgrade() { // PTVS 2.1 Beta 1 shipped with separate .targets files for Bottle // and Flask. In PTVS 2.1 Beta 2 these were removed. This test // ensures that we upgrade projects created in 2.1 Beta 1. var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "OldBottleProject.pyproj", Expected = 1 }, new { Name = "OldFlaskProject.pyproj", Expected = 1 } }) { int actual; Guid factoryGuid; string newLocation; // Use a copy of the project so we don't interfere with other // tests using them. var project = Path.Combine("TestData", "ProjectUpgrade", testCase.Name); using (FileUtils.Backup(project)) { var origText = File.ReadAllText(project); var hr = upgrade.UpgradeProject( project, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); Assert.AreEqual(project, newLocation, string.Format("Wrong location for {0}", testCase.Name)); var text = File.ReadAllText(project); if (testCase.Expected != 0) { Assert.IsFalse( text.Contains("<Import Project=\"$(VSToolsPath)"), string.Format("Upgraded {0} should not import from $(VSToolsPath)", testCase.Name) ); Assert.IsTrue( text.Contains("Microsoft.PythonTools.Web.targets"), string.Format("Upgraded {0} should import Web.targets", testCase.Name) ); Assert.IsTrue( text.Contains("<PythonWsgiHandler>"), string.Format("Upgraded {0} should contain <PythonWsgiHandler>", testCase.Name) ); } else { Assert.IsTrue( text == origText, string.Format("Non-upgraded {0} has different content to original", testCase.Name) ); } Assert.AreEqual(Guid.Empty, factoryGuid); } } } [TestMethod, Priority(1)] public void CommonPropsProjectUpgrade() { var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; var project = TestData.GetPath("TestData\\ProjectUpgrade\\OldCommonProps.pyproj"); using (FileUtils.Backup(project)) { int actual; Guid factoryGuid; string newLocation; var hr = upgrade.UpgradeProject( project, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for OldCommonProps.pyproj")); Assert.AreEqual(1, actual, string.Format("Wrong result for OldCommonProps.pyproj")); Assert.AreEqual(project, newLocation, string.Format("Wrong location for OldCommonProps.pyproj")); Assert.IsFalse( File.ReadAllText(project).Contains("<Import Project=\"" + PythonProjectFactory.CommonProps), string.Format("Upgraded OldCommonProps.pyproj should not import from $(VSToolsPath)") ); Assert.AreEqual(Guid.Empty, factoryGuid); } } [TestMethod, Priority(1)] public void CommonTargetsProjectUpgrade() { var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; var project = TestData.GetPath("TestData\\ProjectUpgrade\\OldCommonTargets.pyproj"); using (FileUtils.Backup(project)) { int actual; Guid factoryGuid; string newLocation; var hr = upgrade.UpgradeProject( project, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for OldCommonTargets.pyproj")); Assert.AreEqual(1, actual, string.Format("Wrong result for OldCommonTargets.pyproj")); Assert.AreEqual(project, newLocation, string.Format("Wrong location for OldCommonTargets.pyproj")); var text = File.ReadAllText(project); Assert.IsTrue( text.Contains("<Import Project=\"" + PythonProjectFactory.CommonTargets + "\" Condition=\"!Exists($(PtvsTargetsFile)"), string.Format("Upgraded OldCommonTargets.pyproj should conditionally import from $(VSToolsPath)") ); Assert.IsTrue( text.Contains("<VisualStudioVersion"), string.Format("Upgraded OldCommonTargets.pyproj should define $(VisualStudioVersion)") ); Assert.IsTrue( text.Contains("<PtvsTargetsFile>" + PythonProjectFactory.PtvsTargets), string.Format("Upgraded OldCommonTargets.pyproj should define $(PtvsTargetsFile)") ); Assert.IsTrue( text.Contains("<Import Project=\"$(PtvsTargetsFile)\" Condition=\"Exists($(PtvsTargetsFile))\""), string.Format("Upgraded OldCommonTargets.pyproj should import $(PtvsTargetsFile)") ); Assert.AreEqual(Guid.Empty, factoryGuid); } } [TestMethod, Priority(1)] public void WebProjectCompatibility() { const int ExpressSkuValue = 500; const int ShellSkuValue = 1000; const int ProSkuValue = 2000; const int PremiumUltimateSkuValue = 3000; const int VWDExpressSkuValue = 0x0040; const int WDExpressSkuValue = 0x8000; const int PremiumSubSkuValue = 0x0080; const int UltimateSubSkuValue = 0x0188; const uint Compatible = (uint)0; const uint Incompatible = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_INCOMPATIBLE; var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); var shell = new MockVsShell(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); sp.Services[typeof(SVsShell).GUID] = shell; factory.Site = sp; var projectFile = TestData.GetPath(Path.Combine("TestData", "ProjectUpgrade", "WebProjectType.pyproj")); var upgrade = (IVsProjectUpgradeViaFactory4)factory; foreach (var testCase in new[] { new { Name = "Ultimate", Sku1 = PremiumUltimateSkuValue, Sku2 = UltimateSubSkuValue, Expected = Compatible }, new { Name = "Premium", Sku1 = PremiumUltimateSkuValue, Sku2 = PremiumSubSkuValue, Expected = Compatible }, new { Name = "Professional", Sku1 = ProSkuValue, Sku2 = 0, Expected = Compatible }, new { Name = "VWDExpress", Sku1 = ExpressSkuValue, Sku2 = VWDExpressSkuValue, Expected = Compatible }, new { Name = "WDExpress", Sku1 = ExpressSkuValue, Sku2 = WDExpressSkuValue, Expected = Incompatible }, new { Name = "Shell", Sku1 = ShellSkuValue, Sku2 = 0, Expected = Incompatible } }) { uint actual; Guid factoryGuid; uint flags; // Change the SKU for each test case. shell.Properties[(int)__VSSPROPID2.VSSPROPID_SKUEdition] = testCase.Sku1; shell.Properties[(int)__VSSPROPID2.VSSPROPID_SubSKUEdition] = testCase.Sku2; upgrade.UpgradeProject_CheckOnly( projectFile, null, out actual, out factoryGuid, out flags ); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); } } [TestMethod, Priority(1)] public void InterpreterIdUpgrade() { // PTVS 3.0 changed interpreter ID format. var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "CPythonInterpreterId.pyproj", Expected = 1, Id = "Global|PythonCore|2.7|x86" }, new { Name = "CPython35InterpreterId.pyproj", Expected = 1, Id = "Global|PythonCore|3.5-32|x86" }, new { Name = "CPythonx64InterpreterId.pyproj", Expected = 1, Id = "Global|PythonCore|3.5|x64" }, new { Name = "MSBuildInterpreterId.pyproj", Expected = 1, Id = "MSBuild|env|$(MSBuildProjectFullPath)" }, new { Name = "IronPythonInterpreterId.pyproj", Expected = 1, Id = "IronPython|2.7-32" }, }) { int actual; Guid factoryGuid; string newLocation; var project = TestData.GetPath("TestData\\ProjectUpgrade\\" + testCase.Name); using (FileUtils.Backup(project)) { var hr = upgrade.UpgradeProject( project, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); Assert.AreEqual(project, newLocation, string.Format("Wrong location for {0}", testCase.Name)); AssertUtil.Contains( File.ReadAllText(project), "<InterpreterId>{0}</InterpreterId>".FormatInvariant(testCase.Id) ); Assert.AreEqual(Guid.Empty, factoryGuid); } } } [TestMethod, Priority(1)] public void InterpreterReferenceUpgrade() { // PTVS 3.0 changed interpreter ID format. var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "CPythonInterpreterReference.pyproj", Expected = 1, Id = "Global|PythonCore|3.5-32|x86" }, new { Name = "IronPythonInterpreterReference.pyproj", Expected = 1, Id = "IronPython|2.7-32" }, }) { int actual; Guid factoryGuid; string newLocation; var project = TestData.GetPath("TestData\\ProjectUpgrade\\" + testCase.Name); using (FileUtils.Backup(project)) { var hr = upgrade.UpgradeProject( project, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); Assert.AreEqual(project, newLocation, string.Format("Wrong location for {0}", testCase.Name)); AssertUtil.Contains( File.ReadAllText(project), "<InterpreterReference Include=\"{0}\" />".FormatInvariant(testCase.Id) ); Assert.AreEqual(Guid.Empty, factoryGuid); } } } [TestMethod, Priority(1)] public void BaseInterpreterUpgrade() { // PTVS 3.0 changed interpreter ID format. var factory = new PythonProjectFactory(null); var sp = new MockServiceProvider(); sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null; sp.Services[typeof(SVsActivityLog).GUID] = new MockActivityLog(); factory.Site = sp; var upgrade = (IVsProjectUpgradeViaFactory)factory; foreach (var testCase in new[] { new { Name = "CPythonBaseInterpreter.pyproj", Expected = 1, Id = "Global|PythonCore|3.4|x86" }, }) { int actual; Guid factoryGuid; string newLocation; var project = TestData.GetPath("TestData\\ProjectUpgrade\\" + testCase.Name); using (FileUtils.Backup(project)) { var hr = upgrade.UpgradeProject( project, 0u, // no backups null, out newLocation, null, out actual, out factoryGuid ); Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name)); Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name)); Assert.AreEqual(project, newLocation, string.Format("Wrong location for {0}", testCase.Name)); AssertUtil.Contains( File.ReadAllText(project), "<BaseInterpreter>{0}</BaseInterpreter>".FormatInvariant(testCase.Id) ); Assert.AreEqual(Guid.Empty, factoryGuid); } } } } }
// Copyright (c) 2018 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Runtime.InteropServices; namespace Icu { internal static partial class NativeMethods { private class ResourceBundleMethodsContainer { [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_openDelegate(string packageName, string locale, out ErrorCode status); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void ures_closeDelegate(IntPtr resourceBundle); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_getKeyDelegate(IntPtr resourceBundle); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)] internal delegate IntPtr ures_getStringDelegate(IntPtr resourceBundle, out int len, out ErrorCode status); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_getLocaleDelegate(IntPtr resourceBundle, out ErrorCode status); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_getByKeyDelegate(IntPtr resourceBundle, string key, IntPtr fillIn, out ErrorCode status); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_getStringByKeyDelegate(IntPtr resourceBundle, string key, out int len, out ErrorCode status); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate void ures_resetIteratorDelegate(IntPtr resourceBundle); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_getNextStringDelegate(IntPtr resourceBundle, out int len, out IntPtr key, out ErrorCode status); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool ures_hasNextDelegate(IntPtr resourceBundle); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr ures_getNextResourceDelegate(IntPtr resourceBundle, IntPtr fillIn, out ErrorCode status); internal ures_openDelegate ures_open; internal ures_closeDelegate ures_close; internal ures_getKeyDelegate ures_getKey; internal ures_getStringDelegate ures_getString; internal ures_getLocaleDelegate ures_getLocale; internal ures_getByKeyDelegate ures_getByKey; internal ures_getStringByKeyDelegate ures_getStringByKey; internal ures_resetIteratorDelegate ures_resetIterator; internal ures_getNextStringDelegate ures_getNextString; internal ures_hasNextDelegate ures_hasNext; internal ures_getNextResourceDelegate ures_getNextResource; } private static ResourceBundleMethodsContainer _ResourceBundleMethods; private static ResourceBundleMethodsContainer ResourceBundleMethods => _ResourceBundleMethods ?? (_ResourceBundleMethods = new ResourceBundleMethodsContainer()); /// <summary/> public static IntPtr ures_open(string packageName, string locale, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_open == null) { ResourceBundleMethods.ures_open = GetMethod<ResourceBundleMethodsContainer.ures_openDelegate>( IcuCommonLibHandle, nameof(ures_open)); } return ResourceBundleMethods.ures_open(packageName, locale, out status); } /// <summary/> public static void ures_close(IntPtr resourceBundle) { if (ResourceBundleMethods.ures_close == null) { ResourceBundleMethods.ures_close = GetMethod<ResourceBundleMethodsContainer.ures_closeDelegate>( IcuCommonLibHandle, nameof(ures_close)); } ResourceBundleMethods.ures_close(resourceBundle); } /// <summary/> public static IntPtr ures_getKey(IntPtr resourceBundle) { if (ResourceBundleMethods.ures_getKey == null) { ResourceBundleMethods.ures_getKey = GetMethod<ResourceBundleMethodsContainer.ures_getKeyDelegate>( IcuCommonLibHandle, nameof(ures_getKey)); } return ResourceBundleMethods.ures_getKey(resourceBundle); } /// <summary/> public static IntPtr ures_getString(IntPtr resourceBundle, out int len, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_getString == null) { ResourceBundleMethods.ures_getString = GetMethod<ResourceBundleMethodsContainer.ures_getStringDelegate>( IcuCommonLibHandle, nameof(ures_getString)); } return ResourceBundleMethods.ures_getString(resourceBundle, out len, out status); } /// <summary/> public static IntPtr ures_getLocale(IntPtr resourceBundle, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_getLocale == null) { ResourceBundleMethods.ures_getLocale = GetMethod<ResourceBundleMethodsContainer.ures_getLocaleDelegate>( IcuCommonLibHandle, nameof(ures_getLocale)); } return ResourceBundleMethods.ures_getLocale(resourceBundle, out status); } /// <summary/> public static IntPtr ures_getByKey(IntPtr resourceBundle, string key, IntPtr fillIn, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_getByKey == null) { ResourceBundleMethods.ures_getByKey = GetMethod<ResourceBundleMethodsContainer.ures_getByKeyDelegate>( IcuCommonLibHandle, nameof(ures_getByKey)); } return ResourceBundleMethods.ures_getByKey(resourceBundle, key, fillIn, out status); } /// <summary/> public static IntPtr ures_getStringByKey(IntPtr resourceBundle, string key, out int len, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_getStringByKey == null) { ResourceBundleMethods.ures_getStringByKey = GetMethod<ResourceBundleMethodsContainer.ures_getStringByKeyDelegate>( IcuCommonLibHandle, nameof(ures_getStringByKey)); } return ResourceBundleMethods.ures_getStringByKey(resourceBundle, key, out len, out status); } /// <summary/> public static void ures_resetIterator(IntPtr resourceBundle) { if (ResourceBundleMethods.ures_resetIterator == null) { ResourceBundleMethods.ures_resetIterator = GetMethod<ResourceBundleMethodsContainer.ures_resetIteratorDelegate>( IcuCommonLibHandle, nameof(ures_resetIterator)); } ResourceBundleMethods.ures_resetIterator(resourceBundle); } /// <summary/> public static IntPtr ures_getNextString(IntPtr resourceBundle, out int len, out IntPtr key, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_getNextString == null) { ResourceBundleMethods.ures_getNextString = GetMethod<ResourceBundleMethodsContainer.ures_getNextStringDelegate>( IcuCommonLibHandle, nameof(ures_getNextString)); } return ResourceBundleMethods.ures_getNextString(resourceBundle, out len, out key, out status); } /// <summary/> public static IntPtr ures_getNextResource(IntPtr resourceBundle, IntPtr fillIn, out ErrorCode status) { status = ErrorCode.NoErrors; if (ResourceBundleMethods.ures_getNextResource == null) { ResourceBundleMethods.ures_getNextResource = GetMethod<ResourceBundleMethodsContainer.ures_getNextResourceDelegate>( IcuCommonLibHandle, nameof(ures_getNextResource)); } return ResourceBundleMethods.ures_getNextResource(resourceBundle, fillIn, out status); } /// <summary/> public static bool ures_hasNext(IntPtr resourceBundle) { if (ResourceBundleMethods.ures_hasNext == null) { ResourceBundleMethods.ures_hasNext = GetMethod<ResourceBundleMethodsContainer.ures_hasNextDelegate>( IcuCommonLibHandle, nameof(ures_hasNext)); } return ResourceBundleMethods.ures_hasNext(resourceBundle); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.ExpressRoute; using Microsoft.WindowsAzure.Management.ExpressRoute.Models; namespace Microsoft.WindowsAzure.Management.ExpressRoute { internal partial class DedicatedCircuitLinkAuthorizationOperations : IServiceOperations<ExpressRouteManagementClient>, Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitLinkAuthorizationOperations { /// <summary> /// Initializes a new instance of the /// DedicatedCircuitLinkAuthorizationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DedicatedCircuitLinkAuthorizationOperations(ExpressRouteManagementClient client) { this._client = client; } private ExpressRouteManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient. /// </summary> public ExpressRouteManagementClient Client { get { return this._client; } } /// <summary> /// The Remove Dedicated Circuit Link Authorization operation deletes /// an existing dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Required. Service key representing the dedicated circuit. /// </param> /// <param name='authId'> /// Required. The GUID representing the authorization /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, string authId, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (authId == null) { throw new ArgumentNullException("authId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("authId", authId); Tracing.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/authorizations/" + authId.Trim() + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the link authorization for the specified dedicated circuit. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='authId'> /// Required. The GUID representing the authorization /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get link authorization operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitLinkAuthorizationGetResponse> GetAsync(string serviceKey, string authId, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (authId == null) { throw new ArgumentNullException("authId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("authId", authId); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/authorizations/" + authId.Trim() + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkAuthorizationGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkAuthorizationGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinkAuthorizationElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinkAuthorizationElement != null) { AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization(); result.DedicatedCircuitLinkAuthorization = dedicatedCircuitLinkAuthorizationInstance; XElement descriptionElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance; } XElement limitElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure")); if (limitElement != null) { int limitInstance = int.Parse(limitElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance; } XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure")); if (linkAuthorizationIdElement != null) { string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value; dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance; } XElement microsoftIdsElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure")); if (microsoftIdsElement != null) { string microsoftIdsInstance = microsoftIdsElement.Value; dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance; } XElement usedElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure")); if (usedElement != null) { int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the specified link authorization for the specified dedicated /// circuit. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List link authorization operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitLinkAuthorizationListResponse> ListAsync(string serviceKey, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/authorizations?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkAuthorizationListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkAuthorizationListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinkAuthorizationsSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorizations", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinkAuthorizationsSequenceElement != null) { foreach (XElement dedicatedCircuitLinkAuthorizationsElement in dedicatedCircuitLinkAuthorizationsSequenceElement.Elements(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure"))) { AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization(); result.DedicatedCircuitLinkAuthorizations.Add(dedicatedCircuitLinkAuthorizationInstance); XElement descriptionElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance; } XElement limitElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure")); if (limitElement != null) { int limitInstance = int.Parse(limitElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance; } XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure")); if (linkAuthorizationIdElement != null) { string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value; dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance; } XElement microsoftIdsElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure")); if (microsoftIdsElement != null) { string microsoftIdsInstance = microsoftIdsElement.Value; dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance; } XElement usedElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure")); if (usedElement != null) { int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the specified link authorization for the specified dedicated /// circuit. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the new Dedicated Circuit link /// authorization operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get link authorization operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitLinkAuthorizationNewResponse> NewAsync(string serviceKey, DedicatedCircuitLinkAuthorizationNewParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "NewAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/authorizations?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement createDedicatedCircuitLinkAuthorizationElement = new XElement(XName.Get("CreateDedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(createDedicatedCircuitLinkAuthorizationElement); if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; createDedicatedCircuitLinkAuthorizationElement.Add(descriptionElement); } XElement limitElement = new XElement(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure")); limitElement.Value = parameters.Limit.ToString(); createDedicatedCircuitLinkAuthorizationElement.Add(limitElement); if (parameters.MicrosoftIds != null) { XElement microsoftIdsElement = new XElement(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure")); microsoftIdsElement.Value = parameters.MicrosoftIds; createDedicatedCircuitLinkAuthorizationElement.Add(microsoftIdsElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkAuthorizationNewResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkAuthorizationNewResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinkAuthorizationElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinkAuthorizationElement != null) { AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization(); result.DedicatedCircuitLinkAuthorization = dedicatedCircuitLinkAuthorizationInstance; XElement descriptionElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement2 != null) { string descriptionInstance = descriptionElement2.Value; dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance; } XElement limitElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure")); if (limitElement2 != null) { int limitInstance = int.Parse(limitElement2.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance; } XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure")); if (linkAuthorizationIdElement != null) { string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value; dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance; } XElement microsoftIdsElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure")); if (microsoftIdsElement2 != null) { string microsoftIdsInstance = microsoftIdsElement2.Value; dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance; } XElement usedElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure")); if (usedElement != null) { int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Remove Dedicated Circuit Link Authorization operation deletes /// an existing dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Required. Service Key associated with the dedicated circuit. /// </param> /// <param name='authId'> /// Required. The GUID representing the authorization /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, string authId, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (authId == null) { throw new ArgumentNullException("authId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("authId", authId); Tracing.Enter(invocationId, this, "RemoveAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/authorizations/" + authId.Trim() + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode >= HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationStatusResponse result = null; result = new ExpressRouteOperationStatusResponse(); result.StatusCode = statusCode; if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates the specified link authorization for the specified /// dedicated circuit. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='authId'> /// Required. The GUID representing the authorization /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Dedicated Circuit link /// authorization operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Update link authorization operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitLinkAuthorizationUpdateResponse> UpdateAsync(string serviceKey, string authId, DedicatedCircuitLinkAuthorizationUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (authId == null) { throw new ArgumentNullException("authId"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("authId", authId); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/authorizations/" + authId.Trim() + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement updateDedicatedCircuitLinkAuthorizationElement = new XElement(XName.Get("UpdateDedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(updateDedicatedCircuitLinkAuthorizationElement); if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; updateDedicatedCircuitLinkAuthorizationElement.Add(descriptionElement); } XElement limitElement = new XElement(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure")); limitElement.Value = parameters.Limit.ToString(); updateDedicatedCircuitLinkAuthorizationElement.Add(limitElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkAuthorizationUpdateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkAuthorizationUpdateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinkAuthorizationElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinkAuthorizationElement != null) { AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization(); result.DedicatedCircuitLinkAuthorization = dedicatedCircuitLinkAuthorizationInstance; XElement descriptionElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement2 != null) { string descriptionInstance = descriptionElement2.Value; dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance; } XElement limitElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure")); if (limitElement2 != null) { int limitInstance = int.Parse(limitElement2.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance; } XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure")); if (linkAuthorizationIdElement != null) { string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value; dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance; } XElement microsoftIdsElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure")); if (microsoftIdsElement != null) { string microsoftIdsInstance = microsoftIdsElement.Value; dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance; } XElement usedElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure")); if (usedElement != null) { int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using Azure; using Management; using Network; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// A common class for general resource information /// </summary> [JsonTransformation] public partial class VirtualNetworkGateway : Resource { /// <summary> /// Initializes a new instance of the VirtualNetworkGateway class. /// </summary> public VirtualNetworkGateway() { } /// <summary> /// Initializes a new instance of the VirtualNetworkGateway class. /// </summary> /// <param name="ipConfigurations">IP configurations for virtual /// network gateway.</param> /// <param name="gatewayType">The type of this virtual network gateway. /// Possible values are: 'Vpn' and 'ExpressRoute'. Possible values /// include: 'Vpn', 'ExpressRoute'</param> /// <param name="vpnType">The type of this virtual network gateway. /// Possible values are: 'PolicyBased' and 'RouteBased'. Possible /// values include: 'PolicyBased', 'RouteBased'</param> /// <param name="id">Resource ID.</param> /// <param name="name">Resource name.</param> /// <param name="type">Resource type.</param> /// <param name="location">Resource location.</param> /// <param name="tags">Resource tags.</param> /// <param name="enableBgp">Whether BGP is enabled for this virtual /// network gateway or not.</param> /// <param name="activeActive">ActiveActive flag</param> /// <param name="gatewayDefaultSite">The reference of the /// LocalNetworkGateway resource which represents local network site /// having default routes. Assign Null value in case of removing /// existing default site setting.</param> /// <param name="sku">The reference of the VirtualNetworkGatewaySku /// resource which represents the SKU selected for Virtual network /// gateway.</param> /// <param name="vpnClientConfiguration">The reference of the /// VpnClientConfiguration resource which represents the P2S VpnClient /// configurations.</param> /// <param name="bgpSettings">Virtual network gateway's BGP speaker /// settings.</param> /// <param name="resourceGuid">The resource GUID property of the /// VirtualNetworkGateway resource.</param> /// <param name="provisioningState">The provisioning state of the /// VirtualNetworkGateway resource. Possible values are: 'Updating', /// 'Deleting', and 'Failed'.</param> /// <param name="etag">Gets a unique read-only string that changes /// whenever the resource is updated.</param> public VirtualNetworkGateway(IList<VirtualNetworkGatewayIPConfiguration> ipConfigurations, string gatewayType, string vpnType, string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), bool? enableBgp = default(bool?), bool? activeActive = default(bool?), SubResource gatewayDefaultSite = default(SubResource), VirtualNetworkGatewaySku sku = default(VirtualNetworkGatewaySku), VpnClientConfiguration vpnClientConfiguration = default(VpnClientConfiguration), BgpSettings bgpSettings = default(BgpSettings), string resourceGuid = default(string), string provisioningState = default(string), string etag = default(string)) : base(id, name, type, location, tags) { IpConfigurations = ipConfigurations; GatewayType = gatewayType; VpnType = vpnType; EnableBgp = enableBgp; ActiveActive = activeActive; GatewayDefaultSite = gatewayDefaultSite; Sku = sku; VpnClientConfiguration = vpnClientConfiguration; BgpSettings = bgpSettings; ResourceGuid = resourceGuid; ProvisioningState = provisioningState; Etag = etag; } /// <summary> /// Gets or sets IP configurations for virtual network gateway. /// </summary> [JsonProperty(PropertyName = "properties.ipConfigurations")] public IList<VirtualNetworkGatewayIPConfiguration> IpConfigurations { get; set; } /// <summary> /// Gets or sets the type of this virtual network gateway. Possible /// values are: 'Vpn' and 'ExpressRoute'. Possible values include: /// 'Vpn', 'ExpressRoute' /// </summary> [JsonProperty(PropertyName = "properties.gatewayType")] public string GatewayType { get; set; } /// <summary> /// Gets or sets the type of this virtual network gateway. Possible /// values are: 'PolicyBased' and 'RouteBased'. Possible values /// include: 'PolicyBased', 'RouteBased' /// </summary> [JsonProperty(PropertyName = "properties.vpnType")] public string VpnType { get; set; } /// <summary> /// Gets or sets whether BGP is enabled for this virtual network /// gateway or not. /// </summary> [JsonProperty(PropertyName = "properties.enableBgp")] public bool? EnableBgp { get; set; } /// <summary> /// Gets or sets activeActive flag /// </summary> [JsonProperty(PropertyName = "properties.activeActive")] public bool? ActiveActive { get; set; } /// <summary> /// Gets or sets the reference of the LocalNetworkGateway resource /// which represents local network site having default routes. Assign /// Null value in case of removing existing default site setting. /// </summary> [JsonProperty(PropertyName = "properties.gatewayDefaultSite")] public SubResource GatewayDefaultSite { get; set; } /// <summary> /// Gets or sets the reference of the VirtualNetworkGatewaySku resource /// which represents the SKU selected for Virtual network gateway. /// </summary> [JsonProperty(PropertyName = "properties.sku")] public VirtualNetworkGatewaySku Sku { get; set; } /// <summary> /// Gets or sets the reference of the VpnClientConfiguration resource /// which represents the P2S VpnClient configurations. /// </summary> [JsonProperty(PropertyName = "properties.vpnClientConfiguration")] public VpnClientConfiguration VpnClientConfiguration { get; set; } /// <summary> /// Gets or sets virtual network gateway's BGP speaker settings. /// </summary> [JsonProperty(PropertyName = "properties.bgpSettings")] public BgpSettings BgpSettings { get; set; } /// <summary> /// Gets or sets the resource GUID property of the /// VirtualNetworkGateway resource. /// </summary> [JsonProperty(PropertyName = "properties.resourceGuid")] public string ResourceGuid { get; set; } /// <summary> /// Gets the provisioning state of the VirtualNetworkGateway resource. /// Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; protected set; } /// <summary> /// Gets a unique read-only string that changes whenever the resource /// is updated. /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (IpConfigurations == null) { throw new ValidationException(ValidationRules.CannotBeNull, "IpConfigurations"); } if (GatewayType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "GatewayType"); } if (VpnType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "VpnType"); } if (IpConfigurations != null) { foreach (var element in IpConfigurations) { if (element != null) { element.Validate(); } } } if (Sku != null) { Sku.Validate(); } } } }
using System; using System.Data; using System.Data.OleDb; namespace PCSUtils.Utils { /// <summary> /// This class for excel data reader /// </summary> public class ExcelReader : IDisposable { #region Variables private int[] _PKCol; private string _strExcelFilename; private bool _blnMixedData=true; private bool _blnHeaders=false; private string _strSheetName; private string _strSheetRange; private bool _blnKeepConnectionOpen=false; private OleDbConnection _oleConn; private OleDbCommand _oleCmdSelect; private OleDbCommand _oleCmdUpdate; #endregion #region properties public int[] PKCols { get {return _PKCol;} set {_PKCol=value;} } public string ColName(int intCol) { string sColName=""; if (intCol<26) sColName= Convert.ToString(Convert.ToChar((Convert.ToByte((char) 'A')+intCol)) ); else { int intFirst = ((int) intCol / 26); int intSecond = ((int) intCol % 26); sColName= Convert.ToString(Convert.ToByte((char) 'A')+intFirst); sColName += Convert.ToString(Convert.ToByte((char) 'A')+intSecond); } return sColName; } public int ColNumber(string strCol) { strCol = strCol.ToUpper(); int intColNumber=0; if (strCol.Length>1) { intColNumber = Convert.ToInt16(Convert.ToByte(strCol[1])-65); intColNumber += Convert.ToInt16(Convert.ToByte(strCol[1])-64)*26; } else intColNumber = Convert.ToInt16(Convert.ToByte(strCol[0])-65); return intColNumber; } public String[] GetExcelSheetNames() { System.Data.DataTable dt = null; try { if (_oleConn ==null) Open(); // Get the data table containing the schema dt = _oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if(dt == null) { return null; } String[] excelSheets = new String[dt.Rows.Count]; int i = 0; // Add the sheet name to the string array. foreach(DataRow row in dt.Rows) { string strSheetTableName = row["TABLE_NAME"].ToString(); strSheetTableName = strSheetTableName.Replace("'", string.Empty); excelSheets[i] = strSheetTableName.Substring(0,strSheetTableName.Length-1); i++; } return excelSheets; } catch(Exception) { return null; } finally { // Clean up. if(this.KeepConnectionOpen==false) { this.Close(); } if(dt != null) { dt.Dispose(); dt=null; } } } public string ExcelFilename { get { return _strExcelFilename;} set { _strExcelFilename=value;} } public string SheetName { get { return _strSheetName;} set { _strSheetName=value;} } public string SheetRange { get {return _strSheetRange;} set { if (value.IndexOf(":")==-1) throw new Exception("Invalid range length"); _strSheetRange=value;} } public bool KeepConnectionOpen { get { return _blnKeepConnectionOpen;} set {_blnKeepConnectionOpen=value;} } public bool Headers { get { return _blnHeaders;} set { _blnHeaders=value;} } public bool MixedData { get {return _blnMixedData;} set {_blnMixedData=value;} } #endregion #region Methods #region Excel Connection private string ExcelConnectionOptions() { string strOpts=""; if (this.MixedData ==true) strOpts += "Imex=2;"; if (this.Headers==true) strOpts += "HDR=Yes;"; else strOpts += "HDR=No;"; return strOpts; } private string ExcelConnection() { return @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + _strExcelFilename + ";" + @"Extended Properties=" + Convert.ToChar(34).ToString() + @"Excel 8.0;"+ ExcelConnectionOptions() + Convert.ToChar(34).ToString(); } #endregion #region Open / Close public void Open() { try { if (_oleConn !=null) { if (_oleConn.State==ConnectionState.Open) { _oleConn.Close(); } _oleConn=null; } if (System.IO.File.Exists(_strExcelFilename)==false) { throw new Exception("Excel file " + _strExcelFilename + "could not be found."); } _oleConn = new OleDbConnection(ExcelConnection()); _oleConn.Open(); } catch (Exception ex) { throw ex; } } public void Close() { if (_oleConn !=null) { if (_oleConn.State != ConnectionState.Closed) _oleConn.Close(); _oleConn.Dispose(); _oleConn=null; } } #endregion #region Command Select private bool SetSheetQuerySelect() { try { if (_oleConn == null) { throw new Exception("Connection is unassigned or closed."); } if (_strSheetName.Length ==0) throw new Exception("Sheetname was not assigned."); _oleCmdSelect =new OleDbCommand( @"SELECT * FROM [" + _strSheetName + "$" + _strSheetRange + "]", _oleConn); return true; } catch (Exception ex) { throw ex; } } #endregion #region simple utilities private string AddWithComma(string strSource,string strAdd) { if (strSource !="") strSource = strSource += ", "; return strSource + strAdd; } private string AddWithAnd(string strSource,string strAdd) { if (strSource !="") strSource = strSource += " and "; return strSource + strAdd; } #endregion private OleDbDataAdapter SetSheetQueryAdapter(DataTable dt) { // Deleting in Excel workbook is not possible //So this command is not defined try { if (_oleConn == null) { throw new Exception("Connection is unassigned or closed."); } if (_strSheetName.Length ==0) throw new Exception("Sheetname was not assigned."); if (PKCols == null) throw new Exception("Cannot update excel sheet with no primarykey set."); if (PKCols.Length<1) throw new Exception("Cannot update excel sheet with no primarykey set."); OleDbDataAdapter oleda = new OleDbDataAdapter(_oleCmdSelect); string strUpdate=""; string strInsertPar=""; string strInsert=""; string strWhere=""; for (int iPK=0;iPK<PKCols.Length;iPK++) { strWhere = AddWithAnd(strWhere,dt.Columns[iPK].ColumnName + "=?"); } strWhere =" Where "+strWhere; for (int iCol=0;iCol<dt.Columns.Count;iCol++) { strInsert= AddWithComma(strInsert,dt.Columns[iCol].ColumnName); strInsertPar= AddWithComma(strInsertPar,"?"); strUpdate= AddWithComma(strUpdate,dt.Columns[iCol].ColumnName)+"=?"; } string strTable = "["+ this.SheetName + "$" + this.SheetRange + "]"; strInsert = "INSERT INTO "+ strTable + "(" + strInsert +") Values (" + strInsertPar + ")"; strUpdate = "Update " + strTable + " Set " + strUpdate + strWhere; oleda.InsertCommand = new OleDbCommand(strInsert,_oleConn); oleda.UpdateCommand = new OleDbCommand(strUpdate,_oleConn); OleDbParameter oleParIns = null; OleDbParameter oleParUpd = null; for (int iCol=0;iCol<dt.Columns.Count;iCol++) { oleParIns = new OleDbParameter("?",dt.Columns[iCol].DataType.ToString()); oleParUpd = new OleDbParameter("?",dt.Columns[iCol].DataType.ToString()); oleParIns.SourceColumn =dt.Columns[iCol].ColumnName; oleParUpd.SourceColumn =dt.Columns[iCol].ColumnName; oleda.InsertCommand.Parameters.Add(oleParIns); oleda.UpdateCommand.Parameters.Add(oleParUpd); oleParIns=null; oleParUpd=null; } for (int iPK=0;iPK<PKCols.Length;iPK++) { oleParUpd = new OleDbParameter("?",dt.Columns[iPK].DataType.ToString()); oleParUpd.SourceColumn =dt.Columns[iPK].ColumnName; oleParUpd.SourceVersion = DataRowVersion.Original; oleda.UpdateCommand.Parameters.Add(oleParUpd); } return oleda; } catch (Exception ex) { throw ex; } } #region command Singe Value Update private bool SetSheetQuerySingelValUpdate(string strVal) { try { if (_oleConn == null) { throw new Exception("Connection is unassigned or closed."); } if (_strSheetName.Length ==0) throw new Exception("Sheetname was not assigned."); _oleCmdUpdate =new OleDbCommand( @" Update [" + _strSheetName + "$" + _strSheetRange + "] set F1=" + strVal, _oleConn); return true; } catch (Exception ex) { throw ex; } } #endregion public void SetPrimaryKey(int intCol) { _PKCol = new int[1] { intCol }; } public DataTable GetTable() { return GetTable("ExcelTable"); } private void SetPrimaryKey(DataTable dt) { try { if (PKCols!=null) { //set the primary key if (PKCols.Length>0) { DataColumn[] dc; dc = new DataColumn[PKCols.Length]; for (int i=0;i<PKCols.Length;i++) { dc[i] =dt.Columns[PKCols[i]]; } dt.PrimaryKey = dc; } } } catch (Exception ex) { throw ex; } } public DataTable GetTable(string strTableName) { try { //Open and query if (_oleConn ==null) Open(); if (_oleConn.State != ConnectionState.Open) throw new Exception("Connection cannot open error."); if (SetSheetQuerySelect()==false) return null; //Fill table OleDbDataAdapter oleAdapter = new OleDbDataAdapter(); oleAdapter.SelectCommand = _oleCmdSelect; DataTable dt = new DataTable(strTableName); oleAdapter.FillSchema(dt,SchemaType.Source); oleAdapter.Fill(dt); if (this.Headers ==false) { if (_strSheetRange.IndexOf(":")>0) { string FirstCol = _strSheetRange.Substring(0,_strSheetRange.IndexOf(":")-1); int intCol = this.ColNumber(FirstCol); for (int intI=0;intI<dt.Columns.Count;intI++) { dt.Columns[intI].Caption =ColName(intCol+intI); } } } SetPrimaryKey(dt); //Cannot delete rows in Excel workbook dt.DefaultView.AllowDelete =false; //Clean up _oleCmdSelect.Dispose(); _oleCmdSelect=null; oleAdapter.Dispose(); oleAdapter=null; if (KeepConnectionOpen==false) Close(); return dt; } catch (Exception ex) { throw ex; } } private void CheckPKExists(DataTable dt) { if (dt.PrimaryKey.Length==0) if (this.PKCols !=null) { SetPrimaryKey(dt); } else throw new Exception("Provide an primary key to the datatable"); } public DataTable SetTable(DataTable dt) { try { DataTable dtChanges = dt.GetChanges(); if (dtChanges == null) throw new Exception("There are no changes to be saved!"); CheckPKExists(dt); //Open and query if (_oleConn ==null) Open(); if (_oleConn.State != ConnectionState.Open) throw new Exception("Connection cannot open error."); if (SetSheetQuerySelect()==false) return null; //Fill table OleDbDataAdapter oleAdapter = SetSheetQueryAdapter(dtChanges); oleAdapter.Update(dtChanges); //Clean up _oleCmdSelect.Dispose(); _oleCmdSelect=null; oleAdapter.Dispose(); oleAdapter=null; if (KeepConnectionOpen==false) Close(); return dt; } catch (Exception ex) { throw ex; } } #region Get/Set Single Value public void SetSingleCellRange(string strCell) { _strSheetRange = strCell + ":" + strCell; } public object GetValue(string strCell) { SetSingleCellRange(strCell); object objValue=null; //Open and query if (_oleConn ==null) Open(); if (_oleConn.State != ConnectionState.Open) throw new Exception("Connection is not open error."); if (SetSheetQuerySelect()==false) return null; objValue = _oleCmdSelect.ExecuteScalar(); _oleCmdSelect.Dispose(); _oleCmdSelect=null; if (KeepConnectionOpen==false) Close(); return objValue; } public void SetValue(string strCell,object objValue) { try { SetSingleCellRange(strCell); //Open and query if (_oleConn ==null) Open(); if (_oleConn.State != ConnectionState.Open) throw new Exception("Connection is not open error."); if (SetSheetQuerySingelValUpdate(objValue.ToString())==false) return; objValue = _oleCmdUpdate.ExecuteNonQuery(); _oleCmdUpdate.Dispose(); _oleCmdUpdate=null; if (KeepConnectionOpen==false) Close(); } catch (Exception ex) { throw ex; } finally { if (_oleCmdUpdate != null) { _oleCmdUpdate.Dispose(); _oleCmdUpdate=null; } } } #endregion #endregion #region Dispose / Destructor public void Dispose() { if (_oleConn !=null) { _oleConn.Dispose(); _oleConn=null; } if (_oleCmdSelect!=null) { _oleCmdSelect.Dispose(); _oleCmdSelect=null; } // Dispose of remaining objects. } #endregion #region CTOR public ExcelReader() { // // TODO: Add constructor logic here // } #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. //#define LOGGING using System; using System.Collections; using System.Threading; using System.Runtime.InteropServices; using MS.Internal; using MS.Internal.Interop; using System.Security; // The SecurityHelper class differs between assemblies and could not actually be // shared, so it is duplicated across namespaces to prevent name collision. #if WINDOWS_BASE using MS.Internal.WindowsBase; #elif PRESENTATION_CORE using MS.Internal.PresentationCore; #elif PRESENTATIONFRAMEWORK using MS.Internal.PresentationFramework; #elif DRT using MS.Internal.Drt; #else #error Attempt to use a class (duplicated across multiple namespaces) from an unknown assembly. #endif namespace MS.Win32 { internal static class ManagedWndProcTracker { static ManagedWndProcTracker() { // Listen for ProcessExit so we can detach ourselves when the CLR shuts down // and avoid unmanaged code from calling back in to managed code during shutdown. ManagedWndProcTrackerShutDownListener listener = new ManagedWndProcTrackerShutDownListener(); } internal static void TrackHwndSubclass(HwndSubclass subclass, IntPtr hwnd) { lock (_hwndList) { // We use HwndSubclass as the key and the hwnd ptr as the value. // This supports the case where two (or more) HwndSubclasses // get attached to the same Hwnd. At AppDomain shutdown, we may // end up sending the Detach message to the Hwnd more than once, // but that won't cause any harm. _hwndList[subclass] = hwnd; } #if LOGGING LogStartHWND(hwnd, "Core HwndWrapper..ctor"); #endif } internal static void UnhookHwndSubclass(HwndSubclass subclass) { // if exiting the AppDomain, ignore this call. This avoids changing // the list during the loop in OnAppDomainProcessExit if (_exiting) return; lock (_hwndList) { _hwndList.Remove(subclass); } } private static void OnAppDomainProcessExit() { // AppDomain is exiting -- if anyone tries to call back into managed code // after this point, bad things will happen. We must remove all unmanaged // code references to our WndProc delegates. USER will explode if we set the // WndProc to null, so the next most reasonable thing we can do is hook up // the DefaultWindowProc. //DbgUserBreakPoint(); _exiting = true; lock (_hwndList) { foreach (DictionaryEntry entry in _hwndList) { IntPtr hwnd = (IntPtr)entry.Value; int windowStyle = UnsafeNativeMethods.GetWindowLong(new HandleRef(null,hwnd), NativeMethods.GWL_STYLE); if((windowStyle & NativeMethods.WS_CHILD) != 0) { // Tell all the HwndSubclass WndProcs for WS_CHILD windows // to detach themselves. This is particularly important when // the parent hwnd belongs to a separate AppDomain in a // cross AppDomain hosting scenario. In this scenario it is // possible that the host has subclassed the WS_CHILD window // and hence it is important to notify the host before we set the // WndProc to DefWndProc. Also note that we do not want to make a // blocking SendMessage call to all the subclassed Hwnds in the // AppDomain because this can lead to slow shutdown speed. // Eg. Consider a MessageOnlyHwnd created and subclassed on a // worker thread which is no longer responsive. The SendMessage // call in this case will block. To avoid this we limit the conversation // only to WS_CHILD windows. We understand that this solution is // not foolproof but it is the best outside of re-designing the cleanup // of Hwnd subclasses. UnsafeNativeMethods.SendMessage(hwnd, HwndSubclass.DetachMessage, IntPtr.Zero /* wildcard */, (IntPtr) 2 /* force and forward */); } // the last WndProc on the chain might be managed as well // (see HwndSubclass.SubclassWndProc for explanation). // Just in case, restore the DefaultWindowProc. HookUpDefWindowProc(hwnd); } } } private static void HookUpDefWindowProc(IntPtr hwnd) { #if LOGGING LogFinishHWND(hwnd, "Core HookUpDWP"); #endif IntPtr result = IntPtr.Zero ; // We've already cleaned up, return immediately. if (hwnd == IntPtr.Zero) { return; } IntPtr defWindowProc = GetDefWindowProcAddress(hwnd); if (defWindowProc != IntPtr.Zero) { try { result = UnsafeNativeMethods.SetWindowLong(new HandleRef(null,hwnd), NativeMethods.GWL_WNDPROC, defWindowProc); } catch(System.ComponentModel.Win32Exception e) { // We failed to change the window proc. Now what? if (e.NativeErrorCode != 1400) // ERROR_INVALID_WINDOW_HANDLE { // For debugging purposes, throw an exception so we can debug // this and know if it's possible to call SetWindowLong on // the wrong thread. throw; } } if (result != IntPtr.Zero ) { UnsafeNativeMethods.PostMessage(new HandleRef(null,hwnd), WindowMessage.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } } // Get the DWP for the given HWND -- returns DefWindowProcA or DefWindowProcW // depending on IsWindowUnicode(hwnd). private static IntPtr GetDefWindowProcAddress(IntPtr hwnd) { // We need to swap back in the DefWindowProc, but which one we use depends on // what the Unicode-ness of the window. if (SafeNativeMethods.IsWindowUnicode(new HandleRef(null,hwnd))) { if (_cachedDefWindowProcW == IntPtr.Zero) { _cachedDefWindowProcW = GetUser32ProcAddress("DefWindowProcW"); } return _cachedDefWindowProcW; } else { if (_cachedDefWindowProcA == IntPtr.Zero) { _cachedDefWindowProcA = GetUser32ProcAddress("DefWindowProcA") ; } return _cachedDefWindowProcA; } } private static IntPtr GetUser32ProcAddress(string export) { IntPtr hModule = UnsafeNativeMethods.GetModuleHandle(ExternDll.User32); if (hModule != IntPtr.Zero) { return UnsafeNativeMethods.GetProcAddress(new HandleRef(null, hModule), export); } return IntPtr.Zero; } private sealed class ManagedWndProcTrackerShutDownListener : ShutDownListener { public ManagedWndProcTrackerShutDownListener() : base(null, ShutDownEvents.AppDomain) { } internal override void OnShutDown(object target, object sender, EventArgs e) { ManagedWndProcTracker.OnAppDomainProcessExit(); } } #if LOGGING [DllImport("ntdll.dll")] private static extern void DbgUserBreakPoint(); [DllImport("ntdll.dll")] private static extern void DbgPrint(string msg); internal static void LogStartHWND(IntPtr hwnd, string fromWhere) { string msg = String.Format("BEGIN: {0:X} -- Setting DWP, process = {1} ({2}) {3}", hwnd, System.Diagnostics.Process.GetCurrentProcess().ProcessName, fromWhere, System.Environment.NewLine); Log(msg); } internal static void LogFinishHWND(IntPtr hwnd, string fromWhere) { string msg = String.Format("END: {0:X} -- Setting DWP, process = {1} ({2}) {3}", hwnd, System.Diagnostics.Process.GetCurrentProcess().ProcessName, fromWhere, System.Environment.NewLine); Log(msg); } private static void Log(string msg) { //DbgUserBreakPoint(); /* byte[] msgBytes = System.Text.Encoding.ASCII.GetBytes(msg); System.IO.FileStream fs = System.IO.File.Open("c:\\dwplog.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); fs.Write(msgBytes, 0, msgBytes.Length); fs.Flush(); fs.Close(); */ } #endif private static IntPtr _cachedDefWindowProcA = IntPtr.Zero; private static IntPtr _cachedDefWindowProcW = IntPtr.Zero; private static Hashtable _hwndList = new Hashtable(10); private static bool _exiting = false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace System.DirectoryServices.AccountManagement { public class PrincipalCollection : ICollection<Principal>, ICollection, IEnumerable<Principal>, IEnumerable { // // ICollection // void ICollection.CopyTo(Array array, int index) { CheckDisposed(); // Parameter validation if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.PrincipalCollectionNotOneDimensional); if (index >= array.GetLength(0)) throw new ArgumentException(SR.PrincipalCollectionIndexNotInArray); ArrayList tempArray = new ArrayList(); lock (_resultSet) { ResultSetBookmark bookmark = null; try { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: bookmarking"); bookmark = _resultSet.BookmarkAndReset(); PrincipalCollectionEnumerator containmentEnumerator = new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); int arraySize = array.GetLength(0) - index; int tempArraySize = 0; while (containmentEnumerator.MoveNext()) { tempArray.Add(containmentEnumerator.Current); checked { tempArraySize++; } // Make sure the array has enough space, allowing for the "index" offset. // We check inline, rather than doing a PrincipalCollection.Count upfront, // because counting is just as expensive as enumerating over all the results, so we // only want to do it once. if (arraySize < tempArraySize) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "CopyTo: array too small (has {0}, need >= {1}", arraySize, tempArraySize); throw new ArgumentException(SR.PrincipalCollectionArrayTooSmall); } } } finally { if (bookmark != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "CopyTo: restoring from bookmark"); _resultSet.RestoreBookmark(bookmark); } } } foreach (object o in tempArray) { array.SetValue(o, index); checked { index++; } } } int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return IsSynchronized; } } object ICollection.SyncRoot { get { return SyncRoot; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } // // IEnumerable // IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } // // ICollection<Principal> // public void CopyTo(Principal[] array, int index) { ((ICollection)this).CopyTo((Array)array, index); } public bool IsReadOnly { get { return false; } } public int Count { get { CheckDisposed(); // Yes, this is potentially quite expensive. Count is unfortunately // an expensive operation to perform. lock (_resultSet) { ResultSetBookmark bookmark = null; try { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: bookmarking"); bookmark = _resultSet.BookmarkAndReset(); PrincipalCollectionEnumerator containmentEnumerator = new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); int count = 0; // Count all the members (including inserted members, but not including removed members) while (containmentEnumerator.MoveNext()) { count++; } return count; } finally { if (bookmark != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Count: restoring from bookmark"); _resultSet.Reset(); _resultSet.RestoreBookmark(bookmark); } } } } } // // IEnumerable<Principal> // public IEnumerator<Principal> GetEnumerator() { CheckDisposed(); return new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); } // // Add // public void Add(UserPrincipal user) { Add((Principal)user); } public void Add(GroupPrincipal group) { Add((Principal)group); } public void Add(ComputerPrincipal computer) { Add((Principal)computer); } public void Add(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException(nameof(principal)); if (Contains(principal)) throw new PrincipalExistsException(SR.PrincipalExistsExceptionText); MarkChange(); // If the value to be added is an uncommitted remove, just remove the uncommitted remove from the list. if (_removedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: removing from removedValuesPending"); _removedValuesPending.Remove(principal); // If they did a Add(x) --> Save() --> Remove(x) --> Add(x), we'll end up with x in neither // the ResultSet or the insertedValuesCompleted list. This is bad. Avoid that by adding x // back to the insertedValuesCompleted list here. // // Note, this will add x to insertedValuesCompleted even if it's already in the resultSet. // This is not a problem --- PrincipalCollectionEnumerator will detect such a situation and // only return x once. if (!_insertedValuesCompleted.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: adding to insertedValuesCompleted"); _insertedValuesCompleted.Add(principal); } } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Add: making it a pending insert"); // make it a pending insert _insertedValuesPending.Add(principal); // in case the value to be added is also a previous-but-already-committed remove _removedValuesCompleted.Remove(principal); } } public void Add(PrincipalContext context, IdentityType identityType, string identityValue) { CheckDisposed(); if (context == null) throw new ArgumentNullException(nameof(context)); if (identityValue == null) throw new ArgumentNullException(nameof(identityValue)); Principal principal = Principal.FindByIdentity(context, identityType, identityValue); if (principal != null) { Add(principal); } else { // No Principal matching the IdentityReference could be found in the PrincipalContext GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Add(urn/urn): no match"); throw new NoMatchingPrincipalException(SR.NoMatchingPrincipalExceptionText); } } // // Clear // public void Clear() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Clear"); CheckDisposed(); // Ask the StoreCtx to verify that this group can be cleared. Right now, the only // reason it couldn't is if it's an AD group with one principals that are members of it // by virtue of their primaryGroupId. // // If storeCtxToUse == null, then we must be unpersisted, in which case there clearly // can't be any such primary group members pointing to this group on the store. StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); string explanation; Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true); if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupBeCleared(_owningGroup, out explanation))) throw new InvalidOperationException(explanation); MarkChange(); // We wipe out everything that's been inserted/removed _insertedValuesPending.Clear(); _removedValuesPending.Clear(); _insertedValuesCompleted.Clear(); _removedValuesCompleted.Clear(); // flag that the collection has been cleared, so the StoreCtx and PrincipalCollectionEnumerator // can take appropriate action _clearPending = true; } // // Remove // public bool Remove(UserPrincipal user) { return Remove((Principal)user); } public bool Remove(GroupPrincipal group) { return Remove((Principal)group); } public bool Remove(ComputerPrincipal computer) { return Remove((Principal)computer); } public bool Remove(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException(nameof(principal)); // Ask the StoreCtx to verify that this member can be removed. Right now, the only // reason it couldn't is if it's actually a member by virtue of its primaryGroupId // pointing to this group. // // If storeCtxToUse == null, then we must be unpersisted, in which case there clearly // can't be any such primary group members pointing to this group on the store. StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); string explanation; Debug.Assert(storeCtxToUse != null || _owningGroup.unpersisted == true); if ((storeCtxToUse != null) && (!storeCtxToUse.CanGroupMemberBeRemoved(_owningGroup, principal, out explanation))) throw new InvalidOperationException(explanation); bool removed = false; // If the value was previously inserted, we just remove it from insertedValuesPending. if (_insertedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: removing from insertedValuesPending"); MarkChange(); _insertedValuesPending.Remove(principal); removed = true; // If they did a Remove(x) --> Save() --> Add(x) --> Remove(x), we'll end up with x in neither // the ResultSet or the removedValuesCompleted list. This is bad. Avoid that by adding x // back to the removedValuesCompleted list here. // // At worst, we end up with x on the removedValuesCompleted list even though it's not even in // resultSet. That's not a problem. The only thing we use the removedValuesCompleted list for // is deciding which values in resultSet to skip, anyway. if (!_removedValuesCompleted.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: adding to removedValuesCompleted"); _removedValuesCompleted.Add(principal); } } else { // They're trying to remove an already-persisted value. We add it to the // removedValues list. Then, if it's already been loaded into insertedValuesCompleted, // we remove it from insertedValuesCompleted. removed = Contains(principal); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Remove: making it a pending remove, removed={0}", removed); if (removed) { MarkChange(); _removedValuesPending.Add(principal); // in case it's the result of a previous-but-already-committed insert _insertedValuesCompleted.Remove(principal); } } return removed; } public bool Remove(PrincipalContext context, IdentityType identityType, string identityValue) { CheckDisposed(); if (context == null) throw new ArgumentNullException(nameof(context)); if (identityValue == null) throw new ArgumentNullException(nameof(identityValue)); Principal principal = Principal.FindByIdentity(context, identityType, identityValue); if (principal == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalCollection", "Remove(urn/urn): no match"); throw new NoMatchingPrincipalException(SR.NoMatchingPrincipalExceptionText); } return Remove(principal); } // // Contains // private bool ContainsEnumTest(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException(nameof(principal)); // Yes, this is potentially quite expensive. Contains is unfortunately // an expensive operation to perform. lock (_resultSet) { ResultSetBookmark bookmark = null; try { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: bookmarking"); bookmark = _resultSet.BookmarkAndReset(); PrincipalCollectionEnumerator containmentEnumerator = new PrincipalCollectionEnumerator( _resultSet, this, _removedValuesCompleted, _removedValuesPending, _insertedValuesCompleted, _insertedValuesPending); while (containmentEnumerator.MoveNext()) { Principal p = containmentEnumerator.Current; if (p.Equals(principal)) return true; } } finally { if (bookmark != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsEnumTest: restoring from bookmark"); _resultSet.RestoreBookmark(bookmark); } } } return false; } private bool ContainsNativeTest(Principal principal) { CheckDisposed(); if (principal == null) throw new ArgumentNullException(nameof(principal)); // If they explicitly inserted it, then we certainly contain it if (_insertedValuesCompleted.Contains(principal) || _insertedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: found insert"); return true; } // If they removed it, we don't contain it, regardless of the group membership on the store if (_removedValuesCompleted.Contains(principal) || _removedValuesPending.Contains(principal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: found remove"); return false; } // The list was cleared at some point and the principal has not been reinsterted yet if (_clearPending || _clearCompleted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: Clear pending"); return false; } // Otherwise, check the store if (_owningGroup.unpersisted == false && principal.unpersisted == false) return _owningGroup.GetStoreCtxToUse().IsMemberOfInStore(_owningGroup, principal); // We (or the principal) must not be persisted, so there's no store membership to check. // Out of things to check. We must not contain it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ContainsNativeTest: no store to check"); return false; } public bool Contains(UserPrincipal user) { return Contains((Principal)user); } public bool Contains(GroupPrincipal group) { return Contains((Principal)group); } public bool Contains(ComputerPrincipal computer) { return Contains((Principal)computer); } public bool Contains(Principal principal) { StoreCtx storeCtxToUse = _owningGroup.GetStoreCtxToUse(); // If the store has a shortcut for testing membership, use it. // Otherwise we enumerate all members and look for a match. if ((storeCtxToUse != null) && (storeCtxToUse.SupportsNativeMembershipTest)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Contains: using native test (store ctx is null = {0})", (storeCtxToUse == null)); return ContainsNativeTest(principal); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Contains: using enum test"); return ContainsEnumTest(principal); } } public bool Contains(PrincipalContext context, IdentityType identityType, string identityValue) { CheckDisposed(); if (context == null) throw new ArgumentNullException(nameof(context)); if (identityValue == null) throw new ArgumentNullException(nameof(identityValue)); bool found = false; Principal principal = Principal.FindByIdentity(context, identityType, identityValue); if (principal != null) found = Contains(principal); return found; } // // Internal constructor // // Constructs a fresh PrincipalCollection based on the supplied ResultSet. // The ResultSet may not be null (use an EmptySet instead). internal PrincipalCollection(BookmarkableResultSet results, GroupPrincipal owningGroup) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Ctor"); Debug.Assert(results != null); _resultSet = results; _owningGroup = owningGroup; } // // Internal "disposer" // // Ideally, we'd like to implement IDisposable, since we need to dispose of the ResultSet. // But IDisposable would have to be a public interface, and we don't want the apps calling Dispose() // on us, only the Principal that owns us. So we implement an "internal" form of Dispose(). internal void Dispose() { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing"); lock (_resultSet) { if (_resultSet != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "Dispose: disposing resultSet"); _resultSet.Dispose(); } } _disposed = true; } } // // Private implementation // // The group we're a PrincipalCollection of private readonly GroupPrincipal _owningGroup; // // SYNCHRONIZATION // Access to: // resultSet // must be synchronized, since multiple enumerators could be iterating over us at once. // Synchronize by locking on resultSet. // Represents the Principals retrieved from the store for this collection private readonly BookmarkableResultSet _resultSet; // Contains Principals inserted into this collection for which the insertion has not been persisted to the store private readonly List<Principal> _insertedValuesCompleted = new List<Principal>(); private readonly List<Principal> _insertedValuesPending = new List<Principal>(); // Contains Principals removed from this collection for which the removal has not been persisted // to the store private readonly List<Principal> _removedValuesCompleted = new List<Principal>(); private readonly List<Principal> _removedValuesPending = new List<Principal>(); // Has this collection been cleared? private bool _clearPending = false; private bool _clearCompleted = false; internal bool ClearCompleted { get { return _clearCompleted; } } // Used so our enumerator can detect changes to the collection and throw an exception private DateTime _lastChange = DateTime.UtcNow; internal DateTime LastChange { get { return _lastChange; } } internal void MarkChange() { _lastChange = DateTime.UtcNow; } // To support disposal private bool _disposed = false; private void CheckDisposed() { if (_disposed) throw new ObjectDisposedException("PrincipalCollection"); } // // Load/Store Implementation // internal List<Principal> Inserted { get { return _insertedValuesPending; } } internal List<Principal> Removed { get { return _removedValuesPending; } } internal bool Cleared { get { return _clearPending; } } // Return true if the membership has changed (i.e., either insertedValuesPending or removedValuesPending is // non-empty) internal bool Changed { get { return ((_insertedValuesPending.Count > 0) || (_removedValuesPending.Count > 0) || (_clearPending)); } } // Resets the change-tracking of the membership to 'unchanged', by moving all pending operations to completed status. internal void ResetTracking() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ResetTracking"); foreach (Principal p in _removedValuesPending) { Debug.Assert(!_removedValuesCompleted.Contains(p)); _removedValuesCompleted.Add(p); } _removedValuesPending.Clear(); foreach (Principal p in _insertedValuesPending) { Debug.Assert(!_insertedValuesCompleted.Contains(p)); _insertedValuesCompleted.Add(p); } _insertedValuesPending.Clear(); if (_clearPending) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalCollection", "ResetTracking: clearing"); _clearCompleted = true; _clearPending = false; } } } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using SIL.Extensions; using SIL.PlatformUtilities; using SIL.Reporting; namespace SIL.IO { public static class PathUtilities { // On Unix there are more characters valid in file names, but we // want the result to be identical on both platforms, so we want // to use the larger invalid Windows list for both platforms public static char[] GetInvalidOSIndependentFileNameChars() { return new char[] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', '"', '<', '>', '|', ':', '*', '?', '\\', '/' }; } // map directory name to its disk device number (not used on Windows) private static Dictionary<string,int> _deviceNumber = new Dictionary<string, int>(); public static int GetDeviceNumber(string filePath) { if (Platform.IsWindows) { var driveInfo = new DriveInfo(Path.GetPathRoot(filePath)); return driveInfo.Name.ToUpper()[0] - 'A' + 1; } // path can mean a file or a directory. Get the directory // so that our device number cache can work better. (fewer // unique directory names than filenames) var pathToCheck = filePath; if (File.Exists(pathToCheck)) pathToCheck = Path.GetDirectoryName(pathToCheck); else if (!Directory.Exists(pathToCheck)) { // Work up the path until a directory exists. do { pathToCheck = Path.GetDirectoryName(pathToCheck); } while (!String.IsNullOrEmpty(pathToCheck) && !Directory.Exists(pathToCheck)); // If the whole path is invalid, give up. if (String.IsNullOrEmpty(pathToCheck)) return -1; } int retval; // Use cached value if we can to avoid process invocation. if (_deviceNumber.TryGetValue(pathToCheck, out retval)) return retval; using (var process = new Process()) { var statFlags = Platform.IsMac ? "-f" : "-c"; process.StartInfo = new ProcessStartInfo { FileName = "stat", Arguments = string.Format("{0} %d \"{1}\"", statFlags, pathToCheck), UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; process.Start(); var output = process.StandardOutput.ReadToEnd(); // This process is frequently not exiting even after filling the output string // with the desired information. So we'll wait a couple of seconds instead of // waiting forever and just go on. If there's data to process, we'll use it. // (2 seconds should be more than enough for that simple command to execute. // "time statc -c %d "/tmp" reports 2ms of real time and 2ms of user time.) // See https://jira.sil.org/browse/BL-771 for a bug report involving this code // with a simple process.WaitForExit(). // This feels like a Mono bug of some sort, so feel free to regard this as a // workaround hack. process.WaitForExit(2000); if (!String.IsNullOrWhiteSpace(output)) { if (Int32.TryParse(output.Trim(), out retval)) { _deviceNumber.Add(pathToCheck, retval); return retval; } } return -1; } } public static bool PathsAreOnSameVolume(string firstPath, string secondPath) { if (string.IsNullOrEmpty(firstPath) || string.IsNullOrEmpty(secondPath)) return false; return PathUtilities.GetDeviceNumber(firstPath) == PathUtilities.GetDeviceNumber(secondPath); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)] private struct SHFILEOPSTRUCT { public IntPtr hwnd; [MarshalAs(UnmanagedType.U4)] public int wFunc; public string pFrom; public string pTo; public short fFlags; [MarshalAs(UnmanagedType.Bool)] public bool fAnyOperationsAborted; public IntPtr hNameMappings; public string lpszProgressTitle; } [DllImport("shell32.dll", CharSet = CharSet.Auto)] private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp); private const int FO_DELETE = 3; private const int FOF_ALLOWUNDO = 0x40; private const int FOF_NOCONFIRMATION = 0x10; // Don't prompt the user private const int FOF_SIMPLEPROGRESS = 0x0100; private static void WriteTrashInfoFile(string trashPath, string filePath, string trashedFile) { var trashInfo = Path.Combine(trashPath, "info", trashedFile + ".trashinfo"); var lines = new List<string>(); lines.Add("[Trash Info]"); lines.Add(string.Format("Path={0}", filePath)); lines.Add(string.Format("DeletionDate={0}", DateTime.Now.ToString("yyyyMMddTHH:mm:ss", CultureInfo.InvariantCulture))); File.WriteAllLines(trashInfo, lines); } /// <summary> /// Delete a file or directory by moving it to the trash bin /// </summary> /// <param name="filePath">Full path of the file.</param> /// <returns><c>true</c> if successfully deleted.</returns> public static bool DeleteToRecycleBin(string filePath) { if (PlatformUtilities.Platform.IsWindows) { if (!File.Exists(filePath) && !Directory.Exists(filePath)) return false; // alternative using visual basic dll: // FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin); //moves it to the recyle bin var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; string pathWith2Nulls = filePath + "\0\0"; shf.pFrom = pathWith2Nulls; SHFileOperation(ref shf); return !shf.fAnyOperationsAborted; } // On Linux we'll have to move the file to $XDG_DATA_HOME/Trash/files and create // a filename.trashinfo file in $XDG_DATA_HOME/Trash/info that contains the original // filepath and the deletion date. See http://stackoverflow.com/a/20255190 // and http://freedesktop.org/wiki/Specifications/trash-spec/. // Environment.SpecialFolder.LocalApplicationData corresponds to $XDG_DATA_HOME. // move file or directory if (Directory.Exists(filePath) || File.Exists(filePath)) { var trashPath = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData), "Trash"); var trashedFileName = Path.GetRandomFileName(); if (!Directory.Exists(trashPath)) { // in case the trash bin doesn't exist we create it. This can happen e.g. // on the build machine Directory.CreateDirectory(Path.Combine(trashPath, "files")); Directory.CreateDirectory(Path.Combine(trashPath, "info")); } var recyclePath = Path.Combine(Path.Combine(trashPath, "files"), trashedFileName); WriteTrashInfoFile(trashPath, filePath, trashedFileName); // Directory.Move works for directories and files DirectoryUtilities.MoveDirectorySafely(filePath, recyclePath); return true; } return false; } [DllImport("shell32.dll", ExactSpelling = true)] public static extern void ILFree(IntPtr pidlList); [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern IntPtr ILCreateFromPathW(string pszPath); [DllImport("shell32.dll", ExactSpelling = true)] public static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags); public static void SelectItemInExplorerEx(string path) { var pidlList = ILCreateFromPathW(path); if(pidlList == IntPtr.Zero) throw new Exception(string.Format("ILCreateFromPathW({0}) failed", path)); try { Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0)); } finally { ILFree(pidlList); } } /// <summary> /// On Windows this selects the file or directory in Windows Explorer; on Linux it selects the file /// in the default file manager if that supports selecting a file and we know it, /// otherwise we fall back to xdg-open and open the directory that contains that file. /// </summary> /// <param name="path">File or directory path.</param> public static void SelectFileInExplorer(string path) { if (Platform.IsWindows) { //we need to use this becuase of a bug in windows that strips composed characters before trying to find the target path (http://stackoverflow.com/a/30405340/723299) var pidlList = ILCreateFromPathW(path); if(pidlList == IntPtr.Zero) throw new Exception(string.Format("ILCreateFromPathW({0}) failed", path)); try { Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0)); } finally { ILFree(pidlList); } } else { var fileManager = DefaultFileManager; string arguments; switch (fileManager) { case "nautilus": case "nemo": arguments = string.Format("\"{0}\"", path); break; default: fileManager = "xdg-open"; arguments = string.Format("\"{0}\"", Path.GetDirectoryName(path)); break; } Process.Start(fileManager, arguments); } } /// <summary> /// Opens the specified directory in the default file manager /// </summary> /// <param name="directory">Full path of the directory</param> public static void OpenDirectoryInExplorer(string directory) { //Enhance: on Windows, use ShellExecuteExW instead, as it will probably be able to //handle languages with combining characters (diactrics), whereas this explorer //approach will fail (at least as of windows 8.1) var fileManager = DefaultFileManager; var arguments = "\"{0}\""; // the value returned by GetDefaultFileManager() may include arguments var firstSpace = fileManager.IndexOf(' '); if (firstSpace > -1) { arguments = fileManager.Substring(firstSpace + 1) + " " + arguments; fileManager = fileManager.Substring(0, firstSpace); } arguments = string.Format(arguments, directory); Process.Start(new ProcessStartInfo() { FileName = fileManager, Arguments = arguments, UseShellExecute = false }); } /// <summary> /// Opens the file in the application associated with the file type. /// </summary> /// <param name="filePath">Full path to the file</param> public static void OpenFileInApplication(string filePath) { Process.Start(filePath); } private static string GetDefaultFileManager() { if (PlatformUtilities.Platform.IsWindows) return "explorer.exe"; const string fallbackFileManager = "xdg-open"; using (var xdgmime = new Process()) { bool processError = false; xdgmime.RunProcess("xdg-mime", "query default inode/directory", exception => { processError = true; }); if (processError) { Logger.WriteMinorEvent("Error executing 'xdg-mime query default inode/directory'"); return fallbackFileManager; } string desktopFile = xdgmime.StandardOutput.ReadToEnd().TrimEnd(' ', '\n', '\r'); xdgmime.WaitForExit(); if (string.IsNullOrEmpty(desktopFile)) { Logger.WriteMinorEvent("Didn't find default value for mime type inode/directory"); return fallbackFileManager; } // Look in /usr/share/applications for .desktop file var desktopFilename = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "applications", desktopFile); if (!File.Exists(desktopFilename)) { // We didn't find the .desktop file yet, so check in ~/.local/share/applications desktopFilename = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "applications", desktopFile); } if (!File.Exists(desktopFilename)) { Logger.WriteMinorEvent("Can't find desktop file for {0}", desktopFile); return fallbackFileManager; } using (var reader = File.OpenText(desktopFilename)) { string line; for (line = reader.ReadLine(); !line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase) && !reader.EndOfStream; line = reader.ReadLine()) { } if (!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase)) { Logger.WriteMinorEvent("Can't find Exec line in {0}", desktopFile); _defaultFileManager = string.Empty; return _defaultFileManager; } var start = "Exec=".Length; var argStart = line.IndexOf('%'); var cmdLine = argStart > 0 ? line.Substring(start, argStart - start) : line.Substring(start); cmdLine = cmdLine.TrimEnd(); Logger.WriteMinorEvent("Detected default file manager as {0}", cmdLine); return cmdLine; } } } private static string _defaultFileManager; private static string DefaultFileManager { get { if (_defaultFileManager == null) _defaultFileManager = GetDefaultFileManager(); return _defaultFileManager; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.Serialization; using System.Security; using System.Diagnostics.Contracts; [Serializable] [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public struct UIntPtr : ISerializable { [SecurityCritical] unsafe private void* m_value; public static readonly UIntPtr Zero; [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe UIntPtr(uint value) { m_value = (void *)value; } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe UIntPtr(ulong value) { #if WIN32 m_value = (void*)checked((uint)value); #else m_value = (void *)value; #endif } [System.Security.SecurityCritical] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public unsafe UIntPtr(void* value) { m_value = value; } [System.Security.SecurityCritical] // auto-generated private unsafe UIntPtr(SerializationInfo info, StreamingContext context) { ulong l = info.GetUInt64("value"); if (Size==4 && l>UInt32.MaxValue) { throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue")); } m_value = (void *)l; } #if FEATURE_SERIALIZATION [System.Security.SecurityCritical] unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); info.AddValue("value", (ulong)m_value); } #endif [System.Security.SecuritySafeCritical] // auto-generated public unsafe override bool Equals(Object obj) { if (obj is UIntPtr) { return (m_value == ((UIntPtr)obj).m_value); } return false; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe override int GetHashCode() { return unchecked((int)((long)m_value)) & 0x7fffffff; } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe uint ToUInt32() { #if WIN32 return (uint)m_value; #else return checked((uint)m_value); #endif } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe ulong ToUInt64() { return (ulong)m_value; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe override String ToString() { Contract.Ensures(Contract.Result<String>() != null); #if WIN32 return ((uint)m_value).ToString(CultureInfo.InvariantCulture); #else return ((ulong)m_value).ToString(CultureInfo.InvariantCulture); #endif } [System.Runtime.Versioning.NonVersionable] public static explicit operator UIntPtr (uint value) { return new UIntPtr(value); } [System.Runtime.Versioning.NonVersionable] public static explicit operator UIntPtr (ulong value) { return new UIntPtr(value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator uint(UIntPtr value) { #if WIN32 return (uint)value.m_value; #else return checked((uint)value.m_value); #endif } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator ulong (UIntPtr value) { return (ulong)value.m_value; } [System.Security.SecurityCritical] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator UIntPtr (void* value) { return new UIntPtr(value); } [System.Security.SecurityCritical] [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator void* (UIntPtr value) { return value.m_value; } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator == (UIntPtr value1, UIntPtr value2) { return value1.m_value == value2.m_value; } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator != (UIntPtr value1, UIntPtr value2) { return value1.m_value != value2.m_value; } [System.Runtime.Versioning.NonVersionable] public static UIntPtr Add(UIntPtr pointer, int offset) { return pointer + offset; } [System.Runtime.Versioning.NonVersionable] public static UIntPtr operator +(UIntPtr pointer, int offset) { #if WIN32 return new UIntPtr(pointer.ToUInt32() + (uint)offset); #else return new UIntPtr(pointer.ToUInt64() + (ulong)offset); #endif } [System.Runtime.Versioning.NonVersionable] public static UIntPtr Subtract(UIntPtr pointer, int offset) { return pointer - offset; } [System.Runtime.Versioning.NonVersionable] public static UIntPtr operator -(UIntPtr pointer, int offset) { #if WIN32 return new UIntPtr(pointer.ToUInt32() - (uint)offset); #else return new UIntPtr(pointer.ToUInt64() - (ulong)offset); #endif } public static int Size { [System.Runtime.Versioning.NonVersionable] get { #if WIN32 return 4; #else return 8; #endif } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public unsafe void* ToPointer() { return m_value; } } }
// JsonBoolean.cs // // Copyright (C) 2006 Andy Kernahan // // 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 using System; using System.Diagnostics; namespace NetServ.Net.Json { /// <summary> /// Represents a JavaScript Object Notation Boolean data type. This class /// cannot be inherited. /// </summary> [Serializable()] [DebuggerDisplay("{_value}")] public sealed class JsonBoolean : JsonTypeSkeleton, IJsonBoolean { #region Private Fields. private readonly bool _value; #endregion #region Public Interface. /// <summary> /// Defines the Json true string. This field is constant. /// </summary> public const string TrueString = "true"; /// <summary> /// Defines the Json false string. This field is constant. /// </summary> public const string FalseString = "false"; /// <summary> /// Defines a true JsonBoolean instance. This field is readonly. /// </summary> public static readonly JsonBoolean True = new JsonBoolean(true); /// <summary> /// Defines a false JsonBoolean instance. This field is readonly. /// </summary> public static readonly JsonBoolean False = new JsonBoolean(false); /// <summary> /// Writes the contents of this Json type using the specified /// <see cref="NetServ.Net.Json.IJsonWriter"/>. /// </summary> /// <param name="writer">The Json writer.</param> public override void Write(IJsonWriter writer) { if(writer == null) throw new ArgumentNullException("writer"); writer.WriteValue(ToString()); } /// <summary> /// Returns a <see cref="System.String"/> representation of this JsonBoolean instance. /// </summary> /// <returns> <see cref="System.String"/> representation of this JsonBoolean instance</returns> public override string ToString() { return this.Value ? JsonBoolean.TrueString : JsonBoolean.FalseString; } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// <see cref="System.Object"/>. /// </summary> /// <param name="obj">The object to compare.</param> /// <returns>True if the specified object is equal to this instance, otherwise; /// false.</returns> public override bool Equals(object obj) { if(obj == null) return false; if(obj.GetType() != GetType()) return false; return Equals((JsonBoolean)obj); } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// JsonBoolean. /// </summary> /// <param name="other">The value to compare.</param> /// <returns>True if the specified instance is equal to this instance, otherwise; /// false.</returns> public bool Equals(JsonBoolean other) { return other != null && this.Value == other.Value; } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// <see cref="NetServ.Net.Json.IJsonBoolean"/>. /// </summary> /// <param name="other">The value to compare.</param> /// <returns>True if the specified instance is equal to this instance, otherwise; /// false.</returns> public bool Equals(IJsonBoolean other) { return other != null && this.Value == other.Value; } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// <see cref="System.Boolean"/>. /// </summary> /// <param name="other">The value to compare.</param> /// <returns>True if the specified bool is equal to this instance, otherwise; /// false.</returns> public bool Equals(bool other) { return this.Value == other; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance.</returns> public override int GetHashCode() { return this.Value.GetHashCode(); } /// <summary> /// Gets the value of this JsonBoolean. /// </summary> public bool Value { get { return _value; } } /// <summary> /// Returns a static JsonBoolean instance representing <paramref name="value"/>. /// </summary> /// <param name="value">The value.</param> /// <returns>A static JsonBoolean instance representing <paramref name="value"/>. /// </returns> public static JsonBoolean Get(bool value) { return value ? JsonBoolean.True : JsonBoolean.False; } /// <summary> /// Determines if the two <see cref="NetServ.Net.Json.JsonBoolean"/>s are /// equal. /// </summary> /// <param name="a">The first JsonBoolean.</param> /// <param name="b">The second JsonBoolean.</param> /// <returns>True if the JsonBooleans are equal, otherwise; false.</returns> public static bool Equals(JsonBoolean a, JsonBoolean b) { object ao = a; object bo = b; if(ao == bo) return true; if(ao == null || bo == null) return false; return a.Value == b.Value; } /// <summary> /// Equality operator. /// </summary> /// <param name="a">The first JsonBoolean.</param> /// <param name="b">The second JsonBoolean.</param> /// <returns>True if the JsonBooleans are equal, otherwise; false.</returns> public static bool operator ==(JsonBoolean a, JsonBoolean b) { return JsonBoolean.Equals(a, b); } /// <summary> /// Inequality operator. /// </summary> /// <param name="a">The first JsonBoolean.</param> /// <param name="b">The second JsonBoolean.</param> /// <returns>True if the JsonBooleans are not equal, otherwise; false.</returns> public static bool operator !=(JsonBoolean a, JsonBoolean b) { return !JsonBoolean.Equals(a, b); } /// <summary> /// Implicit <see cref="System.Boolean"/> conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator JsonBoolean(bool value) { return JsonBoolean.Get(value); } /// <summary> /// Implicit <see cref="NetServ.Net.Json.JsonNull"/> conversion operator. /// </summary> /// <param name="value"></param> /// <returns>This method always returns null.</returns> public static implicit operator JsonBoolean(JsonNull value) { return null; } /// <summary> /// Explicit <see cref="NetServ.Net.Json.JsonBoolean"/> conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static explicit operator bool(JsonBoolean value) { if(value == null) throw new ArgumentNullException(); return value.Value; } #endregion #region Private Impl. /// <summary> /// Initialises a new instance of the JsonBoolean class and specifies the /// value. /// </summary> /// <param name="value"></param> private JsonBoolean(bool value) : base(JsonTypeCode.Boolean) { _value = value; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace SimShift.MapTool { public class Ets2Item { public int Origin = 0; public Ets2Item(ulong uid, Ets2Sector sector, int offset) { ItemUID = uid; Navigation = new Dictionary<Ets2Item, Tuple<float, float, IEnumerable<Ets2Item>>>(); Sector = sector; FileOffset = offset; FilePath = sector.FilePath; NodesList = new Dictionary<ulong, Ets2Node>(); Type = (Ets2ItemType) BitConverter.ToUInt32(sector.Stream, offset); int nodeCount; switch (Type) { case Ets2ItemType.Road: StartNodeUID = BitConverter.ToUInt64(sector.Stream, offset + 141); EndNodeUID = BitConverter.ToUInt64(sector.Stream, offset + 149); var lookId = BitConverter.ToUInt32(sector.Stream, offset + 61); // unique UINT32 ID with road look RoadLook = Sector.Mapper.LookupRoadLookID(lookId); // Need to create LUT to translate road_look.sii <> ID // Then we can parse highway routes etc. HideUI = (sector.Stream[offset + 0x37] & 0x02) != 0; // Make sure these UID's exist in the world. if ((StartNodeUID != 0 && sector.Mapper.Nodes.ContainsKey(StartNodeUID)) || (EndNodeUID != 0 && sector.Mapper.Nodes.ContainsKey(EndNodeUID))) { Valid = true; var stamps = BitConverter.ToInt32(sector.Stream, offset + 433); BlockSize = 437 + stamps * 24; } else { Valid = false; } break; case Ets2ItemType.Prefab: if (uid == 0x2935de9c700704) { // } nodeCount = BitConverter.ToInt32(sector.Stream, offset + 81); HideUI = (sector.Stream[offset + 0x36] & 0x02) != 0; if (nodeCount > 0x20) { Valid = false; return; } var somethingOffset = offset + 85 + 8 * nodeCount; if (somethingOffset < offset || somethingOffset > sector.Stream.Length) { Valid = false; return; } var something = BitConverter.ToInt32(sector.Stream, somethingOffset); if (something < 0 || something > 32) { Valid = false; return; } var OriginOffset = offset + 0x61 + nodeCount * 8 + something * 8; if (OriginOffset < offset || OriginOffset > sector.Stream.Length) { Valid = false; return; } Origin = sector.Stream[OriginOffset] & 0x03; //Console.WriteLine("PREFAB @ " + uid.ToString("X16") + " origin: " + Origin); var prefabId = (int) BitConverter.ToUInt32(sector.Stream, offset + 57); // Invalidate unreasonable amount of node counts.. if (nodeCount < 0x20 && nodeCount != 0) { Valid = true; for (int i = 0; i < nodeCount; i++) { var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 81 + 4 + i * 8); //Console.WriteLine("prefab node link " + i + ": " + nodeUid.ToString("X16")); // TODO: if node is in other sector.. if (AddNodeUID(nodeUid) == false) { //Console.WriteLine("Could not add prefab node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16")); break; } } PrefabNodeUID = NodesList.Keys.FirstOrDefault(); } //Console.WriteLine("PREFAB ID: " + prefabId.ToString("X8")); Prefab = sector.Mapper.LookupPrefab(prefabId); if (Prefab == null) { //Console.WriteLine("Prefab ID: " + uid.ToString("X16") + " / " + prefabId.ToString("X") + // " not found"); } break; case Ets2ItemType.Company: Valid = true; // There are 3 nodes subtracted from found in sector: // 1) The node of company itself // 2) The node of loading area // 3) The node of job nodeCount = Sector.Nodes.Count(x => x.ForwardItemUID == uid) - 2; BlockSize = nodeCount * 8 + 109; // Invalidate unreasonable amount of node counts.. if (nodeCount < 0x20) { var prefabItemUid = BitConverter.ToUInt64(sector.Stream, offset + 73); var loadAreaNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 93); var jobAreaNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 81); if (AddNodeUID(loadAreaNodeUid) == false) { //Console.WriteLine("Could not add loading area node " + loadAreaNodeUid.ToString("X16")); } else if (AddNodeUID(jobAreaNodeUid) == false) { //Console.WriteLine("Could not add job area node" + jobAreaNodeUid.ToString("X16")); } else { for (int i = 0; i < nodeCount; i++) { var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 113 + i * 8); //Console.WriteLine("company node link " + i + ": " + nodeUid.ToString("X16")); if (AddNodeUID(nodeUid) == false) { //Console.WriteLine("Could not add cargo area node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16")); break; } } } } else { Valid = false; } break; case Ets2ItemType.Building: var buildingNodeUid1 = BitConverter.ToUInt64(sector.Stream, offset + 73); var buildingNodeUid2 = BitConverter.ToUInt64(sector.Stream, offset + 65); Valid = AddNodeUID(buildingNodeUid1) && AddNodeUID(buildingNodeUid2); BlockSize = 97; break; case Ets2ItemType.Sign: var signNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 65); BlockSize = 153; Valid = AddNodeUID(signNodeUid); break; case Ets2ItemType.Model: var modelNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 81); BlockSize = 101; Valid = AddNodeUID(modelNodeUid); break; case Ets2ItemType.MapOverlay: var mapOverlayNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 65); BlockSize = 73; Valid = AddNodeUID(mapOverlayNodeUid); break; case Ets2ItemType.Ferry: var ferryNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 73); BlockSize = 93; Valid = AddNodeUID(ferryNodeUid); break; case Ets2ItemType.CutPlane: nodeCount = BitConverter.ToInt32(sector.Stream, offset + 57); // Invalidate unreasonable amount of node counts.. if (nodeCount < 0x20) { Valid = true; for (int i = 0; i < nodeCount; i++) { var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57 + 4 + i * 8); //Console.WriteLine("cut plane node " + i + ": " + nodeUid.ToString("X16")); if (AddNodeUID(nodeUid) == false) { //Console.WriteLine("Could not add cut plane node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16")); break; } } } BlockSize = 61 + 8 * nodeCount; break; case Ets2ItemType.TrafficRule: nodeCount = BitConverter.ToInt32(sector.Stream, offset + 57); // Invalidate unreasonable amount of node counts.. if (nodeCount < 0x20) { Valid = true; for (int i = 0; i < nodeCount; i++) { var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57 + 4 + i * 8); //Console.WriteLine("traffic area node " + i + ": " + nodeUid.ToString("X16")); if (AddNodeUID(nodeUid) == false) { //Console.WriteLine("Could not add traffic area node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16")); break; } } } BlockSize = 73 + 8 * nodeCount; break; case Ets2ItemType.Trigger: nodeCount = BitConverter.ToInt32(sector.Stream, offset + 57); // Invalidate unreasonable amount of node counts.. if (nodeCount < 0x20) { Valid = true; for (int i = 0; i < nodeCount; i++) { var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57 + 4 + i * 8); //Console.WriteLine("trigger node " + i + ": " + nodeUid.ToString("X16")); if (AddNodeUID(nodeUid) == false) { //Console.WriteLine("Could not add trigger node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16")); break; } } } BlockSize = 117 + 8 * nodeCount; break; case Ets2ItemType.BusStop: var busStopUid = BitConverter.ToUInt64(sector.Stream, offset + 73); BlockSize = 81; Valid = AddNodeUID(busStopUid); break; case Ets2ItemType.Garage: // TODO: at offset 65 there is a int '1' value.. is it a list? var garageUid = BitConverter.ToUInt64(sector.Stream, offset + 69); BlockSize = 85; Valid = AddNodeUID(garageUid); break; case Ets2ItemType.FuelPump: var dunno2Uid = BitConverter.ToUInt64(sector.Stream, offset + 57); BlockSize = 73; Valid = AddNodeUID(dunno2Uid); break; case Ets2ItemType.Dunno: Valid = true; break; case Ets2ItemType.Service: var locationNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57); Valid = AddNodeUID(locationNodeUid); BlockSize = 73; break; case Ets2ItemType.City: var CityID = BitConverter.ToUInt64(sector.Stream, offset + 57); var NodeID = BitConverter.ToUInt64(sector.Stream, offset + 73); if ((CityID >> 56) != 0) { break; } City = Sector.Mapper.LookupCityID(CityID); Valid = City != string.Empty && NodeID != 0 && sector.Mapper.Nodes.ContainsKey(NodeID); if (!Valid) { Console.WriteLine("Unknown city ID " + CityID.ToString("X16") + " at " + ItemUID.ToString("X16")); } else { StartNodeUID = NodeID; //Console.WriteLine(CityID.ToString("X16") + " === " + City); } BlockSize = 81; break; default: Valid = false; break; } //if (Valid) // Console.WriteLine("Item " + uid.ToString("X16") + " (" + Type.ToString() + ") is found at " + offset.ToString("X")); } public int BlockSize { get; private set; } // City/company info public string City { get; private set; } public string Company { get; set; } public Ets2Node EndNode { get; private set; } public ulong EndNodeUID { get; private set; } public int FileOffset { get; set; } public string FilePath { get; set; } public bool HideUI { get; private set; } public ulong ItemUID { get; private set; } // Dictionary <Prefab> , <NavigationWeight, Length, RoadList>> public Dictionary<Ets2Item, Tuple<float, float, IEnumerable<Ets2Item>>> Navigation { get; private set; } public Dictionary<ulong, Ets2Node> NodesList { get; private set; } /** Item specific values/interpretations **/ // Prefab type public Ets2Prefab Prefab { get; private set; } public Ets2Node PrefabNode { get; set; } public ulong PrefabNodeUID { get; set; } // Road info public Ets2RoadLook RoadLook { get; private set; } public IEnumerable<PointF> RoadPolygons { get; private set; } public Ets2Sector Sector { get; private set; } public Ets2Node StartNode { get; private set; } public ulong StartNodeUID { get; private set; } public Ets2ItemType Type { get; set; } public bool Valid { get; private set; } public bool Apply(Ets2Node node) { if (node.NodeUID == PrefabNodeUID) { PrefabNode = node; } if (node.NodeUID == StartNodeUID) { StartNode = node; return true; } else if (node.NodeUID == EndNodeUID) { EndNode = node; return true; } else if (NodesList.ContainsKey(node.NodeUID)) { NodesList[node.NodeUID] = node; return true; } else { //Console.WriteLine("Could not apply node " + node.NodeUID.ToString("X16") + " to item " + ItemUID.ToString("X16")); return false; } } /// <summary> /// Generate road curves for a specific lane. The curve is generated with [steps] /// nodes and positioned left or right from the road's middle point. /// Additionally, each extra lane is shifted 4.5 game units outward. /// </summary> /// <param name="steps"></param> /// <param name="leftlane"></param> /// <param name="lane"></param> /// <returns></returns> public IEnumerable<Ets2Point> GenerateRoadCurve(int steps, bool leftlane, int lane) { var ps = new Ets2Point[steps]; var sx = StartNode.X; var ex = EndNode.X; var sz = StartNode.Z; var ez = EndNode.Z; if (steps == 2) { sx += (float) Math.Sin(-StartNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f); sz += (float) Math.Cos(-StartNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f); ex += (float) Math.Sin(-EndNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f); ez += (float) Math.Cos(-EndNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f); ps[0] = new Ets2Point(sx, 0, sz, StartNode.Yaw); ps[1] = new Ets2Point(ex, 0, ez, EndNode.Yaw); return ps; } var radius = (float) Math.Sqrt((sx - ex) * (sx - ex) + (sz - ez) * (sz - ez)); var tangentSX = (float) Math.Cos(-StartNode.Yaw) * radius; var tangentEX = (float) Math.Cos(-EndNode.Yaw) * radius; var tangentSZ = (float) Math.Sin(-StartNode.Yaw) * radius; var tangentEZ = (float) Math.Sin(-EndNode.Yaw) * radius; for (int k = 0; k < steps; k++) { var s = (float) k / (float) (steps - 1); var x = (float) Ets2CurveHelper.Hermite(s, sx, ex, tangentSX, tangentEX); var z = (float) Ets2CurveHelper.Hermite(s, sz, ez, tangentSZ, tangentEZ); var tx = (float) Ets2CurveHelper.HermiteTangent(s, sx, ex, tangentSX, tangentEX); var ty = (float) Ets2CurveHelper.HermiteTangent(s, sz, ez, tangentSZ, tangentEZ); var yaw = (float) Math.Atan2(ty, tx); x += (float) Math.Sin(-yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f); z += (float) Math.Cos(-yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f); ps[k] = new Ets2Point(x, 0, z, yaw); } return ps; } public void GenerateRoadPolygon(int steps) { if (RoadPolygons == null) RoadPolygons = new PointF[0]; if (RoadPolygons != null && RoadPolygons.Count() == steps) return; if (StartNode == null || EndNode == null) return; if (Type != Ets2ItemType.Road) return; var ps = new PointF[steps]; var sx = StartNode.X; var ex = EndNode.X; var sy = StartNode.Z; var ey = EndNode.Z; var radius = (float) Math.Sqrt((sx - ex) * (sx - ex) + (sy - ey) * (sy - ey)); var tangentSX = (float) Math.Cos(-StartNode.Yaw) * radius; var tangentEX = (float) Math.Cos(-EndNode.Yaw) * radius; var tangentSY = (float) Math.Sin(-StartNode.Yaw) * radius; var tangentEY = (float) Math.Sin(-EndNode.Yaw) * radius; for (int k = 0; k < steps; k++) { var s = (float) k / (float) (steps - 1); var x = (float) Ets2CurveHelper.Hermite(s, sx, ex, tangentSX, tangentEX); var y = (float) Ets2CurveHelper.Hermite(s, sy, ey, tangentSY, tangentEY); ps[k] = new PointF(x, y); } RoadPolygons = ps; } public override string ToString() { return "Item #" + ItemUID.ToString("X16") + " (" + Type.ToString() + ")"; } private bool AddNodeUID(ulong nodeUid) { if (nodeUid == 0 || Sector.Mapper.Nodes.ContainsKey(nodeUid) == false) { Valid = false; return false; } else { NodesList.Add(nodeUid, null); return true; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Linq; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish; using Microsoft.WindowsAzure.Commands.Common.Storage; using Microsoft.WindowsAzure.Storage.Auth; using System; using System.Management.Automation; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions.DSC { /// <summary> /// Uploads a Desired State Configuration script to Azure blob storage, which /// later can be applied to Azure Virtual Machines using the /// Set-AzureVMDscExtension cmdlet. /// </summary> [Cmdlet( VerbsData.Publish, "AzureVMDscConfiguration", SupportsShouldProcess = true, DefaultParameterSetName = UploadArchiveParameterSetName), OutputType( typeof(String))] public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase { private const string CreateArchiveParameterSetName = "CreateArchive"; private const string UploadArchiveParameterSetName = "UploadArchive"; /// <summary> /// Path to a file containing one or more configurations; the file can be a /// PowerShell script (*.ps1) or MOF interface (*.mof). /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file containing one or more configurations")] [ValidateNotNullOrEmpty] public string ConfigurationPath { get; set; } /// <summary> /// Name of the Azure Storage Container the configuration is uploaded to. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")] [ValidateNotNullOrEmpty] public string ContainerName { get; set; } /// <summary> /// By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs. /// Use -Force to overwrite them. /// </summary> [Parameter(HelpMessage = "By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs")] public SwitchParameter Force { get; set; } /// <summary> /// The Azure Storage Context that provides the security settings used to upload /// the configuration script to the container specified by ContainerName. This /// context should provide write access to the container. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "The Azure Storage Context that provides the security settings used to upload " + "the configuration script to the container specified by ContainerName")] [ValidateNotNullOrEmpty] public AzureStorageContext StorageContext { get; set; } /// <summary> /// Path to a local ZIP file to write the configuration archive to. /// When using this parameter, Publish-AzureVMDscConfiguration creates a /// local ZIP archive instead of uploading it to blob storage.. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CreateArchiveParameterSetName, HelpMessage = "Path to a local ZIP file to write the configuration archive to.")] [ValidateNotNullOrEmpty] public string ConfigurationArchivePath { get; set; } /// <summary> /// Suffix for the storage end point, e.g. core.windows.net /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")] [ValidateNotNullOrEmpty] public string StorageEndpointSuffix { get; set; } /// <summary> /// Excludes DSC resource dependencies from the configuration archive /// </summary> [Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")] public SwitchParameter SkipDependencyDetection { get; set; } /// <summary> ///Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")] [ValidateNotNullOrEmpty] public string ConfigurationDataPath { get; set; } /// <summary> /// Path to a file or a directory to include in the configuration archive /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file or a directory to include in the configuration archive")] [ValidateNotNullOrEmpty] public String[] AdditionalPath { get; set; } /// <summary> /// Outputs the blob url for configuration archive path /// </summary> [Parameter(HelpMessage = "Outputs the blob url for configuration archive path")] public SwitchParameter PassThru { get; set; } /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; protected override void ProcessRecord() { try { // Create a cloud context, only in case of upload. if (ParameterSetName == UploadArchiveParameterSetName) { base.ProcessRecord(); } ExecuteCommand(); } finally { DeleteTemporaryFiles(); } } private void ExecuteCommand() { //check the PS version ValidatePsVersion(); //validate cmdlet params ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath); ValidateConfigurationPath(ConfigurationPath, ParameterSetName); if (ConfigurationDataPath != null) { ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath); ValidateConfigurationDataPath(ConfigurationDataPath); } if(AdditionalPath != null && AdditionalPath.Length > 0) { for(var count = 0; count < AdditionalPath.Length; count++) { AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]); } } switch (ParameterSetName) { case CreateArchiveParameterSetName: ConfigurationArchivePath = GetUnresolvedProviderPathFromPSPath(ConfigurationArchivePath); break; case UploadArchiveParameterSetName: _storageCredentials = this.GetStorageCredentials(StorageContext); if (ContainerName == null) { ContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (StorageEndpointSuffix == null) { StorageEndpointSuffix = Profile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } break; } PublishConfiguration( ConfigurationPath, ConfigurationDataPath, AdditionalPath, ConfigurationArchivePath, StorageEndpointSuffix, ContainerName, ParameterSetName, Force.IsPresent, SkipDependencyDetection.IsPresent, _storageCredentials, PassThru.IsPresent ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class MinTests { // Get a set of ranges from 0 to each count, with an extra parameter for a minimum where each item is negated (-x). public static IEnumerable<object[]> MinData(int[] counts) { Func<int, int> min = x => 1 - x; foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), min)) { yield return results; } } // // Min // [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Int(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Min()); Assert.Equal(0, query.Select(x => (int?)x).Min()); Assert.Equal(min, query.Min(x => -x)); Assert.Equal(min, query.Min(x => -(int?)x)); } [Theory] [OuterLoop] [MemberData("MinData", (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int min) { Min_Int(labeled, count, min); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (int?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(int?)x : null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (int?)null).Min()); Assert.Null(query.Min(x => (int?)null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Long(Labeled<ParallelQuery<int>> labeled, int count, long min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (long)x).Min()); Assert.Equal(0, query.Select(x => (long?)x).Min()); Assert.Equal(min, query.Min(x => -(long)x)); Assert.Equal(min, query.Min(x => -(long?)x)); } [Theory] [OuterLoop] [MemberData("MinData", (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long min) { Min_Long(labeled, count, min); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (long?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(long?)x : null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (long?)null).Min()); Assert.Null(query.Min(x => (long?)null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Float(Labeled<ParallelQuery<int>> labeled, int count, float min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (float)x).Min()); Assert.Equal(0, query.Select(x => (float?)x).Min()); Assert.Equal(min, query.Min(x => -(float)x)); Assert.Equal(min, query.Min(x => -(float?)x)); Assert.Equal(float.NegativeInfinity, query.Select(x => x == count / 2 ? float.NegativeInfinity : x).Min()); Assert.Equal(float.NegativeInfinity, query.Select(x => x == count / 2 ? (float?)float.NegativeInfinity : x).Min()); Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? float.NaN : x).Min()); Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? (float?)float.NaN : x).Min()); } [Theory] [OuterLoop] [MemberData("MinData", (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float min) { Min_Float(labeled, count, min); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (float?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(float?)x : null)); } [Theory] [MemberData("MinData", (object)(new int[] { 3 }))] public static void Min_Float_Special(Labeled<ParallelQuery<int>> labeled, int count, float min) { // Null is defined as 'least' when ordered, but is not the minimum. Func<int, float?> translate = x => x % 3 == 0 ? (float?)null : x % 3 == 1 ? float.MinValue : float.NaN; ParallelQuery<int> query = labeled.Item; Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? float.NaN : float.MinValue).Min()); Assert.Equal(float.NaN, query.Select(translate).Min()); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (float?)null).Min()); Assert.Null(query.Min(x => (float?)null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Double(Labeled<ParallelQuery<int>> labeled, int count, double min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (double)x).Min()); Assert.Equal(0, query.Select(x => (double?)x).Min()); Assert.Equal(min, query.Min(x => -(double)x)); Assert.Equal(min, query.Min(x => -(double?)x)); Assert.Equal(double.NegativeInfinity, query.Select(x => x == count / 2 ? double.NegativeInfinity : x).Min()); Assert.Equal(double.NegativeInfinity, query.Select(x => x == count / 2 ? (double?)double.NegativeInfinity : x).Min()); Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? double.NaN : x).Min()); Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? (double?)double.NaN : x).Min()); } [Theory] [OuterLoop] [MemberData("MinData", (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double min) { Min_Double(labeled, count, min); } [Theory] [MemberData("MinData", (object)(new int[] { 3 }))] public static void Min_Double_Special(Labeled<ParallelQuery<int>> labeled, int count, double min) { // Null is defined as 'least' when ordered, but is not the minimum. Func<int, double?> translate = x => x % 3 == 0 ? (double?)null : x % 3 == 1 ? double.MinValue : double.NaN; ParallelQuery<int> query = labeled.Item; Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? double.NaN : double.MinValue).Min()); Assert.Equal(double.NaN, query.Select(translate).Min()); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (double?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(double?)x : null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (double?)null).Min()); Assert.Null(query.Min(x => (double?)null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (decimal)x).Min()); Assert.Equal(0, query.Select(x => (decimal?)x).Min()); Assert.Equal(min, query.Min(x => -(decimal)x)); Assert.Equal(min, query.Min(x => -(decimal?)x)); } [Theory] [OuterLoop] [MemberData("MinData", (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { Min_Decimal(labeled, count, min); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (decimal?)x : null).Min()); Assert.Equal(min, query.Min(x => x >= count / 2 ? -(decimal?)x : null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (decimal?)null).Min()); Assert.Null(query.Min(x => (decimal?)null)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Other(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => DelgatedComparable.Delegate(x, Comparer<int>.Default)).Min().Value); Assert.Equal(count - 1, query.Select(x => DelgatedComparable.Delegate(x, ReverseComparer.Instance)).Min().Value); } [Theory] [OuterLoop] [MemberData("MinData", (object)(new int[] { 1024 * 32, 1024 * 1024 }))] public static void Min_Other_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int min) { Min_Other(labeled, count, min); } [Theory] [MemberData("MinData", (object)(new int[] { 1, }))] public static void Min_NotComparable(Labeled<ParallelQuery<int>> labeled, int count, int min) { NotComparable a = new NotComparable(0); Assert.Equal(a, labeled.Item.Min(x => a)); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Other_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count / 2, query.Min(x => x >= count / 2 ? DelgatedComparable.Delegate(x, Comparer<int>.Default) : null).Value); Assert.Equal(count - 1, query.Min(x => x >= count / 2 ? DelgatedComparable.Delegate(x, ReverseComparer.Instance) : null).Value); } [Theory] [MemberData("MinData", (object)(new int[] { 1, 2, 16 }))] public static void Min_Other_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int min) { ParallelQuery<int> query = labeled.Item; Assert.Null(query.Select(x => (string)null).Min()); Assert.Null(query.Min(x => (string)null)); } [Theory] [MemberData("Ranges", (object)(new int[] { 0 }), MemberType = typeof(UnorderedSources))] public static void Min_EmptyNullable(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Null(labeled.Item.Min(x => (int?)x)); Assert.Null(labeled.Item.Min(x => (long?)x)); Assert.Null(labeled.Item.Min(x => (float?)x)); Assert.Null(labeled.Item.Min(x => (double?)x)); Assert.Null(labeled.Item.Min(x => (decimal?)x)); Assert.Null(labeled.Item.Min(x => new object())); } [Theory] [MemberData("Ranges", (object)(new int[] { 0 }), MemberType = typeof(UnorderedSources))] public static void Min_InvalidOperationException(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Throws<InvalidOperationException>(() => labeled.Item.Min()); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (long)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (float)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (double)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (decimal)x)); Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => new NotComparable(x))); } [Theory] [MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Min_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (decimal?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => new NotComparable(x))); } [Theory] [MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Min_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, NotComparable>)(x => { throw new DeliberateTestException(); }))); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Min_AggregateException_NotComparable(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<ArgumentException>(() => labeled.Item.Min(x => new NotComparable(x))); } [Fact] public static void Min_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Min((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Min((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Min((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Min((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Min((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Min((Func<float?, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Min((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Min((Func<double?, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Min((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Min((Func<decimal?, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<NotComparable>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Min((Func<int, NotComparable>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<object>)null).Min()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(new object(), 1).Min((Func<object, object>)null)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Text.RegularExpressions; using Microsoft.NodejsTools.Debugger; using Microsoft.NodejsTools.Debugger.Commands; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; namespace NodejsTests.Debugger.Commands { [TestClass] public class SetBreakpointCommandTests { [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateLocalScriptRegExpShouldCreateCaseInSensitiveRegularExpression() { const string drive = "c:"; var pathParts = new[] { "nOdE", "IS", "awesome.js" }; string fileName = Path.Combine(drive, Path.Combine(pathParts)); var scriptRegExp = new Regex(SetBreakpointCommand.CreateLocalScriptRegExp(fileName)); Assert.IsTrue(scriptRegExp.IsMatch(fileName)); Assert.IsTrue(scriptRegExp.IsMatch(fileName.ToUpperInvariant())); Assert.IsTrue(scriptRegExp.IsMatch(fileName.ToLowerInvariant())); Assert.IsTrue(scriptRegExp.IsMatch(Path.Combine(drive.ToUpperInvariant(), Path.Combine(pathParts)))); Assert.IsTrue(scriptRegExp.IsMatch(Path.Combine(drive.ToLowerInvariant(), Path.Combine(pathParts)))); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateLocalScriptRegExpShouldOnlyMatchExactPath() { const string drive = "c:"; var pathParts = new[] { "nOdE", "IS", "awsome.js" }; string fileName = Path.Combine(drive, Path.Combine(pathParts)); var scriptRegExp = new Regex(SetBreakpointCommand.CreateLocalScriptRegExp(fileName)); Assert.IsFalse(scriptRegExp.IsMatch(Path.Combine("d:", Path.Combine(pathParts)))); Assert.IsFalse(scriptRegExp.IsMatch(fileName + 'x')); Assert.IsFalse(scriptRegExp.IsMatch(Path.Combine(fileName, "x"))); Assert.IsFalse(scriptRegExp.IsMatch("x" + fileName)); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateSetBreakpointCommand() { // Arrange const int commandId = 3; const int moduleId = 5; const int line = 2; const int column = 0; const string fileName = "module.js"; var module = new NodeModule(moduleId, fileName); var breakOn = new BreakOn(BreakOnKind.Equal, 2); var position = new FilePosition(fileName, line, column); var breakpoint = new NodeBreakpoint(null, position, true, breakOn, null); // Act var setBreakpointCommand = new SetBreakpointCommand(commandId, module, breakpoint, false, false); // Assert Assert.AreEqual(commandId, setBreakpointCommand.Id); Assert.AreEqual( string.Format( "{{\"command\":\"setbreakpoint\",\"seq\":{0},\"type\":\"request\",\"arguments\":{{\"line\":{1},\"column\":{2},\"type\":\"scriptId\",\"target\":{3},\"ignoreCount\":1}}}}", commandId, line, column, module.Id), setBreakpointCommand.ToString()); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateSetBreakpointCommandOnFirstLine() { // Arrange const int commandId = 3; const int moduleId = 5; const int line = 0; const int column = 0; const string fileName = "c:\\module.js"; var module = new NodeModule(moduleId, fileName); var breakOn = new BreakOn(BreakOnKind.Equal, 2); var position = new FilePosition(fileName, line, column); var breakpoint = new NodeBreakpoint(null, position, true, breakOn, null); // Act var setBreakpointCommand = new SetBreakpointCommand(commandId, module, breakpoint, false, false); // Assert Assert.AreEqual(commandId, setBreakpointCommand.Id); Assert.AreEqual( string.Format( "{{\"command\":\"setbreakpoint\",\"seq\":{0},\"type\":\"request\",\"arguments\":{{\"line\":{1},\"column\":{2},\"type\":\"scriptId\",\"target\":{3},\"ignoreCount\":1}}}}", commandId, line, column + NodeConstants.ScriptWrapBegin.Length, module.Id), setBreakpointCommand.ToString()); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateSetBreakpointCommandOnRemoteFile() { // Arrange const int commandId = 3; const int line = 2; const int column = 0; const string fileName = @"module.js"; var breakOn = new BreakOn(BreakOnKind.Equal, 2); var position = new FilePosition(fileName, line, column); var breakpoint = new NodeBreakpoint(null, position, true, breakOn, null); // Act var setBreakpointCommand = new SetBreakpointCommand(commandId, null, breakpoint, false, true); // Assert Assert.AreEqual(commandId, setBreakpointCommand.Id); Assert.AreEqual( string.Format( "{{\"command\":\"setbreakpoint\",\"seq\":{0},\"type\":\"request\",\"arguments\":{{\"line\":{1},\"column\":{2},\"type\":\"scriptRegExp\",\"target\":\"^[Mm][Oo][Dd][Uu][Ll][Ee]\\\\.[Jj][Ss]$\",\"ignoreCount\":1}}}}", commandId, line, column), setBreakpointCommand.ToString()); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateSetBreakpointCommandOnLocalFile() { // Arrange const int commandId = 3; const int line = 2; const int column = 0; const string fileName = @"c:\module.js"; var breakOn = new BreakOn(BreakOnKind.Equal, 2); var position = new FilePosition(fileName, line, column); var breakpoint = new NodeBreakpoint(null, position, true, breakOn, null); // Act var setBreakpointCommand = new SetBreakpointCommand(commandId, null, breakpoint, false, false); // Assert Assert.AreEqual(commandId, setBreakpointCommand.Id); Assert.AreEqual( string.Format( "{{\"command\":\"setbreakpoint\",\"seq\":{0},\"type\":\"request\",\"arguments\":{{\"line\":{1},\"column\":{2},\"type\":\"scriptRegExp\",\"target\":\"{3}\",\"ignoreCount\":1}}}}", commandId, line, column, SetBreakpointCommand.CreateLocalScriptRegExp(fileName).Replace(@"\", @"\\")), setBreakpointCommand.ToString()); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateSetBreakpointCommandWithoutPredicate() { // Arrange const int commandId = 3; const int moduleId = 5; const int line = 2; const int column = 0; const string fileName = "module.js"; var module = new NodeModule(moduleId, fileName); var breakOn = new BreakOn(BreakOnKind.Equal, 2); var position = new FilePosition(fileName, line, column); var breakpoint = new NodeBreakpoint(null, position, true, breakOn, null); // Act var setBreakpointCommand = new SetBreakpointCommand(commandId, module, breakpoint, true, false); // Assert Assert.AreEqual(commandId, setBreakpointCommand.Id); Assert.AreEqual( string.Format( "{{\"command\":\"setbreakpoint\",\"seq\":{0},\"type\":\"request\",\"arguments\":{{\"line\":{1},\"column\":{2},\"type\":\"scriptId\",\"target\":{3}}}}}", commandId, line, column, moduleId), setBreakpointCommand.ToString()); } [TestMethod, Priority(0), TestCategory("Debugging")] public void ProcessSetBreakpointResponse() { // Arrange const int commandId = 3; const int moduleId = 33; const int line = 2; const int column = 0; const string fileName = "module.js"; var module = new NodeModule(moduleId, fileName); var breakOn = new BreakOn(BreakOnKind.Equal, 2); var position = new FilePosition(fileName, line, column); var breakpoint = new NodeBreakpoint(null, position, true, breakOn, null); var setBreakpointCommand = new SetBreakpointCommand(commandId, module, breakpoint, false, false); JObject breakpointResponse = SerializationTestData.GetSetBreakpointResponse(); // Act setBreakpointCommand.ProcessResponse(breakpointResponse); // Assert Assert.AreEqual(2, setBreakpointCommand.BreakpointId); Assert.AreEqual(0, setBreakpointCommand.Column); Assert.AreEqual(0, setBreakpointCommand.Line); Assert.AreEqual(false, setBreakpointCommand.Running); Assert.AreEqual(33, setBreakpointCommand.ScriptId); } [TestMethod, Priority(0), TestCategory("Debugging")] public void CreateSetBreakpointCommandWithNullBreakpoint() { // Arrange const int commandId = 3; const int moduleId = 5; const string fileName = "module.js"; var module = new NodeModule(moduleId, fileName); SetBreakpointCommand setBreakpointCommand = null; Exception exception = null; // Act try { setBreakpointCommand = new SetBreakpointCommand(commandId, module, null, false, false); } catch (Exception e) { exception = e; } // Assert Assert.IsNull(setBreakpointCommand); Assert.IsNotNull(exception); Assert.IsInstanceOfType(exception, typeof(ArgumentNullException)); } } }
// /* // SharpNative - C# to D Transpiler // (C) 2014 Irio Systems // */ #region Imports using System; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; #endregion namespace SharpNative.Compiler.DlangAst { public class CSharpToDlangRewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; public CSharpToDlangRewriter(SemanticModel semanticModel) { _semanticModel = semanticModel; } public override SyntaxNode Visit(SyntaxNode node) { Context.LastNode = node; try { if (node is NameEqualsSyntax) return (node); // SyntaxNode visit; //Needs update // if (FixPropertyUnaryExpressions(node, out visit)) // return visit; if (node is IdentifierNameSyntax && // (node.Parent is ExpressionSyntax || node.Parent is MethodDeclarationSyntax || node.Parent is PropertyDeclarationSyntax // || node.Parent is BlockSyntax) && !(node.Parent.Parent is InitializerExpressionSyntax) && !(node.Parent is QualifiedNameSyntax) && !(node.Parent is MemberAccessExpressionSyntax) && !(node.Parent is ThisExpressionSyntax)) { //Lets fully qualify these so that we can have property code working var symbolInfo = _semanticModel.GetSymbolInfo(node); if (symbolInfo.Symbol != null && (symbolInfo.Symbol.Kind == SymbolKind.Field || symbolInfo.Symbol.Kind == SymbolKind.Property)) { if (symbolInfo.Symbol.ContainingType != null && symbolInfo.Symbol.IsStatic) { var newName = symbolInfo.Symbol.ContainingType.GetFullNameCSharp() + "." + symbolInfo.Symbol.Name; return SyntaxFactory.ParseExpression(newName); } else { var firstParent = TypeProcessor.GetDeclaredSymbol(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First()); //_semanticModel.GetSymbolInfo(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First()); if (symbolInfo.Symbol.ContainingType != null && !symbolInfo.Symbol.IsStatic && symbolInfo.Symbol.ContainingType == firstParent) return SyntaxFactory.ParseExpression("this." + symbolInfo.Symbol.Name); } return base.Visit(node); } } if (node is MemberAccessExpressionSyntax && // (node.Parent is ExpressionSyntax || node.Parent is MethodDeclarationSyntax || node.Parent is PropertyDeclarationSyntax // || node.Parent is BlockSyntax) && !(node.Parent.Parent is InitializerExpressionSyntax) && !(node.Parent is QualifiedNameSyntax) && !(node.Parent is MemberAccessExpressionSyntax) && !(node.Parent is ThisExpressionSyntax)) { var nodeasMember = node as MemberAccessExpressionSyntax; if (!(nodeasMember.Expression is ThisExpressionSyntax)) { //Lets fully qualify these so that we can have property code working var symbolInfo = _semanticModel.GetSymbolInfo(node); if (symbolInfo.Symbol != null && (symbolInfo.Symbol.Kind == SymbolKind.Field || symbolInfo.Symbol.Kind == SymbolKind.Property)) { if (symbolInfo.Symbol.ContainingType != null && symbolInfo.Symbol.IsStatic) { var newName = symbolInfo.Symbol.ContainingType.GetFullNameCSharp() + "." + symbolInfo.Symbol.Name; return SyntaxFactory.ParseExpression(newName); } else { ISymbol symbol = TypeProcessor.GetSymbolInfo((node as MemberAccessExpressionSyntax).Expression).Symbol; if ( symbol != null && (!(symbol is ILocalSymbol) && !(symbol is IParameterSymbol) && symbol.Name != ".ctor")) { var firstParent = TypeProcessor.GetDeclaredSymbol( node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First()); //_semanticModel.GetSymbolInfo(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First()); if (symbolInfo.Symbol.ContainingType != null && !symbolInfo.Symbol.IsStatic && symbolInfo.Symbol.ContainingType == firstParent) return SyntaxFactory.ParseExpression("this." + node.ToFullString()); } } } return base.Visit(node); } } return base.Visit(node); } catch (Exception ex) { throw ex; } } public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node) //TODO: Should fix string switch here { return base.VisitSwitchSection(node); } private static bool FixPropertyUnaryExpressions(SyntaxNode node, out SyntaxNode visit) { if (node is PostfixUnaryExpressionSyntax) { var expression = node as PostfixUnaryExpressionSyntax; if (expression.Operand is MemberAccessExpressionSyntax) { var memberAccess = expression.Operand as MemberAccessExpressionSyntax; var typeInfo = TypeProcessor.GetSymbolInfo(memberAccess.Name); if (typeInfo.Symbol.Kind == SymbolKind.Property) { switch (expression.OperatorToken.RawKind) { case (int) SyntaxKind.MinusMinusToken: var refactored = SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, expression.Operand, SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, expression.Operand, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1))) ).NormalizeWhitespace(); { visit = refactored; return true; } case (int) SyntaxKind.PlusPlusToken: var refactored1 = SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, expression.Operand, SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, expression.Operand, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1))) ).NormalizeWhitespace(); { visit = refactored1; return true; } default: throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " + Utility.Descriptor(expression)); } } } } if (node is PrefixUnaryExpressionSyntax) { var expression = node as PrefixUnaryExpressionSyntax; if (expression.Operand is MemberAccessExpressionSyntax) { var memberAccess = expression.Operand as MemberAccessExpressionSyntax; var typeInfo = TypeProcessor.GetSymbolInfo(memberAccess.Name); if (typeInfo.Symbol.Kind == SymbolKind.Property) { switch (expression.OperatorToken.RawKind) { case (int) SyntaxKind.MinusMinusToken: var refactored = SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, expression.Operand, SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, expression.Operand, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1))) ).NormalizeWhitespace(); { visit = refactored; return true; } case (int) SyntaxKind.PlusPlusToken: var refactored1 = SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, expression.Operand, SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, expression.Operand, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1))) ).NormalizeWhitespace(); { visit = refactored1; return true; } default: throw new Exception("No support for " + expression.OperatorToken.RawKind + " at " + Utility.Descriptor(expression)); } } } } visit = null; return false; } } }
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System; using System.Threading; using System.Threading.Tasks; using Amqp; using Amqp.Framing; using Amqp.Types; using System.Linq; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Test.Amqp { [TestClass] public class TaskTests { private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(10); TestTarget testTarget = new TestTarget(); [ClassInitialize] public static void Initialize(TestContext context) { } #if !NETFX40 [TestMethod] public async Task BasicSendReceiveAsync() { string testName = "BasicSendReceiveAsync"; int nMsgs = 100; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); } [TestMethod] public async Task InterfaceSendReceiveAsync() { string testName = "BasicSendReceiveAsync"; int nMsgs = 100; IConnectionFactory factory = new ConnectionFactory(); IConnection connection = await factory.CreateAsync(this.testTarget.Address); ISession session = connection.CreateSession(); ISenderLink sender = session.CreateSender("sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(Timeout.InfiniteTimeSpan); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); } [TestMethod] public async Task SendToNonExistingAsync() { string testName = "SendToNonExistingAsync"; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "$explicit:sender-" + testName, Guid.NewGuid().ToString()); try { await sender.SendAsync(new Message("test")); Assert.IsTrue(false, "Send should fail with not-found error"); } catch (AmqpException exception) { Assert.AreEqual((Symbol)ErrorCode.NotFound, exception.Error.Condition); } await connection.CloseAsync(); } [TestMethod] public async Task ReceiveFromNonExistingAsync() { string testName = "ReceiveFromNonExistingAsync"; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "$explicit:receiver-" + testName, Guid.NewGuid().ToString()); try { await receiver.ReceiveAsync(); Assert.IsTrue(false, "Receive should fail with not-found error"); } catch (AmqpException exception) { Assert.AreEqual((Symbol)ErrorCode.NotFound, exception.Error.Condition); } await connection.CloseAsync(); } [TestMethod] public async Task ReceiverSenderAsync() { string testName = "ReceiverSenderAsync"; ConnectionFactory connectionFactory = new ConnectionFactory(); // Creating first ReceiverLink Connection firstReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address); Session firstReceiverSession = new Session(firstReceiverConnection); ReceiverLink firstReceiverLink = new ReceiverLink(firstReceiverSession, "receiver-link", testName); // Does not work when creating SenderLink after first ReceiverLink var senderConnection = await connectionFactory.CreateAsync(this.testTarget.Address); var senderSession = new Session(senderConnection); var senderLink = new SenderLink(senderSession, "sender-link", testName); // Send and receive message await senderLink.SendAsync(new Message(testName)); Message firstMessageReceived = await firstReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000)); // Close first reveiver link await firstReceiverLink.CloseAsync(); await firstReceiverSession.CloseAsync(); await firstReceiverConnection.CloseAsync(); // Creating second ReceiverLink Connection secondReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address); Session secondReceiverSession = new Session(secondReceiverConnection); ReceiverLink secondReceiverLink = new ReceiverLink(secondReceiverSession, "receiver-link", testName); // Send and receive message await senderLink.SendAsync(new Message(testName)); Message message = await secondReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000)); Assert.IsTrue(message != null, "No message received"); secondReceiverLink.Accept(message); // Close second reveiver link await secondReceiverLink.CloseAsync(); await secondReceiverSession.CloseAsync(); await secondReceiverConnection.CloseAsync(); // Close sender link await senderLink.CloseAsync(); await senderSession.CloseAsync(); await senderConnection.CloseAsync(); } #endif #if NETFX40 // 40 cannot handle TestMethod with Task return type // MsTest fails with "Index was outside the bounds of the array." [TestMethod] public void BasicSendReceiveAsync() { this.BasicSendReceiveAsyncTest().GetAwaiter().GetResult(); } async Task BasicSendReceiveAsyncTest() { string testName = "BasicSendReceiveAsync"; int nMsgs = 100; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); } #endif #if NETFX && !NETFX40 [TestMethod] public async Task CustomMessageBody() { string testName = "CustomMessageBody"; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); Student student = new Student("Tom"); student.Age = 16; student.Address = new StreetAddress() { FullAddress = "100 Main St. Small Town" }; student.DateOfBirth = new System.DateTime(1988, 5, 1, 1, 2, 3, 100, System.DateTimeKind.Utc); Message message = new Message(student); message.Properties = new Properties() { MessageId = "student" }; await sender.SendAsync(message); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); Message message2 = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message2.Properties); receiver.Accept(message2); await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); Student student2 = message2.GetBody<Student>(); Assert.AreEqual(student.Age, student2.Age - 1); // incremented in OnDeserialized Assert.AreEqual(student.DateOfBirth, student2.DateOfBirth); Assert.AreEqual(student.Address.FullAddress, student2.Address.FullAddress); } [TestMethod] public async Task LargeMessageSendReceiveAsync() { string testName = "LargeMessageSendReceiveAsync"; int nMsgs = 50; Connection connection = await Connection.Factory.CreateAsync( this.testTarget.Address, new Open() { ContainerId = "c1", MaxFrameSize = 4096 }, null); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); int messageSize = 100 * 1024; for (int i = 0; i < nMsgs; ++i) { Message message = new Message(new string('D', messageSize)); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); string value = message.GetBody<string>(); Trace.WriteLine(TraceLevel.Information, "receive: {0} body {1}x{2}", message.ApplicationProperties["sn"], value[0], value.Length); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); } [TestMethod] public async Task LargeMessageOnMessageCallback() { string testName = "LargeMessageOnMessageCallback"; int nMsgs = 50; Connection connection = await Connection.Factory.CreateAsync( this.testTarget.Address, new Open() { ContainerId = "c1", MaxFrameSize = 4096 }, null); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); int messageSize = 10 * 1024; for (int i = 0; i < nMsgs; ++i) { Message message = new Message(new string('D', messageSize)); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); ManualResetEvent done = new ManualResetEvent(false); int count = 0; receiver.Start(30, (link, message) => { string value = message.GetBody<string>(); Trace.WriteLine(TraceLevel.Information, "receive: {0} body {1}x{2}", message.ApplicationProperties["sn"], value[0], value.Length); receiver.Accept(message); if (++count == nMsgs) done.Set(); }); Assert.IsTrue(done.WaitOne(120000)); connection.Close(); } [TestMethod] public async Task CustomTransportConfiguration() { string testName = "CustomTransportConfiguration"; ConnectionFactory factory = new ConnectionFactory(); factory.TCP.NoDelay = true; factory.TCP.SendBufferSize = 16 * 1024; factory.TCP.SendTimeout = 30000; factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true; factory.AMQP.MaxFrameSize = 64 * 1024; factory.AMQP.HostName = "contoso.com"; factory.AMQP.ContainerId = "container:" + testName; Address sslAddress = new Address("amqps://guest:guest@127.0.0.1:5671"); Connection connection = await factory.CreateAsync(sslAddress); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); Message message = new Message("custom transport config"); message.Properties = new Properties() { MessageId = testName }; await sender.SendAsync(message); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); Message message2 = await receiver.ReceiveAsync(); Assert.IsTrue(message2 != null, "no message received"); receiver.Accept(message2); await connection.CloseAsync(); } [TestMethod] public async Task ConcurrentWritersMultipleConnections() { // Up to version 2.1.3, multiple writers from a single task could cause // a deadlock (cf issue https://github.com/Azure/amqpnetlite/issues/287) // This test checks that it's fixed const int NbProducerTasks = 4; var data = Enumerable.Range(0, 100 * 1024).Select(x => (byte)x).ToArray(); // Open 2 connections and sender links to 2 queues var connection1 = await Connection.Factory.CreateAsync( testTarget.Address, new Open() { ContainerId = "c1", MaxFrameSize = 4096 }, null); var connection2 = await Connection.Factory.CreateAsync( testTarget.Address, new Open() { ContainerId = "c2", MaxFrameSize = 4096 }, null); var senderLink1 = new SenderLink(new Session(connection1), "Sender 1", "q1"); var senderLink2 = new SenderLink(new Session(connection2), "Sender 2", "q2"); // Start multiple sender tasks that will use both sender links concurrently var tasks = Enumerable.Range(0, NbProducerTasks).Select(_ => Task.Run(async () => { // Send 10 messages on both queues for (int i = 0; i < 10; i++) { var message = new Message() { BodySection = new Data() { Binary = data } }; await senderLink1.SendAsync(message, TimeSpan.FromSeconds(10)); await senderLink2.SendAsync(message, TimeSpan.FromSeconds(10)); } })); var sendersFinished = Task.WhenAll(tasks); var timeoutTask = Task.Delay(TestTimeout); Assert.AreEqual(sendersFinished, await Task.WhenAny(sendersFinished, timeoutTask), "Probable deadlock detected: timeout while waiting for concurrent sender tasks to complete"); await connection1.CloseAsync(); await connection2.CloseAsync(); } [TestMethod] public async Task ConcurrentWritersOneConnectionSession() { const int NbProducerTasks = 4; var data = Enumerable.Range(0, 100 * 1024).Select(x => (byte)x).ToArray(); var connection = await Connection.Factory.CreateAsync(testTarget.Address); var session = new Session(connection); var senderLink1 = new SenderLink(session, "Sender 1", "q1"); var senderLink2 = new SenderLink(session, "Sender 2", "q2"); // Start multiple sender tasks that will use both sender links concurrently var tasks = Enumerable.Range(0, NbProducerTasks).Select(t => Task.Run(async () => { for (int i = 0; i < 10; i++) { var message = new Message() { BodySection = new Data() { Binary = data } }; await senderLink1.SendAsync(message, TimeSpan.FromSeconds(30)); await senderLink2.SendAsync(message, TimeSpan.FromSeconds(30)); } })); var sendersFinished = Task.WhenAll(tasks); var timeoutTask = Task.Delay(TestTimeout); Assert.AreEqual(sendersFinished, await Task.WhenAny(sendersFinished, timeoutTask), "Probable deadlock detected: timeout while waiting for concurrent sender tasks to complete"); await connection.CloseAsync(); } [TestMethod] public async Task ConcurrentLinkCreateClose() { const int NbProducerTasks = 4; var connection = await Connection.Factory.CreateAsync(testTarget.Address); var session = new Session(connection); var tasks = Enumerable.Range(0, NbProducerTasks).Select(n => Task.Run(async () => { for (int i = 0; i < 100; i++) { var senderLink = new SenderLink(session, $"link{n % NbProducerTasks}", $"q{n % 2}"); await senderLink.CloseAsync().ConfigureAwait(false); } })); await Task.WhenAll(tasks); await connection.CloseAsync(); } #endif } }
// // Mono.System.Xml.Query.XQueryConvert // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2004 Novell Inc. // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System; using System.Globalization; using System.IO; using System.Text; using Mono.System.Xml; using Mono.System.Xml.Schema; namespace Mono.System.Xml { // basically this class is obsoleted and removed from .NET 2.0. internal class XQueryConvert { private XQueryConvert () { } public static XmlTypeCode GetFallbackType (XmlTypeCode type) { switch (type) { case XmlTypeCode.AnyAtomicType: return XmlTypeCode.Item; case XmlTypeCode.UntypedAtomic: return XmlTypeCode.String; case XmlTypeCode.Notation: return XmlTypeCode.QName; case XmlTypeCode.NormalizedString: case XmlTypeCode.Token: case XmlTypeCode.Language: case XmlTypeCode.NmToken: case XmlTypeCode.Name: case XmlTypeCode.NCName: case XmlTypeCode.Id: case XmlTypeCode.Idref: case XmlTypeCode.Entity: return XmlTypeCode.String; case XmlTypeCode.NonPositiveInteger: return XmlTypeCode.Decimal; case XmlTypeCode.NegativeInteger: return XmlTypeCode.NonPositiveInteger; case XmlTypeCode.Long: return XmlTypeCode.Integer; case XmlTypeCode.Short: return XmlTypeCode.Int; case XmlTypeCode.Byte: return XmlTypeCode.Int; case XmlTypeCode.NonNegativeInteger: return XmlTypeCode.Decimal; case XmlTypeCode.UnsignedLong: return XmlTypeCode.NonNegativeInteger; case XmlTypeCode.UnsignedInt: return XmlTypeCode.Integer; case XmlTypeCode.UnsignedShort: return XmlTypeCode.Int; case XmlTypeCode.UnsignedByte: return XmlTypeCode.UnsignedShort; case XmlTypeCode.PositiveInteger: return XmlTypeCode.NonNegativeInteger; default: return XmlTypeCode.None; } } // Individual conversion public static string AnyUriToString (string value) { return value; } public static byte [] Base64BinaryToHexBinary (byte [] value) { return XmlConvert.FromBinHexString (Convert.ToBase64String (value)); } public static string Base64BinaryToString (byte [] value) { return Convert.ToBase64String (value); } public static decimal BooleanToDecimal (bool value) { return Convert.ToDecimal (value); } public static double BooleanToDouble (bool value) { return Convert.ToDouble (value); } public static float BooleanToFloat (bool value) { return Convert.ToSingle (value); } public static int BooleanToInt (bool value) { return Convert.ToInt32 (value); } public static long BooleanToInteger (bool value) { return Convert.ToInt64 (value); } public static string BooleanToString (bool value) { // It looks not returning "True" return value ? "true" : "false"; } public static DateTime DateTimeToDate (DateTime value) { return value.Date; } public static DateTime DateTimeToGDay (DateTime value) { return new DateTime (0, 0, value.Day); } public static DateTime DateTimeToGMonth (DateTime value) { return new DateTime (0, value.Month, 0); } public static DateTime DateTimeToGMonthDay (DateTime value) { return new DateTime (0, value.Month, value.Day); } public static DateTime DateTimeToGYear (DateTime value) { return new DateTime (value.Year, 0, 0); } public static DateTime DateTimeToGYearMonth (DateTime value) { return new DateTime (value.Year, value.Month, 0); } public static DateTime DateTimeToTime (DateTime value) { return new DateTime (value.TimeOfDay.Ticks); } public static DateTime DateToDateTime (DateTime value) { return value.Date; } public static DateTime DateToGDay (DateTime value) { return new DateTime (0, 0, value.Day); } public static DateTime DateToGMonth (DateTime value) { return new DateTime (0, value.Month, 0); } public static DateTime DateToGMonthDay (DateTime value) { return new DateTime (0, value.Month, value.Day); } public static DateTime DateToGYear (DateTime value) { return new DateTime (value.Year, 0, 0); } public static DateTime DateToGYearMonth (DateTime value) { return new DateTime (value.Year, value.Month, 0); } public static string DateToString (DateTime value) { return XmlConvert.ToString (value); } public static string DateTimeToString (DateTime value) { return XmlConvert.ToString (value); } public static string DayTimeDurationToDuration (TimeSpan value) { return XmlConvert.ToString (value); } public static string DayTimeDurationToString (TimeSpan value) { return DayTimeDurationToDuration (value); } public static bool DecimalToBoolean (decimal value) { return value != 0; } public static double DecimalToDouble (decimal value) { return Convert.ToDouble (value); } public static float DecimalToFloat (decimal value) { return Convert.ToSingle (value); } public static int DecimalToInt (decimal value) { return Convert.ToInt32 (value); } public static long DecimalToInteger (decimal value) { return Convert.ToInt64 (value); } public static string DecimalToString (decimal value) { return XmlConvert.ToString (value); } public static bool DoubleToBoolean (double value) { return value != 0; } public static decimal DoubleToDecimal (double value) { return (decimal) value; } public static float DoubleToFloat (double value) { return Convert.ToSingle (value); } public static int DoubleToInt (double value) { return Convert.ToInt32 (value); } public static long DoubleToInteger (double value) { return Convert.ToInt64 (value); } public static string DoubleToString (double value) { return XmlConvert.ToString (value); } public static TimeSpan DurationToDayTimeDuration (string value) { return XmlConvert.ToTimeSpan (value); } public static string DurationToString (string value) { return XmlConvert.ToString (XmlConvert.ToTimeSpan (value)); } public static TimeSpan DurationToYearMonthDuration (string value) { return XmlConvert.ToTimeSpan (value); } public static bool FloatToBoolean (float value) { return value != 0; } public static decimal FloatToDecimal (float value) { return (decimal) value; } public static double FloatToDouble (float value) { return Convert.ToDouble (value); } public static int FloatToInt (float value) { return Convert.ToInt32 (value); } public static long FloatToInteger (float value) { return Convert.ToInt64 (value); } public static string FloatToString (float value) { return XmlConvert.ToString (value); } public static string GDayToString (DateTime value) { return XmlConvert.ToString (TimeSpan.FromDays (value.Day)); } public static string GMonthDayToString (DateTime value) { return XmlConvert.ToString (new TimeSpan (value.Day, value.Hour, value.Minute, value.Second)); } public static string GMonthToString (DateTime value) { return XmlConvert.ToString (new TimeSpan (0, value.Month, 1)); } public static string GYearMonthToString (DateTime value) { return XmlConvert.ToString (new TimeSpan (value.Year, value.Month, 1)); } public static string GYearToString (DateTime value) { return XmlConvert.ToString (new TimeSpan (new DateTime (value.Year, 1, 1).Ticks)); } public static string HexBinaryToString (byte [] data) { return XmlConvert.ToBinHexString (data); } public static byte [] HexBinaryToBase64Binary (byte [] data) { return data;//XmlConvert.ToBinHexString (data); } public static bool IntegerToBoolean (long value) { return value != 0; } public static decimal IntegerToDecimal (long value) { return (decimal) value; } public static decimal IntegerToDecimal (ulong value) { return (decimal) value; } public static double IntegerToDouble (long value) { return Convert.ToDouble (value); } public static float IntegerToFloat (long value) { return Convert.ToSingle (value); } public static int IntegerToInt (long value) { return Convert.ToInt32 (value); } public static string IntegerToString (long value) { return XmlConvert.ToString (value); } public static bool IntToBoolean (int value) { return value != 0; } public static decimal IntToDecimal (int value) { return (decimal) value; } public static double IntToDouble (int value) { return Convert.ToDouble (value); } public static float IntToFloat (int value) { return Convert.ToSingle (value); } public static long IntToInteger (int value) { return value; } public static string IntToString (int value) { return XmlConvert.ToString (value); } public static string NonNegativeIntegerToString (decimal value) { return XmlConvert.ToString (value); } public static string NonPositiveIntegerToString (decimal value) { return XmlConvert.ToString (value); } public static DateTime TimeToDateTime (DateTime value) { return value; } public static string TimeToString (DateTime value) { return XmlConvert.ToString (value, "HH:mm:ssZ"); } public static string YearMonthDurationToDuration (TimeSpan value) { return XmlConvert.ToString (value); } public static string YearMonthDurationToString (TimeSpan value) { return YearMonthDurationToDuration (value); } public static string StringToAnyUri (string value) { return value; } public static byte [] StringToBase64Binary (string value) { return Convert.FromBase64String (value); } public static bool StringToBoolean (string value) { return XmlConvert.ToBoolean (value); } public static DateTime StringToDate (string value) { return XmlConvert.ToDateTime (value); } public static DateTime StringToDateTime (string value) { return XmlConvert.ToDateTime (value); } public static TimeSpan StringToDayTimeDuration (string value) { return XmlConvert.ToTimeSpan (value); } public static decimal StringToDecimal (string value) { return XmlConvert.ToDecimal (value); } public static double StringToDouble (string value) { return XmlConvert.ToDouble (value); } public static string StringToDuration (string value) { return XmlConvert.ToString (XmlConvert.ToTimeSpan (value)); } public static float StringToFloat (string value) { return XmlConvert.ToSingle (value); } public static DateTime StringToGDay (string value) { return XmlConvert.ToDateTime (value); } public static DateTime StringToGMonth (string value) { return XmlConvert.ToDateTime (value); } public static DateTime StringToGMonthDay (string value) { return XmlConvert.ToDateTime (value); } public static DateTime StringToGYear (string value) { return XmlConvert.ToDateTime (value); } public static DateTime StringToGYearMonth (string value) { return XmlConvert.ToDateTime (value); } public static byte [] StringToHexBinary (string value) { return XmlConvert.FromBinHexString (value); } public static int StringToInt (string value) { return XmlConvert.ToInt32 (value); } public static long StringToInteger (string value) { return XmlConvert.ToInt64 (value); } public static decimal StringToNonNegativeInteger (string value) { return XmlConvert.ToDecimal (value); } public static decimal StringToNonPositiveInteger (string value) { return XmlConvert.ToDecimal (value); } public static DateTime StringToTime (string value) { return XmlConvert.ToDateTime (value); } public static long StringToUnsignedInt (string value) { return XmlConvert.ToUInt32 (value); } public static decimal StringToUnsignedLong (string value) { return XmlConvert.ToUInt64 (value); } public static int StringToUnsignedShort (string value) { return XmlConvert.ToUInt16 (value); } public static TimeSpan StringToYearMonthDuration (string value) { return XmlConvert.ToTimeSpan (value); } } } #endif
using System; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * implementation of RipeMD see, * http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html */ internal class RipeMD160Digest : GeneralDigest { private const int DigestLength = 20; private int H0, H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public RipeMD160Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public RipeMD160Digest(RipeMD160Digest t) : base(t) { CopyIn(t); } private void CopyIn(RipeMD160Digest t) { base.CopyIn(t); this.H0 = t.H0; this.H1 = t.H1; this.H2 = t.H2; this.H3 = t.H3; this.H4 = t.H4; Array.Copy(t.X, 0, this.X, 0, t.X.Length); this.xOff = t.xOff; } public override string AlgorithmName { get { return "RIPEMD160"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { this.X[this.xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if(this.xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if(this.xOff > 14) { ProcessBlock(); } this.X[14] = (int)(bitLength & 0xffffffff); this.X[15] = (int)((ulong)bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint)word >> 8); outBytes[outOff + 2] = (byte)((uint)word >> 16); outBytes[outOff + 3] = (byte)((uint)word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(this.H0, output, outOff); UnpackWord(this.H1, output, outOff + 4); UnpackWord(this.H2, output, outOff + 8); UnpackWord(this.H3, output, outOff + 12); UnpackWord(this.H4, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); this.H0 = unchecked((int)0x67452301); this.H1 = unchecked((int)0xefcdab89); this.H2 = unchecked((int)0x98badcfe); this.H3 = unchecked((int)0x10325476); this.H4 = unchecked((int)0xc3d2e1f0); this.xOff = 0; for(int i = 0; i != this.X.Length; i++) { this.X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int)((uint)x >> (32 - n)); } /* * f1,f2,f3,f4,f5 are the basic RipeMD160 functions. */ /* * rounds 0-15 */ private int F1( int x, int y, int z) { return x ^ y ^ z; } /* * rounds 16-31 */ private int F2( int x, int y, int z) { return (x & y) | (~x & z); } /* * rounds 32-47 */ private int F3( int x, int y, int z) { return (x | ~y) ^ z; } /* * rounds 48-63 */ private int F4( int x, int y, int z) { return (x & z) | (y & ~z); } /* * rounds 64-79 */ private int F5( int x, int y, int z) { return x ^ (y | ~z); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; int e, ee; a = aa = this.H0; b = bb = this.H1; c = cc = this.H2; d = dd = this.H3; e = ee = this.H4; // // Rounds 1 - 16 // // left a = RL(a + F1(b, c, d) + this.X[0], 11) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + this.X[1], 14) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + this.X[2], 15) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + this.X[3], 12) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + this.X[4], 5) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + this.X[5], 8) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + this.X[6], 7) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + this.X[7], 9) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + this.X[8], 11) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + this.X[9], 13) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + this.X[10], 14) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + this.X[11], 15) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + this.X[12], 6) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + this.X[13], 7) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + this.X[14], 9) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + this.X[15], 8) + e; c = RL(c, 10); // right aa = RL(aa + F5(bb, cc, dd) + this.X[5] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + this.X[14] + unchecked((int)0x50a28be6), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + this.X[7] + unchecked((int)0x50a28be6), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + this.X[0] + unchecked((int)0x50a28be6), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + this.X[9] + unchecked((int)0x50a28be6), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + this.X[2] + unchecked((int)0x50a28be6), 15) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + this.X[11] + unchecked((int)0x50a28be6), 15) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + this.X[4] + unchecked((int)0x50a28be6), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + this.X[13] + unchecked((int)0x50a28be6), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + this.X[6] + unchecked((int)0x50a28be6), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + this.X[15] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + this.X[8] + unchecked((int)0x50a28be6), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + this.X[1] + unchecked((int)0x50a28be6), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + this.X[10] + unchecked((int)0x50a28be6), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + this.X[3] + unchecked((int)0x50a28be6), 12) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + this.X[12] + unchecked((int)0x50a28be6), 6) + ee; cc = RL(cc, 10); // // Rounds 16-31 // // left e = RL(e + F2(a, b, c) + this.X[7] + unchecked((int)0x5a827999), 7) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + this.X[4] + unchecked((int)0x5a827999), 6) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + this.X[13] + unchecked((int)0x5a827999), 8) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + this.X[1] + unchecked((int)0x5a827999), 13) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + this.X[10] + unchecked((int)0x5a827999), 11) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + this.X[6] + unchecked((int)0x5a827999), 9) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + this.X[15] + unchecked((int)0x5a827999), 7) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + this.X[3] + unchecked((int)0x5a827999), 15) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + this.X[12] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + this.X[0] + unchecked((int)0x5a827999), 12) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + this.X[9] + unchecked((int)0x5a827999), 15) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + this.X[5] + unchecked((int)0x5a827999), 9) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + this.X[2] + unchecked((int)0x5a827999), 11) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + this.X[14] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + this.X[11] + unchecked((int)0x5a827999), 13) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + this.X[8] + unchecked((int)0x5a827999), 12) + d; b = RL(b, 10); // right ee = RL(ee + F4(aa, bb, cc) + this.X[6] + unchecked((int)0x5c4dd124), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + this.X[11] + unchecked((int)0x5c4dd124), 13) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + this.X[3] + unchecked((int)0x5c4dd124), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + this.X[7] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + this.X[0] + unchecked((int)0x5c4dd124), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + this.X[13] + unchecked((int)0x5c4dd124), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + this.X[5] + unchecked((int)0x5c4dd124), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + this.X[10] + unchecked((int)0x5c4dd124), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + this.X[14] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + this.X[15] + unchecked((int)0x5c4dd124), 7) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + this.X[8] + unchecked((int)0x5c4dd124), 12) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + this.X[12] + unchecked((int)0x5c4dd124), 7) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + this.X[4] + unchecked((int)0x5c4dd124), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + this.X[9] + unchecked((int)0x5c4dd124), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + this.X[1] + unchecked((int)0x5c4dd124), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + this.X[2] + unchecked((int)0x5c4dd124), 11) + dd; bb = RL(bb, 10); // // Rounds 32-47 // // left d = RL(d + F3(e, a, b) + this.X[3] + unchecked((int)0x6ed9eba1), 11) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + this.X[10] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + this.X[14] + unchecked((int)0x6ed9eba1), 6) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + this.X[4] + unchecked((int)0x6ed9eba1), 7) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + this.X[9] + unchecked((int)0x6ed9eba1), 14) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + this.X[15] + unchecked((int)0x6ed9eba1), 9) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + this.X[8] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + this.X[1] + unchecked((int)0x6ed9eba1), 15) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + this.X[2] + unchecked((int)0x6ed9eba1), 14) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + this.X[7] + unchecked((int)0x6ed9eba1), 8) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + this.X[0] + unchecked((int)0x6ed9eba1), 13) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + this.X[6] + unchecked((int)0x6ed9eba1), 6) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + this.X[13] + unchecked((int)0x6ed9eba1), 5) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + this.X[11] + unchecked((int)0x6ed9eba1), 12) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + this.X[5] + unchecked((int)0x6ed9eba1), 7) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + this.X[12] + unchecked((int)0x6ed9eba1), 5) + c; a = RL(a, 10); // right dd = RL(dd + F3(ee, aa, bb) + this.X[15] + unchecked((int)0x6d703ef3), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + this.X[5] + unchecked((int)0x6d703ef3), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + this.X[1] + unchecked((int)0x6d703ef3), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + this.X[3] + unchecked((int)0x6d703ef3), 11) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + this.X[7] + unchecked((int)0x6d703ef3), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + this.X[14] + unchecked((int)0x6d703ef3), 6) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + this.X[6] + unchecked((int)0x6d703ef3), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + this.X[9] + unchecked((int)0x6d703ef3), 14) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + this.X[11] + unchecked((int)0x6d703ef3), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + this.X[8] + unchecked((int)0x6d703ef3), 13) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + this.X[12] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + this.X[2] + unchecked((int)0x6d703ef3), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + this.X[10] + unchecked((int)0x6d703ef3), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + this.X[0] + unchecked((int)0x6d703ef3), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + this.X[4] + unchecked((int)0x6d703ef3), 7) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + this.X[13] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10); // // Rounds 48-63 // // left c = RL(c + F4(d, e, a) + this.X[1] + unchecked((int)0x8f1bbcdc), 11) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + this.X[9] + unchecked((int)0x8f1bbcdc), 12) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + this.X[11] + unchecked((int)0x8f1bbcdc), 14) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + this.X[10] + unchecked((int)0x8f1bbcdc), 15) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + this.X[0] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + this.X[8] + unchecked((int)0x8f1bbcdc), 15) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + this.X[12] + unchecked((int)0x8f1bbcdc), 9) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + this.X[4] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + this.X[13] + unchecked((int)0x8f1bbcdc), 9) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + this.X[3] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + this.X[7] + unchecked((int)0x8f1bbcdc), 5) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + this.X[15] + unchecked((int)0x8f1bbcdc), 6) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + this.X[14] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + this.X[5] + unchecked((int)0x8f1bbcdc), 6) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + this.X[6] + unchecked((int)0x8f1bbcdc), 5) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + this.X[2] + unchecked((int)0x8f1bbcdc), 12) + b; e = RL(e, 10); // right cc = RL(cc + F2(dd, ee, aa) + this.X[8] + unchecked((int)0x7a6d76e9), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + this.X[6] + unchecked((int)0x7a6d76e9), 5) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + this.X[4] + unchecked((int)0x7a6d76e9), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + this.X[1] + unchecked((int)0x7a6d76e9), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + this.X[3] + unchecked((int)0x7a6d76e9), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + this.X[11] + unchecked((int)0x7a6d76e9), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + this.X[15] + unchecked((int)0x7a6d76e9), 6) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + this.X[0] + unchecked((int)0x7a6d76e9), 14) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + this.X[5] + unchecked((int)0x7a6d76e9), 6) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + this.X[12] + unchecked((int)0x7a6d76e9), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + this.X[2] + unchecked((int)0x7a6d76e9), 12) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + this.X[13] + unchecked((int)0x7a6d76e9), 9) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + this.X[9] + unchecked((int)0x7a6d76e9), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + this.X[7] + unchecked((int)0x7a6d76e9), 5) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + this.X[10] + unchecked((int)0x7a6d76e9), 15) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + this.X[14] + unchecked((int)0x7a6d76e9), 8) + bb; ee = RL(ee, 10); // // Rounds 64-79 // // left b = RL(b + F5(c, d, e) + this.X[4] + unchecked((int)0xa953fd4e), 9) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + this.X[0] + unchecked((int)0xa953fd4e), 15) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + this.X[5] + unchecked((int)0xa953fd4e), 5) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + this.X[9] + unchecked((int)0xa953fd4e), 11) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + this.X[7] + unchecked((int)0xa953fd4e), 6) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + this.X[12] + unchecked((int)0xa953fd4e), 8) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + this.X[2] + unchecked((int)0xa953fd4e), 13) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + this.X[10] + unchecked((int)0xa953fd4e), 12) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + this.X[14] + unchecked((int)0xa953fd4e), 5) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + this.X[1] + unchecked((int)0xa953fd4e), 12) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + this.X[3] + unchecked((int)0xa953fd4e), 13) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + this.X[8] + unchecked((int)0xa953fd4e), 14) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + this.X[11] + unchecked((int)0xa953fd4e), 11) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + this.X[6] + unchecked((int)0xa953fd4e), 8) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + this.X[15] + unchecked((int)0xa953fd4e), 5) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + this.X[13] + unchecked((int)0xa953fd4e), 6) + a; d = RL(d, 10); // right bb = RL(bb + F1(cc, dd, ee) + this.X[12], 8) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + this.X[15], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + this.X[10], 12) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + this.X[4], 9) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + this.X[1], 12) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + this.X[5], 5) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + this.X[8], 14) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + this.X[7], 6) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + this.X[6], 8) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + this.X[2], 13) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + this.X[13], 6) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + this.X[14], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + this.X[0], 15) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + this.X[3], 13) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + this.X[9], 11) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + this.X[11], 11) + aa; dd = RL(dd, 10); dd += c + this.H1; this.H1 = this.H2 + d + ee; this.H2 = this.H3 + e + aa; this.H3 = this.H4 + a + bb; this.H4 = this.H0 + b + cc; this.H0 = dd; // // reset the offset and clean out the word buffer. // this.xOff = 0; for(int i = 0; i != this.X.Length; i++) { this.X[i] = 0; } } public override IMemoable Copy() { return new RipeMD160Digest(this); } public override void Reset(IMemoable other) { var d = (RipeMD160Digest)other; CopyIn(d); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Orleans.GrainDirectory; namespace Orleans.Runtime.GrainDirectory { [Serializable] internal class ActivationInfo : IActivationInfo { public SiloAddress SiloAddress { get; private set; } public DateTime TimeCreated { get; private set; } public MultiClusterStatus RegistrationStatus { get; set; } public ActivationInfo(SiloAddress siloAddress, MultiClusterStatus registrationStatus) { SiloAddress = siloAddress; TimeCreated = DateTime.UtcNow; RegistrationStatus = registrationStatus; } public ActivationInfo(IActivationInfo iActivationInfo) { SiloAddress = iActivationInfo.SiloAddress; TimeCreated = iActivationInfo.TimeCreated; RegistrationStatus = iActivationInfo.RegistrationStatus; } public override string ToString() { return String.Format("{0}, {1}", SiloAddress, TimeCreated); } } [Serializable] internal class GrainInfo : IGrainInfo { public Dictionary<ActivationId, IActivationInfo> Instances { get; private set; } public int VersionTag { get; private set; } public bool SingleInstance { get; private set; } private static readonly SafeRandom rand; internal const int NO_ETAG = -1; static GrainInfo() { rand = new SafeRandom(); } internal GrainInfo() { Instances = new Dictionary<ActivationId, IActivationInfo>(); VersionTag = 0; SingleInstance = false; } public bool AddActivation(ActivationId act, SiloAddress silo) { if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act)) { throw new InvalidOperationException( "Attempting to add a second activation to an existing grain in single activation mode"); } IActivationInfo info; if (Instances.TryGetValue(act, out info)) { if (info.SiloAddress.Equals(silo)) { // just refresh, no need to generate new VersionTag return false; } } Instances[act] = new ActivationInfo(silo, MultiClusterStatus.Owned); VersionTag = rand.Next(); return true; } public ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo, MultiClusterStatus registrationStatus = MultiClusterStatus.Owned) { SingleInstance = true; if (Instances.Count > 0) { var item = Instances.First(); return ActivationAddress.GetAddress(item.Value.SiloAddress, grain, item.Key); } else { Instances.Add(act, new ActivationInfo(silo, registrationStatus)); VersionTag = rand.Next(); return ActivationAddress.GetAddress(silo, grain, act, registrationStatus); } } public bool RemoveActivation(ActivationAddress addr) { return RemoveActivation(addr.Activation, true); } public bool RemoveActivation(ActivationId act, bool force) { if (force) { Instances.Remove(act); VersionTag = rand.Next(); } else { if (Silo.CurrentSilo.OrleansConfig.Globals.DirectoryLazyDeregistrationDelay > TimeSpan.Zero) { IActivationInfo info; if (Instances.TryGetValue(act, out info)) { if (info.TimeCreated <= DateTime.UtcNow - Silo.CurrentSilo.OrleansConfig.Globals.DirectoryLazyDeregistrationDelay) { Instances.Remove(act); VersionTag = rand.Next(); } } } } return Instances.Count == 0; } public bool Merge(GrainId grain, IGrainInfo other) { bool modified = false; foreach (var pair in other.Instances) { if (Instances.ContainsKey(pair.Key)) continue; Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress, pair.Value.RegistrationStatus); modified = true; } if (modified) { VersionTag = rand.Next(); } if (SingleInstance && (Instances.Count > 0)) { // Grain is supposed to be in single activation mode, but we have two activations!! // Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value. var orderedActivations = Instances.OrderBy(pair => pair.Key); var activationToKeep = orderedActivations.First(); var activationsToDrop = orderedActivations.Skip(1); Instances.Clear(); Instances.Add(activationToKeep.Key, activationToKeep.Value); var list = new List<ActivationAddress>(1); foreach (var activation in activationsToDrop.Select(keyValuePair => ActivationAddress.GetAddress(keyValuePair.Value.SiloAddress, grain, keyValuePair.Key))) { list.Add(activation); InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<ICatalog>(Constants.CatalogId, activation.Silo). DeleteActivations(list).Ignore(); list.Clear(); } return true; } return false; } public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationId activation, SiloAddress silo) { SingleInstance = true; if (Instances.Count > 0) { Instances.Remove(oldActivation); } Instances.Add(activation, new ActivationInfo(silo, MultiClusterStatus.Cached)); } public bool UpdateClusterRegistrationStatus(ActivationId activationId, MultiClusterStatus status, MultiClusterStatus? compareWith = null) { IActivationInfo activationInfo; if (!Instances.TryGetValue(activationId, out activationInfo)) return false; if (compareWith.HasValue && compareWith.Value != activationInfo.RegistrationStatus) return false; activationInfo.RegistrationStatus = status; return true; } } internal class GrainDirectoryPartition { // Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full // parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do // a lot more lookups and so can sort periodically? /// <summary> /// contains a map from grain to its list of activations along with the version (etag) counter for the list /// </summary> private Dictionary<GrainId, IGrainInfo> partitionData; private readonly object lockable; private readonly Logger log; private ISiloStatusOracle membership; internal int Count { get { return partitionData.Count; } } internal GrainDirectoryPartition() { partitionData = new Dictionary<GrainId, IGrainInfo>(); lockable = new object(); log = LogManager.GetLogger("DirectoryPartition"); membership = Silo.CurrentSilo.LocalSiloStatusOracle; } private bool IsValidSilo(SiloAddress silo) { if (membership == null) { membership = Silo.CurrentSilo.LocalSiloStatusOracle; } return membership.IsFunctionalDirectory(silo); } internal void Clear() { lock (lockable) { partitionData.Clear(); } } /// <summary> /// Returns all entries stored in the partition as an enumerable collection /// </summary> /// <returns></returns> public Dictionary<GrainId, IGrainInfo> GetItems() { lock (lockable) { return partitionData.Copy(); } } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <returns>The version associated with this directory mapping</returns> internal virtual int AddActivation(GrainId grain, ActivationId activation, SiloAddress silo) { if (!IsValidSilo(silo)) { return GrainInfo.NO_ETAG; } lock (lockable) { if (!partitionData.ContainsKey(grain)) { partitionData[grain] = new GrainInfo(); } partitionData[grain].AddActivation(activation, silo); } if (log.IsVerbose3) log.Verbose3("Adding activation for grain {0}", grain.ToString()); return partitionData[grain].VersionTag; } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <param name="registrationStatus"></param> /// <returns>The registered ActivationAddress and version associated with this directory mapping</returns> internal virtual AddressAndTag AddSingleActivation(GrainId grain, ActivationId activation, SiloAddress silo, MultiClusterStatus registrationStatus = MultiClusterStatus.Owned) { if (log.IsVerbose3) log.Verbose3("Adding single activation for grain {0}{1}{2}", silo, grain, activation); AddressAndTag result = new AddressAndTag(); if (!IsValidSilo(silo)) return result; lock (lockable) { if (!partitionData.ContainsKey(grain)) { partitionData[grain] = new GrainInfo(); } var grainInfo = partitionData[grain]; result.Address = grainInfo.AddSingleActivation(grain, activation, silo, registrationStatus); result.VersionTag = grainInfo.VersionTag; } return result; } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="force"></param> internal void RemoveActivation(GrainId grain, ActivationId activation, bool force) { lock (lockable) { if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, force)) { partitionData.Remove(grain); } } if (log.IsVerbose3) log.Verbose3("Removing activation for grain {0}", grain.ToString()); } /// <summary> /// Removes the grain (and, effectively, all its activations) from the diretcory /// </summary> /// <param name="grain"></param> internal void RemoveGrain(GrainId grain) { lock (lockable) { partitionData.Remove(grain); } if (log.IsVerbose3) log.Verbose3("Removing grain {0}", grain.ToString()); } /// <summary> /// Returns a list of activations (along with the version number of the list) for the given grain. /// If the grain is not found, null is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal AddressesAndTag LookUpGrain(GrainId grain) { var result = new AddressesAndTag(); lock (lockable) { if (partitionData.ContainsKey(grain)) { result.Addresses = new List<ActivationAddress>(); result.VersionTag = partitionData[grain].VersionTag; foreach (var route in partitionData[grain].Instances.Where(route => IsValidSilo(route.Value.SiloAddress))) { result.Addresses.Add(ActivationAddress.GetAddress(route.Value.SiloAddress, grain, route.Key, route.Value.RegistrationStatus)); } } } return result; } /// <summary> /// Returns the version number of the list of activations for the grain. /// If the grain is not found, -1 is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal int GetGrainETag(GrainId grain) { lock (lockable) { return partitionData.ContainsKey(grain) ? partitionData[grain].VersionTag : GrainInfo.NO_ETAG; } } /// <summary> /// Merges one partition into another, asuuming partitions are disjoint. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="other"></param> internal void Merge(GrainDirectoryPartition other) { lock (lockable) { foreach (var pair in other.partitionData) { if (partitionData.ContainsKey(pair.Key)) { if (log.IsVerbose) log.Verbose("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions"); partitionData[pair.Key].Merge(pair.Key, pair.Value); } else { partitionData.Add(pair.Key, pair.Value); } } } } /// <summary> /// Runs through all entries in the partition and moves/copies (depending on the given flag) the /// entries satisfying the given predicate into a new partition. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param> /// <param name="modifyOrigin">flag controling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param> /// <returns>new grain directory partition containing entries satisfying the given predicate</returns> internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin) { var newDirectory = new GrainDirectoryPartition(); if (modifyOrigin) { // SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here List<KeyValuePair<GrainId, IGrainInfo>> pairs; lock (lockable) { pairs = partitionData.Where(pair => predicate(pair.Key)).ToList(); } foreach (var pair in pairs) { newDirectory.partitionData.Add(pair.Key, pair.Value); } lock (lockable) { foreach (var pair in pairs) { partitionData.Remove(pair.Key); } } } else { lock (lockable) { foreach (var pair in partitionData.Where(pair => predicate(pair.Key))) { newDirectory.partitionData.Add(pair.Key, pair.Value); } } } return newDirectory; } internal List<ActivationAddress> ToListOfActivations(bool singleActivation) { var result = new List<ActivationAddress>(); lock (lockable) { foreach (var pair in partitionData) { var grain = pair.Key; if (pair.Value.SingleInstance == singleActivation) { result.AddRange(pair.Value.Instances.Select(activationPair => ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key)) .Where(addr => IsValidSilo(addr.Silo))); } } } return result; } /// <summary> /// Sets the internal parition dictionary to the one given as input parameter. /// This method is supposed to be used by handoff manager to update the old partition with a new partition. /// </summary> /// <param name="newPartitionData">new internal partition dictionary</param> internal void Set(Dictionary<GrainId, IGrainInfo> newPartitionData) { partitionData = newPartitionData; } /// <summary> /// Updates partition with a new delta of changes. /// This method is supposed to be used by handoff manager to update the partition with a set of delta changes. /// </summary> /// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition. /// If the value for a given key in the delta is valid, then existing entry in the partition is replaced. /// Otherwise, i.e., if the value is null, the corresponding entry is removed. /// </param> internal void Update(Dictionary<GrainId, IGrainInfo> newPartitionDelta) { lock (lockable) { foreach (GrainId grain in newPartitionDelta.Keys) { if (newPartitionDelta[grain] != null) { partitionData[grain] = newPartitionDelta[grain]; } else { partitionData.Remove(grain); } } } } public override string ToString() { var sb = new StringBuilder(); lock (lockable) { foreach (var grainEntry in partitionData) { foreach (var activationEntry in grainEntry.Value.Instances) { sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]"). Append(" => ").Append(activationEntry.Key.ToString()). Append(" @ ").AppendLine(activationEntry.Value.ToString()); } } } return sb.ToString(); } public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationAddress otherClusterAddress) { lock (lockable) { if (partitionData.ContainsKey(grain)) { partitionData[grain].CacheOrUpdateRemoteClusterRegistration(grain, oldActivation, otherClusterAddress.Activation, otherClusterAddress.Silo); } else { AddSingleActivation(grain, otherClusterAddress.Activation, otherClusterAddress.Silo, MultiClusterStatus.Cached); } } } public bool UpdateClusterRegistrationStatus(GrainId grain, ActivationId activationId, MultiClusterStatus registrationStatus, MultiClusterStatus? compareWith = null) { lock (lockable) { if (partitionData.ContainsKey(grain)) { return partitionData[grain].UpdateClusterRegistrationStatus(activationId, registrationStatus, compareWith); } return false; } } } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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 Alphaleonis.Win32.Filesystem; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using DirectoryInfo = Alphaleonis.Win32.Filesystem.DirectoryInfo; using Path = Alphaleonis.Win32.Filesystem.Path; namespace AlphaFS.UnitTest { /// <summary>This is a test class for DirectoryInfo and is intended to contain all DirectoryInfo Unit Tests.</summary> [TestClass] public class DirectoryInfoTest { private void DumpRefresh(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPathSysIo = Path.GetTempPath("DirectoryInfo.Refresh()-directory-SysIo-" + Path.GetRandomFileName()); string tempPath = Path.GetTempPath("DirectoryInfo.Refresh()-directory-AlphaFS-" + Path.GetRandomFileName()); if (!isLocal) tempPathSysIo = Path.LocalToUnc(tempPathSysIo); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path: [{0}]", tempPath); #endregion // Setup #region Refresh try { System.IO.DirectoryInfo diSysIo = new System.IO.DirectoryInfo(tempPathSysIo); DirectoryInfo di = new DirectoryInfo(tempPath); bool existsSysIo = diSysIo.Exists; bool exists = di.Exists; Console.WriteLine("\nnew DirectoryInfo(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Create(); di.Create(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Create(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Delete(); di.Delete(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Delete(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // true Assert.AreEqual(existsSysIo, exists); diSysIo.Refresh(); di.Refresh(); existsSysIo = diSysIo.Exists; exists = di.Exists; Console.WriteLine("\ndi.Refresh(): Exists (Should be {0}): [{1}]", existsSysIo, exists); // false Assert.AreEqual(existsSysIo, exists); } finally { if (Directory.Exists(tempPathSysIo)) { Directory.Delete(tempPathSysIo); Assert.IsFalse(Directory.Exists(tempPathSysIo), "Cleanup failed: Directory should have been removed."); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } Console.WriteLine(); } #endregion // Refresh } [TestMethod] public void EnumerateDirectories() { Console.WriteLine("DirectoryInfo.EnumerateDirectories()"); // Should only return folders. foreach (var di in new DirectoryInfo(UnitTestConstants.SysRoot).EnumerateDirectories(DirectoryEnumerationOptions.FilesAndFolders)) Assert.IsTrue(di.IsDirectory, "Expected a folder, not a file."); foreach (var di in new DirectoryInfo(UnitTestConstants.SysRoot).EnumerateDirectories(DirectoryEnumerationOptions.Files)) Assert.IsTrue(di.IsDirectory, "Expected a folder, not a file."); } [TestMethod] public void EnumerateFiles() { Console.WriteLine("DirectoryInfo.EnumerateFiles()"); // Should only return files. foreach (var di in new DirectoryInfo(UnitTestConstants.SysRoot).EnumerateFiles(DirectoryEnumerationOptions.FilesAndFolders)) Assert.IsTrue(!di.IsDirectory, "Expected a file, not a folder."); foreach (var di in new DirectoryInfo(UnitTestConstants.SysRoot).EnumerateFiles(DirectoryEnumerationOptions.Folders)) Assert.IsTrue(!di.IsDirectory, "Expected a file, not a folder."); } [TestMethod] public void EnumerateFileSystemInfos() { Console.WriteLine("DirectoryInfo.EnumerateFileSystemInfos()"); // Should only return folders. foreach (FileSystemInfo di in new DirectoryInfo(UnitTestConstants.SysRoot).EnumerateFileSystemInfos(DirectoryEnumerationOptions.Folders)) Assert.IsTrue(di.IsDirectory, string.Format("Expected a folder, not a file: [{0}]", di.FullName)); // Should only return files. foreach (FileSystemInfo fi in new DirectoryInfo(UnitTestConstants.SysRoot).EnumerateFileSystemInfos(DirectoryEnumerationOptions.Files)) Assert.IsTrue(!fi.IsDirectory, string.Format("Expected a file, not a folder: [{0}]", fi.FullName)); } [TestMethod] public void Refresh() { Console.WriteLine("DirectoryInfo.Refresh()"); DumpRefresh(true); DumpRefresh(false); } #region SetSecurity (Issue-19788) private string GetTempDirectoryName() { return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); } [TestMethod] public void Test_AlphaFS___SetSecurity_ShouldNotProduceError() { SetSecurityAlpha(GetTempDirectoryName()); } [TestMethod] public void Test_System___SetSecurity_ShouldNotProduceError() { SetSecuritySystem(GetTempDirectoryName()); } [TestMethod] public void Test_System___AnalyzeSecurity_LocalAcessShouldNotExist() { string testDir = GetTempDirectoryName(); SetSecuritySystem(testDir); var dirsec = new System.IO.DirectoryInfo(testDir + @"\inherited").GetAccessControl(); AuthorizationRuleCollection accessRules = dirsec.GetAccessRules(true, true, targetType: typeof(SecurityIdentifier)); Assert.IsFalse(HasLocalAces(accessRules), "local access rules found"); } [TestMethod] public void Test_AlphaFS___AnalyzeSecurity_LocalAcessShouldNotExist() { string testDir = GetTempDirectoryName(); SetSecuritySystem(testDir); var dirsec = new DirectoryInfo(testDir + @"\inherited").GetAccessControl(); AuthorizationRuleCollection accessRules = dirsec.GetAccessRules(true, true, targetType: typeof(SecurityIdentifier)); Assert.IsFalse(HasLocalAces(accessRules), "local access rules found"); } public bool HasLocalAces(AuthorizationRuleCollection rules) { bool res = false; AccessRule locaACE = rules.Cast<AccessRule>().FirstOrDefault(a => a.IsInherited == false); res = (locaACE == null ? false : true); return res; } private void SetSecurityAlpha(string directory) { //create the test structure if (Directory.Exists(directory)) Directory.Delete(directory, true); Directory.CreateDirectory(directory); Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited")); DirectoryInfo testDirInfo = new DirectoryInfo(directory); //System.IO.Directory.CreateDirectory(_testDir); //System.IO.Directory.CreateDirectory(System.IO.Path.Combine(_testDir, "inherited")); //System.IO.DirectoryInfo testDirInfo = new System.IO.DirectoryInfo(_testDir); var ds = testDirInfo.GetAccessControl(AccessControlSections.Access); ds.SetAccessRuleProtection(true, false); ds.AddAccessRule(new FileSystemAccessRule( identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null), fileSystemRights: FileSystemRights.FullControl, inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, propagationFlags: PropagationFlags.None, type: AccessControlType.Allow )); //using (new PrivilegeEnabler(Privilege.Impersonate, Privilege.Backup, Privilege.Restore, Privilege.Security, Privilege.TakeOwnership, Privilege.TrustedCredManAccess, Privilege.Audit)) { testDirInfo.SetAccessControl(ds); } } private void SetSecuritySystem(string directory) { //create the test structure if (System.IO.Directory.Exists(directory)) System.IO.Directory.Delete(directory, true); System.IO.Directory.CreateDirectory(directory); System.IO.Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited")); System.IO.DirectoryInfo testDirInfo = new System.IO.DirectoryInfo(directory); var ds = testDirInfo.GetAccessControl(AccessControlSections.Access); ds.SetAccessRuleProtection(true, false); ds.AddAccessRule(new FileSystemAccessRule( identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null), fileSystemRights: FileSystemRights.FullControl, inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, propagationFlags: PropagationFlags.None, type: AccessControlType.Allow )); testDirInfo.SetAccessControl(ds); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Text; using Microsoft.Protocols.TestTools.StackSdk; namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeusb { /// <summary> /// The base class of TS_URB_RESULT structures. /// Sending in response to the TRANSFER_IN_REQUEST and TRANSFER_OUT_REQUEST messages. /// Be sent via the URB_COMPLETION or URB_COMPLETION_NO_DATA messages. /// These messages contain the TS_URB_RESULT field. /// </summary> public abstract class TS_URB_RESULT : BasePDU { /// <summary> /// Constructor /// </summary> protected TS_URB_RESULT() { header = new TS_URB_RESULT_HEADER(); } /// <summary> /// Common header of TS_URB_RESULT /// </summary> protected TS_URB_RESULT_HEADER header; /// <summary> /// Common header of TS_URB_RESULT /// </summary> public TS_URB_RESULT_HEADER Header { set { header = value; } get { return header; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { header.Encode(marshaler); } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { header.Decode(marshaler); } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { return header.ToString(); } } /// <summary> /// The TS_USBD_INTERFACE_INFORMATION_RESULT structure /// Based on the USBD_INTERFACE_INFORMATION structure /// </summary> public class TS_USBD_INTERFACE_INFORMATION : BasePDU { /// <summary> /// A 16-bit unsigned integer. /// The size in bytes of the TS_USBD_INTERFACE_INFORMATION structure /// </summary> private ushort len; /// <summary> /// A 16-bit unsigned integer. /// The size in bytes of the TS_USBD_INTERFACE_INFORMATION structure /// </summary> public ushort Length { set { len = value; } get { return len; } } /// <summary> /// A 32-bit unsigned integer /// The number of USBD_PIPE_INFORMATION structures found in the USBD_INTERFACE_INFORMATION. /// Also indicates the number of Pipes array elements that are to follow. /// </summary> private ushort numberOfPipesExpected; /// <summary> /// A 32-bit unsigned integer. /// The number of USBD_PIPE_INFORMATION structures found in the USBD_INTERFACE_INFORMATION. /// Also indicates the number of Pipes array elements that are to follow. /// </summary> public ushort NumberOfPipesExpected { set { numberOfPipesExpected = value; } get { return numberOfPipesExpected; } } /// <summary> /// A 8-bit unsigned integer. This value is from the InterfaceNumber field in USBD_INTERFACE_INFORMATION. /// </summary> private byte interfaceNumber; /// <summary> /// A 8-bit unsigned integer. This value is from the InterfaceNumber field in USBD_INTERFACE_INFORMATION. /// </summary> public byte InterfaceNumber { set { interfaceNumber = value; } get { return interfaceNumber; } } /// <summary> /// A 8-bit unsigned integer. /// Represents the AlternateSetting field in USBD_INTERFACE_INFORMATION. /// </summary> private byte alternateSetting; /// <summary> /// A 8-bit unsigned integer. /// Represents the AlternateSetting field in USBD_INTERFACE_INFORMATION. /// </summary> public byte AlternateSetting { set { alternateSetting = value; } get { return alternateSetting; } } /// <summary> /// A 16-bit unsigned integer for padding /// </summary> private ushort padding; /// <summary> /// A 16-bit unsigned integer for padding /// </summary> public ushort Padding { set { padding = value; } get { return padding; } } /// <summary> /// A 32-bit unsigned integer /// Represents the NumberOfPipes field in USBD_INTERFACE_INFORMATION /// Also indicates the number of Pipes array elements that are to follow. /// </summary> private uint numberOfPipes; /// <summary> /// A 32-bit unsigned integer /// Represents the NumberOfPipes field in USBD_INTERFACE_INFORMATION /// Also indicates the number of Pipes array elements that are to follow. /// </summary> public uint NumberOfPipes { set { numberOfPipes = value; } get { return numberOfPipes; } } /// <summary> /// An array of TS_USBD_PIPE_INFORMATION structures /// </summary> private TS_USBD_PIPE_INFORMATION[] informations; /// <summary> /// An array of TS_USBD_PIPE_INFORMATION structures /// </summary> public TS_USBD_PIPE_INFORMATION[] Infomations { set { informations = value; } get { return informations; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { marshaler.WriteUInt16(len); marshaler.WriteUInt16(numberOfPipesExpected); marshaler.WriteByte(interfaceNumber); marshaler.WriteByte(alternateSetting); marshaler.WriteUInt16(padding); marshaler.WriteUInt32(numberOfPipes); for (int i = 0; i < informations.Length; i++) { informations[i].Encode(marshaler); } } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { len = marshaler.ReadUInt16(); numberOfPipes = marshaler.ReadUInt16(); interfaceNumber = marshaler.ReadByte(); alternateSetting = marshaler.ReadByte(); padding = marshaler.ReadUInt16(); numberOfPipes = marshaler.ReadUInt32(); informations = new TS_USBD_PIPE_INFORMATION[numberOfPipes]; for (int i = 0; i < numberOfPipes; i++) { informations[i].Decode(marshaler); } } catch (Exception) { // TODO: All generic exceptions should be got rid of. return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = string.Format("len: 0x{0:x4}\r\n", len); s += string.Format("numberOfPipes: 0x{0:x4}\r\n", numberOfPipes); s += string.Format("interfaceNumber: 0x{0:x2}\r\n", interfaceNumber); s += string.Format("alternateSetting: 0x{0:x2}\r\n", alternateSetting); s += string.Format("padding: 0x{0:x4}\r\n", padding); s += string.Format("numberOfPipes: 0x{0:x8}\r\n", numberOfPipes); s += string.Format("informations: \r\n"); for (int i = 0; i < numberOfPipes; i++) { s += string.Format("informations[{0}]: \r\n", i); s += informations[i].ToString(); } return s; } }; /// <summary> /// Common header of TS_URB_RESULT /// </summary> public class TS_URB_RESULT_HEADER : BasePDU { /// <summary> /// The size in bytes of the TS_URB_RESULT structure /// </summary> private ushort size; /// <summary> /// The size in bytes of the TS_URB_RESULT structure /// </summary> public ushort Size { set { size = value; } get { return size; } } /// <summary> /// A 16-bit unsigned integer for padding /// </summary> private ushort padding; /// <summary> /// A 16-bit unsigned integer for padding /// </summary> public ushort Padding { set { padding = value; } get { return padding; } } /// <summary> /// This value represents the USBD Status /// </summary> private uint usbdStatus; /// <summary> /// This value represents the USBD Status /// </summary> public uint UsbdStatus { set { usbdStatus = value; } get { return usbdStatus; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { marshaler.WriteUInt16(size); marshaler.WriteUInt16(padding); marshaler.WriteUInt32(usbdStatus); } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { size = marshaler.ReadUInt16(); padding = marshaler.ReadUInt16(); usbdStatus = marshaler.ReadUInt32(); } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = string.Format("size: 0x{0:x4}\r\n", size); s += string.Format("padding: 0x{0:x4}\r\n", padding); s += string.Format("usbdStatus: 0x{0:x8}\r\n", usbdStatus); return s; } }; /// <summary> /// Based on the USBD_INTERFACE_INFORMATION structure /// </summary> public class TS_USBD_INTERFACE_INFORMATION_RESULT : BasePDU { /// <summary> /// The size in bytes of the TS_USBD_INTERFACE_INFORMATION_RESULT structure /// </summary> private ushort length; /// <summary> /// The size in bytes of the TS_USBD_INTERFACE_INFORMATION_RESULT structure /// </summary> public ushort Length { set { length = value; } get { return length; } } /// <summary> /// This value represents the InterfaceNumber field in USBD_INTERFACE_INFORMATION /// </summary> private byte interfaceNumber; /// <summary> /// This value represents the InterfaceNumber field in USBD_INTERFACE_INFORMATION /// </summary> public byte InterfaceNumber { set { interfaceNumber = value; } get { return interfaceNumber; } } /// <summary> /// This value represents the AlternateSetting field in USBD_INTERFACE_INFORMATION /// </summary> private byte alternateSetting; /// <summary> /// This value represents the AlternateSetting field in USBD_INTERFACE_INFORMATION /// </summary> public byte AlternateSetting { set { alternateSetting = value; } get { return alternateSetting; } } /// <summary> /// This value represents the Class field in USBD_INTERFACE_INFORMATION /// </summary> private byte class_field; /// <summary> /// This value represents the Class field in USBD_INTERFACE_INFORMATION /// </summary> public byte Class { set { class_field = value; } get { return class_field; } } /// <summary> /// This value represents the SubClass field in USBD_INTERFACE_INFORMATION /// </summary> private byte subClass; /// <summary> /// This value represents the SubClass field in USBD_INTERFACE_INFORMATION /// </summary> public byte SubClass { set { subClass = value; } get { return subClass; } } /// <summary> /// This value represents the Protocol field in USBD_INTERFACE_INFORMATION /// </summary> private byte protocol; /// <summary> /// This value represents the Protocol field in USBD_INTERFACE_INFORMATION /// </summary> public byte Protocol { set { protocol = value; } get { return protocol; } } /// <summary> /// A 8-bit unsigned integer for padding /// </summary> private byte padding; /// <summary> /// A 8-bit unsigned integer for padding /// </summary> public byte Padding { set { padding = value; } get { return padding; } } /// <summary> /// This value represents the InterfaceHandle field in USBD_INTERFACE_INFORMATION /// </summary> private uint interfaceHandle; /// <summary> /// This value represents the InterfaceHandle field in USBD_INTERFACE_INFORMATION /// </summary> public uint InterfaceHandle { set { interfaceHandle = value; } get { return interfaceHandle; } } /// <summary> /// This value represents the NumberOfPipes field in USBD_INTERFACE_INFORMATION /// </summary> private uint numberOfPipes; /// <summary> /// This value represents the NumberOfPipes field in USBD_INTERFACE_INFORMATION /// </summary> public uint NumberOfPipes { set { numberOfPipes = value; } get { return numberOfPipes; } } /// <summary> /// An array of TS_USBD_PIPE_INFORMATION_RESULT structures /// </summary> private TS_USBD_PIPE_INFORMATION_RESULT[] pipes; /// <summary> /// An array of TS_USBD_PIPE_INFORMATION_RESULT structures /// </summary> public TS_USBD_PIPE_INFORMATION_RESULT[] Pipes { set { pipes = value; } get { return pipes; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { marshaler.WriteUInt16(length); marshaler.WriteByte(interfaceNumber); marshaler.WriteByte(alternateSetting); marshaler.WriteByte(class_field); marshaler.WriteByte(subClass); marshaler.WriteByte(protocol); marshaler.WriteByte(padding); marshaler.WriteUInt32(interfaceHandle); marshaler.WriteUInt32(numberOfPipes); if (null != pipes) { for (int i = 0; i < pipes.Length; i++) { pipes[i].Encode(marshaler); } } } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { length = marshaler.ReadUInt16(); interfaceNumber = marshaler.ReadByte(); alternateSetting = marshaler.ReadByte(); class_field = marshaler.ReadByte(); subClass = marshaler.ReadByte(); protocol = marshaler.ReadByte(); padding = marshaler.ReadByte(); interfaceHandle = marshaler.ReadUInt32(); numberOfPipes = marshaler.ReadUInt32(); if (numberOfPipes > 0) { pipes = new TS_USBD_PIPE_INFORMATION_RESULT[numberOfPipes]; for (int i = 0; i < pipes.Length; i++) { pipes[i] = new TS_USBD_PIPE_INFORMATION_RESULT(); pipes[i].Decode(marshaler); } } else { pipes = null; } } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(base.ToString()); sb.AppendFormat("length: 0x{0:x4}\r\n", length); sb.AppendFormat("interfaceNumber: 0x{0:x2}\r\n", interfaceNumber); sb.AppendFormat("alternateSetting: 0x{0:x2}\r\n", alternateSetting); sb.AppendFormat("class_field: 0x{0:x2}\r\n", class_field); sb.AppendFormat("subClass: 0x{0:x2}\r\n", subClass); sb.AppendFormat("protocol: 0x{0:x2}\r\n", protocol); sb.AppendFormat("padding: 0x{0:x2}\r\n", padding); sb.AppendFormat("interfaceHandle: 0x{0:x8}\r\n", interfaceHandle); sb.AppendFormat("numberOfPipes: 0x{0:x8}\r\n", numberOfPipes); if (null != pipes) { for (int i = 0; i < pipes.Length; i++) { sb.AppendFormat("pipes[{0}]: \r\n{1}", i, pipes[i]); } } return sb.ToString(); } } /// <summary> /// Based on the USBD_PIPE_INFORMATION structure /// </summary> public class TS_USBD_PIPE_INFORMATION : BasePDU { /// <summary> /// A 16-bit unsigned integer. /// This value is from the MaximumPacketSize field in USBD_PIPE_INFORMATION /// </summary> private ushort maximumPacketSize; /// <summary> /// A 16-bit unsigned integer. /// This value is from the MaximumPacketSize field in USBD_PIPE_INFORMATION /// </summary> public ushort MaximumPacketSize { set { maximumPacketSize = value; } get { return maximumPacketSize; } } /// <summary> /// A 16-bit unsigned integer for padding /// </summary> private ushort padding; /// <summary> /// A 16-bit unsigned integer for padding /// </summary> public ushort Padding { set { padding = value; } get { return padding; } } /// <summary> /// A 32-bit unsigned integer. /// This value is from the MaximumTransferSize field in USBD_PIPE_INFORMATION /// </summary> private uint maximumTransferSize; /// <summary> /// A 32-bit unsigned integer. /// This value is from the MaximumTransferSize field in USBD_PIPE_INFORMATION /// </summary> public uint MaximumTransferSize { set { maximumTransferSize = value; } get { return maximumTransferSize; } } /// <summary> /// A 32-bit unsigned integer. /// This value is from the PipeFlags field in USBD_PIPE_INFORMATION /// </summary> private uint pipeFlags; /// <summary> /// A 32-bit unsigned integer. /// This value is from the PipeFlags field in USBD_PIPE_INFORMATION /// </summary> public uint PipeFlags { set { pipeFlags = value; } get { return pipeFlags; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { marshaler.WriteUInt16(maximumPacketSize); marshaler.WriteUInt16(padding); marshaler.WriteUInt32(maximumTransferSize); marshaler.WriteUInt32(pipeFlags); } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { maximumPacketSize = marshaler.ReadUInt16(); padding = marshaler.ReadUInt16(); maximumTransferSize = marshaler.ReadUInt32(); pipeFlags = marshaler.ReadUInt32(); } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = string.Format("maximumPacketSize: 0x{0:x4}\r\n", maximumPacketSize); s += string.Format("padding: 0x{0:x4}\r\n", padding); s += string.Format("maximumTransferSize: 0x{0:x8}\r\n", maximumTransferSize); s += string.Format("pipeFlags: 0x{0:x8}\r\n", pipeFlags); return s; } }; /// <summary> /// Based on the USBD_PIPE_INFORMATION structure /// </summary> public class TS_USBD_PIPE_INFORMATION_RESULT : BasePDU { /// <summary> /// A 16-bit unsigned integer. /// This value represents the MaximumPacketSize field in USBD_PIPE_INFORMATION. /// </summary> private ushort maximumPacketSize; /// <summary> /// A 16-bit unsigned integer. /// This value represents the MaximumPacketSize field in USBD_PIPE_INFORMATION. /// </summary> public ushort MaximumPacketSize { set { maximumPacketSize = value; } get { return maximumPacketSize; } } /// <summary> /// A 8-bit unsigned integer /// This value represents the EndpointAddress field in USBD_PIPE_INFORMATION /// </summary> private byte endpointAddress; /// <summary> /// A 8-bit unsigned integer /// This value represents the EndpointAddress field in USBD_PIPE_INFORMATION /// </summary> public byte EndpointAddress { set { endpointAddress = value; } get { return endpointAddress; } } /// <summary> /// A 8-bit unsigned integer. /// This value represents the Interval field in USBD_PIPE_INFORMATION /// </summary> private byte interval; /// <summary> /// A 8-bit unsigned integer. /// This value represents the Interval field in USBD_PIPE_INFORMATION /// </summary> public byte Interval { set { interval = value; } get { return interval; } } /// <summary> /// A 32-bit unsigned integer. /// This value represents the PipeType field in USBD_PIPE_INFORMATION /// </summary> private uint pipeType; /// <summary> /// A 32-bit unsigned integer. /// This value represents the PipeType field in USBD_PIPE_INFORMATION /// </summary> public uint PipeType { set { pipeType = value; } get { return pipeType; } } /// <summary> /// A 32-bit unsigned integer /// An opaque handle to the pipe /// </summary> private uint pipeHandle; /// <summary> /// A 32-bit unsigned integer /// An opaque handle to the pipe /// </summary> public uint PipeHandle { set { pipeHandle = value; } get { return pipeHandle; } } /// <summary> /// A 32-bit unsigned integer /// This value represents the MaximumTransferSize field in USBD_PIPE_INFORMATION /// </summary> private uint maximumTransferSize; /// <summary> /// A 32-bit unsigned integer /// This value represents the MaximumTransferSize field in USBD_PIPE_INFORMATION /// </summary> public uint MaximumTransferSize { set { maximumTransferSize = value; } get { return maximumTransferSize; } } /// <summary> /// A 32-bit unsigned integer /// This value represents the PipeFlags field in USBD_PIPE_INFORMATION /// </summary> private uint pipeFlags; /// <summary> /// A 32-bit unsigned integer /// This value represents the PipeFlags field in USBD_PIPE_INFORMATION /// </summary> public uint PipeFlags { set { pipeFlags = value; } get { return pipeFlags; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { marshaler.WriteUInt16(maximumPacketSize); marshaler.WriteByte(endpointAddress); marshaler.WriteByte(interval); marshaler.WriteUInt32(pipeType); marshaler.WriteUInt32(pipeHandle); marshaler.WriteUInt32(maximumTransferSize); marshaler.WriteUInt32(pipeFlags); } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { maximumPacketSize = marshaler.ReadUInt16(); endpointAddress = marshaler.ReadByte(); interval = marshaler.ReadByte(); pipeType = marshaler.ReadUInt32(); pipeHandle = marshaler.ReadUInt32(); maximumTransferSize = marshaler.ReadUInt32(); pipeFlags = marshaler.ReadUInt32(); } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = string.Format("maximumPacketSize: 0x{0:x4}\r\n", maximumPacketSize); s += string.Format("endpointAddress: 0x{0:x2}\r\n", endpointAddress); s += string.Format("interval: 0x{0:x2}\r\n", interval); s += string.Format("pipeType: 0x{0:x8}\r\n", pipeType); s += string.Format("pipeHandle: 0x{0:x8}\r\n", pipeHandle); s += string.Format("maximumTransferSize: 0x{0:x8}\r\n", maximumTransferSize); s += string.Format("pipeFlags: 0x{0:x8}\r\n", pipeFlags); return s; } } /// <summary> /// Represents the result of the TRANSFER_IN_REQUEST with TS_URB_SELECT_CONFIGURATION. The TS_URB_SELECT_CONFIGURATION_RESULT. /// Be sent via the URB_COMPLETION_NO_DATA message. /// </summary> public class TS_URB_SELECT_CONFIGURATION_RESULT : TS_URB_RESULT { /// <summary> /// A 32-bit unsigned integer. /// An opaque handle that identifies the configuration described by TS_URB_SELECT_CONFIGURATION /// </summary> private uint configurationHandle; /// <summary> /// A 32-bit unsigned integer. /// An opaque handle that identifies the configuration described by TS_URB_SELECT_CONFIGURATION /// </summary> public uint ConfigurationHandle { set { configurationHandle = value; } get { return configurationHandle; } } /// <summary> /// A 32-bit unsigned integer. /// The number of Interface fields that are to follow /// </summary> private uint numInterfaces; /// <summary> /// A 32-bit unsigned integer. /// The number of Interface fields that are to follow /// </summary> public uint NumInterfaces { set { numInterfaces = value; } get { return numInterfaces; } } /// <summary> /// TS_USBD_INTERFACE_INFORMATION_RESULT structures /// </summary> private TS_USBD_INTERFACE_INFORMATION_RESULT[] interfaces; /// <summary> /// TS_USBD_INTERFACE_INFORMATION_RESULT structures /// </summary> public TS_USBD_INTERFACE_INFORMATION_RESULT[] Interface { set { interfaces = value; } get { return interfaces; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { base.Encode(marshaler); marshaler.WriteUInt32(configurationHandle); marshaler.WriteUInt32(numInterfaces); if (null != Interface) { for (int i = 0; i < Interface.Length; i++) { interfaces[i].Encode(marshaler); } } } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { if (!base.Decode(marshaler)) { return false; } configurationHandle = marshaler.ReadUInt32(); numInterfaces = marshaler.ReadUInt32(); if (numInterfaces == 0) { interfaces = null; } else { interfaces = new TS_USBD_INTERFACE_INFORMATION_RESULT[numInterfaces]; for (int i = 0; i < numInterfaces; i++) { interfaces[i] = new TS_USBD_INTERFACE_INFORMATION_RESULT(); if (!interfaces[i].Decode(marshaler)) { return false; } } } } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(base.ToString()); sb.AppendFormat("configurationHandle: 0x{0:x8}\r\n", configurationHandle); sb.AppendFormat("numInterfaces: 0x{0:x8}\r\n", numInterfaces); if (numInterfaces > 0) { sb.AppendFormat("Interface: \r\n"); for (int i = 0; i < interfaces.Length; i++) { sb.AppendFormat("interface [{0}]:\r\n{1}", i, interfaces[i]); } } return sb.ToString(); } } /// <summary> /// Class include result of the TRANSFER_IN_REQUEST with TS_URB_SELECT_INTERFACE /// </summary> public class TS_URB_SELECT_INTERFACE_RESULT : TS_URB_RESULT { /// <summary> /// A TS_USBD_INTERFACE_INFORMATION_RESULT structure /// </summary> private TS_USBD_INTERFACE_INFORMATION_RESULT interface_field; /// <summary> /// A TS_USBD_INTERFACE_INFORMATION_RESULT structure /// </summary> public TS_USBD_INTERFACE_INFORMATION_RESULT Interface { set { interface_field = value; } get { return interface_field; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { base.Encode(marshaler); interface_field.Encode(marshaler); } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { base.Decode(marshaler); interface_field.Decode(marshaler); } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = base.ToString(); s += interface_field.ToString(); return s; } } /// <summary> /// Class include result of the TRANSFER_IN_REQUEST with TS_URB_GET_CURRENT_FRAME_NUMBER /// </summary> public class TS_URB_GET_CURRENT_FRAME_NUMBER_RESULT : TS_URB_RESULT { /// <summary> /// A 32-bit unsigned integer. /// The current frame number /// </summary> private uint frameNumber; /// <summary> /// A 32-bit unsigned integer. /// The current frame number /// </summary> public uint FrameNumber { set { frameNumber = value; } get { return frameNumber; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { base.Encode(marshaler); marshaler.WriteUInt32(frameNumber); } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { base.Decode(marshaler); frameNumber = marshaler.ReadUInt32(); } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = base.ToString(); s += string.Format("frameNumber: 0x{0:x8}\r\n", frameNumber); return s; } } /// <summary> /// Class include result of TRANSFER_IN_REQUEST or TRANSFER_OUT_REQUEST with TS_URB_ISOCH_TRANSFER /// </summary> public class TS_URB_ISOCH_TRANSFER_RESULT : TS_URB_RESULT { /// <summary> /// The resulting StartFrame value as specified in URB_ISOCH_TRANSFER /// </summary> private uint startFrame; /// <summary> /// The resulting StartFrame value as specified in URB_ISOCH_TRANSFER /// </summary> public uint StartFrame { set { startFrame = value; } get { return startFrame; } } /// <summary> /// This value is the number of URB_ISOCH_TRANSFER following the IsoPacket field /// </summary> private uint numberOfPackets; /// <summary> /// This value is the number of URB_ISOCH_TRANSFER following the IsoPacket field /// </summary> public uint NumberOfPackets { set { numberOfPackets = value; } get { return numberOfPackets; } } /// <summary> /// The resulting ErrorCount value as described in URB_ISOCH_TRANSFER /// </summary> private uint errorCount; /// <summary> /// The resulting ErrorCount value as described in URB_ISOCH_TRANSFER /// </summary> public uint ErrorCount { set { errorCount = value; } get { return errorCount; } } /// <summary> /// The resulting array of USBD_ISO_PACKET_DESCRIPTOR structures /// </summary> private USBD_ISO_PACKET_DESCRIPTOR[] isoPacket; /// <summary> /// The resulting array of USBD_ISO_PACKET_DESCRIPTOR structures /// </summary> public USBD_ISO_PACKET_DESCRIPTOR[] IsoPacket { set { isoPacket = value; } get { return isoPacket; } } /// <summary> /// Encode this PDU to the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to encode the fields of this PDU.</param> public override void Encode(PduMarshaler marshaler) { base.Encode(marshaler); marshaler.WriteUInt32(startFrame); marshaler.WriteUInt32(numberOfPackets); marshaler.WriteUInt32(errorCount); for (int i = 0; i < isoPacket.Length; i++) { isoPacket[i].Encode(marshaler); } } /// <summary> /// Decode this PDU from the PduMarshaler. /// </summary> /// <param name="marshaler">This is used to decode the fields of this PDU.</param> public override bool Decode(PduMarshaler marshaler) { try { base.Decode(marshaler); startFrame = marshaler.ReadUInt32(); numberOfPackets = marshaler.ReadUInt32(); errorCount = marshaler.ReadUInt32(); isoPacket = new USBD_ISO_PACKET_DESCRIPTOR[numberOfPackets]; for (int i = 0; i < isoPacket.Length; i++) { isoPacket[i].Decode(marshaler); } } catch (Exception) { return false; } return true; } /// <summary> /// Convert the fields of this PDU to a string. /// </summary> /// <returns>A string contains the fields of this PDU.</returns> public override string ToString() { string s = base.ToString(); s += string.Format("startFrame: 0x{0:x8}\r\n", startFrame); s += string.Format("numberOfPackets: 0x{0:x8}\r\n", numberOfPackets); s += string.Format("errorCount: 0x{0:x8}\r\n", errorCount); for (int i = 0; i < isoPacket.Length; i++) { s += string.Format("isoPacket[{0}]: \r\n", i); s += isoPacket[i].ToString(); } return s; } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.IO; using System.Threading; using SR = System.Reflection; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using Mono.Collections.Generic; namespace Mono.Cecil { public enum ReadingMode { Immediate = 1, Deferred = 2, } public sealed class ReaderParameters { ReadingMode reading_mode; internal IAssemblyResolver assembly_resolver; internal IMetadataResolver metadata_resolver; #if !READ_ONLY internal IMetadataImporterProvider metadata_importer_provider; #if !PCL && !NET_CORE internal IReflectionImporterProvider reflection_importer_provider; #endif #endif Stream symbol_stream; ISymbolReaderProvider symbol_reader_provider; bool read_symbols; bool projections; bool in_memory; bool read_write; public ReadingMode ReadingMode { get { return reading_mode; } set { reading_mode = value; } } public bool InMemory { get { return in_memory; } set { in_memory = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public IMetadataResolver MetadataResolver { get { return metadata_resolver; } set { metadata_resolver = value; } } #if !READ_ONLY public IMetadataImporterProvider MetadataImporterProvider { get { return metadata_importer_provider; } set { metadata_importer_provider = value; } } #if !PCL && !NET_CORE public IReflectionImporterProvider ReflectionImporterProvider { get { return reflection_importer_provider; } set { reflection_importer_provider = value; } } #endif #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolReaderProvider SymbolReaderProvider { get { return symbol_reader_provider; } set { symbol_reader_provider = value; } } public bool ReadSymbols { get { return read_symbols; } set { read_symbols = value; } } public bool ReadWrite { get { return read_write; } set { read_write = value; } } public bool ApplyWindowsRuntimeProjections { get { return projections; } set { projections = value; } } public ReaderParameters () : this (ReadingMode.Deferred) { } public ReaderParameters (ReadingMode readingMode) { this.reading_mode = readingMode; } } #if !READ_ONLY public sealed class ModuleParameters { ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; IAssemblyResolver assembly_resolver; IMetadataResolver metadata_resolver; #if !READ_ONLY IMetadataImporterProvider metadata_importer_provider; #if !PCL && !NET_CORE IReflectionImporterProvider reflection_importer_provider; #endif #endif public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public IMetadataResolver MetadataResolver { get { return metadata_resolver; } set { metadata_resolver = value; } } #if !READ_ONLY public IMetadataImporterProvider MetadataImporterProvider { get { return metadata_importer_provider; } set { metadata_importer_provider = value; } } #if !PCL && !NET_CORE public IReflectionImporterProvider ReflectionImporterProvider { get { return reflection_importer_provider; } set { reflection_importer_provider = value; } } #endif #endif public ModuleParameters () { this.kind = ModuleKind.Dll; this.Runtime = GetCurrentRuntime (); this.architecture = TargetArchitecture.I386; } static TargetRuntime GetCurrentRuntime () { #if !PCL && !NET_CORE return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime (); #else var corlib_name = AssemblyNameReference.Parse (typeof (object).GetAssembly ().FullName); var corlib_version = corlib_name.Version; switch (corlib_version.Major) { case 1: return corlib_version.Minor == 0 ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case 2: return TargetRuntime.Net_2_0; case 4: return TargetRuntime.Net_4_0; default: throw new NotSupportedException (); } #endif } } public sealed class WriterParameters { Stream symbol_stream; ISymbolWriterProvider symbol_writer_provider; bool write_symbols; #if !PCL && !NET_CORE SR.StrongNameKeyPair key_pair; #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolWriterProvider SymbolWriterProvider { get { return symbol_writer_provider; } set { symbol_writer_provider = value; } } public bool WriteSymbols { get { return write_symbols; } set { write_symbols = value; } } #if !PCL && !NET_CORE public SR.StrongNameKeyPair StrongNameKeyPair { get { return key_pair; } set { key_pair = value; } } #endif } #endif public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider, IDisposable { internal Image Image; internal MetadataSystem MetadataSystem; internal ReadingMode ReadingMode; internal ISymbolReaderProvider SymbolReaderProvider; internal ISymbolReader symbol_reader; internal Disposable<IAssemblyResolver> assembly_resolver; internal IMetadataResolver metadata_resolver; internal TypeSystem type_system; internal readonly MetadataReader reader; readonly string file_name; internal string runtime_version; internal ModuleKind kind; WindowsRuntimeProjections projections; MetadataKind metadata_kind; TargetRuntime runtime; TargetArchitecture architecture; ModuleAttributes attributes; ModuleCharacteristics characteristics; Guid mvid; internal AssemblyDefinition assembly; MethodDefinition entry_point; #if !READ_ONLY #if !PCL && !NET_CORE internal IReflectionImporter reflection_importer; #endif internal IMetadataImporter metadata_importer; #endif Collection<CustomAttribute> custom_attributes; Collection<AssemblyNameReference> references; Collection<ModuleReference> modules; Collection<Resource> resources; Collection<ExportedType> exported_types; TypeDefinitionCollection types; public bool IsMain { get { return kind != ModuleKind.NetModule; } } public ModuleKind Kind { get { return kind; } set { kind = value; } } public MetadataKind MetadataKind { get { return metadata_kind; } set { metadata_kind = value; } } internal WindowsRuntimeProjections Projections { get { if (projections == null) Interlocked.CompareExchange (ref projections, new WindowsRuntimeProjections (this), null); return projections; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; runtime_version = runtime.RuntimeVersionString (); } } public string RuntimeVersion { get { return runtime_version; } set { runtime_version = value; runtime = runtime_version.ParseRuntime (); } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public ModuleAttributes Attributes { get { return attributes; } set { attributes = value; } } public ModuleCharacteristics Characteristics { get { return characteristics; } set { characteristics = value; } } [Obsolete("Use FileName")] public string FullyQualifiedName { get { return file_name; } } public string FileName { get { return file_name; } } public Guid Mvid { get { return mvid; } set { mvid = value; } } internal bool HasImage { get { return Image != null; } } public bool HasSymbols { get { return symbol_reader != null; } } public ISymbolReader SymbolReader { get { return symbol_reader; } } public override MetadataScopeType MetadataScopeType { get { return MetadataScopeType.ModuleDefinition; } } public AssemblyDefinition Assembly { get { return assembly; } } #if !READ_ONLY #if !PCL && !NET_CORE internal IReflectionImporter ReflectionImporter { get { if (reflection_importer == null) Interlocked.CompareExchange (ref reflection_importer, new ReflectionImporter (this), null); return reflection_importer; } } #endif internal IMetadataImporter MetadataImporter { get { if (metadata_importer == null) Interlocked.CompareExchange (ref metadata_importer, new MetadataImporter (this), null); return metadata_importer; } } #endif public IAssemblyResolver AssemblyResolver { get { #if !PCL && !NET_CORE if (assembly_resolver.value == null) { lock (module_lock) { assembly_resolver = Disposable.Owned (new DefaultAssemblyResolver () as IAssemblyResolver); } } #endif return assembly_resolver.value; } } public IMetadataResolver MetadataResolver { get { if (metadata_resolver == null) Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null); return metadata_resolver; } } public TypeSystem TypeSystem { get { if (type_system == null) Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null); return type_system; } } public bool HasAssemblyReferences { get { if (references != null) return references.Count > 0; return HasImage && Image.HasTable (Table.AssemblyRef); } } public Collection<AssemblyNameReference> AssemblyReferences { get { if (references != null) return references; if (HasImage) return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ()); return references = new Collection<AssemblyNameReference> (); } } public bool HasModuleReferences { get { if (modules != null) return modules.Count > 0; return HasImage && Image.HasTable (Table.ModuleRef); } } public Collection<ModuleReference> ModuleReferences { get { if (modules != null) return modules; if (HasImage) return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ()); return modules = new Collection<ModuleReference> (); } } public bool HasResources { get { if (resources != null) return resources.Count > 0; if (HasImage) return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ()); return false; } } public Collection<Resource> Resources { get { if (resources != null) return resources; if (HasImage) return Read (ref resources, this, (_, reader) => reader.ReadResources ()); return resources = new Collection<Resource> (); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (this); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); } } public bool HasTypes { get { if (types != null) return types.Count > 0; return HasImage && Image.HasTable (Table.TypeDef); } } public Collection<TypeDefinition> Types { get { if (types != null) return types; if (HasImage) return Read (ref types, this, (_, reader) => reader.ReadTypes ()); return types = new TypeDefinitionCollection (this); } } public bool HasExportedTypes { get { if (exported_types != null) return exported_types.Count > 0; return HasImage && Image.HasTable (Table.ExportedType); } } public Collection<ExportedType> ExportedTypes { get { if (exported_types != null) return exported_types; if (HasImage) return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ()); return exported_types = new Collection<ExportedType> (); } } public MethodDefinition EntryPoint { get { if (entry_point != null) return entry_point; if (HasImage) return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ()); return entry_point = null; } set { entry_point = value; } } internal ModuleDefinition () { this.MetadataSystem = new MetadataSystem (); this.token = new MetadataToken (TokenType.Module, 1); } internal ModuleDefinition (Image image) : this () { this.Image = image; this.kind = image.Kind; this.RuntimeVersion = image.RuntimeVersion; this.architecture = image.Architecture; this.attributes = image.Attributes; this.characteristics = image.Characteristics; this.file_name = image.FileName; this.reader = new MetadataReader (this); } public void Dispose () { if (Image != null) Image.Dispose (); if (symbol_reader != null) symbol_reader.Dispose (); if (assembly_resolver.value != null) assembly_resolver.Dispose (); } public bool HasTypeReference (string fullName) { return HasTypeReference (string.Empty, fullName); } public bool HasTypeReference (string scope, string fullName) { CheckFullName (fullName); if (!HasImage) return false; return GetTypeReference (scope, fullName) != null; } public bool TryGetTypeReference (string fullName, out TypeReference type) { return TryGetTypeReference (string.Empty, fullName, out type); } public bool TryGetTypeReference (string scope, string fullName, out TypeReference type) { CheckFullName (fullName); if (!HasImage) { type = null; return false; } return (type = GetTypeReference (scope, fullName)) != null; } TypeReference GetTypeReference (string scope, string fullname) { return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2)); } public IEnumerable<TypeReference> GetTypeReferences () { if (!HasImage) return Empty<TypeReference>.Array; return Read (this, (_, reader) => reader.GetTypeReferences ()); } public IEnumerable<MemberReference> GetMemberReferences () { if (!HasImage) return Empty<MemberReference>.Array; return Read (this, (_, reader) => reader.GetMemberReferences ()); } public IEnumerable<CustomAttribute> GetCustomAttributes () { if (!HasImage) return Empty<CustomAttribute>.Array; return Read (this, (_, reader) => reader.GetCustomAttributes ()); } public TypeReference GetType (string fullName, bool runtimeName) { return runtimeName ? TypeParser.ParseType (this, fullName) : GetType (fullName); } public TypeDefinition GetType (string fullName) { CheckFullName (fullName); var position = fullName.IndexOf ('/'); if (position > 0) return GetNestedType (fullName); return ((TypeDefinitionCollection) this.Types).GetType (fullName); } public TypeDefinition GetType (string @namespace, string name) { Mixin.CheckName (name); return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name); } public IEnumerable<TypeDefinition> GetTypes () { return GetTypes (Types); } static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types) { for (int i = 0; i < types.Count; i++) { var type = types [i]; yield return type; if (!type.HasNestedTypes) continue; foreach (var nested in GetTypes (type.NestedTypes)) yield return nested; } } static void CheckFullName (string fullName) { if (fullName == null) throw new ArgumentNullException ("fullName"); if (fullName.Length == 0) throw new ArgumentException (); } TypeDefinition GetNestedType (string fullname) { var names = fullname.Split ('/'); var type = GetType (names [0]); if (type == null) return null; for (int i = 1; i < names.Length; i++) { var nested_type = type.GetNestedType (names [i]); if (nested_type == null) return null; type = nested_type; } return type; } internal FieldDefinition Resolve (FieldReference field) { #if PCL || NET_CORE if (MetadataResolver == null) throw new NotSupportedException (); #endif return MetadataResolver.Resolve (field); } internal MethodDefinition Resolve (MethodReference method) { #if PCL || NET_CORE if (MetadataResolver == null) throw new NotSupportedException (); #endif return MetadataResolver.Resolve (method); } internal TypeDefinition Resolve (TypeReference type) { #if PCL || NET_CORE if (MetadataResolver == null) throw new NotSupportedException (); #endif return MetadataResolver.Resolve (type); } #if !READ_ONLY static void CheckContext (IGenericParameterProvider context, ModuleDefinition module) { if (context == null) return; if (context.Module != module) throw new ArgumentException (); } static ImportGenericContext GenericContextFor (IGenericParameterProvider context) { return context != null ? new ImportGenericContext (context) : default (ImportGenericContext); } #if !PCL && !NET_CORE [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (Type type) { return ImportReference (type, null); } public TypeReference ImportReference (Type type) { return ImportReference (type, null); } [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (Type type, IGenericParameterProvider context) { return ImportReference (type, context); } public TypeReference ImportReference (Type type, IGenericParameterProvider context) { Mixin.CheckType (type); CheckContext (context, this); return ReflectionImporter.ImportReference (type, context); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (SR.FieldInfo field) { return ImportReference (field, null); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context) { return ImportReference (field, context); } public FieldReference ImportReference (SR.FieldInfo field) { return ImportReference (field, null); } public FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context) { Mixin.CheckField (field); CheckContext (context, this); return ReflectionImporter.ImportReference (field, context); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (SR.MethodBase method) { return ImportReference (method, null); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context) { return ImportReference (method, context); } public MethodReference ImportReference (SR.MethodBase method) { return ImportReference (method, null); } public MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context) { Mixin.CheckMethod (method); CheckContext (context, this); return ReflectionImporter.ImportReference (method, context); } #endif [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (TypeReference type) { return ImportReference (type, null); } [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (TypeReference type, IGenericParameterProvider context) { return ImportReference (type, context); } public TypeReference ImportReference (TypeReference type) { return ImportReference (type, null); } public TypeReference ImportReference (TypeReference type, IGenericParameterProvider context) { Mixin.CheckType (type); if (type.Module == this) return type; CheckContext (context, this); return MetadataImporter.ImportReference (type, context); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (FieldReference field) { return ImportReference (field, null); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (FieldReference field, IGenericParameterProvider context) { return ImportReference (field, context); } public FieldReference ImportReference (FieldReference field) { return ImportReference (field, null); } public FieldReference ImportReference (FieldReference field, IGenericParameterProvider context) { Mixin.CheckField (field); if (field.Module == this) return field; CheckContext (context, this); return MetadataImporter.ImportReference (field, context); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (MethodReference method) { return ImportReference (method, null); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (MethodReference method, IGenericParameterProvider context) { return ImportReference (method, context); } public MethodReference ImportReference (MethodReference method) { return ImportReference (method, null); } public MethodReference ImportReference (MethodReference method, IGenericParameterProvider context) { Mixin.CheckMethod (method); if (method.Module == this) return method; CheckContext (context, this); return MetadataImporter.ImportReference (method, context); } #endif public IMetadataTokenProvider LookupToken (int token) { return LookupToken (new MetadataToken ((uint) token)); } public IMetadataTokenProvider LookupToken (MetadataToken token) { return Read (token, (t, reader) => reader.LookupToken (t)); } readonly object module_lock = new object(); internal object SyncRoot { get { return module_lock; } } internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read) { lock (module_lock) { var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return ret; } } internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class { lock (module_lock) { if (variable != null) return variable; var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return variable = ret; } } public bool HasDebugHeader { get { return Image != null && !Image.Debug.IsZero; } } public ImageDebugDirectory GetDebugHeader (out byte [] header) { if (!HasDebugHeader) throw new InvalidOperationException (); return Image.GetDebugHeader (out header); } void ProcessDebugHeader () { if (!HasDebugHeader) return; byte [] header; var directory = GetDebugHeader (out header); if (!symbol_reader.ProcessDebugHeader (directory, header)) throw new InvalidOperationException (); } #if !READ_ONLY public static ModuleDefinition CreateModule (string name, ModuleKind kind) { return CreateModule (name, new ModuleParameters { Kind = kind }); } public static ModuleDefinition CreateModule (string name, ModuleParameters parameters) { Mixin.CheckName (name); Mixin.CheckParameters (parameters); var module = new ModuleDefinition { Name = name, kind = parameters.Kind, Runtime = parameters.Runtime, architecture = parameters.Architecture, mvid = Guid.NewGuid (), Attributes = ModuleAttributes.ILOnly, Characteristics = (ModuleCharacteristics) 0x8540, }; if (parameters.AssemblyResolver != null) module.assembly_resolver = Disposable.NotOwned (parameters.AssemblyResolver); if (parameters.MetadataResolver != null) module.metadata_resolver = parameters.MetadataResolver; #if !READ_ONLY if (parameters.MetadataImporterProvider != null) module.metadata_importer = parameters.MetadataImporterProvider.GetMetadataImporter (module); #if !PCL && !NET_CORE if (parameters.ReflectionImporterProvider != null) module.reflection_importer = parameters.ReflectionImporterProvider.GetReflectionImporter (module); #endif #endif if (parameters.Kind != ModuleKind.NetModule) { var assembly = new AssemblyDefinition (); module.assembly = assembly; module.assembly.Name = CreateAssemblyName (name); assembly.main_module = module; } module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic)); return module; } static AssemblyNameDefinition CreateAssemblyName (string name) { if (name.EndsWith (".dll") || name.EndsWith (".exe")) name = name.Substring (0, name.Length - 4); return new AssemblyNameDefinition (name, Mixin.ZeroVersion); } #endif #if !PCL && !NET_CORE public void ReadSymbols () { if (string.IsNullOrEmpty (file_name)) throw new InvalidOperationException (); var provider = SymbolProvider.GetPlatformReaderProvider (); if (provider == null) throw new InvalidOperationException (); ReadSymbols (provider.GetSymbolReader (this, file_name)); } #endif public void ReadSymbols (ISymbolReader reader) { if (reader == null) throw new ArgumentNullException ("reader"); symbol_reader = reader; ProcessDebugHeader (); if (HasImage && ReadingMode == ReadingMode.Immediate) { var immediate_reader = new ImmediateModuleReader (Image); immediate_reader.ReadSymbols (this); } } #if !PCL public static ModuleDefinition ReadModule (string fileName) { return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters) { var stream = GetFileStream (fileName, FileMode.Open, parameters.ReadWrite ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read); if (parameters.InMemory) { var memory = new MemoryStream (stream.CanSeek ? (int) stream.Length : 0); using (stream) stream.CopyTo (memory); memory.Position = 0; stream = memory; } try { return ReadModule (Disposable.Owned (stream), fileName, parameters); } catch (Exception) { stream.Dispose (); throw; } } static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share) { Mixin.CheckFileName (fileName); return new FileStream (fileName, mode, access, share); } #endif public static ModuleDefinition ReadModule (Stream stream) { return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters) { Mixin.CheckStream (stream); Mixin.CheckReadSeek (stream); return ReadModule (Disposable.NotOwned (stream), "", parameters); } static ModuleDefinition ReadModule (Disposable<Stream> stream, string fileName, ReaderParameters parameters) { Mixin.CheckParameters (parameters); return ModuleReader.CreateModule ( ImageReader.ReadImage (stream, fileName), parameters); } #if !READ_ONLY #if !PCL public void Write (string fileName) { Write (fileName, new WriterParameters ()); } public void Write (string fileName, WriterParameters parameters) { Mixin.CheckParameters (parameters); var file = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None); ModuleWriter.WriteModuleTo (this, Disposable.Owned (file), parameters); } #endif public void Write () { Write (new WriterParameters ()); } public void Write (WriterParameters parameters) { if (!HasImage) throw new InvalidOperationException (); var image_stream = Image.Stream.value; image_stream.Position = 0; Write (image_stream, parameters); } public void Write (Stream stream) { Write (stream, new WriterParameters ()); } public void Write (Stream stream, WriterParameters parameters) { Mixin.CheckStream (stream); Mixin.CheckWriteSeek (stream); Mixin.CheckParameters (parameters); ModuleWriter.WriteModuleTo (this, Disposable.NotOwned (stream), parameters); } #endif } static partial class Mixin { public static void CheckFileName (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (fileName.Length == 0) throw new ArgumentException (); } public static void CheckStream (object stream) { if (stream == null) throw new ArgumentNullException ("stream"); } public static void CheckWriteSeek (Stream stream) { if (!stream.CanWrite || !stream.CanSeek) throw new ArgumentException (); } public static void CheckReadSeek (Stream stream) { if (!stream.CanRead || !stream.CanSeek) throw new ArgumentException (); } #if !READ_ONLY public static void CheckType (object type) { if (type == null) throw new ArgumentNullException ("type"); } public static void CheckField (object field) { if (field == null) throw new ArgumentNullException ("field"); } public static void CheckMethod (object method) { if (method == null) throw new ArgumentNullException ("method"); } #endif public static void CheckParameters (object parameters) { if (parameters == null) throw new ArgumentNullException ("parameters"); } public static bool HasImage (this ModuleDefinition self) { return self != null && self.HasImage; } public static bool IsCoreLibrary (this ModuleDefinition module) { if (module.Assembly == null) return false; var assembly_name = module.Assembly.Name.Name; if (assembly_name != "mscorlib" && assembly_name != "System.Runtime") return false; if (module.HasImage && module.Read (module, (m, reader) => reader.image.GetTableLength (Table.AssemblyRef) > 0)) return false; return true; } public static string GetFileName (this Stream self) { #if !PCL var file_stream = self as FileStream; if (file_stream == null) return string.Empty; return Path.GetFullPath (file_stream.Name); #else return string.Empty; #endif } #if !NET_4_0 public static void CopyTo (this Stream self, Stream target) { var buffer = new byte [1024 * 8]; int read; while ((read = self.Read (buffer, 0, buffer.Length)) > 0) target.Write (buffer, 0, read); } #endif public static TargetRuntime ParseRuntime (this string self) { switch (self [1]) { case '1': return self [3] == '0' ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case '2': return TargetRuntime.Net_2_0; case '4': default: return TargetRuntime.Net_4_0; } } public static string RuntimeVersionString (this TargetRuntime runtime) { switch (runtime) { case TargetRuntime.Net_1_0: return "v1.0.3705"; case TargetRuntime.Net_1_1: return "v1.1.4322"; case TargetRuntime.Net_2_0: return "v2.0.50727"; case TargetRuntime.Net_4_0: default: return "v4.0.30319"; } } public static bool IsWindowsMetadata (this ModuleDefinition module) { return module.MetadataKind != MetadataKind.Ecma335; } #if !PCL public static byte [] ReadAll (this Stream self) { int read; var memory = new MemoryStream ((int) self.Length); var buffer = new byte [1024]; while ((read = self.Read (buffer, 0, buffer.Length)) != 0) memory.Write (buffer, 0, read); return memory.ToArray (); } #endif public static void Read (object o) { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using Xunit; namespace System.Security.Cryptography.EcDsa.Tests { public partial class ECDsaTests { public static IEnumerable<object[]> AllImplementations() { return new[] { new ECDsa[] { ECDsaFactory.Create() }, new ECDsa[] { new ECDsaStub() }, }; } [Theory, MemberData("AllImplementations")] public void SignDataByteArray_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.SignData((byte[])null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArray_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.SignData(null, -1, -1, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_NegativeOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.SignData(new byte[0], -1, -1, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_OffsetGreaterThanCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.SignData(new byte[0], 2, 1, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_NegativeCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.SignData(new byte[0], 0, -1, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_CountGreaterThanLengthMinusOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.SignData(new byte[0], 0, 1, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], 0, 0, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataByteArraySpan_EmptyHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[10], 0, 10, new HashAlgorithmName(""))); } [Theory, MemberData("AllImplementations")] public void SignDataStream_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.SignData((Stream)null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void SignDataStream_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new MemoryStream(), default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArray_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((byte[])null, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArray_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new byte[0], null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArray_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[0], new byte[0], default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((byte[])null, -1, -1, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_NegativeOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.VerifyData(new byte[0], -1, -1, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_OffsetGreaterThanCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.VerifyData(new byte[0], 2, 1, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_NegativeCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.VerifyData(new byte[0], 0, -1, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_CountGreaterThanLengthMinusOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa) { Assert.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.VerifyData(new byte[0], 0, 1, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new byte[0], 0, 0, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataByteArraySpan_EmptyHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[10], 0, 10, new byte[0], new HashAlgorithmName(""))); } [Theory, MemberData("AllImplementations")] public void VerifyDataStream_NullData_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((Stream)null, null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataStream_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new MemoryStream(), null, default(HashAlgorithmName))); } [Theory, MemberData("AllImplementations")] public void VerifyDataStream_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa) { Assert.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new MemoryStream(), new byte[0], default(HashAlgorithmName))); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static IEnumerable<object[]> RealImplementations() { return new[] { new ECDsa[] { ECDsaFactory.Create() }, }; } [Theory, MemberData("RealImplementations")] public void SignHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>( "hash", () => ecdsa.SignHash(null)); } [Theory, MemberData("RealImplementations")] public void VerifyHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>( "hash", () => ecdsa.VerifyHash(null, null)); } [Theory, MemberData("RealImplementations")] public void VerifyHash_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa) { Assert.Throws<ArgumentNullException>( "signature", () => ecdsa.VerifyHash(new byte[0], null)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory, MemberData("RealImplementations")] public void SignDataByteArray_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.SignData(new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData("RealImplementations")] public void SignDataByteArraySpan_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.SignData(new byte[0], 0, 0, new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData("RealImplementations")] public void SignDataStream_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.SignData(new MemoryStream(), new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData("RealImplementations")] public void VerifyDataByteArray_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.VerifyData(new byte[0], new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData("RealImplementations")] public void VerifyDataByteArraySpan_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.VerifyData(new byte[0], 0, 0, new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } [Theory, MemberData("RealImplementations")] public void VerifyDataStream_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa) { Assert.Throws<CryptographicException>( () => ecdsa.VerifyData(new MemoryStream(), new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM"))); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory, MemberData("RealImplementations")] public void SignData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa) { // Explicitly larger than Array.Empty byte[] data = new byte[10]; byte[] signature = ecdsa.SignData(data, data.Length, 0, HashAlgorithmName.SHA256); Assert.True(ecdsa.VerifyData(Array.Empty<byte>(), signature, HashAlgorithmName.SHA256)); } [Theory, MemberData("RealImplementations")] public void VerifyData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa) { // Explicitly larger than Array.Empty byte[] data = new byte[10]; byte[] signature = ecdsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA256); Assert.True(ecdsa.VerifyData(data, data.Length, 0, signature, HashAlgorithmName.SHA256)); } [Theory, MemberData("RealImplementations")] public void Roundtrip_WithOffset(ECDsa ecdsa) { byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] halfData = { 5, 6, 7, 8, 9 }; byte[] dataSignature = ecdsa.SignData(data, 5, data.Length - 5, HashAlgorithmName.SHA256); byte[] halfDataSignature = ecdsa.SignData(halfData, HashAlgorithmName.SHA256); // Cross-feed the VerifyData calls to prove that both offsets work Assert.True(ecdsa.VerifyData(data, 5, data.Length - 5, halfDataSignature, HashAlgorithmName.SHA256)); Assert.True(ecdsa.VerifyData(halfData, dataSignature, HashAlgorithmName.SHA256)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static IEnumerable<object[]> InteroperableSignatureConfigurations() { foreach (HashAlgorithmName hashAlgorithm in new[] { HashAlgorithmName.MD5, HashAlgorithmName.SHA1, HashAlgorithmName.SHA256, HashAlgorithmName.SHA384, HashAlgorithmName.SHA512 }) { yield return new object[] { ECDsaFactory.Create(), hashAlgorithm }; } } [Theory, MemberData("InteroperableSignatureConfigurations")] public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; MemoryStream dataStream = new MemoryStream(dataArray, true); while (dataStream.Position < dataArray.Length - data.Length) { dataStream.Write(data, 0, data.Length); } dataStream.Position = 0; byte[] dataArray2 = new byte[dataArray.Length + 2]; dataArray.CopyTo(dataArray2, 1); ArraySegment<byte> dataSpan = new ArraySegment<byte>(dataArray2, 1, dataArray.Length); HashAlgorithm halg; if (hashAlgorithm == HashAlgorithmName.MD5) halg = MD5.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA1) halg = SHA1.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA256) halg = SHA256.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA384) halg = SHA384.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA512) halg = SHA512.Create(); else throw new Exception("Hash algorithm not supported."); List<byte[]> signatures = new List<byte[]>(6); // Compute a signature using each of the SignData overloads. Then, verify it using each // of the VerifyData overloads, and VerifyHash overloads. // // Then, verify that VerifyHash fails if the data is tampered with. signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm)); dataStream.Position = 0; signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream))); dataStream.Position = 0; foreach (byte[] signature in signatures) { Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1"); Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2"); Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A"); dataStream.Position = 0; Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A"); dataStream.Position = 0; } int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count(); Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized"); foreach (byte[] signature in signatures) { signature[signature.Length - 1] ^= 0xFF; // flip some bits Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1"); Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2"); Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B"); dataStream.Position = 0; Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B"); dataStream.Position = 0; } } private class ByteArrayComparer : IEqualityComparer<byte[]> { public bool Equals(byte[] x, byte[] y) { return x.SequenceEqual(y); } public int GetHashCode(byte[] obj) { int h = 5381; foreach (byte b in obj) { h = ((h << 5) + h) ^ b.GetHashCode(); } return h; } } } }
// 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 Xunit; namespace System.Tests { public static partial class CompareToTests { [Fact] public static void FromBoolean() { Assert.Equal(0, false.CompareTo(false)); Assert.Equal(0, true.CompareTo(true)); Assert.True(0 > false.CompareTo(true)); Assert.True(0 < true.CompareTo(false)); Assert.Equal(0, false.CompareTo((object)false)); Assert.Equal(0, true.CompareTo((object)true)); Assert.True(0 > false.CompareTo((object)true)); Assert.True(0 < true.CompareTo((object)false)); Assert.Throws<ArgumentException>(() => false.CompareTo("hello")); } [Fact] public static void FromByte() { Assert.Equal(0, ((byte)0).CompareTo((byte)0)); Assert.True(0 > byte.MinValue.CompareTo((byte)1)); Assert.True(0 < byte.MaxValue.CompareTo((byte)0)); Assert.True(0 > ((byte)0).CompareTo((byte)1)); Assert.Equal(0, ((byte)0).CompareTo((object)(byte)0)); Assert.True(0 > byte.MinValue.CompareTo((object)(byte)1)); Assert.True(0 < byte.MaxValue.CompareTo((object)(byte)0)); Assert.True(0 > ((byte)0).CompareTo((object)(byte)1)); Assert.Throws<ArgumentException>(() => ((byte)0.CompareTo("hello"))); } [Fact] public static void FromChar() { Assert.Equal(0, 'c'.CompareTo('c')); Assert.True(0 > 'a'.CompareTo('c')); Assert.True(0 < 'd'.CompareTo('c')); Assert.Throws<ArgumentException>(() => 'x'.CompareTo("hello")); } [Fact] public static void FromDecimal() { Assert.Equal(0, ((decimal)0).CompareTo((decimal)0)); Assert.True(0 > decimal.MinValue.CompareTo((decimal)0)); Assert.True(0 < decimal.MaxValue.CompareTo((decimal)0)); Assert.True(0 > ((decimal)0).CompareTo((decimal)1)); Assert.True(0 < ((decimal)0).CompareTo((decimal)-1)); Assert.Equal(0, ((decimal)0).CompareTo((object)(decimal)0)); Assert.True(0 > decimal.MinValue.CompareTo((object)(decimal)0)); Assert.True(0 < decimal.MaxValue.CompareTo((object)(decimal)0)); Assert.True(0 > ((decimal)0).CompareTo((object)(decimal)1)); Assert.True(0 < ((decimal)0).CompareTo((object)(decimal)-1)); Assert.Throws<ArgumentException>(() => ((decimal)0.CompareTo("hello"))); } [Fact] public static void FromDouble() { Assert.Equal(0, ((double)0).CompareTo((double)0)); Assert.True(0 > double.MinValue.CompareTo((double)0)); Assert.True(0 < double.MaxValue.CompareTo((double)0)); Assert.True(0 > ((double)0).CompareTo((double)1)); Assert.True(0 < ((double)0).CompareTo((double)-1)); Assert.Equal(0, ((double)0).CompareTo((object)(double)0)); Assert.True(0 > double.MinValue.CompareTo((object)(double)0)); Assert.True(0 < double.MaxValue.CompareTo((object)(double)0)); Assert.True(0 > ((double)0).CompareTo((object)(double)1)); Assert.True(0 < ((double)0).CompareTo((object)(double)-1)); Assert.Throws<ArgumentException>(() => ((double)0.CompareTo("hello"))); } [Fact] public static void FromInt16() { Assert.Equal(0, ((short)0).CompareTo((short)0)); Assert.True(0 > short.MinValue.CompareTo((short)0)); Assert.True(0 < short.MaxValue.CompareTo((short)0)); Assert.True(0 > ((short)0).CompareTo((short)1)); Assert.True(0 < ((short)0).CompareTo((short)-1)); Assert.Equal(0, ((short)0).CompareTo((object)(short)0)); Assert.True(0 > short.MinValue.CompareTo((object)(short)0)); Assert.True(0 < short.MaxValue.CompareTo((object)(short)0)); Assert.True(0 > ((short)0).CompareTo((object)(short)1)); Assert.True(0 < ((short)0).CompareTo((object)(short)-1)); Assert.Throws<ArgumentException>(() => ((short)0.CompareTo("hello"))); } [Fact] public static void FromInt32() { Assert.Equal(0, ((int)0).CompareTo((int)0)); Assert.True(0 > int.MinValue.CompareTo((int)0)); Assert.True(0 < int.MaxValue.CompareTo((int)0)); Assert.True(0 > ((int)0).CompareTo((int)1)); Assert.True(0 < ((int)0).CompareTo((int)-1)); Assert.Equal(0, ((int)0).CompareTo((object)(int)0)); Assert.True(0 > int.MinValue.CompareTo((object)(int)0)); Assert.True(0 < int.MaxValue.CompareTo((object)(int)0)); Assert.True(0 > ((int)0).CompareTo((object)(int)1)); Assert.True(0 < ((int)0).CompareTo((object)(int)-1)); Assert.Throws<ArgumentException>(() => ((int)0.CompareTo("hello"))); } [Fact] public static void FromInt64() { Assert.Equal(0, ((long)0).CompareTo((long)0)); Assert.True(0 > long.MinValue.CompareTo((long)0)); Assert.True(0 < long.MaxValue.CompareTo((long)0)); Assert.True(0 > ((long)0).CompareTo((long)1)); Assert.True(0 < ((long)0).CompareTo((long)-1)); Assert.Equal(0, ((long)0).CompareTo((object)(long)0)); Assert.True(0 > long.MinValue.CompareTo((object)(long)0)); Assert.True(0 < long.MaxValue.CompareTo((object)(long)0)); Assert.True(0 > ((long)0).CompareTo((object)(long)1)); Assert.True(0 < ((long)0).CompareTo((object)(long)-1)); Assert.Throws<ArgumentException>(() => ((long)0.CompareTo("hello"))); } public static void FromSByte() { Assert.Equal(0, ((sbyte)0).CompareTo((sbyte)0)); Assert.True(0 > sbyte.MinValue.CompareTo((sbyte)0)); Assert.True(0 < sbyte.MaxValue.CompareTo((sbyte)0)); Assert.True(0 > ((sbyte)0).CompareTo((sbyte)1)); Assert.True(0 < ((sbyte)0).CompareTo((sbyte)-1)); Assert.Equal(0, ((sbyte)0).CompareTo((object)(sbyte)0)); Assert.True(0 > sbyte.MinValue.CompareTo((object)(sbyte)0)); Assert.True(0 < sbyte.MaxValue.CompareTo((object)(sbyte)0)); Assert.True(0 > ((sbyte)0).CompareTo((object)(sbyte)1)); Assert.True(0 < ((sbyte)0).CompareTo((object)(sbyte)-1)); Assert.Throws<ArgumentException>(() => ((sbyte)0.CompareTo("hello"))); } [Fact] public static void FromSingle() { Assert.Equal(0, ((float)0).CompareTo((float)0)); Assert.True(0 > float.MinValue.CompareTo((float)0)); Assert.True(0 < float.MaxValue.CompareTo((float)0)); Assert.True(0 > ((float)0).CompareTo((float)1)); Assert.True(0 < ((float)0).CompareTo((float)-1)); Assert.Equal(0, ((float)0).CompareTo((object)(float)0)); Assert.True(0 > float.MinValue.CompareTo((object)(float)0)); Assert.True(0 < float.MaxValue.CompareTo((object)(float)0)); Assert.True(0 > ((float)0).CompareTo((object)(float)1)); Assert.True(0 < ((float)0).CompareTo((object)(float)-1)); Assert.Throws<ArgumentException>(() => ((float)0.CompareTo("hello"))); } [Fact] public static void FromUInt16() { Assert.Equal(0, ((ushort)0).CompareTo((ushort)0)); Assert.True(0 > ushort.MinValue.CompareTo((ushort)1)); Assert.True(0 < ushort.MaxValue.CompareTo((ushort)0)); Assert.True(0 > ((ushort)0).CompareTo((ushort)1)); Assert.Equal(0, ((ushort)0).CompareTo((object)(ushort)0)); Assert.True(0 > ushort.MinValue.CompareTo((object)(ushort)1)); Assert.True(0 < ushort.MaxValue.CompareTo((object)(ushort)0)); Assert.True(0 > ((ushort)0).CompareTo((object)(ushort)1)); Assert.Throws<ArgumentException>(() => ((ushort)0.CompareTo("hello"))); } [Fact] public static void FromUInt32() { Assert.Equal(0, ((uint)0).CompareTo((uint)0)); Assert.True(0 > uint.MinValue.CompareTo((uint)1)); Assert.True(0 < uint.MaxValue.CompareTo((uint)0)); Assert.True(0 > ((uint)0).CompareTo((uint)1)); Assert.Equal(0, ((uint)0).CompareTo((object)(uint)0)); Assert.True(0 > uint.MinValue.CompareTo((object)(uint)1)); Assert.True(0 < uint.MaxValue.CompareTo((object)(uint)0)); Assert.True(0 > ((uint)0).CompareTo((object)(uint)1)); Assert.Throws<ArgumentException>(() => ((uint)0.CompareTo("hello"))); } [Fact] public static void FromUInt64() { Assert.Equal(0, ((ulong)0).CompareTo((ulong)0)); Assert.True(0 > ulong.MinValue.CompareTo((ulong)1)); Assert.True(0 < ulong.MaxValue.CompareTo((ulong)0)); Assert.True(0 > ((ulong)0).CompareTo((ulong)1)); Assert.Equal(0, ((ulong)0).CompareTo((object)(ulong)0)); Assert.True(0 > ulong.MinValue.CompareTo((object)(ulong)1)); Assert.True(0 < ulong.MaxValue.CompareTo((object)(ulong)0)); Assert.True(0 > ((ulong)0).CompareTo((object)(ulong)1)); Assert.Throws<ArgumentException>(() => ((ulong)0.CompareTo("hello"))); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition { using Microsoft.Azure.Management.ContainerService.Fluent; using Microsoft.Azure.Management.ContainerService.Fluent.KubernetesClusterAgentPool.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition; using Microsoft.Azure.Management.ContainerService.Fluent.Models; using System.Collections.Generic; /// <summary> /// The Kubernetes cluster definition allowing to specify a network profile. /// </summary> public interface INetworkProfileDefinitionStages { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify the DNS prefix label. /// </summary> public interface IWithDnsPrefix { /// <summary> /// Specifies the DNS prefix to be used to create the FQDN for the master pool. /// </summary> /// <param name="dnsPrefix">The DNS prefix to be used to create the FQDN for the master pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithCreate WithDnsPrefix(string dnsPrefix); } /// <summary> /// The stage of the definition which contains all the minimum required inputs for /// the resource to be created, but also allows for any other optional settings to /// be specified. /// </summary> public interface IWithCreate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.ContainerService.Fluent.IKubernetesCluster>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithNetworkProfile, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithDnsPrefix, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAddOnProfiles, Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithCreate> { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify the service principal secret. /// </summary> public interface IWithServicePrincipalProfile { /// <summary> /// Properties for service principal. /// </summary> /// <param name="secret">The secret password associated with the service principal.</param> /// <return>The next stage.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAgentPool WithServicePrincipalSecret(string secret); } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify the cluster's add-on's profiles. /// </summary> public interface IWithAddOnProfiles : Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAddOnProfilesBeta { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specific the Linux root username. /// </summary> public interface IWithLinuxRootUsername { /// <summary> /// Begins the definition to specify Linux root username. /// </summary> /// <param name="rootUserName">The root username.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithLinuxSshKey WithRootUsername(string rootUserName); } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify a network profile. /// </summary> public interface IWithNetworkProfile : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Gets Begins the definition of a network profile to be attached to the Kubernetes cluster. /// </summary> /// <summary> /// Gets the stage representing configuration for the network profile. /// </summary> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IBlank<Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithCreate> DefineNetworkProfile { get; } } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify the service principal client ID. /// </summary> public interface IWithServicePrincipalClientId { /// <summary> /// Properties for Kubernetes cluster service principal. /// </summary> /// <param name="clientId">The ID for the service principal.</param> /// <return>The next stage.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithServicePrincipalProfile WithServicePrincipalClientId(string clientId); } /// <summary> /// The final stage of a network profile definition. /// At this stage, any remaining optional settings can be specified, or the container service agent pool /// can be attached to the parent container service definition. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithAttach<ParentT> : Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithNetworkPolicy<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithPodCidr<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithServiceCidr<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithDnsServiceIP<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithDockerBridgeCidr<ParentT>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<ParentT> { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify an agent pool profile. /// </summary> public interface IWithAgentPool { /// <summary> /// Begins the definition of an agent pool profile to be attached to the Kubernetes cluster. /// </summary> /// <param name="name">The name for the agent pool profile.</param> /// <return>The stage representing configuration for the agent pool profile.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesClusterAgentPool.Definition.IBlank<Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithCreate> DefineAgentPool(string name); } /// <summary> /// The first stage of a network profile definition. /// </summary> /// <typeparam name="ParentT">The stage of the Kubernetes cluster network profile definition to return to after attaching this definition.</typeparam> public interface IBlank<ParentT> : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> { /// <summary> /// Specifies the network plugin type to be used for building the Kubernetes network. /// </summary> /// <param name="networkPlugin">The network plugin type to be used for building the Kubernetes network.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> WithNetworkPlugin(NetworkPlugin networkPlugin); } /// <summary> /// Interface for all the definitions related to a Kubernetes cluster. /// </summary> public interface IDefinition : Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IBlank, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithGroup, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithVersion, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithLinuxRootUsername, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithLinuxSshKey, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithServicePrincipalClientId, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithServicePrincipalProfile, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithDnsPrefix, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAgentPool, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithNetworkProfile, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAddOnProfiles, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithCreate { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specific the Linux SSH key. /// </summary> public interface IWithLinuxSshKey { /// <summary> /// Begins the definition to specify Linux ssh key. /// </summary> /// <param name="sshKeyData">The SSH key data.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithServicePrincipalClientId WithSshKey(string sshKeyData); } /// <summary> /// The stage of a network profile definition allowing to specify a CIDR notation IP range assigned to the /// Docker bridge network. /// </summary> /// <typeparam name="ParentT">The stage of the network profile definition to return to after attaching this definition.</typeparam> public interface IWithDockerBridgeCidr<ParentT> { /// <summary> /// Specifies a CIDR notation IP range assigned to the Docker bridge network; it must not overlap with /// any subnet IP ranges or the Kubernetes service address range. /// </summary> /// <param name="dockerBridgeCidr"> /// The CIDR notation IP range assigned to the Docker bridge network; it must not /// overlap with any subnet IP ranges or the Kubernetes service address range. /// </param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> WithDockerBridgeCidr(string dockerBridgeCidr); } /// <summary> /// The stage of a network profile definition allowing to specify an IP address assigned to the Kubernetes DNS service. /// </summary> /// <typeparam name="ParentT">The stage of the network profile definition to return to after attaching this definition.</typeparam> public interface IWithDnsServiceIP<ParentT> { /// <summary> /// Specifies an IP address assigned to the Kubernetes DNS service; it must be within the Kubernetes service /// address range specified in the service CIDR. /// </summary> /// <param name="dnsServiceIP"> /// The IP address assigned to the Kubernetes DNS service; it must be within the /// Kubernetes service address range specified in the service CIDR. /// </param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> WithDnsServiceIP(string dnsServiceIP); } /// <summary> /// The stage of a network profile definition allowing to specify a CIDR notation IP range from which to /// assign service cluster IPs. /// </summary> /// <typeparam name="ParentT">The stage of the network profile definition to return to after attaching this definition.</typeparam> public interface IWithServiceCidr<ParentT> { /// <summary> /// Specifies a CIDR notation IP range from which to assign service cluster IPs; must not overlap with /// any subnet IP ranges. /// </summary> /// <param name="serviceCidr"> /// The CIDR notation IP range from which to assign service cluster IPs; it must not /// overlap with any Subnet IP ranges. /// </param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> WithServiceCidr(string serviceCidr); } /// <summary> /// The Kubernetes cluster network profile definition. /// The entirety of a Kubernetes cluster network profile definition as a part of a parent definition. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface INetworkProfileDefinition<ParentT> : Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IBlank<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithNetworkPolicy<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithPodCidr<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithServiceCidr<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithDnsServiceIP<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithDockerBridgeCidr<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify the resource group. /// </summary> public interface IWithGroup : Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition.IWithGroup<Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithVersion> { } /// <summary> /// The stage of a network profile definition allowing to specify a CIDR notation IP range from which to /// assign pod IPs when kubenet is used. /// </summary> /// <typeparam name="ParentT">The stage of the network profile definition to return to after attaching this definition.</typeparam> public interface IWithPodCidr<ParentT> { /// <summary> /// Specifies a CIDR notation IP range from which to assign pod IPs when kubenet is used. /// </summary> /// <param name="podCidr">The CIDR notation IP range from which to assign pod IPs when kubenet is used.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> WithPodCidr(string podCidr); } /// <summary> /// The stage of a network profile definition allowing to specify the network policy. /// </summary> /// <typeparam name="ParentT">The stage of the network profile definition to return to after attaching this definition.</typeparam> public interface IWithNetworkPolicy<ParentT> { /// <summary> /// Specifies the network policy to be used for building the Kubernetes network. /// </summary> /// <param name="networkPolicy">The network policy to be used for building the Kubernetes network.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithAttach<ParentT> WithNetworkPolicy(NetworkPolicy networkPolicy); } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify orchestration type. /// </summary> public interface IWithVersion { /// <summary> /// Uses the latest version for the Kubernetes cluster. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithLinuxRootUsername WithLatestVersion(); /// <summary> /// Specifies the version for the Kubernetes cluster. /// </summary> /// <param name="kubernetesVersion">The kubernetes version.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithLinuxRootUsername WithVersion(Models.KubernetesVersion kubernetesVersion); /// <summary> /// Specifies the version for the Kubernetes cluster. /// </summary> /// <param name="kubernetesVersion">The kubernetes version.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithLinuxRootUsername WithVersion(string kubernetesVersion); } /// <summary> /// The first stage of a container service definition. /// </summary> public interface IBlank : Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithRegion<Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Definition.IWithGroup> { } /// <summary> /// The stage of the Kubernetes cluster definition allowing to specify the cluster's add-on's profiles. /// </summary> public interface IWithAddOnProfilesBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Updates the cluster's add-on's profiles. /// </summary> /// <param name="addOnProfileMap">The cluster's add-on's profiles.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.ContainerService.Fluent.KubernetesCluster.Update.IUpdate WithAddOnProfiles(IDictionary<string,Microsoft.Azure.Management.ContainerService.Fluent.Models.ManagedClusterAddonProfile> addOnProfileMap); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.CodeTools { using System; using System.Runtime.InteropServices; using System.Collections.Generic; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.CodeTools; using Microsoft.VisualStudio.Shell; using System.Timers; internal class TaskManager : ITaskManager , IVsTaskProvider, IVsTaskProvider2, IVsTaskProvider3 , IVsRunningDocTableEvents , IServiceProvider , IVsTaskManager , Microsoft.Build.Framework.ITaskHost { #region Fields private List<Task> tasks = new List<Task>(); private string providerName; private bool released; private int refreshDelay; private Timer refreshTimer; private bool needRefreshPrevious; private bool needRefresh; public List<IClearTasksEvent> OnClearTasks = new List<IClearTasksEvent>(); public const int DefaultRefreshDelay = 1000; // milliseconds public bool TrackMarkerEvents { get { return (refreshDelay > 0); } } #endregion #region Construction public TaskManager(string providerName) : this(providerName, DefaultRefreshDelay) { } public TaskManager(string providerName, int refreshDelay) { released = false; this.providerName = providerName; this.refreshDelay = refreshDelay; if (refreshDelay > 0 && refreshDelay < 500) this.refreshDelay = 500; if (refreshDelay > 0) { refreshTimer = new Timer(refreshDelay); refreshTimer.Elapsed += new ElapsedEventHandler(refreshTimer_Elapsed); refreshTimer.AutoReset = false; // one pulse only } InitializeTaskProvider(); InitializeRunningDocTableEvents(); InitializeOutputWindow(); } ~TaskManager() { Release(); } internal int sharedCount; #endregion #region Refresh timer internal void RefreshDelayed() { // called from Task's when text markers change Common.Trace("RefreshDelayed"); needRefresh = true; if (!released && refreshTimer != null && !refreshTimer.Enabled) { refreshTimer.Start(); } } private void refreshTimer_Elapsed(object sender, ElapsedEventArgs e) { if (!released) { if (needRefresh) { needRefreshPrevious = true; needRefresh = false; // cannot race as we are always in the UI thread refreshTimer.Start(); // pulse again } else if (needRefreshPrevious) { // one cycle no change Common.Trace("Refresh task list"); needRefreshPrevious = false; refreshTimer.Stop(); Refresh(); } } } #endregion #region ITaskManager public void Release() { if (!released) { released = true; if (refreshTimer != null) { refreshTimer.Stop(); refreshTimer.Dispose(); refreshTimer = null; } ClearTasks(); SolutionRelease(); DisposeOutputWindow(); DisposeTaskProvider(); DisposeRunningDocTableEvents(); } } public void AddTask(string description, string tipText, string code, string helpKeyword , TaskPriority priority, TaskCategory category , TaskMarker marker, Guid outputPane , string projectName , string fileName, int startLine, int startColumn, int endLine, int endColumn , ITaskCommands commands ) { Common.ThreadSafeASync(delegate () { // Add a new task Location span = new Location(projectName, fileName, startLine, startColumn, endLine, endColumn); Task task = new Task(this , description, tipText, code, helpKeyword , priority, category, marker , span , commands); tasks.Add(task); // show standard error in the build output pane if (outputPane != TaskOutputPane.None && description != null) { string kind; switch (category) { case TaskCategory.Error: kind = "error "; break; case TaskCategory.Warning: kind = "warning "; break; case TaskCategory.Message: kind = "message "; break; default: kind = ""; break; } OutputString(span + ": " + kind + (code != null ? code : "") + ": " + description + "\n", outputPane); } RefreshDelayed(); }); } public void OutputString(string message, Guid outputPane) { if (message != null) { Common.ThreadSafeASync(delegate () { IVsOutputWindowPane pane = GetOutputPane(ref outputPane); if (pane != null) { pane.OutputString(message); } }); } } public void Refresh() { Common.ThreadSafeASync(delegate () { TaskListRefresh(); }); } private void InvokeHandlers(string command) { var handlers = OnClearTasks.ToArray(); for (int i = 0; i < handlers.Length; i++) { var handler = handlers[i]; try { handler.Invoke(this, command); handlers[i] = null; } catch { } } try { // now delete all handlers that failed for (int i = 0; i < handlers.Length; i++) { var failed = handlers[i]; if (failed != null) { OnClearTasks.Remove(failed); } } } catch { } } public void SolutionBuildStart() { Common.ThreadSafeInvoke(delegate () // synchronous to make sure processes die before we start building { InvokeHandlers("<buildStart>"); }); } public void SolutionBuildDone(bool success) { Common.ThreadSafeASync(delegate () { InvokeHandlers((success) ? "<buildDone>" : "<buildFailed>"); }); } public void SolutionBuildCancel() { Common.ThreadSafeInvoke(delegate () { InvokeHandlers("<buildCancel>"); }); } public void SolutionBuildCancelAsync() { Common.ThreadSafeASync(delegate () { InvokeHandlers("<buildCancel>"); }); } public void SolutionRelease() { Common.ThreadSafeASync(delegate () { InvokeHandlers("<release>"); }); } public void ClearTasks() { Common.ThreadSafeASync(delegate () { InvokeHandlers(""); foreach (Task t in tasks) { if (t != null) { t.OnDeleteTask(); } } tasks.Clear(); Refresh(); }); } public void ClearTasksOnSource(string projectName /* can be null */, string fileName) { if (fileName != null && fileName.Length > 0) { Common.ThreadSafeASync(delegate () { IVsHierarchy project = Common.GetProjectByName(providerName); foreach (Task t in tasks) { if (t != null && t.IsSameFile(project, fileName)) { t.OnDeleteTask(); } } tasks.RemoveAll(delegate (Task t) { return (t == null || t.IsSameFile(project, fileName)); }); Refresh(); }); } } public void ClearTasksOnSourceSpan(string projectName, string fileName , int startLine, int startColumn, int endLine, int endColumn) { if (fileName != null && fileName.Length > 0) { Common.ThreadSafeASync(delegate () { Location span = new Location(projectName, fileName, startLine, startColumn, endLine, endColumn); foreach (Task t in tasks) { if (t != null && t.Overlaps(span)) { t.OnDeleteTask(); } } tasks.RemoveAll(delegate (Task t) { return (t == null || t.Overlaps(span)); }); Refresh(); }); } } public void ClearTasksOnProject(string projectName) { Common.ThreadSafeASync(delegate () { ClearTasksOnHierarchy(Common.GetProjectByName(projectName)); }); } internal void ClearTasksOnHierarchy(IVsHierarchy hier) { if (hier != null) { InvokeHandlers(Common.GetProjectName(hier)); foreach (Task t in tasks) { if (t != null && t.IsSameHierarchy(hier)) { t.OnDeleteTask(); } } tasks.RemoveAll(delegate (Task t) { return (t == null ? false : t.IsSameHierarchy(hier)); }); Refresh(); } } internal void ClearTask(object task) { if (task != null) { int index = tasks.FindIndex(delegate (Task t) { return ((object)t == task); }); if (index >= 0) { Task t = tasks[index]; t.OnDeleteTask(); tasks.RemoveAt(index); Refresh(); } } } internal void RefreshTask(object taskObj) { // Refresh(); if (taskObj != null) { Task task = tasks.Find(delegate (Task t) { return ((object)t == taskObj); }); if (task != null) { TaskListRefreshTask(task); } } } #endregion #region Output window private IVsOutputWindow outputWindow; // we cache the output window private IVsOutputWindowPane GetOutputPane(ref Guid outputPaneGuid) { if (outputPaneGuid != Guid.Empty) { if (outputWindow != null) { IVsOutputWindowPane pane; outputWindow.GetPane(ref outputPaneGuid, out pane); return pane; } } return null; } private void InitializeOutputWindow() { try { // sometimes failed on VS2010 outputWindow = Common.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; } catch { outputWindow = null; } } private void DisposeOutputWindow() { outputWindow = null; } #endregion #region IVsTaskProvider private uint taskListCookie; private IVsTaskList taskList; private void InitializeTaskProvider() { taskList = Common.GetService(typeof(SVsErrorList)) as IVsTaskList; if (taskList != null) { taskList.RegisterTaskProvider(this, out taskListCookie); #if DEBUG System.Diagnostics.Debugger.Launch(); #endif } } private void DisposeTaskProvider() { ClearTasks(); OnTaskListFinalRelease(taskList); } private void TaskListRefresh() { if (taskList != null && taskListCookie != 0) { taskList.RefreshTasks(taskListCookie); } } private void TaskListRefreshTask(Task task) { if (taskList != null && taskListCookie != 0 && task != null) { IVsTaskList2 taskList2 = taskList as IVsTaskList2; if (taskList2 != null) { IVsTaskItem[] taskItems = { task }; taskList2.RefreshOrAddTasks(taskListCookie, 1, taskItems); } } } public int EnumTaskItems(out IVsEnumTaskItems ppenum) { // remove user deleted tasks // tasks.RemoveAll( delegate( Task t ) { return (t==null || t.isDeleted); }); ppenum = new TaskEnumerator(tasks); return 0; } public int ImageList(out IntPtr phImageList) { phImageList = IntPtr.Zero; return VSConstants.E_NOTIMPL; } public int OnTaskListFinalRelease(IVsTaskList pTaskList) { if (pTaskList != null) { if (taskListCookie != 0) { pTaskList.UnregisterTaskProvider(taskListCookie); taskListCookie = 0; taskList = null; } } return 0; } public int ReRegistrationKey(out string pbstrKey) { pbstrKey = null; return VSConstants.E_NOTIMPL; } public int SubcategoryList(uint cbstr, string[] rgbstr, out uint pcActual) { pcActual = 0; if (cbstr != 0 || rgbstr != null) { if (rgbstr != null && rgbstr.Length > 0) { rgbstr[0] = "Error"; } } return 0; } #endregion #region IVsRunningDocTableEvents Members private IVsRunningDocumentTable rdt; private uint rdtEventsCookie; // = 0 private void InitializeRunningDocTableEvents() { rdt = Common.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { rdt.AdviseRunningDocTableEvents(this, out rdtEventsCookie); } } private void DisposeRunningDocTableEvents() { if (rdt != null && rdtEventsCookie != 0) { rdt.UnadviseRunningDocTableEvents(rdtEventsCookie); rdtEventsCookie = 0; } rdt = null; } private void OnOpenDocument(uint docCookie) { if (rdt != null) { uint flags; uint readLocks; uint editLocks; string fileName; IVsHierarchy hier; uint itemId; IntPtr docData; int hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks , out fileName, out hier, out itemId, out docData); if (hr == 0 && !docData.Equals(IntPtr.Zero)) { IVsTextLines textLines = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(docData) as IVsTextLines; if (textLines != null) { foreach (Task t in tasks) { t.OnOpenDocument(hier, itemId, fileName, textLines); } } } } } public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { /* Common.Trace(string.Format("OnAfterFirstDocumentLock: {0} - {1} - {2} ", dwRDTLockType, dwReadLocksRemaining, dwEditLocksRemaining )); if (rdt != null && dwReadLocksRemaining == 1 && dwEditLocksRemaining==1) { OnOpenDocument(docCookie); } */ return 0; } public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) { /* Common.Trace("OnAfterAttributeChange: " + grfAttribs.ToString("X4")); if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) == (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) { OnOpenDocument(docCookie); } */ return 0; } public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) { return 0; } public int OnAfterSave(uint docCookie) { return 0; } public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) { // Common.Trace("OnBeforeDocumentWindowShow firstShow = " + fFirstShow); if (fFirstShow != 0) { OnOpenDocument(docCookie); } return 0; } public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { return 0; } #endregion #region IVsTaskProvider2 public int MaintainInitialTaskOrder(out int bMaintainOrder) { bMaintainOrder = 0; return 0; } #endregion #region IVsTaskProvider3 Members public int GetColumn(int iColumn, VSTASKCOLUMN[] pColumn) { return VSConstants.E_NOTIMPL; } public int GetColumnCount(out int pnColumns) { pnColumns = 0; return VSConstants.E_NOTIMPL; } public int GetProviderFlags(out uint tpfFlags) { tpfFlags = 0; return VSConstants.E_NOTIMPL; } public int GetProviderGuid(out Guid pguidProvider) { pguidProvider = Guid.Empty; return VSConstants.E_NOTIMPL; } public int GetProviderName(out string pbstrName) { if (providerName != null) { pbstrName = providerName; return 0; } else { pbstrName = null; return VSConstants.E_NOTIMPL; } } public int GetProviderToolbar(out Guid pguidGroup, out uint pdwID) { pguidGroup = Guid.Empty; pdwID = 0; return VSConstants.E_NOTIMPL; } public int GetSurrogateProviderGuid(out Guid pguidProvider) { pguidProvider = Guid.Empty; return VSConstants.E_NOTIMPL; } public int OnBeginTaskEdit(IVsTaskItem pItem) { return 0; } public int OnEndTaskEdit(IVsTaskItem pItem, int fCommitChanges, out int pfAllowChanges) { pfAllowChanges = 1; return VSConstants.E_NOTIMPL; } #endregion #region IServiceProvider Members public object GetService(Type serviceType) { return Common.GetService(serviceType); } #endregion #region IVsTaskManager Members public object GetHierarchy(string projectName) { return Common.GetProjectByName(projectName); } public void AddClearTasksEvent(IClearTasksEvent handler) { OnClearTasks.Add(handler); } public void RemoveClearTasksEvent(IClearTasksEvent handler) { OnClearTasks.Remove(handler); } #endregion } internal class TaskEnumerator : IVsEnumTaskItems { private List<Task> tasks; private int pos; public TaskEnumerator(List<Task> tasks) { this.tasks = tasks; // pos = 0; } public virtual int Clone(out IVsEnumTaskItems ppenum) { ppenum = new TaskEnumerator(tasks); return 0; } public virtual int Next(uint celt, IVsTaskItem[] rgelt, uint[] pceltFetched) { uint fetched = 0; while (pos < tasks.Count && fetched < celt) { Task task = tasks[pos]; if (task != null && task.IsVisible()) { if (rgelt != null && rgelt.Length > fetched) { rgelt[fetched] = task; } fetched++; } pos++; } if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = fetched; } return (fetched < celt ? VSConstants.S_FALSE : 0); } public virtual int Reset() { pos = 0; return 0; } public virtual int Skip(uint celt) { uint skipped = 0; while (pos < tasks.Count && skipped < celt) { Task task = tasks[pos]; if (task != null && task.IsVisible()) { skipped++; } pos++; } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class Post : VotableThing { private const string CommentUrl = "/api/comment"; private const string RemoveUrl = "/api/remove"; private const string DelUrl = "/api/del"; private const string GetCommentsUrl = "/comments/{0}.json"; private const string ApproveUrl = "/api/approve"; private const string EditUserTextUrl = "/api/editusertext"; private const string HideUrl = "/api/hide"; private const string UnhideUrl = "/api/unhide"; private const string SetFlairUrl = "/r/{0}/api/flair"; private const string MarkNSFWUrl = "/api/marknsfw"; private const string UnmarkNSFWUrl = "/api/unmarknsfw"; private const string ContestModeUrl = "/api/set_contest_mode"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } public Post Init(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings); return this; } public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); await Task.Factory.StartNew(() => JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings)); return this; } private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent) { base.Init(reddit, webAgent, post); Reddit = reddit; WebAgent = webAgent; } [JsonProperty("author")] public string AuthorName { get; set; } [JsonIgnore] public RedditUser Author { get { return Reddit.GetUser(AuthorName); } } public Comment[] Comments { get { return ListComments().ToArray(); } } [JsonProperty("approved_by")] public string ApprovedBy { get; set; } [JsonProperty("author_flair_css_class")] public string AuthorFlairCssClass { get; set; } [JsonProperty("author_flair_text")] public string AuthorFlairText { get; set; } [JsonProperty("banned_by")] public string BannedBy { get; set; } [JsonProperty("domain")] public string Domain { get; set; } [JsonProperty("edited")] public bool Edited { get; set; } [JsonProperty("is_self")] public bool IsSelfPost { get; set; } [JsonProperty("link_flair_css_class")] public string LinkFlairCssClass { get; set; } [JsonProperty("link_flair_text")] public string LinkFlairText { get; set; } [JsonProperty("num_comments")] public int CommentCount { get; set; } [JsonProperty("over_18")] public bool NSFW { get; set; } [JsonProperty("permalink")] [JsonConverter(typeof(UrlParser))] public Uri Permalink { get; set; } [JsonProperty("score")] public int Score { get; set; } [JsonProperty("selftext")] public string SelfText { get; set; } [JsonProperty("selftext_html")] public string SelfTextHtml { get; set; } [JsonProperty("thumbnail")] [JsonConverter(typeof(UrlParser))] public Uri Thumbnail { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("subreddit")] public string SubredditName { get; set; } [JsonIgnore] public Subreddit Subreddit { get { return Reddit.GetSubreddit("/r/" + SubredditName); } } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonProperty("num_reports")] public int? Reports { get; set; } public Comment Comment(string message) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(CommentUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { text = message, thing_id = FullName, uh = Reddit.User.Modhash, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); if (json["json"]["ratelimit"] != null) throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>())); return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this); } private string SimpleAction(string endpoint) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } private string SimpleActionToggle(string endpoint, bool value) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, state = value, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } public void Approve() { var data = SimpleAction(ApproveUrl); } public void Remove() { RemoveImpl(false); } public void RemoveSpam() { RemoveImpl(true); } private void RemoveImpl(bool spam) { var request = WebAgent.CreatePost(RemoveUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, spam = spam, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void Del() { var data = SimpleAction(DelUrl); } public void Hide() { var data = SimpleAction(HideUrl); } public void Unhide() { var data = SimpleAction(UnhideUrl); } public void MarkNSFW() { var data = SimpleAction(MarkNSFWUrl); } public void UnmarkNSFW() { var data = SimpleAction(UnmarkNSFWUrl); } public void ContestMode(bool state) { var data = SimpleActionToggle(ContestModeUrl, state); } #region Obsolete Getter Methods [Obsolete("Use Comments property instead")] public Comment[] GetComments() { return Comments; } #endregion Obsolete Getter Methods /// <summary> /// Replaces the text in this post with the input text. /// </summary> /// <param name="newText">The text to replace the post's contents</param> public void EditText(string newText) { if (Reddit.User == null) throw new Exception("No user logged in."); if (!IsSelfPost) throw new Exception("Submission to edit is not a self-post."); var request = WebAgent.CreatePost(EditUserTextUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", text = newText, thing_id = FullName, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); JToken json = JToken.Parse(result); if (json["json"].ToString().Contains("\"errors\": []")) SelfText = newText; else throw new Exception("Error editing text."); } public void Update() { JToken post; if (!this.IsSelfPost) post = Reddit.GetToken(new Uri("https://reddit.com" + this.Permalink)); else post = Reddit.GetToken(this.Url); JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings); } public void SetFlair(string flairText, string flairClass) { if (Reddit.User == null) throw new Exception("No user logged in."); var request = WebAgent.CreatePost(string.Format(SetFlairUrl,SubredditName)); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", css_class = flairClass, link = FullName, name = Reddit.User.Name, text = flairText, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); LinkFlairText = flairText; } public List<Comment> ListComments(int? limit = null) { var url = string.Format(GetCommentsUrl, Id); if (limit.HasValue) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("limit", limit.Value.ToString()); url = string.Format("{0}?{1}", url, query); } var request = WebAgent.CreateGet(url); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JArray.Parse(data); var postJson = json.Last()["data"]["children"]; var comments = new List<Comment>(); foreach (var comment in postJson) { comments.Add(new Comment().Init(Reddit, comment, WebAgent, this)); } return comments; } } }
using System; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Python.Runtime { /// <summary> /// Abstract class defining boiler plate methods that /// Custom Marshalers will use. /// </summary> internal abstract class MarshalerBase : ICustomMarshaler { public object MarshalNativeToManaged(IntPtr pNativeData) { throw new NotImplementedException(); } public abstract IntPtr MarshalManagedToNative(object managedObj); public void CleanUpNativeData(IntPtr pNativeData) { Marshal.FreeHGlobal(pNativeData); } public void CleanUpManagedData(object managedObj) { // Let GC deal with it } public int GetNativeDataSize() { return IntPtr.Size; } } /// <summary> /// Custom Marshaler to deal with Managed String to Native /// conversion differences on UCS2/UCS4. /// </summary> internal class UcsMarshaler : MarshalerBase { internal static readonly int _UCS = Runtime.PyUnicode_GetMax() <= 0xFFFF ? 2 : 4; internal static readonly Encoding PyEncoding = _UCS == 2 ? Encoding.Unicode : Encoding.UTF32; private static readonly MarshalerBase Instance = new UcsMarshaler(); public override IntPtr MarshalManagedToNative(object managedObj) { var s = managedObj as string; if (s == null) { return IntPtr.Zero; } byte[] bStr = PyEncoding.GetBytes(s + "\0"); IntPtr mem = Marshal.AllocHGlobal(bStr.Length); try { Marshal.Copy(bStr, 0, mem, bStr.Length); } catch (Exception) { Marshal.FreeHGlobal(mem); throw; } return mem; } public static ICustomMarshaler GetInstance(string cookie) { return Instance; } public static string PtrToStringUni(IntPtr p) { if (p == IntPtr.Zero) { return null; } int size = GetUnicodeByteLength(p); var buffer = new byte[size]; Marshal.Copy(p, buffer, 0, size); return PyEncoding.GetString(buffer, 0, size); } public static int GetUnicodeByteLength(IntPtr p) { var len = 0; while (true) { int c = _UCS == 2 ? Marshal.ReadInt16(p, len * 2) : Marshal.ReadInt32(p, len * 4); if (c == 0) { return len * _UCS; } checked { ++len; } } } /// <summary> /// Utility function for Marshaling Unicode on PY3 and AnsiStr on PY2. /// Use on functions whose Input signatures changed between PY2/PY3. /// Ex. Py_SetPythonHome /// </summary> /// <param name="s">Managed String</param> /// <returns> /// Ptr to Native String ANSI(PY2)/Unicode(PY3/UCS2)/UTF32(PY3/UCS4. /// </returns> /// <remarks> /// You MUST deallocate the IntPtr of the Return when done with it. /// </remarks> public static IntPtr Py3UnicodePy2StringtoPtr(string s) { return Instance.MarshalManagedToNative(s); } /// <summary> /// Utility function for Marshaling Unicode IntPtr on PY3 and /// AnsiStr IntPtr on PY2 to Managed Strings. Use on Python functions /// whose return type changed between PY2/PY3. /// Ex. Py_GetPythonHome /// </summary> /// <param name="p">Native Ansi/Unicode/UTF32 String</param> /// <returns> /// Managed String /// </returns> public static string PtrToPy3UnicodePy2String(IntPtr p) { return PtrToStringUni(p); } } /// <summary> /// Custom Marshaler to deal with Managed String Arrays to Native /// conversion differences on UCS2/UCS4. /// </summary> internal class StrArrayMarshaler : MarshalerBase { private static readonly MarshalerBase Instance = new StrArrayMarshaler(); private static readonly Encoding PyEncoding = UcsMarshaler.PyEncoding; public override IntPtr MarshalManagedToNative(object managedObj) { var argv = managedObj as string[]; if (argv == null) { return IntPtr.Zero; } int totalStrLength = argv.Sum(arg => arg.Length + 1); int memSize = argv.Length * IntPtr.Size + totalStrLength * UcsMarshaler._UCS; IntPtr mem = Marshal.AllocHGlobal(memSize); try { // Preparing array of pointers to strings IntPtr curStrPtr = mem + argv.Length * IntPtr.Size; for (var i = 0; i < argv.Length; i++) { byte[] bStr = PyEncoding.GetBytes(argv[i] + "\0"); Marshal.Copy(bStr, 0, curStrPtr, bStr.Length); Marshal.WriteIntPtr(mem + i * IntPtr.Size, curStrPtr); curStrPtr += bStr.Length; } } catch (Exception) { Marshal.FreeHGlobal(mem); throw; } return mem; } public static ICustomMarshaler GetInstance(string cookie) { return Instance; } } /// <summary> /// Custom Marshaler to deal with Managed String to Native /// conversion on UTF-8. Use on functions that expect UTF-8 encoded /// strings like `PyUnicode_FromStringAndSize` /// </summary> /// <remarks> /// If instead we used `MarshalAs(UnmanagedType.LPWStr)` the output to /// `foo` would be `f\x00o\x00o\x00`. /// </remarks> internal class Utf8Marshaler : MarshalerBase { private static readonly MarshalerBase Instance = new Utf8Marshaler(); private static readonly Encoding PyEncoding = Encoding.UTF8; public override IntPtr MarshalManagedToNative(object managedObj) { var s = managedObj as string; if (s == null) { return IntPtr.Zero; } byte[] bStr = PyEncoding.GetBytes(s + "\0"); IntPtr mem = Marshal.AllocHGlobal(bStr.Length); try { Marshal.Copy(bStr, 0, mem, bStr.Length); } catch (Exception) { Marshal.FreeHGlobal(mem); throw; } return mem; } public static ICustomMarshaler GetInstance(string cookie) { return Instance; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.Xunit.Performance; using System; using System.Runtime.CompilerServices; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public class Puzzle { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 400; #endif private const int PuzzleSize = 511; private const int ClassMax = 3; private const int TypeMax = 12; private const int D = 8; private int[] _pieceCount = new int[ClassMax + 1]; private int[] _class = new int[TypeMax + 1]; private int[] _pieceMax = new int[TypeMax + 1]; private bool[] _puzzle = new bool[PuzzleSize + 1]; private bool[][] _p; private int _count; private static T[][] AllocArray<T>(int n1, int n2) { T[][] a = new T[n1][]; for (int i = 0; i < n1; ++i) { a[i] = new T[n2]; } return a; } private bool Fit(int i, int j) { for (int k = 0; k <= _pieceMax[i]; k++) { if (_p[i][k]) { if (_puzzle[j + k]) { return false; } } } return true; } private int Place(int i, int j) { int k; for (k = 0; k <= _pieceMax[i]; k++) { if (_p[i][k]) { _puzzle[j + k] = true; } } _pieceCount[_class[i]] = _pieceCount[_class[i]] - 1; for (k = j; k <= PuzzleSize; k++) { if (!_puzzle[k]) { return k; } } return 0; } private void RemoveLocal(int i, int j) { for (int k = 0; k <= _pieceMax[i]; k++) { if (_p[i][k]) { _puzzle[j + k] = false; } } _pieceCount[_class[i]] = _pieceCount[_class[i]] + 1; } private bool Trial(int j) { for (int i = 0; i <= TypeMax; i++) { if (_pieceCount[_class[i]] != 0) { if (Fit(i, j)) { int k = Place(i, j); if (Trial(k) || (k == 0)) { _count = _count + 1; return true; } else { RemoveLocal(i, j); } } } } _count = _count + 1; return false; } private bool DoIt() { int i, j, k, m, n; for (m = 0; m <= PuzzleSize; m++) { _puzzle[m] = true; } for (i = 1; i <= 5; i++) { for (j = 1; j <= 5; j++) { for (k = 1; k <= 5; k++) { _puzzle[i + D * (j + D * k)] = false; } } } for (i = 0; i <= TypeMax; i++) { for (m = 0; m <= PuzzleSize; m++) { _p[i][m] = false; } } for (i = 0; i <= 3; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 0; k++) { _p[0][i + D * (j + D * k)] = true; } } } _class[0] = 0; _pieceMax[0] = 3 + D * 1 + D * D * 0; for (i = 0; i <= 1; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 3; k++) { _p[1][i + D * (j + D * k)] = true; } } } _class[1] = 0; _pieceMax[1] = 1 + D * 0 + D * D * 3; for (i = 0; i <= 0; i++) { for (j = 0; j <= 3; j++) { for (k = 0; k <= 1; k++) { _p[2][i + D * (j + D * k)] = true; } } } _class[2] = 0; _pieceMax[2] = 0 + D * 3 + D * D * 1; for (i = 0; i <= 1; i++) { for (j = 0; j <= 3; j++) { for (k = 0; k <= 0; k++) { _p[3][i + D * (j + D * k)] = true; } } } _class[3] = 0; _pieceMax[3] = 1 + D * 3 + D * D * 0; for (i = 0; i <= 3; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 1; k++) { _p[4][i + D * (j + D * k)] = true; } } } _class[4] = 0; _pieceMax[4] = 3 + D * 0 + D * D * 1; for (i = 0; i <= 0; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 3; k++) { _p[5][i + D * (j + D * k)] = true; } } } _class[5] = 0; _pieceMax[5] = 0 + D * 1 + D * D * 3; for (i = 0; i <= 2; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 0; k++) { _p[6][i + D * (j + D * k)] = true; } } } _class[6] = 1; _pieceMax[6] = 2 + D * 0 + D * D * 0; for (i = 0; i <= 0; i++) { for (j = 0; j <= 2; j++) { for (k = 0; k <= 0; k++) { _p[7][i + D * (j + D * k)] = true; } } } _class[7] = 1; _pieceMax[7] = 0 + D * 2 + D * D * 0; for (i = 0; i <= 0; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 2; k++) { _p[8][i + D * (j + D * k)] = true; } } } _class[8] = 1; _pieceMax[8] = 0 + D * 0 + D * D * 2; for (i = 0; i <= 1; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 0; k++) { _p[9][i + D * (j + D * k)] = true; } } } _class[9] = 2; _pieceMax[9] = 1 + D * 1 + D * D * 0; for (i = 0; i <= 1; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 1; k++) { _p[10][i + D * (j + D * k)] = true; } } } _class[10] = 2; _pieceMax[10] = 1 + D * 0 + D * D * 1; for (i = 0; i <= 0; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 1; k++) { _p[11][i + D * (j + D * k)] = true; } } } _class[11] = 2; _pieceMax[11] = 0 + D * 1 + D * D * 1; for (i = 0; i <= 1; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 1; k++) { _p[12][i + D * (j + D * k)] = true; } } } _class[12] = 3; _pieceMax[12] = 1 + D * 1 + D * D * 1; _pieceCount[0] = 13; _pieceCount[1] = 3; _pieceCount[2] = 1; _pieceCount[3] = 1; m = 1 + D * (1 + D * 1); _count = 0; bool result = true; if (Fit(0, m)) { n = Place(0, m); result = Trial(n); } else { result = false; } return result; } [MethodImpl(MethodImplOptions.NoInlining)] private bool Bench() { _p = AllocArray<bool>(TypeMax + 1, PuzzleSize + 1); bool result = true; for (int i = 0; i < Iterations; ++i) { result &= DoIt(); } return result; } [Benchmark] public static void Test() { Puzzle P = new Puzzle(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { P.Bench(); } } } private static bool TestBase() { Puzzle P = new Puzzle(); bool result = P.Bench(); return result; } public static int Main() { bool result = TestBase(); return (result ? 100 : -1); } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Net; using System.Runtime; using System.Security; using System.ServiceModel.Administration; using System.ServiceModel.Channels; using System.ServiceModel.Configuration; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Text; using System.Runtime.Diagnostics; using System.Threading; using System.ServiceModel.Activation; using System.ServiceModel.Diagnostics.Application; using System.Reflection; using System.Linq.Expressions; public abstract class ServiceHostBase : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable { internal static readonly Uri EmptyUri = new Uri(string.Empty, UriKind.RelativeOrAbsolute); bool initializeDescriptionHasFinished; UriSchemeKeyedCollection baseAddresses; ChannelDispatcherCollection channelDispatchers; TimeSpan closeTimeout = ServiceDefaults.ServiceHostCloseTimeout; ServiceDescription description; ExtensionCollection<ServiceHostBase> extensions; ReadOnlyCollection<Uri> externalBaseAddresses; IDictionary<string, ContractDescription> implementedContracts; IInstanceContextManager instances; TimeSpan openTimeout = ServiceDefaults.OpenTimeout; ServicePerformanceCountersBase servicePerformanceCounters; DefaultPerformanceCounters defaultPerformanceCounters; ServiceThrottle serviceThrottle; ServiceCredentials readOnlyCredentials; ServiceAuthorizationBehavior readOnlyAuthorization; ServiceAuthenticationBehavior readOnlyAuthentication; Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> endpointsByListenUriInfo; int busyCount; EventTraceActivity eventTraceActivity; internal event EventHandler BusyCountIncremented; public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived; protected ServiceHostBase() { TraceUtility.SetEtwProviderId(); this.baseAddresses = new UriSchemeKeyedCollection(this.ThisLock); this.channelDispatchers = new ChannelDispatcherCollection(this, this.ThisLock); this.extensions = new ExtensionCollection<ServiceHostBase>(this, this.ThisLock); this.instances = new InstanceContextManager(this.ThisLock); this.serviceThrottle = new ServiceThrottle(this); this.TraceOpenAndClose = true; this.Faulted += new EventHandler(OnServiceHostFaulted); } internal EventTraceActivity EventTraceActivity { get { if (this.eventTraceActivity == null) { this.eventTraceActivity = new EventTraceActivity(); } return eventTraceActivity; } } public ServiceAuthorizationBehavior Authorization { get { if (this.Description == null) { return null; } else if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening) { return EnsureAuthorization(this.Description); } else { return this.readOnlyAuthorization; } } } public ServiceAuthenticationBehavior Authentication { get { if (this.Description == null) { return null; } else if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening) { return EnsureAuthentication(this.Description); } else { return this.readOnlyAuthentication; } } } public ReadOnlyCollection<Uri> BaseAddresses { get { externalBaseAddresses = new ReadOnlyCollection<Uri>(new List<Uri>(this.baseAddresses)); return externalBaseAddresses; } } public ChannelDispatcherCollection ChannelDispatchers { get { return this.channelDispatchers; } } public TimeSpan CloseTimeout { get { return this.closeTimeout; } set { if (value < TimeSpan.Zero) { string message = SR.GetString(SR.SFxTimeoutOutOfRange0); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", message)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } lock (this.ThisLock) { this.ThrowIfClosedOrOpened(); this.closeTimeout = value; } } } internal ServicePerformanceCountersBase Counters { get { return this.servicePerformanceCounters; } set { this.servicePerformanceCounters = value; this.serviceThrottle.SetServicePerformanceCounters(this.servicePerformanceCounters); } } internal DefaultPerformanceCounters DefaultCounters { get { return this.defaultPerformanceCounters; } set { this.defaultPerformanceCounters = value; } } public ServiceCredentials Credentials { get { if (this.Description == null) { return null; } else if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening) { return EnsureCredentials(this.Description); } else { return this.readOnlyCredentials; } } } protected override TimeSpan DefaultCloseTimeout { get { return this.CloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return this.OpenTimeout; } } public ServiceDescription Description { get { return this.description; } } public IExtensionCollection<ServiceHostBase> Extensions { get { return this.extensions; } } protected internal IDictionary<string, ContractDescription> ImplementedContracts { get { return this.implementedContracts; } } internal UriSchemeKeyedCollection InternalBaseAddresses { get { return this.baseAddresses; } } public int ManualFlowControlLimit { get { return this.ServiceThrottle.ManualFlowControlLimit; } set { this.ServiceThrottle.ManualFlowControlLimit = value; } } public TimeSpan OpenTimeout { get { return this.openTimeout; } set { if (value < TimeSpan.Zero) { string message = SR.GetString(SR.SFxTimeoutOutOfRange0); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", message)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } lock (this.ThisLock) { this.ThrowIfClosedOrOpened(); this.openTimeout = value; } } } internal ServiceThrottle ServiceThrottle { get { return this.serviceThrottle; } } internal virtual object DisposableInstance { get { return null; } } internal Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> EndpointsByListenUriInfo { get { if (this.endpointsByListenUriInfo == null) { this.endpointsByListenUriInfo = this.GetEndpointsByListenUriInfo(); } return this.endpointsByListenUriInfo; } } Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> GetEndpointsByListenUriInfo() { Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> endpointDictionary = new Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>>(); foreach (ServiceEndpoint endpoint in this.Description.Endpoints) { DispatcherBuilder.ListenUriInfo listenUriInfo = DispatcherBuilder.GetListenUriInfoForEndpoint(this, endpoint); if (!endpointDictionary.ContainsKey(listenUriInfo)) { endpointDictionary.Add(listenUriInfo, new Collection<ServiceEndpoint>()); } endpointDictionary[listenUriInfo].Add(endpoint); } return endpointDictionary; } protected void AddBaseAddress(Uri baseAddress) { if (this.initializeDescriptionHasFinished) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxCannotCallAddBaseAddress))); } this.baseAddresses.Add(baseAddress); } public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address) { return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null); } public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("address")); } ServiceEndpoint endpoint = this.AddServiceEndpoint(implementedContract, binding, new Uri(address, UriKind.RelativeOrAbsolute)); if (listenUri != null) { endpoint.UnresolvedListenUri = listenUri; listenUri = MakeAbsoluteUri(listenUri, binding); endpoint.ListenUri = listenUri; } return endpoint; } public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address) { return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null); } public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("address")); } if (binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("binding")); } if (implementedContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("implementedContract")); } if (this.State != CommunicationState.Created && this.State != CommunicationState.Opening) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointAfterOpen))); } if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointWithoutDescription))); } Uri via = this.MakeAbsoluteUri(address, binding); ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.implementedContracts)); ContractDescription contract = configLoader.LookupContract(implementedContract, this.Description.Name); ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contract, binding, new EndpointAddress(via)); this.Description.Endpoints.Add(serviceEndpoint); serviceEndpoint.UnresolvedAddress = address; if (listenUri != null) { serviceEndpoint.UnresolvedListenUri = listenUri; listenUri = MakeAbsoluteUri(listenUri, binding); serviceEndpoint.ListenUri = listenUri; } return serviceEndpoint; } public virtual void AddServiceEndpoint(ServiceEndpoint endpoint) { if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } if (this.State != CommunicationState.Created && this.State != CommunicationState.Opening) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointAfterOpen))); } if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointWithoutDescription))); } if (endpoint.Address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointAddressNotSpecified)); } if (endpoint.Contract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointContractNotSpecified)); } if (endpoint.Binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointBindingNotSpecified)); } if (!endpoint.IsSystemEndpoint || endpoint.Contract.ContractType == typeof(IMetadataExchange)) { ConfigLoader loader = new ConfigLoader(GetContractResolver(this.implementedContracts)); loader.LookupContract(endpoint.Contract.ConfigurationName, this.Description.Name); } this.Description.Endpoints.Add(endpoint); } public void SetEndpointAddress(ServiceEndpoint endpoint, string relativeAddress) { if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } if (relativeAddress == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("relativeAddress"); } if (endpoint.Binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointBindingNotSpecified)); } Uri absoluteUri = MakeAbsoluteUri(new Uri(relativeAddress, UriKind.Relative), endpoint.Binding); endpoint.Address = new EndpointAddress(absoluteUri); } internal Uri MakeAbsoluteUri(Uri relativeOrAbsoluteUri, Binding binding) { return MakeAbsoluteUri(relativeOrAbsoluteUri, binding, this.InternalBaseAddresses); } internal static Uri MakeAbsoluteUri(Uri relativeOrAbsoluteUri, Binding binding, UriSchemeKeyedCollection baseAddresses) { Uri result = relativeOrAbsoluteUri; if (!result.IsAbsoluteUri) { if (binding.Scheme == string.Empty) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxCustomBindingWithoutTransport))); } result = GetVia(binding.Scheme, result, baseAddresses); if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxEndpointNoMatchingScheme, binding.Scheme, binding.Name, GetBaseAddressSchemes(baseAddresses)))); } } return result; } protected virtual void ApplyConfiguration() { if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotApplyConfigurationWithoutDescription))); } ConfigLoader configLoader = new ConfigLoader(GetContractResolver(implementedContracts)); // Call the overload of LoadConfigurationSectionInternal which looks up the serviceElement from ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) LoadConfigurationSectionInternal(configLoader, this.Description, this.Description.ConfigurationName); EnsureAuthenticationAuthorizationDebug(this.Description); } internal void EnsureAuthenticationAuthorizationDebug(ServiceDescription description) { EnsureAuthentication(description); EnsureAuthorization(description); EnsureDebug(description); } public virtual ReadOnlyCollection<ServiceEndpoint> AddDefaultEndpoints() { List<ServiceEndpoint> defaultEndpoints = new List<ServiceEndpoint>(); foreach (Uri baseAddress in this.InternalBaseAddresses) { ProtocolMappingItem protocolMappingItem = ConfigLoader.LookupProtocolMapping(baseAddress.Scheme); if (protocolMappingItem != null) { Binding defaultBinding = ConfigLoader.LookupBinding(protocolMappingItem.Binding, protocolMappingItem.BindingConfiguration); if (defaultBinding != null) { AddDefaultEndpoints(defaultBinding, defaultEndpoints); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Exception(SR.GetString(SR.BindingProtocolMappingNotDefined, baseAddress.Scheme))); } } } if (DiagnosticUtility.ShouldTraceInformation && defaultEndpoints.Count > 0) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary["ServiceConfigurationName"] = this.description.ConfigurationName; TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.DefaultEndpointsAdded, SR.GetString(SR.TraceCodeDefaultEndpointsAdded), new DictionaryTraceRecord(dictionary)); } return new ReadOnlyCollection<ServiceEndpoint>(defaultEndpoints); } internal virtual void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints) { } internal virtual void BindInstance(InstanceContext instance) { this.instances.Add(instance); if (null != this.servicePerformanceCounters) { lock (this.ThisLock) { if (null != this.servicePerformanceCounters) { this.servicePerformanceCounters.ServiceInstanceCreated(); } } } } void IDisposable.Dispose() { Close(); } protected abstract ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts); protected virtual void InitializeRuntime() { if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotInitializeRuntimeWithoutDescription))); } if (this.Description.Endpoints.Count == 0) { this.AddDefaultEndpoints(); } this.EnsureAuthenticationSchemes(); DispatcherBuilder dispatcherBuilder = new DispatcherBuilder(); dispatcherBuilder.InitializeServiceHost(description, this); SecurityValidationBehavior.Instance.AfterBuildTimeValidation(description); } internal virtual void AfterInitializeRuntime(TimeSpan timeout) { } internal virtual IAsyncResult BeginAfterInitializeRuntime(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } internal virtual void EndAfterInitializeRuntime(IAsyncResult result) { CompletedAsyncResult.End(result); } ServiceAuthorizationBehavior EnsureAuthorization(ServiceDescription description) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); ServiceAuthorizationBehavior a = description.Behaviors.Find<ServiceAuthorizationBehavior>(); if (a == null) { a = new ServiceAuthorizationBehavior(); description.Behaviors.Add(a); } return a; } ServiceAuthenticationBehavior EnsureAuthentication(ServiceDescription description) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); ServiceAuthenticationBehavior a = description.Behaviors.Find<ServiceAuthenticationBehavior>(); if (a == null) { a = new ServiceAuthenticationBehavior(); description.Behaviors.Add(a); } return a; } ServiceDebugBehavior EnsureDebug(ServiceDescription description) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); ServiceDebugBehavior m = description.Behaviors.Find<ServiceDebugBehavior>(); if (m == null) { m = new ServiceDebugBehavior(); description.Behaviors.Add(m); } return m; } ServiceCredentials EnsureCredentials(ServiceDescription description) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); ServiceCredentials c = description.Behaviors.Find<ServiceCredentials>(); if (c == null) { c = new ServiceCredentials(); description.Behaviors.Add(c); } return c; } internal void FaultInternal() { this.Fault(); } internal string GetBaseAddressSchemes() { return GetBaseAddressSchemes(baseAddresses); } internal static String GetBaseAddressSchemes(UriSchemeKeyedCollection uriSchemeKeyedCollection) { StringBuilder buffer = new StringBuilder(); bool firstScheme = true; foreach (Uri address in uriSchemeKeyedCollection) { if (firstScheme) { buffer.Append(address.Scheme); firstScheme = false; } else { buffer.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator).Append(address.Scheme); } } return buffer.ToString(); } internal BindingParameterCollection GetBindingParameters() { return DispatcherBuilder.GetBindingParameters(this, new Collection<ServiceEndpoint>()); } internal BindingParameterCollection GetBindingParameters(ServiceEndpoint inputEndpoint) { Collection<ServiceEndpoint> endpoints; if (inputEndpoint == null) { endpoints = new Collection<ServiceEndpoint>(); } else if (!this.EndpointsByListenUriInfo.TryGetValue(DispatcherBuilder.GetListenUriInfoForEndpoint(this, inputEndpoint), out endpoints) || !endpoints.Contains(inputEndpoint)) { endpoints = new Collection<ServiceEndpoint>(); endpoints.Add(inputEndpoint); } return DispatcherBuilder.GetBindingParameters(this, endpoints); } internal BindingParameterCollection GetBindingParameters(Collection<ServiceEndpoint> endpoints) { return DispatcherBuilder.GetBindingParameters(this, endpoints); } internal ReadOnlyCollection<InstanceContext> GetInstanceContexts() { return Array.AsReadOnly<InstanceContext>(this.instances.ToArray()); } internal virtual IContractResolver GetContractResolver(IDictionary<string, ContractDescription> implementedContracts) { ServiceAndBehaviorsContractResolver resolver = new ServiceAndBehaviorsContractResolver(new ImplementedContractsContractResolver(implementedContracts)); resolver.AddBehaviorContractsToResolver(this.description == null ? null : this.description.Behaviors); return resolver; } internal static Uri GetUri(Uri baseUri, Uri relativeUri) { return GetUri(baseUri, relativeUri.OriginalString); } internal static Uri GetUri(Uri baseUri, string path) { if (path.StartsWith("/", StringComparison.Ordinal) || path.StartsWith("\\", StringComparison.Ordinal)) { int i = 1; for (; i < path.Length; ++i) { if (path[i] != '/' && path[i] != '\\') { break; } } path = path.Substring(i); } // VSWhidbey#541152: new Uri(Uri, string.Empty) is broken if (path.Length == 0) return baseUri; if (!baseUri.AbsoluteUri.EndsWith("/", StringComparison.Ordinal)) { baseUri = new Uri(baseUri.AbsoluteUri + "/"); } return new Uri(baseUri, path); } internal Uri GetVia(string scheme, Uri address) { return ServiceHost.GetVia(scheme, address, InternalBaseAddresses); } internal static Uri GetVia(string scheme, Uri address, UriSchemeKeyedCollection baseAddresses) { Uri via = address; if (!via.IsAbsoluteUri) { if (!baseAddresses.Contains(scheme)) { return null; } via = GetUri(baseAddresses[scheme], address); } return via; } public int IncrementManualFlowControlLimit(int incrementBy) { return this.ServiceThrottle.IncrementManualFlowControlLimit(incrementBy); } protected void InitializeDescription(UriSchemeKeyedCollection baseAddresses) { foreach (Uri baseAddress in baseAddresses) { this.baseAddresses.Add(baseAddress); } IDictionary<string, ContractDescription> implementedContracts = null; ServiceDescription description = CreateDescription(out implementedContracts); this.description = description; this.implementedContracts = implementedContracts; ApplyConfiguration(); this.initializeDescriptionHasFinished = true; } protected void LoadConfigurationSection(ServiceElement serviceSection) { if (serviceSection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceSection"); } if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotLoadConfigurationSectionWithoutDescription))); } ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts)); LoadConfigurationSectionInternal(configLoader, this.Description, serviceSection); } internal void LoadConfigurationSectionHelper(Uri baseAddress) { this.AddBaseAddress(baseAddress); } [Fx.Tag.SecurityNote(Critical = "Calls LookupService which is critical.", Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")] [SecuritySafeCritical] void LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, string configurationName) { ServiceElement serviceSection = configLoader.LookupService(configurationName); LoadConfigurationSectionInternal(configLoader, description, serviceSection); } [Fx.Tag.SecurityNote(Critical = "Handles a ServiceElement, which should not be leaked out of SecurityCritical code.", Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")] [SecuritySafeCritical] void LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) { // caller must validate arguments before calling configLoader.LoadServiceDescription(this, description, serviceSection, this.LoadConfigurationSectionHelper); } protected override void OnAbort() { this.instances.Abort(); foreach (ChannelDispatcherBase dispatcher in this.ChannelDispatchers) { if (dispatcher.Listener != null) { dispatcher.Listener.Abort(); } dispatcher.Abort(); } ThreadTrace.StopTracing(); } internal void OnAddChannelDispatcher(ChannelDispatcherBase channelDispatcher) { lock (this.ThisLock) { this.ThrowIfClosedOrOpened(); channelDispatcher.AttachInternal(this); channelDispatcher.Faulted += new EventHandler(OnChannelDispatcherFaulted); } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CloseAsyncResult(timeout, callback, state, this); } void OnBeginOpen() { this.TraceServiceHostOpenStart(); this.TraceBaseAddresses(); MessageLogger.EnsureInitialized(); //force config validation instead of waiting for the first message exchange InitializeRuntime(); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { this.OnBeginOpen(); return new OpenAsyncResult(this, timeout, callback, state); } IAsyncResult BeginOpenChannelDispatchers(TimeSpan timeout, AsyncCallback callback, object state) { return new OpenCollectionAsyncResult(timeout, callback, state, this.SnapshotChannelDispatchers()); } protected override void OnClose(TimeSpan timeout) { try { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (ManagementExtension.IsEnabled && null != this.Description) { ManagementExtension.OnServiceClosing(this); } for (int i = 0; i < this.ChannelDispatchers.Count; i++) { ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i]; if (dispatcher.Listener != null) { dispatcher.Listener.Close(timeoutHelper.RemainingTime()); } } for (int i = 0; i < this.ChannelDispatchers.Count; i++) { ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i]; dispatcher.CloseInput(timeoutHelper.RemainingTime()); } // Wait for existing work to complete this.instances.CloseInput(timeoutHelper.RemainingTime()); // Close instances (closes contexts/channels) this.instances.Close(timeoutHelper.RemainingTime()); // Close dispatchers for (int i = 0; i < this.ChannelDispatchers.Count; i++) { ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i]; dispatcher.Close(timeoutHelper.RemainingTime()); } this.ReleasePerformanceCounters(); this.TraceBaseAddresses(); ThreadTrace.StopTracing(); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose)); } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServiceHostTimeoutOnClose, SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose), this, e); } this.Abort(); } } protected override void OnClosed() { try { for (int i = 0; i < this.ChannelDispatchers.Count; i++) { ChannelDispatcher dispatcher = this.ChannelDispatchers[i] as ChannelDispatcher; if (dispatcher != null) { dispatcher.ReleasePerformanceCounters(); } } } finally { base.OnClosed(); } } void TraceBaseAddresses() { if (DiagnosticUtility.ShouldTraceInformation && this.baseAddresses != null && this.baseAddresses.Count > 0) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ServiceHostBaseAddresses, SR.GetString(SR.TraceCodeServiceHostBaseAddresses), new CollectionTraceRecord("BaseAddresses", "Address", this.baseAddresses), this, null); } } void TraceServiceHostOpenStart() { if (TD.ServiceHostOpenStartIsEnabled()) { TD.ServiceHostOpenStart(this.EventTraceActivity); } } protected override void OnEndClose(IAsyncResult result) { try { CloseAsyncResult.End(result); this.TraceBaseAddresses(); ThreadTrace.StopTracing(); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose)); } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServiceHostTimeoutOnClose, SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose), this, e); } this.Abort(); } } protected override void OnEndOpen(IAsyncResult result) { OpenAsyncResult.End(result); } void EndOpenChannelDispatchers(IAsyncResult result) { OpenCollectionAsyncResult.End(result); } void EnsureAuthenticationSchemes() { if (this.Authentication == null) { return; } //Exit immediately when not hosted in IIS or if VirtualPathExtension is not set. VirtualPathExtension is used as a flag to indicate whether a ServiceHost // is webhosted (WsDualHttpBinding-ChannelFactory is using HttpListener instead of IIS even when running in IIS) if (!AspNetEnvironment.Enabled || this.Extensions.Find<VirtualPathExtension>() == null) { return; } foreach (ServiceEndpoint serviceEndpoint in this.Description.Endpoints) { if (serviceEndpoint.Binding != null && serviceEndpoint.ListenUri != null && ("http".Equals(serviceEndpoint.ListenUri.Scheme, StringComparison.OrdinalIgnoreCase) || "https".Equals(serviceEndpoint.ListenUri.Scheme, StringComparison.OrdinalIgnoreCase)) && this.baseAddresses.Contains(serviceEndpoint.ListenUri.Scheme)) { HttpTransportBindingElement httpTransportBindingElement = serviceEndpoint.Binding.CreateBindingElements().Find<HttpTransportBindingElement>(); if (httpTransportBindingElement != null) { AuthenticationSchemes hostSupportedAuthenticationSchemes = AspNetEnvironment.Current.GetAuthenticationSchemes(this.baseAddresses[serviceEndpoint.ListenUri.Scheme]); if (hostSupportedAuthenticationSchemes != AuthenticationSchemes.None) { //If no authentication schemes are explicitly defined for the ServiceHost... if (this.Authentication.AuthenticationSchemes == AuthenticationSchemes.None) { //Inherit authentication schemes from IIS this.Authentication.AuthenticationSchemes = hostSupportedAuthenticationSchemes; } else { // Build intersection between authenticationSchemes on the ServiceHost and in IIS this.Authentication.AuthenticationSchemes &= hostSupportedAuthenticationSchemes; } } } break; } } } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.OnBeginOpen(); AfterInitializeRuntime(timeoutHelper.RemainingTime()); for (int i = 0; i < this.ChannelDispatchers.Count; i++) { ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i]; dispatcher.Open(timeoutHelper.RemainingTime()); } } protected override void OnOpened() { if (this.Description != null) { ServiceCredentials c = description.Behaviors.Find<ServiceCredentials>(); if (c != null) { ServiceCredentials credentialsCopy = c.Clone(); credentialsCopy.MakeReadOnly(); this.readOnlyCredentials = credentialsCopy; } ServiceAuthorizationBehavior authorization = description.Behaviors.Find<ServiceAuthorizationBehavior>(); if (authorization != null) { ServiceAuthorizationBehavior authorizationCopy = authorization.Clone(); authorizationCopy.MakeReadOnly(); this.readOnlyAuthorization = authorizationCopy; } ServiceAuthenticationBehavior authentication = description.Behaviors.Find<ServiceAuthenticationBehavior>(); if (authentication != null) { ServiceAuthenticationBehavior authenticationCopy = authentication.Clone(); authentication.MakeReadOnly(); this.readOnlyAuthentication = authenticationCopy; } if (ManagementExtension.IsEnabled) { ManagementExtension.OnServiceOpened(this); } } base.OnOpened(); if (TD.ServiceHostOpenStopIsEnabled()) { TD.ServiceHostOpenStop(this.EventTraceActivity); } } internal void OnRemoveChannelDispatcher(ChannelDispatcherBase channelDispatcher) { lock (this.ThisLock) { this.ThrowIfClosedOrOpened(); channelDispatcher.DetachInternal(this); } } void OnChannelDispatcherFaulted(object sender, EventArgs e) { this.Fault(); } void OnServiceHostFaulted(object sender, EventArgs args) { if (TD.ServiceHostFaultedIsEnabled()) { TD.ServiceHostFaulted(this.EventTraceActivity, this); } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServiceHostFaulted, SR.GetString(SR.TraceCodeServiceHostFaulted), this); } foreach (ICommunicationObject channelDispatcher in this.SnapshotChannelDispatchers()) { if (channelDispatcher.State == CommunicationState.Opened) { channelDispatcher.Abort(); } } } internal void RaiseUnknownMessageReceived(Message message) { try { EventHandler<UnknownMessageReceivedEventArgs> handler = UnknownMessageReceived; if (handler != null) { handler(this, new UnknownMessageReceivedEventArgs(message)); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } protected void ReleasePerformanceCounters() { if (this.servicePerformanceCounters != null) { lock (this.ThisLock) { if (this.servicePerformanceCounters != null) { this.servicePerformanceCounters.Dispose(); this.servicePerformanceCounters = null; } } } if (this.defaultPerformanceCounters != null) { lock (this.ThisLock) { if (this.defaultPerformanceCounters != null) { this.defaultPerformanceCounters.Dispose(); this.defaultPerformanceCounters = null; } } } } ICommunicationObject[] SnapshotChannelDispatchers() { lock (this.ThisLock) { ICommunicationObject[] array = new ICommunicationObject[this.ChannelDispatchers.Count]; for (int i = 0; i < array.Length; i++) { array[i] = this.ChannelDispatchers[i]; } return array; } } internal virtual void UnbindInstance(InstanceContext instance) { this.instances.Remove(instance); if (null != this.servicePerformanceCounters) { lock (this.ThisLock) { if (null != this.servicePerformanceCounters) { this.servicePerformanceCounters.ServiceInstanceRemoved(); } } } } internal void IncrementBusyCount() { if (AspNetEnvironment.Enabled) { AspNetEnvironment.Current.IncrementBusyCount(); Interlocked.Increment(ref this.busyCount); } EventHandler handler = this.BusyCountIncremented; if (handler != null) { try { handler(this, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } internal void DecrementBusyCount() { if (AspNetEnvironment.Enabled) { Interlocked.Decrement(ref this.busyCount); AspNetEnvironment.Current.DecrementBusyCount(); } } internal int BusyCount { get { return this.busyCount; } } class OpenAsyncResult : AsyncResult { static AsyncCompletion handleEndAfterInitializeRuntime = new AsyncCompletion(HandleEndAfterInitializeRuntime); static AsyncCompletion handleEndOpenChannelDispatchers = new AsyncCompletion(HandleEndOpenChannelDispatchers); TimeoutHelper timeoutHelper; ServiceHostBase host; public OpenAsyncResult(ServiceHostBase host, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.timeoutHelper = new TimeoutHelper(timeout); this.host = host; if (ProcessAfterInitializeRuntime()) { Complete(true); } } bool ProcessAfterInitializeRuntime() { IAsyncResult result = this.host.BeginAfterInitializeRuntime( this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleEndAfterInitializeRuntime), this); return SyncContinue(result); } static bool HandleEndAfterInitializeRuntime(IAsyncResult result) { OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState; thisPtr.host.EndAfterInitializeRuntime(result); return thisPtr.ProcessOpenChannelDispatchers(); } bool ProcessOpenChannelDispatchers() { IAsyncResult result = this.host.BeginOpenChannelDispatchers( this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleEndOpenChannelDispatchers), this); return SyncContinue(result); } static bool HandleEndOpenChannelDispatchers(IAsyncResult result) { OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState; thisPtr.host.EndOpenChannelDispatchers(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OpenAsyncResult>(result); } } class CloseAsyncResult : AsyncResult { ServiceHostBase serviceHost; TimeoutHelper timeoutHelper; public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ServiceHostBase serviceHost) : base(callback, state) { this.timeoutHelper = new TimeoutHelper(timeout); this.serviceHost = serviceHost; if (ManagementExtension.IsEnabled && null != serviceHost.Description) { ManagementExtension.OnServiceClosing(serviceHost); } this.CloseListeners(true); } void CloseListeners(bool completedSynchronously) { List<ICommunicationObject> listeners = new List<ICommunicationObject>(); for (int i = 0; i < this.serviceHost.ChannelDispatchers.Count; i++) { if (this.serviceHost.ChannelDispatchers[i].Listener != null) { listeners.Add(this.serviceHost.ChannelDispatchers[i].Listener); } } AsyncCallback callback = Fx.ThunkCallback(this.CloseListenersCallback); TimeSpan timeout = this.timeoutHelper.RemainingTime(); Exception exception = null; IAsyncResult result = null; try { result = new CloseCollectionAsyncResult(timeout, callback, this, listeners); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { this.CallComplete(completedSynchronously, exception); } else if (result.CompletedSynchronously) { this.FinishCloseListeners(result, completedSynchronously); } } void CloseListenersCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ((CloseAsyncResult)result.AsyncState).FinishCloseListeners(result, false); } } void FinishCloseListeners(IAsyncResult result, bool completedSynchronously) { Exception exception = null; try { CloseCollectionAsyncResult.End(result); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { this.CallComplete(completedSynchronously, exception); } else { this.CloseInput(completedSynchronously); } } // Wait for existing work to complete void CloseInput(bool completedSynchronously) { AsyncCallback callback = Fx.ThunkCallback(this.CloseInputCallback); Exception exception = null; IAsyncResult result = null; try { for (int i = 0; i < this.serviceHost.ChannelDispatchers.Count; i++) { ChannelDispatcherBase dispatcher = this.serviceHost.ChannelDispatchers[i]; dispatcher.CloseInput(this.timeoutHelper.RemainingTime()); } result = this.serviceHost.instances.BeginCloseInput(this.timeoutHelper.RemainingTime(), callback, this); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { // Any exception during async processing causes this // async callback to report the error and then relies on // Abort to cleanup any unclosed channels or instance contexts. FxTrace.Exception.AsWarning(exception); this.CallComplete(completedSynchronously, exception); } else if (result.CompletedSynchronously) { this.FinishCloseInput(result, completedSynchronously); } } void CloseInputCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ((CloseAsyncResult)result.AsyncState).FinishCloseInput(result, false); } } void FinishCloseInput(IAsyncResult result, bool completedSynchronously) { Exception exception = null; try { serviceHost.instances.EndCloseInput(result); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { this.CallComplete(completedSynchronously, exception); } else { this.CloseInstances(completedSynchronously); } } // Close instances (closes contexts/channels) void CloseInstances(bool completedSynchronously) { AsyncCallback callback = Fx.ThunkCallback(this.CloseInstancesCallback); TimeSpan timeout = this.timeoutHelper.RemainingTime(); Exception exception = null; IAsyncResult result = null; try { result = this.serviceHost.instances.BeginClose(timeout, callback, this); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { this.CallComplete(completedSynchronously, exception); } else if (result.CompletedSynchronously) { this.FinishCloseInstances(result, completedSynchronously); } } void CloseInstancesCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ((CloseAsyncResult)result.AsyncState).FinishCloseInstances(result, false); } } void FinishCloseInstances(IAsyncResult result, bool completedSynchronously) { Exception exception = null; try { this.serviceHost.instances.EndClose(result); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { this.CallComplete(completedSynchronously, exception); } else { this.CloseChannelDispatchers(completedSynchronously); } } void CloseChannelDispatchers(bool completedSynchronously) { IList<ICommunicationObject> channelDispatchers = this.serviceHost.SnapshotChannelDispatchers(); AsyncCallback callback = Fx.ThunkCallback(this.CloseChannelDispatchersCallback); TimeSpan timeout = this.timeoutHelper.RemainingTime(); Exception exception = null; IAsyncResult result = null; try { result = new CloseCollectionAsyncResult(timeout, callback, this, channelDispatchers); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } if (exception != null) { this.CallComplete(completedSynchronously, exception); } else if (result.CompletedSynchronously) { this.FinishCloseChannelDispatchers(result, completedSynchronously); } } void CloseChannelDispatchersCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ((CloseAsyncResult)result.AsyncState).FinishCloseChannelDispatchers(result, false); } } void FinishCloseChannelDispatchers(IAsyncResult result, bool completedSynchronously) { Exception exception = null; try { CloseCollectionAsyncResult.End(result); } catch (Exception e) { if (Fx.IsFatal(e) || completedSynchronously) { throw; } exception = e; } this.CallComplete(completedSynchronously, exception); } void CallComplete(bool completedSynchronously, Exception exception) { this.Complete(completedSynchronously, exception); } public static void End(IAsyncResult result) { AsyncResult.End<CloseAsyncResult>(result); } } class ImplementedContractsContractResolver : IContractResolver { IDictionary<string, ContractDescription> implementedContracts; public ImplementedContractsContractResolver(IDictionary<string, ContractDescription> implementedContracts) { this.implementedContracts = implementedContracts; } public ContractDescription ResolveContract(string contractName) { return this.implementedContracts != null && this.implementedContracts.ContainsKey(contractName) ? this.implementedContracts[contractName] : null; } } internal class ServiceAndBehaviorsContractResolver : IContractResolver { IContractResolver serviceResolver; Dictionary<string, ContractDescription> behaviorContracts; public Dictionary<string, ContractDescription> BehaviorContracts { get { return behaviorContracts; } } public ServiceAndBehaviorsContractResolver(IContractResolver serviceResolver) { this.serviceResolver = serviceResolver; behaviorContracts = new Dictionary<string, ContractDescription>(); } public ContractDescription ResolveContract(string contractName) { ContractDescription contract = serviceResolver.ResolveContract(contractName); if (contract == null) { contract = this.behaviorContracts.ContainsKey(contractName) ? this.behaviorContracts[contractName] : null; } return contract; } public void AddBehaviorContractsToResolver(KeyedByTypeCollection<IServiceBehavior> behaviors) { // It would be nice to make this loop over all Behaviors... someday. if (behaviors != null && behaviors.Contains(typeof(ServiceMetadataBehavior))) { behaviors.Find<ServiceMetadataBehavior>().AddImplementedContracts(this); } } } } public class ServiceHost : ServiceHostBase { object singletonInstance; Type serviceType; ReflectedContractCollection reflectedContracts; IDisposable disposableInstance; protected ServiceHost() { } public ServiceHost(Type serviceType, params Uri[] baseAddresses) { if (serviceType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceType")); } this.serviceType = serviceType; using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityConstructServiceHost, serviceType.FullName), ActivityType.Construct); } InitializeDescription(serviceType, new UriSchemeKeyedCollection(baseAddresses)); } } public ServiceHost(object singletonInstance, params Uri[] baseAddresses) { if (singletonInstance == null) { throw new ArgumentNullException("singletonInstance"); } this.singletonInstance = singletonInstance; this.serviceType = singletonInstance.GetType(); using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityConstructServiceHost, serviceType.FullName), ActivityType.Construct); } InitializeDescription(singletonInstance, new UriSchemeKeyedCollection(baseAddresses)); } } public object SingletonInstance { get { return this.singletonInstance; } } internal override object DisposableInstance { get { return this.disposableInstance; } } public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, string address) { return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null); } public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, string address, Uri listenUri) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("address")); } ServiceEndpoint endpoint = this.AddServiceEndpoint(implementedContract, binding, new Uri(address, UriKind.RelativeOrAbsolute)); if (listenUri != null) { listenUri = MakeAbsoluteUri(listenUri, binding); endpoint.ListenUri = listenUri; } return endpoint; } public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, Uri address) { return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null); } void ValidateContractType(Type implementedContract, ReflectedAndBehaviorContractCollection reflectedAndBehaviorContracts) { if (!implementedContract.IsDefined(typeof(ServiceContractAttribute), false)) { #pragma warning suppress 56506 // implementedContract is never null at this point throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxServiceContractAttributeNotFound, implementedContract.FullName))); } if (!reflectedAndBehaviorContracts.Contains(implementedContract)) { if (implementedContract == typeof(IMetadataExchange)) #pragma warning suppress 56506 // ServiceType is never null at this point throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractKeyNotFoundIMetadataExchange, this.serviceType.FullName))); else #pragma warning suppress 56506 // implementedContract and ServiceType are never null at this point throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractKeyNotFound2, implementedContract.FullName, this.serviceType.FullName))); } } public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, Uri address, Uri listenUri) { if (implementedContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("implementedContract")); } if (this.reflectedContracts == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractsNotInitialized1, implementedContract.FullName))); } ReflectedAndBehaviorContractCollection reflectedAndBehaviorContracts = new ReflectedAndBehaviorContractCollection(this.reflectedContracts, this.Description.Behaviors); ValidateContractType(implementedContract, reflectedAndBehaviorContracts); ServiceEndpoint endpoint = AddServiceEndpoint(reflectedAndBehaviorContracts.GetConfigKey(implementedContract), binding, address); if (listenUri != null) { listenUri = MakeAbsoluteUri(listenUri, binding); endpoint.ListenUri = listenUri; } return endpoint; } internal override void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints) { // don't generate endpoints for contracts that serve as the base type for other reflected contracts List<ContractDescription> mostSpecificContracts = new List<ContractDescription>(); for (int i = 0; i < this.reflectedContracts.Count; i++) { bool addContractEndpoint = true; ContractDescription contract = this.reflectedContracts[i]; Type contractType = contract.ContractType; if (contractType != null) { for (int j = 0; j < this.reflectedContracts.Count; j++) { ContractDescription otherContract = this.reflectedContracts[j]; Type otherContractType = otherContract.ContractType; if (i == j || otherContractType == null) { continue; } if (contractType.IsAssignableFrom(otherContractType)) { addContractEndpoint = false; break; } } } if (addContractEndpoint) { mostSpecificContracts.Add(contract); } } foreach (ContractDescription contract in mostSpecificContracts) { ServiceEndpoint endpoint = AddServiceEndpoint(contract.ConfigurationName, defaultBinding, string.Empty); ConfigLoader.LoadDefaultEndpointBehaviors(endpoint); defaultEndpoints.Add(endpoint); } } // Run static Configure method on service type if it exists, else load configuration from Web.config/App.config protected override void ApplyConfiguration() { // Load from static Configure method if it exists with the right signature Type serviceType = this.Description.ServiceType; if (serviceType != null) { MethodInfo configure = GetConfigureMethod(serviceType); if (configure != null) { // load <host> config ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts)); LoadHostConfigurationInternal(configLoader, this.Description, this.Description.ConfigurationName); // Invoke configure method for service ServiceConfiguration configuration = new ServiceConfiguration(this); InvokeConfigure(configure, configuration); return; } } // else just load from Web.config/App.config base.ApplyConfiguration(); } // Find the Configure method with the required signature, closest to serviceType in the type hierarchy static MethodInfo GetConfigureMethod(Type serviceType) { // Use recursion instead of BindingFlags.FlattenHierarchy because we require return type to be void // base case: all Types are rooted in object eventually if (serviceType == typeof(object)) { return null; } // signature: "public static void Configure(ServiceConfiguration)" MethodInfo configure = serviceType.GetMethod("Configure", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(ServiceConfiguration) }, null); if (configure != null && configure.ReturnType == typeof(void)) { return configure; } else { return GetConfigureMethod(serviceType.BaseType); } } static void InvokeConfigure(MethodInfo configureMethod, ServiceConfiguration configuration) { Action<ServiceConfiguration> call = Delegate.CreateDelegate(typeof(Action<ServiceConfiguration>), configureMethod) as Action<ServiceConfiguration>; call(configuration); } // called from ServiceConfiguration.LoadFromConfiguration() internal void LoadFromConfiguration() { if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotApplyConfigurationWithoutDescription))); } ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts)); // Call the overload of LoadConfigurationSectionInternal which looks up the serviceElement from ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) LoadConfigurationSectionExceptHostInternal(configLoader, this.Description, this.Description.ConfigurationName); EnsureAuthenticationAuthorizationDebug(this.Description); } // called from ServiceConfiguration.LoadFromConfiguration(configuration) internal void LoadFromConfiguration(System.Configuration.Configuration configuration) { if (this.Description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotApplyConfigurationWithoutDescription))); } ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts)); // Look up the serviceElement explicitly on configuration, then call the overload of LoadConfigurationSectionInternal that loads the rest of the config from the same configuration as serviceElement ServicesSection servicesSection = (ServicesSection)configuration.GetSection(ConfigurationStrings.ServicesSectionPath); ServiceElement serviceElement = configLoader.LookupService(this.Description.ConfigurationName, servicesSection); configLoader.LoadServiceDescription(this, this.Description, serviceElement, this.LoadConfigurationSectionHelper, skipHost: true); EnsureAuthenticationAuthorizationDebug(this.Description); } // Load only "host" section within "service" tag [Fx.Tag.SecurityNote(Critical = "Calls LookupService which is critical.", Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")] [SecuritySafeCritical] void LoadHostConfigurationInternal(ConfigLoader configLoader, ServiceDescription description, string configurationName) { ServiceElement serviceSection = configLoader.LookupService(configurationName); if (serviceSection != null) { configLoader.LoadHostConfig(serviceSection, this, (addr => this.InternalBaseAddresses.Add(addr))); } } // Load service description for service from config, but skip "host" section within "service" tag [Fx.Tag.SecurityNote(Critical = "Calls LookupService which is critical.", Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")] [SecuritySafeCritical] void LoadConfigurationSectionExceptHostInternal(ConfigLoader configLoader, ServiceDescription description, string configurationName) { ServiceElement serviceSection = configLoader.LookupService(configurationName); configLoader.LoadServiceDescription(this, description, serviceSection, this.LoadConfigurationSectionHelper, skipHost: true); } internal override string CloseActivityName { get { return SR.GetString(SR.ActivityCloseServiceHost, this.serviceType.FullName); } } internal override string OpenActivityName { get { return SR.GetString(SR.ActivityOpenServiceHost, this.serviceType.FullName); } } protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts) { if (this.serviceType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostCannotCreateDescriptionWithoutServiceType))); } ServiceDescription description; if (this.SingletonInstance != null) { description = ServiceDescription.GetService(this.SingletonInstance); } else { description = ServiceDescription.GetService(this.serviceType); } ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find<ServiceBehaviorAttribute>(); object serviceInstanceUsedAsABehavior = serviceBehavior.GetWellKnownSingleton(); if (serviceInstanceUsedAsABehavior == null) { serviceInstanceUsedAsABehavior = serviceBehavior.GetHiddenSingleton(); this.disposableInstance = serviceInstanceUsedAsABehavior as IDisposable; } if ((typeof(IServiceBehavior).IsAssignableFrom(this.serviceType) || typeof(IContractBehavior).IsAssignableFrom(this.serviceType)) && serviceInstanceUsedAsABehavior == null) { serviceInstanceUsedAsABehavior = ServiceDescription.CreateImplementation(this.serviceType); this.disposableInstance = serviceInstanceUsedAsABehavior as IDisposable; } if (this.SingletonInstance == null) { if (serviceInstanceUsedAsABehavior is IServiceBehavior) { description.Behaviors.Add((IServiceBehavior)serviceInstanceUsedAsABehavior); } } ReflectedContractCollection reflectedContracts = new ReflectedContractCollection(); List<Type> interfaces = ServiceReflector.GetInterfaces(this.serviceType); for (int i = 0; i < interfaces.Count; i++) { Type contractType = interfaces[i]; if (!reflectedContracts.Contains(contractType)) { ContractDescription contract = null; if (serviceInstanceUsedAsABehavior != null) { contract = ContractDescription.GetContract(contractType, serviceInstanceUsedAsABehavior); } else { contract = ContractDescription.GetContract(contractType, this.serviceType); } reflectedContracts.Add(contract); Collection<ContractDescription> inheritedContracts = contract.GetInheritedContracts(); for (int j = 0; j < inheritedContracts.Count; j++) { ContractDescription inheritedContract = inheritedContracts[j]; if (!reflectedContracts.Contains(inheritedContract.ContractType)) { reflectedContracts.Add(inheritedContract); } } } } this.reflectedContracts = reflectedContracts; implementedContracts = reflectedContracts.ToImplementedContracts(); return description; } protected void InitializeDescription(object singletonInstance, UriSchemeKeyedCollection baseAddresses) { if (singletonInstance == null) { throw new ArgumentNullException("singletonInstance"); } this.singletonInstance = singletonInstance; InitializeDescription(singletonInstance.GetType(), baseAddresses); } protected void InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) { if (serviceType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceType")); } this.serviceType = serviceType; base.InitializeDescription(baseAddresses); } protected override void OnClosed() { base.OnClosed(); if (this.disposableInstance != null) { this.disposableInstance.Dispose(); } } class ReflectedContractCollection : KeyedCollection<Type, ContractDescription> { public ReflectedContractCollection() : base(null, 4) { } protected override Type GetKeyForItem(ContractDescription item) { if (item == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); return item.ContractType; } public IDictionary<string, ContractDescription> ToImplementedContracts() { Dictionary<string, ContractDescription> implementedContracts = new Dictionary<string, ContractDescription>(); foreach (ContractDescription contract in this.Items) { implementedContracts.Add(GetConfigKey(contract), contract); } return implementedContracts; } internal static string GetConfigKey(ContractDescription contract) { return contract.ConfigurationName; } } class ReflectedAndBehaviorContractCollection { ReflectedContractCollection reflectedContracts; KeyedByTypeCollection<IServiceBehavior> behaviors; public ReflectedAndBehaviorContractCollection(ReflectedContractCollection reflectedContracts, KeyedByTypeCollection<IServiceBehavior> behaviors) { this.reflectedContracts = reflectedContracts; this.behaviors = behaviors; } internal bool Contains(Type implementedContract) { if (this.reflectedContracts.Contains(implementedContract)) { return true; } if (this.behaviors.Contains(typeof(ServiceMetadataBehavior)) && ServiceMetadataBehavior.IsMetadataImplementedType(implementedContract)) { return true; } return false; } internal string GetConfigKey(Type implementedContract) { if (this.reflectedContracts.Contains(implementedContract)) { return ReflectedContractCollection.GetConfigKey(reflectedContracts[implementedContract]); } if (this.behaviors.Contains(typeof(ServiceMetadataBehavior)) && ServiceMetadataBehavior.IsMetadataImplementedType(implementedContract)) { return ServiceMetadataBehavior.MexContractName; } Fx.Assert("Calls to GetConfigKey are preceeded by calls to Contains."); #pragma warning suppress 56506 // implementedContract is never null at this point throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractKeyNotFound2, implementedContract.FullName, string.Empty))); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Sorting.cs // // Support for sorting. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { //--------------------------------------------------------------------------------------- // The sort helper abstraction hides the implementation of our parallel merge sort. See // comments below for more details. In summary, there will be one sort helper per // partition. Each will, in parallel read the whole key/value set from its input, // perform a local sort on this data, and then cooperatively merge with other concurrent // tasks to generate a single sorted output. The local sort step is done using a simple // quick-sort algorithm. Then we use a log(p) reduction to perform merges in parallel; // during each round of merges, half of the threads will stop doing work and may return. // At the end, one thread will remain and it holds the final sorted output. // internal abstract class SortHelper<TInputOutput> { internal abstract TInputOutput[] Sort(); } internal class SortHelper<TInputOutput, TKey> : SortHelper<TInputOutput>, IDisposable { private QueryOperatorEnumerator<TInputOutput, TKey> _source; // The data source from which to pull data. private int _partitionCount; // The partition count. private int _partitionIndex; // This helper's index. // This data is shared among all partitions. private QueryTaskGroupState _groupState; // To communicate status, e.g. cancellation. private int[][] _sharedIndices; // Shared set of indices used during sorting. private GrowingArray<TKey>[] _sharedKeys; // Shared keys with which to compare elements. private TInputOutput[][] _sharedValues; // The actual values used for comparisons. private Barrier[][] _sharedBarriers; // A matrix of barriers used for synchronizing during merges. private OrdinalIndexState _indexState; // State of the order index private IComparer<TKey> _keyComparer; // Comparer for the order keys //--------------------------------------------------------------------------------------- // Creates a single sort helper object. This is marked private to ensure the only // snippet of code that creates one is the factory, since creating many implies some // implementation detail in terms of dependencies which other places in the codebase // shouldn't need to worry about. // private SortHelper(QueryOperatorEnumerator<TInputOutput, TKey> source, int partitionCount, int partitionIndex, QueryTaskGroupState groupState, int[][] sharedIndices, OrdinalIndexState indexState, IComparer<TKey> keyComparer, GrowingArray<TKey>[] sharedkeys, TInputOutput[][] sharedValues, Barrier[][] sharedBarriers) { Debug.Assert(source != null); Debug.Assert(groupState != null); Debug.Assert(sharedIndices != null); Debug.Assert(sharedkeys != null); Debug.Assert(sharedValues != null); Debug.Assert(sharedBarriers != null); Debug.Assert(sharedIndices.Length <= sharedkeys.Length); Debug.Assert(sharedIndices.Length == sharedValues.Length); // Multi-dim arrays are simulated using jagged arrays. // Because of that, when phaseCount == 0, we end up with an empty sharedBarrier array. // Since there are no cases when phaseCount == 0 where we actually access the sharedBarriers, I am removing this check. // Debug.Assert(sharedIndices.Length == sharedBarriers[0].Length); _source = source; _partitionCount = partitionCount; _partitionIndex = partitionIndex; _groupState = groupState; _sharedIndices = sharedIndices; _indexState = indexState; _keyComparer = keyComparer; _sharedKeys = sharedkeys; _sharedValues = sharedValues; _sharedBarriers = sharedBarriers; Debug.Assert(_sharedKeys.Length >= _sharedValues.Length); } //--------------------------------------------------------------------------------------- // Factory method to create a bunch of sort helpers that are all related. Once created, // these helpers must all run concurrently with one another. // // Arguments: // partitions - the input data partitions to be sorted // groupState - common state used for communication (e.g. cancellation) // // Return Value: // An array of helpers, one for each partition. // internal static SortHelper<TInputOutput, TKey>[] GenerateSortHelpers( PartitionedStream<TInputOutput, TKey> partitions, QueryTaskGroupState groupState) { int degreeOfParallelism = partitions.PartitionCount; SortHelper<TInputOutput, TKey>[] helpers = new SortHelper<TInputOutput, TKey>[degreeOfParallelism]; // Calculate the next highest power of two greater than or equal to the DOP. // Also, calculate phaseCount = log2(degreeOfParallelismPow2) int degreeOfParallelismPow2 = 1, phaseCount = 0; while (degreeOfParallelismPow2 < degreeOfParallelism) { phaseCount++; degreeOfParallelismPow2 <<= 1; } // Initialize shared objects used during sorting. int[][] sharedIndices = new int[degreeOfParallelism][]; GrowingArray<TKey>[] sharedKeys = new GrowingArray<TKey>[degreeOfParallelism]; TInputOutput[][] sharedValues = new TInputOutput[degreeOfParallelism][]; // Note that it is possible that phaseCount is 0. Barrier[][] sharedBarriers = JaggedArray<Barrier>.Allocate(phaseCount, degreeOfParallelism); if (degreeOfParallelism > 1) { // Initialize the barriers we need. Due to the logarithmic reduction, we don't // need to populate the whole matrix. int offset = 1; for (int i = 0; i < sharedBarriers.Length; i++) { // We have jagged arrays. for (int j = 0; j < sharedBarriers[i].Length; j++) { // As the phases increase, the barriers required become more and more sparse. if ((j % offset) == 0) { sharedBarriers[i][j] = new Barrier(2); } } offset *= 2; } } // Lastly populate the array of sort helpers. for (int i = 0; i < degreeOfParallelism; i++) { helpers[i] = new SortHelper<TInputOutput, TKey>( partitions[i], degreeOfParallelism, i, groupState, sharedIndices, partitions.OrdinalIndexState, partitions.KeyComparer, sharedKeys, sharedValues, sharedBarriers); } return helpers; } //--------------------------------------------------------------------------------------- // Disposes of this sort helper's expensive state. // public void Dispose() { // We only dispose of the barriers when the 1st partition finishes. That's because // all others depend on the shared barriers, so we can't get rid of them eagerly. if (_partitionIndex == 0) { for (int i = 0; i < _sharedBarriers.Length; i++) { for (int j = 0; j < _sharedBarriers[i].Length; j++) { Barrier b = _sharedBarriers[i][j]; if (b != null) { b.Dispose(); } } } } } //--------------------------------------------------------------------------------------- // Sorts the data, possibly returning a result. // // Notes: // This method makes some pretty fundamental assumptions about what concurrency // exists in the system. Namely, it assumes all SortHelpers are running in // parallel. If they aren't Sort will end up waiting for certain events that // will never happen -- i.e. we will deadlock. // internal override TInputOutput[] Sort() { // Step 1. Accumulate this partitions' worth of input. GrowingArray<TKey> sourceKeys = null; List<TInputOutput> sourceValues = null; BuildKeysFromSource(ref sourceKeys, ref sourceValues); Debug.Assert(sourceValues != null, "values weren't populated"); Debug.Assert(sourceKeys != null, "keys weren't populated"); // Step 2. Locally sort this partition's key indices in-place. QuickSortIndicesInPlace(sourceKeys, sourceValues, _indexState); // Step 3. Enter into the merging phases, each separated by several barriers. if (_partitionCount > 1) { // We only need to merge if there is more than 1 partition. MergeSortCooperatively(); } return _sharedValues[_partitionIndex]; } //----------------------------------------------------------------------------------- // Generates a list of values and keys from the data source. After calling this, // the keys and values lists will be populated; each key at index i corresponds to // the value at index i in the other list. // // Notes: // Should only be called once per sort helper. // private void BuildKeysFromSource(ref GrowingArray<TKey> keys, ref List<TInputOutput> values) { values = new List<TInputOutput>(); // Enumerate the whole input set, generating a key set in the process. CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; try { TInputOutput current = default(TInputOutput); TKey currentKey = default(TKey); bool hadNext = _source.MoveNext(ref current, ref currentKey); if (keys == null) { keys = new GrowingArray<TKey>(); } if (hadNext) { int i = 0; do { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(cancelToken); // Accumulate the keys and values so that we can sort them in a moment. keys.Add(currentKey); values.Add(current); } while (_source.MoveNext(ref current, ref currentKey)); } } finally { _source.Dispose(); } } //----------------------------------------------------------------------------------- // Produces a list of indices and sorts them in place using a local sort. // // Notes: // Each element in the indices array is an index which refers to an element in // the key/value array. After calling this routine, the indices will be ordered // such that the keys they refere to are in ascending or descending order, // according to the sort criteria used. // private void QuickSortIndicesInPlace(GrowingArray<TKey> keys, List<TInputOutput> values, OrdinalIndexState ordinalIndexState) { Debug.Assert(keys != null); Debug.Assert(values != null); Debug.Assert(keys.Count == values.Count); // Generate a list of keys in forward order. We will sort them in a moment. int[] indices = new int[values.Count]; for (int i = 0; i < indices.Length; i++) { indices[i] = i; } // Now sort the indices in place. if (indices.Length > 1 && ordinalIndexState.IsWorseThan(OrdinalIndexState.Increasing)) { QuickSort(0, indices.Length - 1, keys.InternalArray, indices, _groupState.CancellationState.MergedCancellationToken); } if (_partitionCount == 1) { // If there is only one partition, we will produce the final value set now, // since there will be no merge afterward (which is where we usually do this). TInputOutput[] sortedValues = new TInputOutput[values.Count]; for (int i = 0; i < indices.Length; i++) { sortedValues[i] = values[indices[i]]; } _sharedValues[_partitionIndex] = sortedValues; } else { // Otherwise, a merge will happen. Generate the shared data structures. _sharedIndices[_partitionIndex] = indices; _sharedKeys[_partitionIndex] = keys; _sharedValues[_partitionIndex] = new TInputOutput[values.Count]; // Copy local structures to shared space. values.CopyTo(_sharedValues[_partitionIndex]); } } //----------------------------------------------------------------------------------- // Works cooperatively with other concurrent sort helpers to produce a final sorted // output list of data. Here is an overview of the algorithm used. // // During each phase, we must communicate with a partner task. As a simple // illustration, imagine we have 8 partitions (P=8), numbered 0-7. There will be // Log2(O)+2 phases (separated by barriers), where O is the next power of two greater // than or equal to P, in the sort operation: // // Pairs: (P = 8) // phase=L: [0][1] [2][3] [4][5] [6][7] // phase=0: [0,1] [2,3] [4,5] [6,7] // phase=1: [0,2] [4,6] // phase=2: [0,4] // phase=M: [0] // // During phase L, each partition locally sorts its data. Then, at each subsequent // phase in the logarithmic reduction, two partitions are paired together and cooperate // to accomplish a portion of the merge. The left one then goes on to choose another // partner, in the next phase, and the right one exits. And so on, until phase M, when // there is just one partition left (the 0th), which is when it may publish the final // output from the sort operation. // // Notice we mentioned rounding up to the next power of two when determining the number // of phases. Values of P which aren't powers of 2 are slightly problematic, because // they create a load imbalance in one of the partitions and heighten the depth of the // logarithmic tree. As an illustration, imagine this case: // // Pairs: (P = 5) // phase=L: [0][1] [2][3] [4] // phase=0: [0,1] [2,3] [4,X] [X,X] // phase=1: [0,2] [4,X] // phase=2: [0,4] // phase=M: [0] // // Partition #4 in this example performs its local sort during phase L, but then has nothing // to do during phases 0 and 2. (I.e. it has nobody to merge with.) Only during phase 2 // does it then resume work and help phase 2 perform its merge. This is modeled a bit like // there were actually 8 partitions, which is the next power of two greater than or equal to // 5. This example was chosen as an extreme case of imbalance. We stall a processor (the 5th) // for two complete phases. If P = 6 or 7, the problem would not be nearly so bad, but if // P = 9, the last partition would stall for yet another phase (and so on for every power of // two boundary). We handle these, cases, but note that an overabundance of them will probably // negatively impact speedups. // private void MergeSortCooperatively() { CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; int phaseCount = _sharedBarriers.Length; for (int phase = 0; phase < phaseCount; phase++) { bool isLastPhase = (phase == (phaseCount - 1)); // Calculate our partner for this phase and the next. int partnerIndex = ComputePartnerIndex(phase); // If we have a partner (see above for non power of 2 cases and why the index returned might // be out of bounds), we will coordinate with the partner to produce the merged output. if (partnerIndex < _partitionCount) { // Cache references to our local data. int[] myIndices = _sharedIndices[_partitionIndex]; GrowingArray<TKey> myKeys = _sharedKeys[_partitionIndex]; TKey[] myKeysArr = myKeys.InternalArray; TInputOutput[] myValues = _sharedValues[_partitionIndex]; // First we must rendezvous with our merge partner so we know the previous sort // and merge phase has been completed. By convention, we always use the left-most // partner's barrier for this; all that matters is that both uses the same. _sharedBarriers[phase][Math.Min(_partitionIndex, partnerIndex)].SignalAndWait(cancelToken); // Grab the two sorted inputs and then merge them cooperatively into one list. One // worker merges from left-to-right until it's placed elements up to the half-way // point, and the other worker does the same, but only from right-to-left. if (_partitionIndex < partnerIndex) { // Before moving on to the actual merge, the left-most partition will allocate data // to hold the merged indices and key/value pairs. // First, remember a copy of all of the partner's lists. int[] rightIndices = _sharedIndices[partnerIndex]; TKey[] rightKeys = _sharedKeys[partnerIndex].InternalArray; TInputOutput[] rightValues = _sharedValues[partnerIndex]; // We copy the our own items into the right's (overwriting its values) so that it can // retrieve them after the barrier. This is an exchange operation. _sharedIndices[partnerIndex] = myIndices; _sharedKeys[partnerIndex] = myKeys; _sharedValues[partnerIndex] = myValues; int leftCount = myValues.Length; int rightCount = rightValues.Length; int totalCount = leftCount + rightCount; // Now allocate the lists into which the merged data will go. Share this // with the other thread so that it can place data into it as well. int[] mergedIndices = null; TInputOutput[] mergedValues = new TInputOutput[totalCount]; // Only on the last phase do we need to remember indices and keys. if (!isLastPhase) { mergedIndices = new int[totalCount]; } // Publish our newly allocated merged data structures. _sharedIndices[_partitionIndex] = mergedIndices; _sharedKeys[_partitionIndex] = myKeys; _sharedValues[_partitionIndex] = mergedValues; Debug.Assert(myKeysArr != null); _sharedBarriers[phase][_partitionIndex].SignalAndWait(cancelToken); // Merge the left half into the shared merged space. This is a normal merge sort with // the caveat that we stop merging once we reach the half-way point (since our partner // is doing the same for the right half). Note that during the last phase we only // copy the values and not the indices or keys. int m = (totalCount + 1) / 2; int i = 0, j0 = 0, j1 = 0; while (i < m) { if ((i & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(cancelToken); if (j0 < leftCount && (j1 >= rightCount || _keyComparer.Compare(myKeysArr[myIndices[j0]], rightKeys[rightIndices[j1]]) <= 0)) { if (isLastPhase) { mergedValues[i] = myValues[myIndices[j0]]; } else { mergedIndices[i] = myIndices[j0]; } j0++; } else { if (isLastPhase) { mergedValues[i] = rightValues[rightIndices[j1]]; } else { mergedIndices[i] = leftCount + rightIndices[j1]; } j1++; } i++; } // If it's not the last phase, we just bulk propagate the keys and values. if (!isLastPhase && leftCount > 0) { Array.Copy(myValues, 0, mergedValues, 0, leftCount); } // And now just wait for the second half. We never reuse the same barrier across multiple // phases, so we can always dispose of it when we wake up. _sharedBarriers[phase][_partitionIndex].SignalAndWait(cancelToken); } else { // Wait for the other partition to allocate the shared data. _sharedBarriers[phase][partnerIndex].SignalAndWait(cancelToken); // After the barrier, the other partition will have made two things available to us: // (1) its own indices, keys, and values, stored in the cell that used to hold our data, // and (2) the arrays into which merged data will go, stored in its shared array cells. // We will snag references to all of these things. int[] leftIndices = _sharedIndices[_partitionIndex]; TKey[] leftKeys = _sharedKeys[_partitionIndex].InternalArray; TInputOutput[] leftValues = _sharedValues[_partitionIndex]; int[] mergedIndices = _sharedIndices[partnerIndex]; GrowingArray<TKey> mergedKeys = _sharedKeys[partnerIndex]; TInputOutput[] mergedValues = _sharedValues[partnerIndex]; Debug.Assert(leftValues != null); Debug.Assert(leftKeys != null); int leftCount = leftValues.Length; int rightCount = myValues.Length; int totalCount = leftCount + rightCount; // Merge the right half into the shared merged space. This is a normal merge sort with // the caveat that we stop merging once we reach the half-way point (since our partner // is doing the same for the left half). Note that during the last phase we only // copy the values and not the indices or keys. int m = (totalCount + 1) / 2; int i = totalCount - 1, j0 = leftCount - 1, j1 = rightCount - 1; while (i >= m) { if ((i & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(cancelToken); if (j0 >= 0 && (j1 < 0 || _keyComparer.Compare(leftKeys[leftIndices[j0]], myKeysArr[myIndices[j1]]) > 0)) { if (isLastPhase) { mergedValues[i] = leftValues[leftIndices[j0]]; } else { mergedIndices[i] = leftIndices[j0]; } j0--; } else { if (isLastPhase) { mergedValues[i] = myValues[myIndices[j1]]; } else { mergedIndices[i] = leftCount + myIndices[j1]; } j1--; } i--; } // If it's not the last phase, we just bulk propagate the keys and values. if (!isLastPhase && myValues.Length > 0) { mergedKeys.CopyFrom(myKeysArr, myValues.Length); Array.Copy(myValues, 0, mergedValues, leftCount, myValues.Length); } // Wait for our partner to finish copying too. _sharedBarriers[phase][partnerIndex].SignalAndWait(cancelToken); // Now the greater of the two partners can leave, it's done. break; } } } } //--------------------------------------------------------------------------------------- // Computes our partner index given the logarithmic reduction algorithm specified above. // private int ComputePartnerIndex(int phase) { int offset = 1 << phase; return _partitionIndex + ((_partitionIndex % (offset * 2)) == 0 ? offset : -offset); } //--------------------------------------------------------------------------------------- // Sort algorithm used to sort key/value lists. After this has been called, the indices // will have been placed in sorted order based on the keys provided. // private void QuickSort(int left, int right, TKey[] keys, int[] indices, CancellationToken cancelToken) { Debug.Assert(keys != null, "need a non-null keyset"); Debug.Assert(keys.Length >= indices.Length); Debug.Assert(left <= right); Debug.Assert(0 <= left && left < keys.Length); Debug.Assert(0 <= right && right < keys.Length); // cancellation check. // only test for intervals that are wider than so many items, else this test is // relatively expensive compared to the work being performend. if (right - left > CancellationState.POLL_INTERVAL) CancellationState.ThrowIfCanceled(cancelToken); do { int i = left; int j = right; int pivot = indices[i + ((j - i) >> 1)]; TKey pivotKey = keys[pivot]; do { while (_keyComparer.Compare(keys[indices[i]], pivotKey) < 0) i++; while (_keyComparer.Compare(keys[indices[j]], pivotKey) > 0) j--; Debug.Assert(i >= left && j <= right, "(i>=left && j<=right) sort failed - bogus IComparer?"); if (i > j) { break; } if (i < j) { // Swap the indices. int tmp = indices[i]; indices[i] = indices[j]; indices[j] = tmp; } i++; j--; } while (i <= j); if (j - left <= right - i) { if (left < j) { QuickSort(left, j, keys, indices, cancelToken); } left = i; } else { if (i < right) { QuickSort(i, right, keys, indices, cancelToken); } right = j; } } while (left < right); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; using Codentia.Common.Reporting.BL; using Codentia.Common.WebControls; using Codentia.Common.WebControls.HtmlElements; using Codentia.Common.WebControls.Validators; using Microsoft.Reporting.WebForms; namespace Codentia.Common.Reporting.WebControls { /// <summary> /// This control combines a standard .net ReportViewer with a Parameter Div control to render reports /// </summary> [ToolboxData("<{0}:CEReportViewer runat=server></{0}:CEReportViewer>")] public class CEReportViewer : CECompositeControl { private string _reportCode = string.Empty; private int _reportViewerWidthPercentage = 100; private string _calendarImageURL = string.Empty; private bool _hasValidators = false; private bool _rdlFormat = true; private bool _areParametersPopulated = false; private bool _isInWebPage = true; private CEReport _rep = null; private string _radioButtonCSSClass = string.Empty; private string _dateCSSClass = string.Empty; private bool _autoGenerateIfNoParameters; private bool _hasParameters = false; /// <summary> /// Gets or sets ReportCode /// </summary> public string ReportCode { get { return _reportCode; } set { _reportCode = value; } } /// <summary> /// Gets or sets ReportViewerWidth /// </summary> public int ReportViewerWidthPercentage { get { return _reportViewerWidthPercentage; } set { _reportViewerWidthPercentage = value; } } /// <summary> /// Gets or sets CalendarImageURL /// </summary> public string CalendarImageURL { get { return _calendarImageURL; } set { _calendarImageURL = value; } } /// <summary> /// Gets or sets RadioButtonCSSClass /// </summary> public string RadioButtonCSSClass { get { return _radioButtonCSSClass; } set { _radioButtonCSSClass = value; } } /// <summary> /// Gets or sets DateCSSClass /// </summary> public string DateCSSClass { get { return _dateCSSClass; } set { _dateCSSClass = value; } } /// <summary> /// Gets or sets a value indicating whether [auto generate]. /// </summary> /// <value> /// <c>true</c> if [auto generate]; otherwise, <c>false</c>. /// </value> public bool AutoGenerate { get { return _autoGenerateIfNoParameters; } set { _autoGenerateIfNoParameters = value; } } /// <summary> /// Create PDF /// </summary> /// <param name="pdfFilePath">file path of pdf</param> /// <param name="parameterValues">parameter Values</param> public void CreatePDF(string pdfFilePath, Dictionary<string, object> parameterValues) { _isInWebPage = false; EnsureCEReport(); EnsureChildControls(); ReportViewer rv = (ReportViewer)this.FindChildControl("RV"); SetDataSources(rv, parameterValues); Warning[] warnings; string[] streamids; string mimeType; string encoding; string filenameExtension; byte[] bytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); using (FileStream fs = new FileStream(pdfFilePath, FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); } } /// <summary> /// Create child controls /// </summary> protected override void CreateChildControls() { if (!string.IsNullOrEmpty(_reportCode)) { EnsureCEReport(); _rdlFormat = !_rep.IsRdlc; if (_rep.ParametersAreRendered) { Panel p = new Panel(); p.ID = "parameterPanel"; PopulateParameterPanels(p); this.Controls.Add(p); } if (this.ShowControlsAsButtons) { IdempotentButton b = new IdempotentButton(); b.ID = "generateButton"; b.Text = "Generate Report"; b.Click += new EventHandler(GenerateReportClick); b.CausesValidation = true; b.ValidationGroup = this.ID; this.Controls.Add(b); } else { P linkContainer = new P(); IdempotentLinkButton lb = new IdempotentLinkButton(); lb.ID = "generateButton"; lb.Text = "Generate Report"; lb.Click += new EventHandler(GenerateReportClick); lb.CausesValidation = true; lb.ValidationGroup = this.ID; linkContainer.Controls.Add(lb); this.Controls.Add(linkContainer); } Panel repvPanel = new Panel(); repvPanel.ID = "RVPanel"; this.Controls.Add(repvPanel); ReportViewer rv = new ReportViewer(); rv.ID = "RV"; rv.ProcessingMode = ProcessingMode.Local; rv.LocalReport.EnableExternalImages = true; rv.LocalReport.EnableHyperlinks = true; if (_rdlFormat) { // stream from an rdl file StringReader sr = null; if (_isInWebPage) { sr = _rep.GetRdlStringReader(Path.GetDirectoryName(this.Page.Request.PhysicalPath)); // sr = _rep.GetRdlStringReader(this.Page.Request.PhysicalApplicationPath); } else { sr = _rep.GetRdlStringReader(System.Environment.CurrentDirectory); } rv.LocalReport.LoadReportDefinition(sr); sr.Close(); } else { string rdlSubFolder = string.Empty; if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ReportSubFolder"])) { rdlSubFolder = string.Format(@"{0}\", ConfigurationManager.AppSettings["ReportSubFolder"]); } // load direct from an rdlc file string rdlcPath = string.Format("{0}\\{1}{2}.rdlc", this.Page.Request.PhysicalApplicationPath, rdlSubFolder, _rep.RdlName); rv.LocalReport.ReportPath = rdlcPath; } rv.ShowParameterPrompts = false; rv.ShowReportBody = false; repvPanel.Controls.Add(rv); if (_autoGenerateIfNoParameters) { if (!_hasParameters) { Page.Validate(); GenerateReportClick(null, null); this.FindControl("generateButton").Visible = false; } } } } /// <summary> /// Generate Report Click event /// </summary> /// <param name="sender">sender object</param> /// <param name="e">event args</param> protected void GenerateReportClick(object sender, EventArgs e) { if (Page.IsValid) { EnsureCEReport(); Dictionary<string, object> parameterValues = new Dictionary<string, object>(); IEnumerator<string> ie = _rep.CEReportDataSources.Keys.GetEnumerator(); // Ensure parameters are populated while (ie.MoveNext()) { CEReportDataSource mrds = _rep.CEReportDataSources[ie.Current]; if (mrds.CEReportParameters.Count > 0) { PopulateParameterValues(parameterValues); } } GenerateLocalReport(parameterValues); } } /// <summary> /// Validate checkboxes /// </summary> /// <param name="sender">sender object</param> /// <param name="args">Event Args</param> protected void checkBoxValidator_ServerValidate(object sender, ServerValidateEventArgs args) { CustomValidator cv = (CustomValidator)sender; args.IsValid = false; UnorderedCheckBoxListSelectable ucbl = (UnorderedCheckBoxListSelectable)this.FindChildControl(cv.ControlToValidate); for (int i = 0; i < ucbl.UnorderedCheckBoxList.Items.Count; i++) { if (ucbl.UnorderedCheckBoxList.Items[i].Selected) { args.IsValid = true; } } } /// <summary> /// Save ViewState /// </summary> /// <returns>view state object</returns> protected override object SaveViewState() { return _reportCode; } /// <summary> /// Load ViewState /// </summary> /// <param name="savedState">saved sate object</param> protected override void LoadViewState(object savedState) { _reportCode = Convert.ToString(savedState); } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.DataBinding"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); if (_autoGenerateIfNoParameters) { if (!_hasParameters) { Page.Validate(); GenerateReportClick(null, e); this.FindControl("generateButton").Visible = false; } } } private void EnsureCEReport() { if (_rep == null) { _rep = new CEReport(_reportCode); } } private void GenerateLocalReport(Dictionary<string, object> parameterValues) { // Configure ReportViewer ReportViewer rv = (ReportViewer)this.FindChildControl("RV"); EnsureCEReport(); // allow hyperlinks rv.LocalReport.EnableHyperlinks = true; rv.LocalReport.EnableExternalImages = true; rv.HyperlinkTarget = "_blank"; SetDataSources(rv, parameterValues); rv.Width = Unit.Percentage(_reportViewerWidthPercentage); rv.LocalReport.Refresh(); rv.LocalReport.DisplayName = _reportCode; // disable the print button as it is not cross browser and requires client pack install rv.ShowPrintButton = false; rv.ShowReportBody = true; } private void SetDataSources(ReportViewer rv, Dictionary<string, object> parameterValues) { DataSet ds = _rep.GetReportResultDataSet(parameterValues); rv.LocalReport.DataSources.Clear(); for (int i = 0; i < ds.Tables.Count; i++) { // Add Data Sources DataTable dt = ds.Tables[i]; ReportDataSource rds = new ReportDataSource(dt.TableName, dt); rv.LocalReport.DataSources.Add(rds); } if (_rdlFormat) { // Set Parameters to CollatedParameters For Report rv.LocalReport.SetParameters(_rep.CollatedReportParameters); } } private void PopulateParameterValues(Dictionary<string, object> parameterValues) { if (!_areParametersPopulated) { IEnumerator<string> ie = _rep.CEReportDataSources.Keys.GetEnumerator(); while (ie.MoveNext()) { CEReportDataSource mrds = _rep.CEReportDataSources[ie.Current]; if (mrds.CEReportParameters.Count > 0) { IEnumerator<string> ieP = mrds.CEReportParameters.Keys.GetEnumerator(); while (ieP.MoveNext()) { CEReportParameter param = mrds.CEReportParameters[ieP.Current]; switch (param.ReportParameterType) { case ReportParameterType.CheckBox: parameterValues[ieP.Current] = GetCheckBoxPanelValue(param); break; case ReportParameterType.Date: parameterValues[ieP.Current] = GetDatePanelValue(param); break; case ReportParameterType.TextBox: parameterValues[ieP.Current] = GetTextBoxPanelValue(param); break; case ReportParameterType.DropDown: parameterValues[ieP.Current] = GetDropDownPanelValue(param); break; case ReportParameterType.RadioButton: parameterValues[ieP.Current] = GetRadioButtonPanelValue(param); break; } } } } _areParametersPopulated = true; } } private void PopulateParameterPanels(Panel parameterPanel) { IEnumerator<string> ie = _rep.CEReportDataSources.Keys.GetEnumerator(); while (ie.MoveNext()) { CEReportDataSource mrds = _rep.CEReportDataSources[ie.Current]; if (mrds.CEReportParameters.Count > 0) { _hasParameters = true; IEnumerator<string> ieP = mrds.CEReportParameters.Keys.GetEnumerator(); while (ieP.MoveNext()) { CEReportParameter param = mrds.CEReportParameters[ieP.Current]; if (param.IsRendered) { DataView dv = new DataView(); if (param.ReportParameterType != ReportParameterType.Date) { dv = param.GetParameterDataView(); } Panel paramPanel = new Panel(); paramPanel.ID = string.Format("{0}panel", param.ParameterCode); switch (param.ReportParameterType) { case ReportParameterType.CheckBox: PopulateCheckBoxPanel(param, paramPanel, dv); break; case ReportParameterType.Date: PopulateDatePanel(param, paramPanel); break; case ReportParameterType.TextBox: // Note CSS Class support should be added at some stage PopulateTextBoxPanel(param, paramPanel, string.Empty); break; case ReportParameterType.DropDown: PopulateDropDownPanel(param, paramPanel, dv); break; case ReportParameterType.RadioButton: PopulateRadioButtonPanel(param, paramPanel, dv); break; } parameterPanel.Controls.Add(paramPanel); } } } if (_hasValidators) { ValidationSummary vs = new ValidationSummary(); vs.ValidationGroup = this.ID; parameterPanel.Controls.Add(vs); } } } private object GetCheckBoxPanelValue(CEReportParameter param) { UnorderedCheckBoxListSelectable ucbl = (UnorderedCheckBoxListSelectable)this.FindChildControl(param.ParameterCode); StringBuilder sb = new StringBuilder(); sb.Append("<root>"); for (int i = 0; i < ucbl.UnorderedCheckBoxList.Items.Count; i++) { ListItem li = ucbl.UnorderedCheckBoxList.Items[i]; string state = "off"; if (li.Selected) { state = "on"; } sb.AppendFormat(@"<cb id='{0}' value='{1}'/>", li.Value, state); } sb.Append("</root>"); return sb.ToString(); } private object GetDropDownPanelValue(CEReportParameter param) { DropDownList dd = (DropDownList)this.FindChildControl(param.ParameterCode); return dd.SelectedValue; } private object GetTextBoxPanelValue(CEReportParameter param) { TextBox tb = (TextBox)this.FindChildControl(param.ParameterCode); return tb.Text; } private object GetRadioButtonPanelValue(CEReportParameter param) { UnorderedRadioButtonList urbl = (UnorderedRadioButtonList)this.FindChildControl(param.ParameterCode); string value = string.Empty; for (int i = 0; i < urbl.Items.Count; i++) { ListItem li = urbl.Items[i]; if (li.Selected) { value = li.Value; } } if (param.DbType == DbType.Boolean) { return value == "-1"; } return value; } private object GetDatePanelValue(CEReportParameter param) { TextBox tb = (TextBox)this.FindChildControl(param.ParameterCode); if (string.IsNullOrEmpty(tb.Text)) { return null; } else { return Convert.ToDateTime(tb.Text); } } private void PopulateDropDownPanel(CEReportParameter param, Panel p, DataView dv) { Label l = new Label(); l.Text = param.Caption; p.Controls.Add(l); DropDownList dd = new DropDownList(); dd.DataSource = dv; dd.ID = param.ParameterCode; dd.DataTextField = "Name"; dd.DataValueField = "Value"; dd.DataBind(); dd.SelectedIndex = 0; if (param.DefaultValue != string.Empty) { dd.SelectedValue = param.DefaultValue; } dd.EnableViewState = true; l.AssociatedControlID = dd.ID; p.Controls.Add(dd); } private void PopulateDatePanel(CEReportParameter param, Panel p) { PopulateTextBoxPanel(param, p, _dateCSSClass); } private void PopulateTextBoxPanel(CEReportParameter param, Panel p, string cssClass) { Label l = new Label(); l.Text = param.Caption; TextBox tb = new TextBox(); tb.ID = param.ParameterCode; tb.CssClass = cssClass; // do not add validator if needed if (!param.IsNullAllowed) { _hasValidators = true; RequiredFieldValidator rv = new RequiredFieldValidator(); rv.ID = string.Format("{0}_rv", param.ParameterCode); rv.ValidationGroup = this.ID; rv.ControlToValidate = tb.ID; rv.Text = "*"; rv.ErrorMessage = param.ErrorMessageCaption; } p.Controls.Add(l); p.Controls.Add(tb); } private void PopulateCheckBoxPanel(CEReportParameter param, Panel p, DataView dv) { Label l = new Label(); l.Text = param.Caption; UnorderedCheckBoxListSelectable ucbl = new UnorderedCheckBoxListSelectable(); ucbl.ID = param.ParameterCode; l.AssociatedControlID = ucbl.ID; for (int i = 0; i < dv.Table.Rows.Count; i++) { DataRow dr = dv.Table.Rows[i]; ListItem li = new ListItem(Convert.ToString(dr["Name"]), Convert.ToString(dr["Value"])); ucbl.UnorderedCheckBoxList.Items.Add(li); } p.Controls.Add(l); p.Controls.Add(ucbl); // add a validator to ensure that at least one checkbox is selected ServerValidateEventHandler eh = new ServerValidateEventHandler(checkBoxValidator_ServerValidate); CECustomValidator cv = new CECustomValidator("customCheckBoxValidator", ucbl.ID, "At least one checkbox must be selected", this.ID, false, eh); p.Controls.Add(cv); } private void PopulateRadioButtonPanel(CEReportParameter param, Panel p, DataView dv) { Label l = new Label(); l.Text = param.Caption; p.Controls.Add(l); UnorderedRadioButtonList urbl = new UnorderedRadioButtonList(); urbl.CssClass = _radioButtonCSSClass; urbl.ID = param.ParameterCode; for (int i = 0; i < dv.Table.Rows.Count; i++) { DataRow dr = dv.Table.Rows[i]; ListItem li = new ListItem(Convert.ToString(dr["Name"]), Convert.ToString(dr["Value"])); if (param.DefaultValue != string.Empty) { if (param.DefaultValue == Convert.ToString(dr["Value"])) { li.Selected = true; } } else { if (i == 0) { li.Selected = true; } } urbl.Items.Add(li); } l.AssociatedControlID = urbl.ID; p.Controls.Add(urbl); } } }
// Copyright (c) 2002-2019 "Neo4j," // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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.Diagnostics; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Neo4j.Driver.IntegrationTests.Direct { public class TransactionIT : DirectDriverTestBase { private IDriver Driver => Server.Driver; public TransactionIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } [RequireServerFact] public async Task ShouldRetry() { var session = Driver.AsyncSession(); try { var timer = Stopwatch.StartNew(); var exc = await Record.ExceptionAsync(() => session.WriteTransactionAsync(tx => throw new SessionExpiredException($"Failed at {timer.Elapsed}"))); timer.Stop(); exc.Should().BeOfType<ServiceUnavailableException>() .Which.InnerException.Should().BeOfType<AggregateException>() .Which.InnerExceptions.Should().NotBeEmpty().And.AllBeOfType<SessionExpiredException>(); timer.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(30)); } finally { await session.CloseAsync(); } } [RequireServerFact] public async Task ShouldCommitTransactionByDefault() { var session = Driver.AsyncSession(); try { var createResult = await session.WriteTransactionAsync(tx => tx.RunAndSingleAsync("CREATE (n) RETURN count(n)", null)); // the read operation should see the commited write tx var matchResult = await session.ReadTransactionAsync(tx => tx.RunAndSingleAsync("MATCH (n) RETURN count(n)", null)); createResult.Should().BeEquivalentTo(matchResult); } finally { await session.CloseAsync(); } } [RequireServerFact] public async Task ShouldNotCommitTransaction() { var session = Driver.AsyncSession(); try { var createResult = await session.WriteTransactionAsync(async tx => { var result = await tx.RunAndSingleAsync("CREATE (n) RETURN count(n)", null, r => r[0].As<int>()); await tx.RollbackAsync(); return result; }); // the read operation should not see the rolled back write tx var matchResult = await session.ReadTransactionAsync(tx => tx.RunAndSingleAsync("MATCH (n) RETURN count(n)", null, r => r[0].As<int>())); createResult.Should().Be(matchResult + 1); } finally { await session.CloseAsync(); } } [RequireServerFact] public async Task ShouldNotCommitIfError() { var session = Driver.AsyncSession(); try { var exc = await Record.ExceptionAsync(() => session.WriteTransactionAsync(async tx => { await tx.RunAsync("CREATE (n) RETURN count(n)"); throw new ProtocolException("Broken"); })); exc.Should().NotBeNull(); // the read operation should not see the rolled back write tx var matchResult = await session.ReadTransactionAsync(tx => tx.RunAndSingleAsync("MATCH (n) RETURN count(n)", null, r => r[0].As<int>())); matchResult.Should().Be(0); } finally { await session.CloseAsync(); } } [RequireServerFact] public async Task KeysShouldBeAvailableAfterRun() { using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken)) { var session = driver.AsyncSession(); try { var txc = await session.BeginTransactionAsync(); var cursor = await txc.RunAsync("RETURN 1 As X"); var keys = await cursor.KeysAsync(); keys.Should().HaveCount(1); keys.Should().Contain("X"); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } } [RequireServerFact] public async Task KeysShouldBeAvailableAfterRunAndResultConsumption() { using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken)) { var session = driver.AsyncSession(); try { var txc = await session.BeginTransactionAsync(); var cursor = await txc.RunAsync("RETURN 1 As X"); var keys = await cursor.KeysAsync(); keys.Should().BeEquivalentTo("X"); await cursor.ConsumeAsync(); keys = await cursor.KeysAsync(); keys.Should().BeEquivalentTo("X"); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } } [RequireServerFact] public async Task KeysShouldBeAvailableAfterConsecutiveRun() { using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken)) { var session = driver.AsyncSession(); try { var txc = await session.BeginTransactionAsync(); var cursor1 = await txc.RunAsync("RETURN 1 As X"); var cursor2 = await txc.RunAsync("RETURN 1 As Y"); var keys1 = await cursor1.KeysAsync(); keys1.Should().BeEquivalentTo("X"); var keys2 = await cursor2.KeysAsync(); keys2.Should().BeEquivalentTo("Y"); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } } [RequireServerFact] public async Task KeysShouldBeAvailableAfterConsecutiveRunAndResultConsumption() { using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken)) { var session = driver.AsyncSession(); try { var txc = await session.BeginTransactionAsync(); var cursor1 = await txc.RunAsync("RETURN 1 As X"); var cursor2 = await txc.RunAsync("RETURN 1 As Y"); var keys1 = await cursor1.KeysAsync(); keys1.Should().BeEquivalentTo("X"); var keys2 = await cursor2.KeysAsync(); keys2.Should().BeEquivalentTo("Y"); await cursor1.ConsumeAsync(); await cursor2.ConsumeAsync(); keys1 = await cursor1.KeysAsync(); keys1.Should().BeEquivalentTo("X"); keys2 = await cursor2.KeysAsync(); keys2.Should().BeEquivalentTo("Y"); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } } [RequireServerFact] public async Task KeysShouldBeAvailableAfterConsecutiveRunNoOrder() { using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken)) { var session = driver.AsyncSession(); try { var txc = await session.BeginTransactionAsync(); var cursor1 = await txc.RunAsync("RETURN 1 As X"); var cursor2 = await txc.RunAsync("RETURN 1 As Y"); var keys2 = await cursor2.KeysAsync(); keys2.Should().BeEquivalentTo("Y"); var keys1 = await cursor1.KeysAsync(); keys1.Should().BeEquivalentTo("X"); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } } [RequireServerFact] public async Task KeysShouldBeAvailableAfterConsecutiveRunAndResultConsumptionNoOrder() { using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken)) { var session = driver.AsyncSession(); try { var txc = await session.BeginTransactionAsync(); var cursor1 = await txc.RunAsync("RETURN 1 As X"); var cursor2 = await txc.RunAsync("RETURN 1 As Y"); var keys2 = await cursor2.KeysAsync(); keys2.Should().BeEquivalentTo("Y"); var keys1 = await cursor1.KeysAsync(); keys1.Should().BeEquivalentTo("X"); await cursor2.ConsumeAsync(); await cursor1.ConsumeAsync(); keys2 = await cursor2.KeysAsync(); keys2.Should().BeEquivalentTo("Y"); keys1 = await cursor1.KeysAsync(); keys1.Should().BeEquivalentTo("X"); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } } } }
using Newtonsoft.Json.Linq; using ReactNative.Bridge; using System.Collections.Generic; using TrackPlayer.Logic; using TrackPlayer.Players; using System.Threading.Tasks; namespace TrackPlayer { class TrackPlayerModule : ReactContextNativeModuleBase { public override string Name => "TrackPlayerModule"; public override JObject ModuleConstants { get { var obj = new JObject(); // States obj["STATE_NONE"] = (int) PlaybackState.None; obj["STATE_PLAYING"] = (int) PlaybackState.Playing; obj["STATE_PAUSED"] = (int) PlaybackState.Paused; obj["STATE_STOPPED"] = (int) PlaybackState.Stopped; obj["STATE_BUFFERING"] = (int) PlaybackState.Buffering; // Capabilities obj["CAPABILITY_PLAY"] = (int) Capability.Play; obj["CAPABILITY_PLAY_FROM_ID"] = (int) Capability.Unsupported; obj["CAPABILITY_PLAY_FROM_SEARCH"] = (int) Capability.Unsupported; obj["CAPABILITY_PAUSE"] = (int) Capability.Pause; obj["CAPABILITY_STOP"] = (int) Capability.Stop; obj["CAPABILITY_SEEK_TO"] = (int) Capability.Seek; obj["CAPABILITY_SKIP"] = (int) Capability.Unsupported; obj["CAPABILITY_SKIP_TO_NEXT"] = (int) Capability.Next; obj["CAPABILITY_SKIP_TO_PREVIOUS"] = (int) Capability.Previous; obj["CAPABILITY_SET_RATING"] = (int) Capability.Unsupported; obj["CAPABILITY_JUMP_FORWARD"] = (int) Capability.JumpForward; obj["CAPABILITY_JUMP_BACKWARD"] = (int) Capability.JumpBackward; return obj; } } private MediaManager manager; public TrackPlayerModule(ReactContext reactContext) : base(reactContext) { } public override void Initialize() { manager = new MediaManager(Context); base.Initialize(); } public override async Task OnReactInstanceDisposeAsync() { if (manager != null) { manager.Dispose(); manager = null; } await base.OnReactInstanceDisposeAsync(); } [ReactMethod] public void setupPlayer(JObject options, IPromise promise) { if (manager.GetPlayer() != null) { promise.Resolve(null); return; } manager.SwitchPlayback(manager.CreateLocalPlayback(options)); promise.Resolve(null); } [ReactMethod] public void destroy() { manager?.SwitchPlayback(null); } [ReactMethod] public void updateOptions(JObject options, IPromise promise) { manager.UpdateOptions(options); promise.Resolve(null); } [ReactMethod] public void play(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.Play(); promise.Resolve(null); } [ReactMethod] public void pause(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.Pause(); promise.Resolve(null); } [ReactMethod] public void stop(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.Stop(); promise.Resolve(null); } [ReactMethod] public void reset(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.Reset(); promise.Resolve(null); } [ReactMethod] public void updateMetadataForTrack(string id, JObject metadata, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; var queue = player.GetQueue(); var index = queue.FindIndex(t => t.Id == id); if (index == -1) { promise.Reject("track_not_in_queue", "Track not found"); } else { var track = queue[index]; track.SetMetadata(metadata); player.UpdateTrack(index, track); promise.Resolve(null); } } [ReactMethod] public void removeUpcomingTracks(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.RemoveUpcomingTracks(); promise.Resolve(null); } [ReactMethod] public void add(JArray array, string insertBeforeId, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; List<Track> tracks = new List<Track>(array.Count); foreach (JObject obj in array) { tracks.Add(new Track(obj)); } player.Add(tracks, insertBeforeId, promise); } [ReactMethod] public void remove(JArray array, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; List<string> tracks = new List<string>(array.Count); foreach (string id in array) { tracks.Add(id); } player.Remove(tracks, promise); } [ReactMethod] public void skip(string track, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.Skip(track, promise); } [ReactMethod] public void skipToNext(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.SkipToNext(promise); } [ReactMethod] public void skipToPrevious(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.SkipToPrevious(promise); } [ReactMethod] public void getQueue(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; var queue = player.GetQueue(); var array = new JArray(); foreach(var track in queue) { array.Add(track.ToObject()); } promise.Resolve(array); } [ReactMethod] public void getCurrentTrack(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetCurrentTrack()?.Id); } [ReactMethod] public void getTrack(string id, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetTrack(id)?.ToObject()); } [ReactMethod] public void getVolume(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetVolume()); } [ReactMethod] public void setVolume(double volume, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.SetVolume(volume); promise.Resolve(null); } [ReactMethod] public void getRate(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetRate()); } [ReactMethod] public void setRate(double rate, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.SetRate(rate); promise.Resolve(null); } [ReactMethod] public void seekTo(double seconds, IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; player.SeekTo(seconds); promise.Resolve(null); } [ReactMethod] public void getPosition(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetPosition()); } [ReactMethod] public void getBufferedPosition(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetBufferedPosition()); } [ReactMethod] public void getDuration(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetDuration()); } [ReactMethod] public void getState(IPromise promise) { var player = manager?.GetPlayer(); if (Utils.CheckPlayback(player, promise)) return; promise.Resolve(player.GetState()); } } }
using Content.Server.Climbing; using Content.Server.Cloning; using Content.Server.Medical.Components; using Content.Server.Mind.Components; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.Preferences.Managers; using Content.Shared.ActionBlocker; using Content.Shared.Acts; using Content.Shared.CharacterAppearance.Components; using Content.Shared.Damage; using Content.Shared.DragDrop; using Content.Shared.Interaction; using Content.Shared.MobState.Components; using Content.Shared.Movement; using Content.Shared.Preferences; using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.Network; using Robust.Shared.Player; using static Content.Shared.MedicalScanner.SharedMedicalScannerComponent; namespace Content.Server.Medical { public sealed class MedicalScannerSystem : EntitySystem { [Dependency] private readonly IServerPreferencesManager _prefsManager = null!; [Dependency] private readonly ActionBlockerSystem _blocker = default!; [Dependency] private readonly ClimbSystem _climbSystem = default!; [Dependency] private readonly CloningSystem _cloningSystem = default!; [Dependency] private readonly PopupSystem _popupSystem = default!; private const float UpdateRate = 1f; private float _updateDif; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<MedicalScannerComponent, ComponentInit>(OnComponentInit); SubscribeLocalEvent<MedicalScannerComponent, ActivateInWorldEvent>(OnActivated); SubscribeLocalEvent<MedicalScannerComponent, RelayMovementEntityEvent>(OnRelayMovement); SubscribeLocalEvent<MedicalScannerComponent, GetVerbsEvent<InteractionVerb>>(AddInsertOtherVerb); SubscribeLocalEvent<MedicalScannerComponent, GetVerbsEvent<AlternativeVerb>>(AddAlternativeVerbs); SubscribeLocalEvent<MedicalScannerComponent, DestructionEventArgs>(OnDestroyed); SubscribeLocalEvent<MedicalScannerComponent, DragDropEvent>(HandleDragDropOn); SubscribeLocalEvent<MedicalScannerComponent, ScanButtonPressedMessage>(OnScanButtonPressed); } private void OnComponentInit(EntityUid uid, MedicalScannerComponent scannerComponent, ComponentInit args) { base.Initialize(); scannerComponent.BodyContainer = scannerComponent.Owner.EnsureContainer<ContainerSlot>($"{scannerComponent.Name}-bodyContainer"); UpdateUserInterface(uid, scannerComponent); } private void OnActivated(EntityUid uid, MedicalScannerComponent scannerComponent, ActivateInWorldEvent args) { if (!TryComp<ActorComponent>(args.User, out var actor) || !IsPowered(scannerComponent)) return; scannerComponent.UserInterface?.Toggle(actor.PlayerSession); UpdateUserInterface(uid, scannerComponent); } private void OnRelayMovement(EntityUid uid, MedicalScannerComponent scannerComponent, RelayMovementEntityEvent args) { if (!_blocker.CanInteract(args.Entity, scannerComponent.Owner)) return; EjectBody(uid, scannerComponent); } private void AddInsertOtherVerb(EntityUid uid, MedicalScannerComponent component, GetVerbsEvent<InteractionVerb> args) { if (args.Using == null || !args.CanAccess || !args.CanInteract || IsOccupied(component) || !component.CanInsert(args.Using.Value)) return; string name = "Unknown"; if (TryComp<MetaDataComponent>(args.Using.Value, out var metadata)) name = metadata.EntityName; InteractionVerb verb = new() { Act = () => InsertBody(component.Owner, args.Target, component), Category = VerbCategory.Insert, Text = name }; args.Verbs.Add(verb); } private void AddAlternativeVerbs(EntityUid uid, MedicalScannerComponent component, GetVerbsEvent<AlternativeVerb> args) { if (!args.CanAccess || !args.CanInteract) return; // Eject verb if (IsOccupied(component)) { AlternativeVerb verb = new(); verb.Act = () => EjectBody(uid, component); verb.Category = VerbCategory.Eject; verb.Text = Loc.GetString("medical-scanner-verb-noun-occupant"); args.Verbs.Add(verb); } // Self-insert verb if (!IsOccupied(component) && component.CanInsert(args.User) && _blocker.CanMove(args.User)) { AlternativeVerb verb = new(); verb.Act = () => InsertBody(component.Owner, args.User, component); verb.Text = Loc.GetString("medical-scanner-verb-enter"); args.Verbs.Add(verb); } } private void OnDestroyed(EntityUid uid, MedicalScannerComponent scannerComponent, DestructionEventArgs args) { EjectBody(uid, scannerComponent); } private void HandleDragDropOn(EntityUid uid, MedicalScannerComponent scannerComponent, DragDropEvent args) { InsertBody(uid, args.Dragged, scannerComponent); } private void OnScanButtonPressed(EntityUid uid, MedicalScannerComponent scannerComponent, ScanButtonPressedMessage args) { TrySaveCloningData(uid, scannerComponent); } private static readonly MedicalScannerBoundUserInterfaceState EmptyUIState = new(false); private MedicalScannerBoundUserInterfaceState GetUserInterfaceState(EntityUid uid, MedicalScannerComponent scannerComponent) { EntityUid? containedBody = scannerComponent.BodyContainer.ContainedEntity; if (containedBody == null) { UpdateAppearance(uid, scannerComponent); return EmptyUIState; } if (!HasComp<DamageableComponent>(containedBody)) return EmptyUIState; if (!HasComp<HumanoidAppearanceComponent>(containedBody)) return EmptyUIState; if (!TryComp<MindComponent>(containedBody, out var mindComponent) || mindComponent.Mind == null) return EmptyUIState; bool isScanned = _cloningSystem.HasDnaScan(mindComponent.Mind); return new MedicalScannerBoundUserInterfaceState(!isScanned); } private void UpdateUserInterface(EntityUid uid, MedicalScannerComponent scannerComponent) { if (!IsPowered(scannerComponent)) { return; } var newState = GetUserInterfaceState(uid, scannerComponent); scannerComponent.UserInterface?.SetState(newState); } private MedicalScannerStatus GetStatus(MedicalScannerComponent scannerComponent) { if (IsPowered(scannerComponent)) { var body = scannerComponent.BodyContainer.ContainedEntity; if (body == null) return MedicalScannerStatus.Open; if (!TryComp<MobStateComponent>(body.Value, out var state)) { return MedicalScannerStatus.Open; } return GetStatusFromDamageState(state); } return MedicalScannerStatus.Off; } public bool IsPowered(MedicalScannerComponent scannerComponent) { if (TryComp<ApcPowerReceiverComponent>(scannerComponent.Owner, out var receiver)) { return receiver.Powered; } return false; } public bool IsOccupied(MedicalScannerComponent scannerComponent) { return scannerComponent.BodyContainer.ContainedEntity != null; } private MedicalScannerStatus GetStatusFromDamageState(MobStateComponent state) { if (state.IsAlive()) return MedicalScannerStatus.Green; if (state.IsCritical()) return MedicalScannerStatus.Red; if (state.IsDead()) return MedicalScannerStatus.Death; return MedicalScannerStatus.Yellow; } private void UpdateAppearance(EntityUid uid, MedicalScannerComponent scannerComponent) { if (TryComp<AppearanceComponent>(scannerComponent.Owner, out var appearance)) { appearance.SetData(MedicalScannerVisuals.Status, GetStatus(scannerComponent)); } } public override void Update(float frameTime) { base.Update(frameTime); _updateDif += frameTime; if (_updateDif < UpdateRate) return; _updateDif -= UpdateRate; foreach (var scanner in EntityQuery<MedicalScannerComponent>()) { UpdateAppearance(scanner.Owner, scanner); } } public void InsertBody(EntityUid uid, EntityUid user, MedicalScannerComponent? scannerComponent) { if (!Resolve(uid, ref scannerComponent)) return; if (scannerComponent.BodyContainer.ContainedEntity != null) return; if (!TryComp<MobStateComponent>(user, out var comp)) return; scannerComponent.BodyContainer.Insert(user); UpdateUserInterface(uid, scannerComponent); UpdateAppearance(scannerComponent.Owner, scannerComponent); } public void EjectBody(EntityUid uid, MedicalScannerComponent? scannerComponent) { if (!Resolve(uid, ref scannerComponent)) return; if (scannerComponent.BodyContainer.ContainedEntity is not {Valid: true} contained) return; scannerComponent.BodyContainer.Remove(contained); _climbSystem.ForciblySetClimbing(contained); UpdateUserInterface(uid, scannerComponent); UpdateAppearance(scannerComponent.Owner, scannerComponent); } public void TrySaveCloningData(EntityUid uid, MedicalScannerComponent? scannerComponent) { if (!Resolve(uid, ref scannerComponent)) return; EntityUid? body = scannerComponent.BodyContainer.ContainedEntity; if (body == null) return; // Check to see if they are humanoid if (!TryComp<HumanoidAppearanceComponent>(body, out var humanoid)) { _popupSystem.PopupEntity(Loc.GetString("medical-scanner-component-msg-no-humanoid-component"), uid, Filter.Pvs(uid)); return; } if (!TryComp<MindComponent>(body, out var mindComp) || mindComp.Mind == null) { _popupSystem.PopupEntity(Loc.GetString("medical-scanner-component-msg-no-soul"), uid, Filter.Pvs(uid)); return; } // Null suppression based on above check. Yes, it's explicitly needed var mind = mindComp.Mind; // We need the HumanoidCharacterProfile // TODO: Move this further 'outwards' into a DNAComponent or somesuch. // Ideally this ends with GameTicker & CloningSystem handing DNA to a function that sets up a body for that DNA. var mindUser = mind.UserId; if (mindUser.HasValue == false || mind.Session == null) { // For now assume this means soul departed _popupSystem.PopupEntity(Loc.GetString("medical-scanner-component-msg-soul-broken"), uid, Filter.Pvs(uid)); return; } // TODO get synchronously // This must be changed to grab the details of the mob itself, not session preferences var profile = GetPlayerProfileAsync(mindUser.Value); _cloningSystem.AddToDnaScans(new ClonerDNAEntry(mind, profile)); UpdateUserInterface(uid, scannerComponent); } private HumanoidCharacterProfile GetPlayerProfileAsync(NetUserId userId) { return (HumanoidCharacterProfile) _prefsManager.GetPreferences(userId).SelectedCharacter; } } }
namespace Schema.NET; using System; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// A single or list of values. /// </summary> /// <typeparam name="T">The type of the values.</typeparam> /// <seealso cref="ICollection{T}" /> public readonly struct OneOrMany<T> : IReadOnlyCollection<T>, IEnumerable<T>, IValues, IEquatable<OneOrMany<T>> { private readonly T[]? collection; /// <summary> /// Initializes a new instance of the <see cref="OneOrMany{T}"/> struct. /// </summary> /// <param name="item">The single item value.</param> public OneOrMany(T item) { #pragma warning disable CA1508 // TODO: Remove this suppression in .NET 6 where the warning is fixed. if (item is null || (item is string itemAsString && string.IsNullOrWhiteSpace(itemAsString))) #pragma warning restore CA1508 // TODO: Remove this suppression in .NET 6 where the warning is fixed. { this.collection = null; this.HasOne = false; } else { this.collection = new[] { item }; this.HasOne = true; } } /// <summary> /// Initializes a new instance of the <see cref="OneOrMany{T}"/> struct. /// </summary> /// <param name="span">The span of values.</param> public OneOrMany(ReadOnlySpan<T> span) { if (!span.IsEmpty) { var items = new T[span.Length]; var index = 0; if (typeof(T) == typeof(string)) { for (var i = 0; i < span.Length; i++) { var item = span[i]; #pragma warning disable CA1508 // TODO: Remove this suppression in .NET 6 where the warning is fixed. if (!string.IsNullOrWhiteSpace(item as string)) #pragma warning restore CA1508 // TODO: Remove this suppression in .NET 6 where the warning is fixed. { items[index] = item; index++; } } } else { for (var i = 0; i < span.Length; i++) { var item = span[i]; #pragma warning disable CA1508 // TODO: Remove this suppression in .NET 6 where the warning is fixed. if (item is not null) #pragma warning restore CA1508 // TODO: Remove this suppression in .NET 6 where the warning is fixed. { items[index] = item; index++; } } } if (index > 0) { if (index == span.Length) { this.collection = items; } else { this.collection = new T[index]; Array.Copy(items, 0, this.collection, 0, index); } this.HasOne = index == 1; return; } } this.collection = null; this.HasOne = false; } /// <summary> /// Initializes a new instance of the <see cref="OneOrMany{T}"/> struct. /// </summary> /// <param name="array">The array of values.</param> public OneOrMany(params T[] array) : this(array.AsSpan()) { } /// <summary> /// Initializes a new instance of the <see cref="OneOrMany{T}"/> struct. /// </summary> /// <param name="collection">The collection of values.</param> public OneOrMany(IEnumerable<T> collection) : this(collection.ToArray().AsSpan()) { } /// <summary> /// Initializes a new instance of the <see cref="OneOrMany{T}"/> struct. /// </summary> /// <param name="collection">The list of values.</param> public OneOrMany(IEnumerable<object> collection) : this(collection.Cast<T>().ToArray().AsSpan()) { } /// <summary> /// Gets the number of elements contained in the <see cref="OneOrMany{T}"/>. /// </summary> public int Count => this.collection?.Length ?? 0; /// <summary> /// Gets a value indicating whether this instance has a single item value. /// </summary> /// <value><c>true</c> if this instance has a single item value; otherwise, <c>false</c>.</value> public bool HasOne { get; } /// <summary> /// Gets a value indicating whether this instance has more than one value. /// </summary> /// <value><c>true</c> if this instance has more than one value; otherwise, <c>false</c>.</value> public bool HasMany => this.collection?.Length > 1; /// <summary> /// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="OneOrMany{T}"/>. /// </summary> /// <param name="item">The single item value.</param> /// <returns>The result of the conversion.</returns> #pragma warning disable CA2225 // Operator overloads have named alternates public static implicit operator OneOrMany<T>(T item) => new(item); #pragma warning restore CA2225 // Operator overloads have named alternates /// <summary> /// Performs an implicit conversion from <typeparamref name="T[]"/> to <see cref="OneOrMany{T}"/>. /// </summary> /// <param name="array">The array of values.</param> /// <returns>The result of the conversion.</returns> #pragma warning disable CA2225 // Operator overloads have named alternates public static implicit operator OneOrMany<T>(T[] array) => new(array); #pragma warning restore CA2225 // Operator overloads have named alternates /// <summary> /// Performs an implicit conversion from <see cref="List{T}"/> to <see cref="OneOrMany{T}"/>. /// </summary> /// <param name="list">The list of values.</param> /// <returns>The result of the conversion.</returns> #pragma warning disable CA2225 // Operator overloads have named alternates #pragma warning disable CA1002 // Do not expose generic lists public static implicit operator OneOrMany<T>(List<T> list) => new(list); #pragma warning restore CA1002 // Do not expose generic lists #pragma warning restore CA2225 // Operator overloads have named alternates /// <summary> /// Performs an implicit conversion from <see cref="OneOrMany{T}"/> to <typeparamref name="T"/>. /// </summary> /// <param name="oneOrMany">The values.</param> /// <returns> /// The result of the conversion. /// </returns> #pragma warning disable CA2225 // Operator overloads have named alternates public static implicit operator T?(OneOrMany<T> oneOrMany) => oneOrMany.FirstOrDefault(); #pragma warning restore CA2225 // Operator overloads have named alternates /// <summary> /// Performs an implicit conversion from <see cref="OneOrMany{T}"/> to <typeparamref name="T[]"/>. /// </summary> /// <param name="oneOrMany">The values.</param> /// <returns> /// The result of the conversion. /// </returns> #pragma warning disable CA2225 // Operator overloads have named alternates public static implicit operator T[](OneOrMany<T> oneOrMany) => oneOrMany.ToArray(); #pragma warning restore CA2225 // Operator overloads have named alternates /// <summary> /// Performs an implicit conversion from <see cref="OneOrMany{T}"/> to <see cref="List{T}"/>. /// </summary> /// <param name="oneOrMany">The values.</param> /// <returns> /// The result of the conversion. /// </returns> #pragma warning disable CA2225 // Operator overloads have named alternates #pragma warning disable CA1002 // Do not expose generic lists public static implicit operator List<T>(OneOrMany<T> oneOrMany) => oneOrMany.ToList(); #pragma warning restore CA1002 // Do not expose generic lists #pragma warning restore CA2225 // Operator overloads have named alternates /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(OneOrMany<T> left, OneOrMany<T> right) => left.Equals(right); /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(OneOrMany<T> left, OneOrMany<T> right) => !(left == right); /// <summary> /// Returns an enumerator that iterates through the <see cref="OneOrMany{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="OneOrMany{T}"/>.</returns> public IEnumerator<T> GetEnumerator() { if (this.collection is not null) { for (var i = 0; i < this.collection.Length; i++) { yield return this.collection[i]; } } } /// <summary> /// Returns an enumerator that iterates through the <see cref="OneOrMany{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="OneOrMany{T}"/>.</returns> IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); /// <summary> /// Creates an array from <see cref="OneOrMany{T}" />. /// </summary> /// <returns>An array containing all the elements.</returns> public T[] ToArray() { if (this.HasOne) { return new[] { this.collection![0] }; } else if (this.HasMany) { var result = new T[this.collection!.Length]; Array.Copy(this.collection, 0, result, 0, this.collection.Length); return result; } else { return Array.Empty<T>(); } } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. /// </returns> public bool Equals(OneOrMany<T> other) { if (!this.HasOne && !other.HasOne && !this.HasMany && !other.HasMany) { return true; } else if (this.HasOne && other.HasOne) { return Equals(this.collection![0], other.collection![0]); } else if (this.HasMany && other.HasMany) { if (this.collection!.Length != other.collection!.Length) { return false; } for (var i = 0; i < this.collection.Length; i++) { if (!EqualityComparer<T>.Default.Equals(this.collection[i], other.collection[i])) { return false; } } return true; } return false; } /// <summary> /// Determines whether the specified <see cref="object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object? obj) => obj is OneOrMany<T> oneOrMany && this.Equals(oneOrMany); /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() => HashCode.OfEach(this.collection); }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using ICSharpCode.SharpZipLib.BZip2; using QuantConnect.Data.Market; using QuantConnect.Logging; using QuantConnect.Util; namespace QuantConnect.ToolBox.AlgoSeekOptionsConverter { using Processors = Dictionary<Symbol, List<AlgoSeekOptionsProcessor>>; /// <summary> /// Process a directory of algoseek option files into separate resolutions. /// </summary> public class AlgoSeekOptionsConverter { private string _source; private string _remote; private string _remoteMask; private string _destination; private Resolution _resolution; private DateTime _referenceDate; private readonly ParallelOptions parallelOptionsProcessing = new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount}; private readonly ParallelOptions parallelOptionsZipping = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 5 }; /// <summary> /// Create a new instance of the AlgoSeekOptions Converter. Parse a single input directory into an output. /// </summary> /// <param name="resolution">Convert this resolution</param> /// <param name="referenceDate">Datetime to be added to the milliseconds since midnight. Algoseek data is stored in channel files (XX.bz2) and in a source directory</param> /// <param name="source">Remote directory of the .bz algoseek files</param> /// <param name="source">Source directory of the .csv algoseek files</param> /// <param name="destination">Data directory of LEAN</param> public AlgoSeekOptionsConverter(Resolution resolution, DateTime referenceDate, string remote, string remoteMask, string source, string destination) { _remote = remote; _remoteMask = remoteMask; _source = source; _referenceDate = referenceDate; _destination = destination; _resolution = resolution; } /// <summary> /// Give the reference date and source directory, convert the algoseek options data into n-resolutions LEAN format. /// </summary> /// <param name="symbolFilter">HashSet of symbols as string to process. *Only used for testing*</param> public void Convert(HashSet<string> symbolFilter = null) { //Get the list of all the files, then for each file open a separate streamer. var compressedRawDatafiles = Directory.EnumerateFiles(_remote, _remoteMask).Select(f => new FileInfo(f)).ToList(); var rawDatafiles = new List<FileInfo>(); Log.Trace("AlgoSeekOptionsConverter.Convert(): Loading {0} AlgoSeekOptionsReader for {1} ", compressedRawDatafiles.Count, _referenceDate); //Initialize parameters var totalLinesProcessed = 0L; var totalFiles = compressedRawDatafiles.Count; var totalFilesProcessed = 0; var start = DateTime.MinValue; foreach (var compressedRawDatafile in compressedRawDatafiles) { var counter = 1; var timer = DateTime.UtcNow; var rawDataFile = new FileInfo(Path.Combine(_source, compressedRawDatafile.Name.Replace(".bz2", ""))); var decompressSuccessful = false; do { var attempt = counter == 1 ? string.Empty : $" attempt {counter} of 3"; Log.Trace($"AlgoSeekOptionsConverter.Convert(): Extracting {compressedRawDatafile.Name}{attempt}."); decompressSuccessful = DecompressOpraFile(compressedRawDatafile, rawDataFile); counter++; } while (!decompressSuccessful && counter <= 3); if (!decompressSuccessful) { Log.Error($"Error decompressing {compressedRawDatafile}. Process Stop."); throw new NotImplementedException(); } Log.Trace($"AlgoSeekOptionsConverter.Convert(): Extraction successful in {DateTime.UtcNow - timer:g}."); rawDatafiles.Add(rawDataFile); } //Process each file massively in parallel. Parallel.ForEach(rawDatafiles, parallelOptionsProcessing, rawDataFile => { Log.Trace("Source File :" + rawDataFile.Name); // setting up local processors and the flush event var processors = new Processors(); var waitForFlush = new ManualResetEvent(true); // symbol filters // var symbolFilterNames = new string[] { "AAPL", "TWX", "NWSA", "FOXA", "AIG", "EGLE", "EGEC" }; // var symbolFilter = symbolFilterNames.SelectMany(name => new[] { name, name + "1", name + ".1" }).ToHashSet(); // var reader = new AlgoSeekOptionsReader(csvFile, _referenceDate, symbolFilter); using (var reader = new AlgoSeekOptionsReader(rawDataFile.FullName, _referenceDate, symbolFilter)) { if (start == DateTime.MinValue) { start = DateTime.Now; } var flushStep = TimeSpan.FromMinutes(10); if (reader.Current != null) // reader contains the data { var previousFlush = reader.Current.Time.RoundDown(flushStep); do { var tick = reader.Current as Tick; //If the next minute has clocked over; flush the consolidators; serialize and store data to disk. if (tick.Time.RoundDown(flushStep) > previousFlush) { previousFlush = WriteToDisk(processors, waitForFlush, tick.Time, flushStep); processors = new Processors(); } //Add or create the consolidator-flush mechanism for symbol: List<AlgoSeekOptionsProcessor> symbolProcessors; if (!processors.TryGetValue(tick.Symbol, out symbolProcessors)) { symbolProcessors = new List<AlgoSeekOptionsProcessor>(3) { new AlgoSeekOptionsProcessor(tick.Symbol, _referenceDate, TickType.Trade, _resolution, _destination), new AlgoSeekOptionsProcessor(tick.Symbol, _referenceDate, TickType.Quote, _resolution, _destination), new AlgoSeekOptionsProcessor(tick.Symbol, _referenceDate, TickType.OpenInterest, _resolution, _destination) }; processors[tick.Symbol] = symbolProcessors; } // Pass current tick into processor: enum 0 = trade; 1 = quote, , 2 = oi symbolProcessors[(int)tick.TickType].Process(tick); if (Interlocked.Increment(ref totalLinesProcessed) % 1000000m == 0) { Log.Trace( "AlgoSeekOptionsConverter.Convert(): Processed {0,3}M ticks( {1}k / sec); Memory in use: {2} MB; Total progress: {3}%", Math.Round(totalLinesProcessed / 1000000m, 2), Math.Round(totalLinesProcessed / 1000L / (DateTime.Now - start).TotalSeconds), Process.GetCurrentProcess().WorkingSet64 / (1024 * 1024), 100 * totalFilesProcessed / totalFiles); } } while (reader.MoveNext()); Log.Trace("AlgoSeekOptionsConverter.Convert(): Performing final flush to disk... "); Flush(processors, DateTime.MaxValue, true); WriteToDisk(processors, waitForFlush, DateTime.MaxValue, flushStep, true); } Log.Trace("AlgoSeekOptionsConverter.Convert(): Cleaning up extracted options file {0}", rawDataFile.FullName); } rawDataFile.Delete(); processors = null; Log.Trace("AlgoSeekOptionsConverter.Convert(): Finished processing file: " + rawDataFile); Interlocked.Increment(ref totalFilesProcessed); }); } /// <summary> /// Write the processor queues to disk /// </summary> /// <param name="peekTickTime">Time of the next tick in the stream</param> /// <param name="step">Period between flushes to disk</param> /// <param name="final">Final push to disk</param> /// <returns></returns> private DateTime WriteToDisk(Processors processors, ManualResetEvent waitForFlush, DateTime peekTickTime, TimeSpan step, bool final = false) { waitForFlush.WaitOne(); waitForFlush.Reset(); Flush(processors, peekTickTime, final); Task.Run(() => { try { foreach (var type in Enum.GetValues(typeof(TickType))) { var tickType = type; var groups = processors.Values.Select(x => x[(int)tickType]).Where(x => x.Queue.Count > 0).GroupBy(process => process.Symbol.Underlying.Value); Parallel.ForEach(groups, group => { string zip = string.Empty; try { var symbol = group.Key; zip = group.First().ZipPath.Replace(".zip", string.Empty); foreach (var processor in group) { var tempFileName = Path.Combine(zip, processor.EntryPath); Directory.CreateDirectory(zip); File.AppendAllText(tempFileName, FileBuilder(processor)); } } catch (Exception err) { Log.Error("AlgoSeekOptionsConverter.WriteToDisk() returned error: " + err.Message + " zip name: " + zip); } }); } } catch (Exception err) { Log.Error("AlgoSeekOptionsConverter.WriteToDisk() returned error: " + err.Message); } waitForFlush.Set(); }); //Pause while writing the final flush. if (final) waitForFlush.WaitOne(); return peekTickTime.RoundDown(step); } /// <summary> /// Output a list of basedata objects into a string csv line. /// </summary> /// <param name="processor"></param> /// <returns></returns> private string FileBuilder(AlgoSeekOptionsProcessor processor) { var sb = new StringBuilder(); foreach (var data in processor.Queue) { sb.AppendLine(LeanData.GenerateLine(data, SecurityType.Option, processor.Resolution)); } return sb.ToString(); } private void Flush(Processors processors, DateTime time, bool final) { foreach (var symbol in processors.Keys) { processors[symbol].ForEach(x => x.FlushBuffer(time, final)); } } /// <summary> /// Compress the queue buffers directly to a zip file. Lightening fast as streaming ram-> compressed zip. /// </summary> public void Package(DateTime date) { Log.Trace("AlgoSeekOptionsConverter.Package(): Zipping all files ..."); var destination = Path.Combine(_destination, "option"); var dateMask = date.ToStringInvariant(DateFormat.EightCharacter); var files = Directory.EnumerateFiles(destination, dateMask + "*.csv", SearchOption.AllDirectories) .GroupBy(x => Directory.GetParent(x).FullName); //Zip each file massively in parallel. Parallel.ForEach(files, file => { try { var outputFileName = file.Key + ".zip"; // Create and open a new ZIP file var filesToCompress = Directory.GetFiles(file.Key, "*.csv", SearchOption.AllDirectories); using (var zip = ZipFile.Open(outputFileName, ZipArchiveMode.Create)) { Log.Trace("AlgoSeekOptionsConverter.Package(): Zipping " + outputFileName); foreach (var fileToCompress in filesToCompress) { // Add the entry for each file zip.CreateEntryFromFile(fileToCompress, Path.GetFileName(fileToCompress), CompressionLevel.Optimal); } } try { Directory.Delete(file.Key, true); } catch (Exception err) { Log.Error("AlgoSeekOptionsConverter.Package(): Directory.Delete returned error: " + err.Message); } } catch (Exception err) { Log.Error("File: {0} Err: {1} Source {2} Stack {3}", file, err.Message, err.Source, err.StackTrace); } }); } /// <summary> /// Cleans zip archives and source data folders before run /// </summary> public void Clean(DateTime date) { Log.Trace("AlgoSeekOptionsConverter.Clean(): cleaning all zip and csv files for {0} before start...", date.ToShortDateString()); var extensions = new HashSet<string> { ".zip", ".csv" }; var destination = Path.Combine(_destination, "option"); Directory.CreateDirectory(destination); var dateMask = date.ToStringInvariant(DateFormat.EightCharacter); var files = Directory.EnumerateFiles(destination, dateMask + "_" + "*.*", SearchOption.AllDirectories) .Where(x => extensions.Contains(Path.GetExtension(x))) .ToList(); Log.Trace("AlgoSeekOptionsConverter.Clean(): found {0} files..", files.Count); //Clean each file massively in parallel. Parallel.ForEach(files, parallelOptionsZipping, file => { try { File.Delete(file); } catch (Exception err) { Log.Error("AlgoSeekOptionsConverter.Clean(): File.Delete returned error: " + err.Message); } }); } /// <summary> /// Decompress huge AlgoSeek's opra bz2 files and returns the outcome status. /// </summary> /// <param name="compressedRawDatafile">Fileinfo of the compressed orpa file.</param> /// <param name="rawDatafile">Fileinfo of the uncompressed output file.</param> /// <returns>Boolean indicating if this the process was successful.</returns> /// <remarks>Public static members of the SharpZipLib.BZip2 type are safe for multithreaded operations. /// Source: https://documentation.help/SharpZip/ICSharpCode.SharpZipLib.BZip2.BZip2.html /// </remarks>> private static bool DecompressOpraFile(FileInfo compressedRawDatafile, FileInfo rawDatafile) { var outcome = false; using (FileStream fileToDecompressAsStream = compressedRawDatafile.OpenRead()) using (FileStream decompressedStream = File.Create(rawDatafile.FullName)) { try { BZip2.Decompress(fileToDecompressAsStream, decompressedStream, false); outcome = true; } catch (Exception ex) { Log.Error($"AlgoSeekOptionsConverter.DecompressOpraFile({compressedRawDatafile.Name}, {rawDatafile.Name}): SharpzipLib.BZip2.Decompress returned error: " + ex); } } return outcome; } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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.IO; using System.Text; namespace Google.ProtocolBuffers { /// <summary> /// Encodes and writes protocol message fields. /// </summary> /// <remarks> /// This class contains two kinds of methods: methods that write specific /// protocol message constructs and field types (e.g. WriteTag and /// WriteInt32) and methods that write low-level values (e.g. /// WriteRawVarint32 and WriteRawBytes). If you are writing encoded protocol /// messages, you should use the former methods, but if you are writing some /// other format of your own design, use the latter. The names of the former /// methods are taken from the protocol buffer type names, not .NET types. /// (Hence WriteFloat instead of WriteSingle, and WriteBool instead of WriteBoolean.) /// </remarks> public sealed class CodedOutputStream { /// <summary> /// The buffer size used by CreateInstance(Stream). /// </summary> public static readonly int DefaultBufferSize = 4096; private readonly byte[] buffer; private readonly int limit; private int position; private readonly Stream output; #region Construction private CodedOutputStream(byte[] buffer, int offset, int length) { this.output = null; this.buffer = buffer; this.position = offset; this.limit = offset + length; } private CodedOutputStream(Stream output, byte[] buffer) { this.output = output; this.buffer = buffer; this.position = 0; this.limit = buffer.Length; } /// <summary> /// Creates a new CodedOutputStream which write to the given stream. /// </summary> public static CodedOutputStream CreateInstance(Stream output) { return CreateInstance(output, DefaultBufferSize); } /// <summary> /// Creates a new CodedOutputStream which write to the given stream and uses /// the specified buffer size. /// </summary> public static CodedOutputStream CreateInstance(Stream output, int bufferSize) { return new CodedOutputStream(output, new byte[bufferSize]); } /// <summary> /// Creates a new CodedOutputStream that writes directly to the given /// byte array. If more bytes are written than fit in the array, /// OutOfSpaceException will be thrown. /// </summary> public static CodedOutputStream CreateInstance(byte[] flatArray) { return CreateInstance(flatArray, 0, flatArray.Length); } /// <summary> /// Creates a new CodedOutputStream that writes directly to the given /// byte array slice. If more bytes are written than fit in the array, /// OutOfSpaceException will be thrown. /// </summary> public static CodedOutputStream CreateInstance(byte[] flatArray, int offset, int length) { return new CodedOutputStream(flatArray, offset, length); } #endregion #region Writing of tags etc /// <summary> /// Writes a double field value, including tag, to the stream. /// </summary> public void WriteDouble(int fieldNumber, double value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteDoubleNoTag(value); } /// <summary> /// Writes a float field value, including tag, to the stream. /// </summary> public void WriteFloat(int fieldNumber, float value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteFloatNoTag(value); } /// <summary> /// Writes a uint64 field value, including tag, to the stream. /// </summary> public void WriteUInt64(int fieldNumber, ulong value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64(value); } /// <summary> /// Writes an int64 field value, including tag, to the stream. /// </summary> public void WriteInt64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64((ulong)value); } /// <summary> /// Writes an int32 field value, including tag, to the stream. /// </summary> public void WriteInt32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); if (value >= 0) { WriteRawVarint32((uint)value); } else { // Must sign-extend. WriteRawVarint64((ulong)value); } } /// <summary> /// Writes a fixed64 field value, including tag, to the stream. /// </summary> public void WriteFixed64(int fieldNumber, ulong value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteRawLittleEndian64(value); } /// <summary> /// Writes a fixed32 field value, including tag, to the stream. /// </summary> public void WriteFixed32(int fieldNumber, uint value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteRawLittleEndian32(value); } /// <summary> /// Writes a bool field value, including tag, to the stream. /// </summary> public void WriteBool(int fieldNumber, bool value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawByte(value ? (byte)1 : (byte)0); } /// <summary> /// Writes a string field value, including tag, to the stream. /// </summary> public void WriteString(int fieldNumber, string value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); // Optimise the case where we have enough space to write // the string directly to the buffer, which should be common. int length = Encoding.UTF8.GetByteCount(value); WriteRawVarint32((uint) length); if (limit - position >= length) { Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position); position += length; } else { byte[] bytes = Encoding.UTF8.GetBytes(value); WriteRawBytes(bytes); } } /*ZWL /// <summary> /// Writes a group field value, including tag, to the stream. /// </summary> public void WriteGroup(int fieldNumber, IMessageLite value) { WriteTag(fieldNumber, WireFormat.WireType.StartGroup); value.WriteTo(this); WriteTag(fieldNumber, WireFormat.WireType.EndGroup); } [Obsolete] public void WriteUnknownGroup(int fieldNumber, IMessageLite value) { WriteTag(fieldNumber, WireFormat.WireType.StartGroup); value.WriteTo(this); WriteTag(fieldNumber, WireFormat.WireType.EndGroup); } public void WriteMessage(int fieldNumber, IMessageLite value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32((uint)value.SerializedSize); value.WriteTo(this); } ZWL*/ public void WriteBytes(int fieldNumber, ByteString value) { // TODO(jonskeet): Optimise this! (No need to copy the bytes twice.) WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); byte[] bytes = value.ToByteArray(); WriteRawVarint32((uint)bytes.Length); WriteRawBytes(bytes); } public void WriteUInt32(int fieldNumber, uint value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32(value); } public void WriteEnum(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32((uint)value); } public void WriteSFixed32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteRawLittleEndian32((uint)value); } public void WriteSFixed64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteRawLittleEndian64((ulong)value); } public void WriteSInt32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32(EncodeZigZag32(value)); } public void WriteSInt64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64(EncodeZigZag64(value)); } /*ZWL public void WriteMessageSetExtension(int fieldNumber, IMessageLite value) { WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup); WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber); WriteMessage(WireFormat.MessageSetField.Message, value); WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup); } public void WriteRawMessageSetExtension(int fieldNumber, ByteString value) { WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup); WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber); WriteBytes(WireFormat.MessageSetField.Message, value); WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup); } public void WriteField(FieldType fieldType, int fieldNumber, object value) { switch (fieldType) { case FieldType.Double: WriteDouble(fieldNumber, (double)value); break; case FieldType.Float: WriteFloat(fieldNumber, (float)value); break; case FieldType.Int64: WriteInt64(fieldNumber, (long)value); break; case FieldType.UInt64: WriteUInt64(fieldNumber, (ulong)value); break; case FieldType.Int32: WriteInt32(fieldNumber, (int)value); break; case FieldType.Fixed64: WriteFixed64(fieldNumber, (ulong)value); break; case FieldType.Fixed32: WriteFixed32(fieldNumber, (uint)value); break; case FieldType.Bool: WriteBool(fieldNumber, (bool)value); break; case FieldType.String: WriteString(fieldNumber, (string)value); break; case FieldType.Group: WriteGroup(fieldNumber, (IMessageLite)value); break; case FieldType.Message: WriteMessage(fieldNumber, (IMessageLite)value); break; case FieldType.Bytes: WriteBytes(fieldNumber, (ByteString)value); break; case FieldType.UInt32: WriteUInt32(fieldNumber, (uint)value); break; case FieldType.SFixed32: WriteSFixed32(fieldNumber, (int)value); break; case FieldType.SFixed64: WriteSFixed64(fieldNumber, (long)value); break; case FieldType.SInt32: WriteSInt32(fieldNumber, (int)value); break; case FieldType.SInt64: WriteSInt64(fieldNumber, (long)value); break; case FieldType.Enum: WriteEnum(fieldNumber, ((IEnumLite)value).Number); break; } } public void WriteFieldNoTag(FieldType fieldType, object value) { switch (fieldType) { case FieldType.Double: WriteDoubleNoTag((double)value); break; case FieldType.Float: WriteFloatNoTag((float)value); break; case FieldType.Int64: WriteInt64NoTag((long)value); break; case FieldType.UInt64: WriteUInt64NoTag((ulong)value); break; case FieldType.Int32: WriteInt32NoTag((int)value); break; case FieldType.Fixed64: WriteFixed64NoTag((ulong)value); break; case FieldType.Fixed32: WriteFixed32NoTag((uint)value); break; case FieldType.Bool: WriteBoolNoTag((bool)value); break; case FieldType.String: WriteStringNoTag((string)value); break; case FieldType.Group: WriteGroupNoTag((IMessageLite)value); break; case FieldType.Message: WriteMessageNoTag((IMessageLite)value); break; case FieldType.Bytes: WriteBytesNoTag((ByteString)value); break; case FieldType.UInt32: WriteUInt32NoTag((uint)value); break; case FieldType.SFixed32: WriteSFixed32NoTag((int)value); break; case FieldType.SFixed64: WriteSFixed64NoTag((long)value); break; case FieldType.SInt32: WriteSInt32NoTag((int)value); break; case FieldType.SInt64: WriteSInt64NoTag((long)value); break; case FieldType.Enum: WriteEnumNoTag(((IEnumLite)value).Number); break; } } ZWL*/ #endregion #region Writing of values without tags /// <summary> /// Writes a double field value, including tag, to the stream. /// </summary> public void WriteDoubleNoTag(double value) { // TODO(jonskeet): Test this on different endiannesses #if SILVERLIGHT2 || COMPACT_FRAMEWORK_35 byte[] bytes = BitConverter.GetBytes(value); WriteRawBytes(bytes, 0, 8); #else WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value)); #endif } /// <summary> /// Writes a float field value, without a tag, to the stream. /// </summary> public void WriteFloatNoTag(float value) { // TODO(jonskeet): Test this on different endiannesses byte[] rawBytes = BitConverter.GetBytes(value); uint asInteger = BitConverter.ToUInt32(rawBytes, 0); WriteRawLittleEndian32(asInteger); } /// <summary> /// Writes a uint64 field value, without a tag, to the stream. /// </summary> public void WriteUInt64NoTag(ulong value) { WriteRawVarint64(value); } /// <summary> /// Writes an int64 field value, without a tag, to the stream. /// </summary> public void WriteInt64NoTag(long value) { WriteRawVarint64((ulong)value); } /// <summary> /// Writes an int32 field value, without a tag, to the stream. /// </summary> public void WriteInt32NoTag(int value) { if (value >= 0) { WriteRawVarint32((uint)value); } else { // Must sign-extend. WriteRawVarint64((ulong)value); } } /// <summary> /// Writes a fixed64 field value, without a tag, to the stream. /// </summary> public void WriteFixed64NoTag(ulong value) { WriteRawLittleEndian64(value); } /// <summary> /// Writes a fixed32 field value, without a tag, to the stream. /// </summary> public void WriteFixed32NoTag(uint value) { WriteRawLittleEndian32(value); } /// <summary> /// Writes a bool field value, without a tag, to the stream. /// </summary> public void WriteBoolNoTag(bool value) { WriteRawByte(value ? (byte)1 : (byte)0); } /// <summary> /// Writes a string field value, without a tag, to the stream. /// </summary> public void WriteStringNoTag(string value) { // Optimise the case where we have enough space to write // the string directly to the buffer, which should be common. int length = Encoding.UTF8.GetByteCount(value); WriteRawVarint32((uint)length); if (limit - position >= length) { Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position); position += length; } else { byte[] bytes = Encoding.UTF8.GetBytes(value); WriteRawBytes(bytes); } } /*ZWL /// <summary> /// Writes a group field value, without a tag, to the stream. /// </summary> public void WriteGroupNoTag(IMessageLite value) { value.WriteTo(this); } public void WriteMessageNoTag(IMessageLite value) { WriteRawVarint32((uint)value.SerializedSize); value.WriteTo(this); } ZWL */ public void WriteBytesNoTag(ByteString value) { // TODO(jonskeet): Optimise this! (No need to copy the bytes twice.) byte[] bytes = value.ToByteArray(); WriteRawVarint32((uint)bytes.Length); WriteRawBytes(bytes); } public void WriteUInt32NoTag(uint value) { WriteRawVarint32(value); } public void WriteEnumNoTag(int value) { WriteRawVarint32((uint)value); } public void WriteSFixed32NoTag(int value) { WriteRawLittleEndian32((uint)value); } public void WriteSFixed64NoTag(long value) { WriteRawLittleEndian64((ulong)value); } public void WriteSInt32NoTag(int value) { WriteRawVarint32(EncodeZigZag32(value)); } public void WriteSInt64NoTag(long value) { WriteRawVarint64(EncodeZigZag64(value)); } #endregion #region Underlying writing primitives /// <summary> /// Encodes and writes a tag. /// </summary> public void WriteTag(int fieldNumber, WireFormat.WireType type) { WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type)); } private void SlowWriteRawVarint32(uint value) { while (true) { if ((value & ~0x7F) == 0) { WriteRawByte(value); return; } else { WriteRawByte((value & 0x7F) | 0x80); value >>= 7; } } } /// <summary> /// Writes a 32 bit value as a varint. The fast route is taken when /// there's enough buffer space left to whizz through without checking /// for each byte; otherwise, we resort to calling WriteRawByte each time. /// </summary> public void WriteRawVarint32(uint value) { if (position + 5 > limit) { SlowWriteRawVarint32(value); return; } while (true) { if ((value & ~0x7F) == 0) { buffer[position++] = (byte) value; return; } else { buffer[position++] = (byte)((value & 0x7F) | 0x80); value >>= 7; } } } public void WriteRawVarint64(ulong value) { while (true) { if ((value & ~0x7FUL) == 0) { WriteRawByte((uint)value); return; } else { WriteRawByte(((uint)value & 0x7F) | 0x80); value >>= 7; } } } public void WriteRawLittleEndian32(uint value) { WriteRawByte((byte)value); WriteRawByte((byte)(value >> 8)); WriteRawByte((byte)(value >> 16)); WriteRawByte((byte)(value >> 24)); } public void WriteRawLittleEndian64(ulong value) { WriteRawByte((byte)value); WriteRawByte((byte)(value >> 8)); WriteRawByte((byte)(value >> 16)); WriteRawByte((byte)(value >> 24)); WriteRawByte((byte)(value >> 32)); WriteRawByte((byte)(value >> 40)); WriteRawByte((byte)(value >> 48)); WriteRawByte((byte)(value >> 56)); } public void WriteRawByte(byte value) { if (position == limit) { RefreshBuffer(); } buffer[position++] = value; } public void WriteRawByte(uint value) { WriteRawByte((byte)value); } /// <summary> /// Writes out an array of bytes. /// </summary> public void WriteRawBytes(byte[] value) { WriteRawBytes(value, 0, value.Length); } /// <summary> /// Writes out part of an array of bytes. /// </summary> public void WriteRawBytes(byte[] value, int offset, int length) { if (limit - position >= length) { Array.Copy(value, offset, buffer, position, length); // We have room in the current buffer. position += length; } else { // Write extends past current buffer. Fill the rest of this buffer and // flush. int bytesWritten = limit - position; Array.Copy(value, offset, buffer, position, bytesWritten); offset += bytesWritten; length -= bytesWritten; position = limit; RefreshBuffer(); // Now deal with the rest. // Since we have an output stream, this is our buffer // and buffer offset == 0 if (length <= limit) { // Fits in new buffer. Array.Copy(value, offset, buffer, 0, length); position = length; } else { // Write is very big. Let's do it all at once. output.Write(value, offset, length); } } } #endregion #region Size computations const int LittleEndian64Size = 8; const int LittleEndian32Size = 4; /// <summary> /// Compute the number of bytes that would be needed to encode a /// double field, including the tag. /// </summary> public static int ComputeDoubleSize(int fieldNumber, double value) { return ComputeTagSize(fieldNumber) + LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// float field, including the tag. /// </summary> public static int ComputeFloatSize(int fieldNumber, float value) { return ComputeTagSize(fieldNumber) + LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint64 field, including the tag. /// </summary> public static int ComputeUInt64Size(int fieldNumber, ulong value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int64 field, including the tag. /// </summary> public static int ComputeInt64Size(int fieldNumber, long value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size((ulong)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int32 field, including the tag. /// </summary> public static int ComputeInt32Size(int fieldNumber, int value) { if (value >= 0) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value); } else { // Must sign-extend. return ComputeTagSize(fieldNumber) + 10; } } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed64 field, including the tag. /// </summary> public static int ComputeFixed64Size(int fieldNumber, ulong value) { return ComputeTagSize(fieldNumber) + LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed32 field, including the tag. /// </summary> public static int ComputeFixed32Size(int fieldNumber, uint value) { return ComputeTagSize(fieldNumber) + LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// bool field, including the tag. /// </summary> public static int ComputeBoolSize(int fieldNumber, bool value) { return ComputeTagSize(fieldNumber) + 1; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// string field, including the tag. /// </summary> public static int ComputeStringSize(int fieldNumber, String value) { int byteArraySize = Encoding.UTF8.GetByteCount(value); return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)byteArraySize) + byteArraySize; } /*ZWL /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field, including the tag. /// </summary> public static int ComputeGroupSize(int fieldNumber, IMessageLite value) { return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field represented by an UnknownFieldSet, including the tag. /// </summary> [Obsolete] public static int ComputeUnknownGroupSize(int fieldNumber, IMessageLite value) { return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// embedded message field, including the tag. /// </summary> public static int ComputeMessageSize(int fieldNumber, IMessageLite value) { int size = value.SerializedSize; return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)size) + size; } ZWL*/ /// <summary> /// Compute the number of bytes that would be needed to encode a /// bytes field, including the tag. /// </summary> public static int ComputeBytesSize(int fieldNumber, ByteString value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value.Length) + value.Length; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint32 field, including the tag. /// </summary> public static int ComputeUInt32Size(int fieldNumber, uint value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode a /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// </summary> public static int ComputeEnumSize(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed32 field, including the tag. /// </summary> public static int ComputeSFixed32Size(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed64 field, including the tag. /// </summary> public static int ComputeSFixed64Size(int fieldNumber, long value) { return ComputeTagSize(fieldNumber) + LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint32 field, including the tag. /// </summary> public static int ComputeSInt32Size(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(EncodeZigZag32(value)); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint64 field, including the tag. /// </summary> public static int ComputeSInt64Size(int fieldNumber, long value) { return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(EncodeZigZag64(value)); } /// <summary> /// Compute the number of bytes that would be needed to encode a /// double field, including the tag. /// </summary> public static int ComputeDoubleSizeNoTag(double value) { return LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// float field, including the tag. /// </summary> public static int ComputeFloatSizeNoTag(float value) { return LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint64 field, including the tag. /// </summary> public static int ComputeUInt64SizeNoTag(ulong value) { return ComputeRawVarint64Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int64 field, including the tag. /// </summary> public static int ComputeInt64SizeNoTag(long value) { return ComputeRawVarint64Size((ulong)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// int32 field, including the tag. /// </summary> public static int ComputeInt32SizeNoTag(int value) { if (value >= 0) { return ComputeRawVarint32Size((uint)value); } else { // Must sign-extend. return 10; } } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed64 field, including the tag. /// </summary> public static int ComputeFixed64SizeNoTag(ulong value) { return LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// fixed32 field, including the tag. /// </summary> public static int ComputeFixed32SizeNoTag(uint value) { return LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// bool field, including the tag. /// </summary> public static int ComputeBoolSizeNoTag(bool value) { return 1; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// string field, including the tag. /// </summary> public static int ComputeStringSizeNoTag(String value) { int byteArraySize = Encoding.UTF8.GetByteCount(value); return ComputeRawVarint32Size((uint)byteArraySize) + byteArraySize; } /* /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field, including the tag. /// </summary> public static int ComputeGroupSizeNoTag(IMessageLite value) { return value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// group field represented by an UnknownFieldSet, including the tag. /// </summary> [Obsolete] public static int ComputeUnknownGroupSizeNoTag(IMessageLite value) { return value.SerializedSize; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// embedded message field, including the tag. /// </summary> public static int ComputeMessageSizeNoTag(IMessageLite value) { int size = value.SerializedSize; return ComputeRawVarint32Size((uint)size) + size; } */ /// <summary> /// Compute the number of bytes that would be needed to encode a /// bytes field, including the tag. /// </summary> public static int ComputeBytesSizeNoTag(ByteString value) { return ComputeRawVarint32Size((uint)value.Length) + value.Length; } /// <summary> /// Compute the number of bytes that would be needed to encode a /// uint32 field, including the tag. /// </summary> public static int ComputeUInt32SizeNoTag(uint value) { return ComputeRawVarint32Size(value); } /// <summary> /// Compute the number of bytes that would be needed to encode a /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// </summary> public static int ComputeEnumSizeNoTag(int value) { return ComputeRawVarint32Size((uint)value); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed32 field, including the tag. /// </summary> public static int ComputeSFixed32SizeNoTag(int value) { return LittleEndian32Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sfixed64 field, including the tag. /// </summary> public static int ComputeSFixed64SizeNoTag(long value) { return LittleEndian64Size; } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint32 field, including the tag. /// </summary> public static int ComputeSInt32SizeNoTag(int value) { return ComputeRawVarint32Size(EncodeZigZag32(value)); } /// <summary> /// Compute the number of bytes that would be needed to encode an /// sint64 field, including the tag. /// </summary> public static int ComputeSInt64SizeNoTag(long value) { return ComputeRawVarint64Size(EncodeZigZag64(value)); } /* * Compute the number of bytes that would be needed to encode a * MessageSet extension to the stream. For historical reasons, * the wire format differs from normal fields. */ /// <summary> /// Compute the number of bytes that would be needed to encode a /// MessageSet extension to the stream. For historical reasons, /// the wire format differs from normal fields. /// </summary> /*ZWL public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessageLite value) { return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 + ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) + ComputeMessageSize(WireFormat.MessageSetField.Message, value); } ZWL*/ /// <summary> /// Compute the number of bytes that would be needed to encode an /// unparsed MessageSet extension field to the stream. For /// historical reasons, the wire format differs from normal fields. /// </summary> public static int ComputeRawMessageSetExtensionSize(int fieldNumber, ByteString value) { return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 + ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) + ComputeBytesSize(WireFormat.MessageSetField.Message, value); } /// <summary> /// Compute the number of bytes that would be needed to encode a varint. /// </summary> public static int ComputeRawVarint32Size(uint value) { if ((value & (0xffffffff << 7)) == 0) return 1; if ((value & (0xffffffff << 14)) == 0) return 2; if ((value & (0xffffffff << 21)) == 0) return 3; if ((value & (0xffffffff << 28)) == 0) return 4; return 5; } /// <summary> /// Compute the number of bytes that would be needed to encode a varint. /// </summary> public static int ComputeRawVarint64Size(ulong value) { if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; return 10; } /* /// <summary> /// Compute the number of bytes that would be needed to encode a /// field of arbitrary type, including the tag, to the stream. /// </summary> public static int ComputeFieldSize(FieldType fieldType, int fieldNumber, Object value) { switch (fieldType) { case FieldType.Double: return ComputeDoubleSize(fieldNumber, (double)value); case FieldType.Float: return ComputeFloatSize(fieldNumber, (float)value); case FieldType.Int64: return ComputeInt64Size(fieldNumber, (long)value); case FieldType.UInt64: return ComputeUInt64Size(fieldNumber, (ulong)value); case FieldType.Int32: return ComputeInt32Size(fieldNumber, (int)value); case FieldType.Fixed64: return ComputeFixed64Size(fieldNumber, (ulong)value); case FieldType.Fixed32: return ComputeFixed32Size(fieldNumber, (uint)value); case FieldType.Bool: return ComputeBoolSize(fieldNumber, (bool)value); case FieldType.String: return ComputeStringSize(fieldNumber, (string)value); case FieldType.Group: return ComputeGroupSize(fieldNumber, (IMessageLite)value); case FieldType.Message: return ComputeMessageSize(fieldNumber, (IMessageLite)value); case FieldType.Bytes: return ComputeBytesSize(fieldNumber, (ByteString)value); case FieldType.UInt32: return ComputeUInt32Size(fieldNumber, (uint)value); case FieldType.SFixed32: return ComputeSFixed32Size(fieldNumber, (int)value); case FieldType.SFixed64: return ComputeSFixed64Size(fieldNumber, (long)value); case FieldType.SInt32: return ComputeSInt32Size(fieldNumber, (int)value); case FieldType.SInt64: return ComputeSInt64Size(fieldNumber, (long)value); case FieldType.Enum: return ComputeEnumSize(fieldNumber, ((IEnumLite)value).Number); default: throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); } } /// <summary> /// Compute the number of bytes that would be needed to encode a /// field of arbitrary type, excluding the tag, to the stream. /// </summary> public static int ComputeFieldSizeNoTag(FieldType fieldType, Object value) { switch (fieldType) { case FieldType.Double: return ComputeDoubleSizeNoTag((double)value); case FieldType.Float: return ComputeFloatSizeNoTag((float)value); case FieldType.Int64: return ComputeInt64SizeNoTag((long)value); case FieldType.UInt64: return ComputeUInt64SizeNoTag((ulong)value); case FieldType.Int32: return ComputeInt32SizeNoTag((int)value); case FieldType.Fixed64: return ComputeFixed64SizeNoTag((ulong)value); case FieldType.Fixed32: return ComputeFixed32SizeNoTag((uint)value); case FieldType.Bool: return ComputeBoolSizeNoTag((bool)value); case FieldType.String: return ComputeStringSizeNoTag((string)value); case FieldType.Group: return ComputeGroupSizeNoTag((IMessageLite)value); case FieldType.Message: return ComputeMessageSizeNoTag((IMessageLite)value); case FieldType.Bytes: return ComputeBytesSizeNoTag((ByteString)value); case FieldType.UInt32: return ComputeUInt32SizeNoTag((uint)value); case FieldType.SFixed32: return ComputeSFixed32SizeNoTag((int)value); case FieldType.SFixed64: return ComputeSFixed64SizeNoTag((long)value); case FieldType.SInt32: return ComputeSInt32SizeNoTag((int)value); case FieldType.SInt64: return ComputeSInt64SizeNoTag((long)value); case FieldType.Enum: return ComputeEnumSizeNoTag(((IEnumLite)value).Number); default: throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); } } */ /// <summary> /// Compute the number of bytes that would be needed to encode a tag. /// </summary> public static int ComputeTagSize(int fieldNumber) { return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0)); } #endregion /// <summary> /// Encode a 32-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> public static uint EncodeZigZag32(int n) { // Note: the right-shift must be arithmetic return (uint)((n << 1) ^ (n >> 31)); } /// <summary> /// Encode a 64-bit value with ZigZag encoding. /// </summary> /// <remarks> /// ZigZag encodes signed integers into values that can be efficiently /// encoded with varint. (Otherwise, negative values must be /// sign-extended to 64 bits to be varint encoded, thus always taking /// 10 bytes on the wire.) /// </remarks> public static ulong EncodeZigZag64(long n) { return (ulong)((n << 1) ^ (n >> 63)); } private void RefreshBuffer() { if (output == null) { // We're writing to a single buffer. throw new OutOfSpaceException(); } // Since we have an output stream, this is our buffer // and buffer offset == 0 output.Write(buffer, 0, position); position = 0; } /// <summary> /// Indicates that a CodedOutputStream wrapping a flat byte array /// ran out of space. /// </summary> public sealed class OutOfSpaceException : IOException { internal OutOfSpaceException() : base("CodedOutputStream was writing to a flat byte array and ran out of space.") { } } public void Flush() { if (output != null) { RefreshBuffer(); } } /// <summary> /// Verifies that SpaceLeft returns zero. It's common to create a byte array /// that is exactly big enough to hold a message, then write to it with /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that /// the message was actually as big as expected, which can help bugs. /// </summary> public void CheckNoSpaceLeft() { if (SpaceLeft != 0) { throw new InvalidOperationException("Did not write as much data as expected."); } } /// <summary> /// If writing to a flat array, returns the space left in the array. Otherwise, /// throws an InvalidOperationException. /// </summary> public int SpaceLeft { get { if (output == null) { return limit - position; } else { throw new InvalidOperationException( "SpaceLeft can only be called on CodedOutputStreams that are " + "writing to a flat array."); } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { public static partial class ProtectionEntityOperationsExtensions { /// <summary> /// Commit failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginCommitFailover(this IProtectionEntityOperations operations, string pcName, string name, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).BeginCommitFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Commit failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginCommitFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginCommitFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Planned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginPlannedFailover(this IProtectionEntityOperations operations, string pcName, string name, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).BeginPlannedFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Planned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginPlannedFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginPlannedFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Reprotect operation for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginReprotect(this IProtectionEntityOperations operations, string pcName, string name, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).BeginReprotectAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Reprotect operation for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginReprotectAsync(this IProtectionEntityOperations operations, string pcName, string name, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginReprotectAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Test failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginTestFailover(this IProtectionEntityOperations operations, string pcName, string name, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).BeginTestFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginTestFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginTestFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Unplanned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Unplanned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginUnplannedFailover(this IProtectionEntityOperations operations, string pcName, string name, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).BeginUnplannedFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unplanned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Unplanned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginUnplannedFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginUnplannedFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse CommitFailover(this IProtectionEntityOperations operations, string pcName, string name, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).CommitFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> CommitFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.CommitFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Disable Protection for the given protection enity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse DisableProtection(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).DisableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disable Protection for the given protection enity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> DisableProtectionAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return operations.DisableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse EnableProtection(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).EnableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> EnableProtectionAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return operations.EnableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the protection entity object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Vm object. /// </returns> public static ProtectionEntityResponse Get(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetAsync(protectionContainerId, protectionEntityId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the protection entity object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Vm object. /// </returns> public static Task<ProtectionEntityResponse> GetAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(protectionContainerId, protectionEntityId, customRequestHeaders, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static CommitFailoverOperationResponse GetCommitFailoverStatus(this IProtectionEntityOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetCommitFailoverStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<CommitFailoverOperationResponse> GetCommitFailoverStatusAsync(this IProtectionEntityOperations operations, string operationStatusLink) { return operations.GetCommitFailoverStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static PlannedFailoverOperationResponse GetPlannedFailoverStatus(this IProtectionEntityOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetPlannedFailoverStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<PlannedFailoverOperationResponse> GetPlannedFailoverStatusAsync(this IProtectionEntityOperations operations, string operationStatusLink) { return operations.GetPlannedFailoverStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static ReprotectOperationResponse GetReprotectStatus(this IProtectionEntityOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetReprotectStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<ReprotectOperationResponse> GetReprotectStatusAsync(this IProtectionEntityOperations operations, string operationStatusLink) { return operations.GetReprotectStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static TestFailoverOperationResponse GetTestFailoverStatus(this IProtectionEntityOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetTestFailoverStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<TestFailoverOperationResponse> GetTestFailoverStatusAsync(this IProtectionEntityOperations operations, string operationStatusLink) { return operations.GetTestFailoverStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static UnplannedFailoverOperationResponse GetUnplannedFailoverStatus(this IProtectionEntityOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetUnplannedFailoverStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<UnplannedFailoverOperationResponse> GetUnplannedFailoverStatusAsync(this IProtectionEntityOperations operations, string operationStatusLink) { return operations.GetUnplannedFailoverStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Get the list of all protection entities. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Vm operation. /// </returns> public static ProtectionEntityListResponse List(this IProtectionEntityOperations operations, string protectionContainerId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).ListAsync(protectionContainerId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all protection entities. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Vm operation. /// </returns> public static Task<ProtectionEntityListResponse> ListAsync(this IProtectionEntityOperations operations, string protectionContainerId, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(protectionContainerId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse PlannedFailover(this IProtectionEntityOperations operations, string pcName, string name, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).PlannedFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> PlannedFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.PlannedFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Reprotect(this IProtectionEntityOperations operations, string pcName, string name, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).ReprotectAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> ReprotectAsync(this IProtectionEntityOperations operations, string pcName, string name, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.ReprotectAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse TestFailover(this IProtectionEntityOperations operations, string pcName, string name, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).TestFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> TestFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.TestFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Unplanned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse UnplannedFailover(this IProtectionEntityOperations operations, string pcName, string name, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).UnplannedFailoverAsync(pcName, name, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a profile /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='pcName'> /// Required. Parent Protection Container name. /// </param> /// <param name='name'> /// Required. Protection entity name. /// </param> /// <param name='parameters'> /// Required. Unplanned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> UnplannedFailoverAsync(this IProtectionEntityOperations operations, string pcName, string name, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.UnplannedFailoverAsync(pcName, name, parameters, customRequestHeaders, CancellationToken.None); } } }
// Copyright 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.ObjectModel; using System.Data; using System.Data.SqlClient; using SharpMap.Converters.WellKnownBinary; using NetTopologySuite.Geometries; using NetTopologySuite; namespace SharpMap.Data.Providers { /// <summary> /// Microsoft SQL data provider /// </summary> /// <remarks> /// <para> /// The SQL data table MUST contain five data columns: A binary or image column (a Geometry Column) for storing WKB formatted geometries, /// and four real values holding the boundingbox of the geometry. These must be named: Envelope_MinX, Envelope_MinY, Envelope_MaxX and Envelope_MaxY. /// Any extra columns will be returns as feature data. /// </para> /// <para>For creating a valid MS SQL datatable for SharpMap, see <see cref="CreateDataTable"/> /// for creating and uploading a datasource to MS SQL Server.</para> /// <example> /// Adding a datasource to a layer: /// <code lang="C#"> /// SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My layer"); /// string ConnStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|GeoDatabase.mdf;Integrated Security=True;User Instance=True"; /// myLayer.DataSource = new SharpMap.Data.Providers.MsSql(ConnStr, "myTable"); /// </code> /// </example> /// </remarks> [Serializable] [Obsolete("Use MsSqlSpatial provider instead")] public class MsSql : IProvider { private string _ConnectionString; private string _definitionQuery; private string _GeometryColumn; private bool _IsOpen; private string _ObjectIdColumn; private int _srid = -2; private string _Table; private GeometryFactory _factory; /// <summary> /// Gets or sets the geometry factory used to create geometries /// </summary> public GeometryFactory Factory { get { return _factory ?? (_factory = NtsGeometryServices.Instance.CreateGeometryFactory(_srid)); } set { _factory = value; } } /// <summary> /// Initializes a new connection to MS Sql Server /// </summary> /// <param name="ConnectionStr">Connectionstring</param> /// <param name="tablename">Name of data table</param> /// <param name="geometryColumnName">Name of geometry column</param> /// /// <param name="OID_ColumnName">Name of column with unique identifier</param> public MsSql(string ConnectionStr, string tablename, string geometryColumnName, string OID_ColumnName) { ConnectionString = ConnectionStr; Table = tablename; GeometryColumn = geometryColumnName; //Name of column to store geometry ObjectIdColumn = OID_ColumnName; //Name of object ID column } /// <summary> /// Connectionstring /// </summary> public string ConnectionString { get { return _ConnectionString; } set { _ConnectionString = value; } } /// <summary> /// Data table name /// </summary> public string Table { get { return _Table; } set { _Table = value; } } /// <summary> /// Name of geometry column /// </summary> public string GeometryColumn { get { return _GeometryColumn; } set { _GeometryColumn = value; } } /// <summary> /// Name of column that contains the Object ID /// </summary> public string ObjectIdColumn { get { return _ObjectIdColumn; } set { _ObjectIdColumn = value; } } /// <summary> /// Definition query used for limiting dataset /// </summary> public string DefinitionQuery { get { return _definitionQuery; } set { _definitionQuery = value; } } /// <summary> /// Gets a collection of columns in the dataset /// </summary> public DataColumnCollection Columns { get { throw new NotImplementedException(); } } #region IProvider Members /// <summary> /// Returns true if the datasource is currently open /// </summary> public bool IsOpen { get { return _IsOpen; } } /// <summary> /// Opens the datasource /// </summary> public void Open() { //Don't really do anything. mssql's ConnectionPooling takes over here _IsOpen = true; } /// <summary> /// Closes the datasource /// </summary> public void Close() { //Don't really do anything. mssql's ConnectionPooling takes over here _IsOpen = false; } /// <summary> /// Returns geometries within the specified bounding box /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection<Geometry> GetGeometriesInView(Envelope bbox) { var features = new Collection<Geometry>(); using (var conn = new SqlConnection(_ConnectionString)) { string BoxIntersect = GetBoxClause(bbox); string strSQL = "SELECT " + GeometryColumn + " AS Geom "; strSQL += "FROM " + Table + " WHERE "; strSQL += BoxIntersect; if (!string.IsNullOrEmpty(_definitionQuery)) strSQL += " AND " + DefinitionQuery; using (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { if (dr[0] != DBNull.Value) { var geom = GeometryFromWKB.Parse((byte[]) dr[0], Factory); if (geom != null) features.Add(geom); } } } conn.Close(); } } return features; } /// <summary> /// Returns the geometry corresponding to the Object ID /// </summary> /// <param name="oid">Object ID</param> /// <returns>geometry</returns> public Geometry GetGeometryByID(uint oid) { Geometry geom = null; using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT " + GeometryColumn + " AS Geom FROM " + Table + " WHERE " + ObjectIdColumn + "='" + oid.ToString() + "'"; conn.Open(); using (SqlCommand command = new SqlCommand(strSQL, conn)) { using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { if (dr[0] != DBNull.Value) geom = GeometryFromWKB.Parse((byte[]) dr[0], Factory); } } } conn.Close(); } return geom; } /// <summary> /// Returns geometry Object IDs whose bounding box intersects 'bbox' /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection<uint> GetObjectIDsInView(Envelope bbox) { Collection<uint> objectlist = new Collection<uint>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT " + ObjectIdColumn + " "; strSQL += "FROM " + Table + " WHERE "; strSQL += GetBoxClause(bbox); if (!string.IsNullOrEmpty(_definitionQuery)) strSQL += " AND " + DefinitionQuery + " AND "; using (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { if (dr[0] != DBNull.Value) { uint ID = (uint) (int) dr[0]; objectlist.Add(ID); } } } conn.Close(); } } return objectlist; } /// <summary> /// Returns the features that intersects with 'geom' [NOT IMPLEMENTED] /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { throw new NotImplementedException(); } /// <summary> /// Returns the number of features in the dataset /// </summary> /// <returns>number of features</returns> public int GetFeatureCount() { int count = 0; using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT COUNT(*) FROM " + Table; if (!string.IsNullOrEmpty(_definitionQuery)) strSQL += " WHERE " + DefinitionQuery; using (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); count = (int) command.ExecuteScalar(); conn.Close(); } } return count; } /// <summary> /// Spacial Reference ID /// </summary> public int SRID { get { return _srid; } set { if (value == _srid) return; _srid = value; _factory = null; } } /// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="rowId"></param> /// <returns>datarow</returns> public FeatureDataRow GetFeature(uint rowId) { using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT *, " + GeometryColumn + " AS sharpmap_tempgeometry FROM " + Table + " WHERE " + ObjectIdColumn + "='" + rowId.ToString() + "'"; using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { DataSet ds = new DataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdr[col.ColumnName] = dr[col]; if (dr["sharpmap_tempgeometry"] != DBNull.Value) fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory); return fdr; } else return null; } else return null; } } } /// <summary> /// Boundingbox of dataset /// </summary> /// <returns>boundingbox</returns> public Envelope GetExtents() { Envelope box = null; using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT Min(Envelope_MinX) AS MinX, Min(Envelope_MinY) AS MinY, Max(Envelope_MaxX) AS MaxX, Max(Envelope_MaxY) AS MaxY FROM " + Table; if (!string.IsNullOrEmpty(_definitionQuery)) strSQL += " WHERE " + DefinitionQuery; using (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); using (SqlDataReader dr = command.ExecuteReader()) if (dr.Read()) { box = new Envelope(new Coordinate((float) dr[0], (float) dr[1]), new Coordinate((float) dr[2], (float) dr[3])); } conn.Close(); } return box; } } /// <summary> /// Gets the connection ID of the datasource /// </summary> public string ConnectionID { get { return _ConnectionString; } } /// <summary> /// Returns all features with the view box /// </summary> /// <param name="bbox">view box</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds) { //List<Geometries.Geometry> features = new List<NetTopologySuite.Geometries.Geometry>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT *, " + GeometryColumn + " AS sharpmap_tempgeometry "; strSQL += "FROM " + Table + " WHERE "; strSQL += GetBoxClause(bbox); if (!string.IsNullOrEmpty(_definitionQuery)) strSQL += " AND " + DefinitionQuery; using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); DataSet ds2 = new DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]); foreach (DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdr[col.ColumnName] = dr[col]; if (dr["sharpmap_tempgeometry"] != DBNull.Value) fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } } #endregion #region Disposers and finalizers private bool _disposed; /// <summary> /// Disposes the object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //Close(); } _disposed = true; } } /// <summary> /// Finalizer /// </summary> ~MsSql() { Dispose(); } #endregion private static string GetBoxClause(Envelope bbox) { return String.Format(Map.NumberFormatEnUs, "(Envelope_MinX <= {0} AND Envelope_MaxX >= {1} AND Envelope_MinY <= {2} AND Envelope_MaxY >= {3})", bbox.MaxX, bbox.MinX, bbox.MaxY, bbox.MinY); } /// <summary> /// Creates a new table in a Microsoft SQL Server database and copies rows from an existing datasource. /// </summary> /// <remarks> /// <para>The datatable created will contain six extra columns besides the attribute data: "OID" (Object ID row), /// "WKB_Geometry" (Geometry stored as WKB), and Envelope_MinX, Envelope_MinY, Envelope_MaxX, Envelope_MaxY /// for geometry bounding box.</para> /// <para> /// <example> /// Upload a ShapeFile to a database: /// <code> /// public void CreateDatabase(string shapeFile) /// { /// if (!System.IO.File.Exists(shapeFile)) /// { /// MessageBox.Show("File not found"); /// return; /// } /// ShapeFile shp = new ShapeFile(shapeFile, false); /// //Create tablename from filename /// string tablename = shapeFile.Substring(shapeFile.LastIndexOf('\\') + 1, /// shapeFile.LastIndexOf('.') - shapeFile.LastIndexOf('\\') - 1); /// //Create connectionstring /// string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|GeoDatabase.mdf;Integrated Security=True;User Instance=True"; /// int count = SharpMap.Data.Providers.MsSql.CreateDataTable(shp, tablename, connstr); /// MessageBox.Show("Uploaded " + count.ToString() + " features to datatable '" + tablename + "'"); /// } /// </code> /// </example> /// </para> /// </remarks> /// <param name="datasource">Datasource to upload</param> /// <param name="tablename">Name of table to create (existing table will be overwritten!)</param> /// <param name="connstr">Connection string to database</param> /// <returns>Number or rows inserted, -1 if failed and 0 if table created but no rows inserted.</returns> public static int CreateDataTable(IProvider datasource, string tablename, string connstr) { datasource.Open(); FeatureDataRow geom = datasource.GetFeature(0); DataColumnCollection columns = geom.Table.Columns; int counter = -1; using (SqlConnection conn = new SqlConnection(connstr)) { SqlCommand command = new SqlCommand(); command.Connection = conn; conn.Open(); //Try to drop table if it exists try { command.CommandText = "DROP TABLE \"" + tablename + "\";"; command.ExecuteNonQuery(); } catch { } //Create new table for storing the datasource string sql = "CREATE TABLE " + tablename + " (oid INTEGER IDENTITY PRIMARY KEY, WKB_Geometry Image, " + "Envelope_MinX real, Envelope_MinY real, Envelope_MaxX real, Envelope_MaxY real"; foreach (DataColumn col in columns) if (col.DataType != typeof (String)) sql += ", " + col.ColumnName + " " + Type2SqlType(col.DataType).ToString(); else sql += ", " + col.ColumnName + " VARCHAR(256)"; command.CommandText = sql + ");"; command.ExecuteNonQuery(); counter++; Collection<uint> indexes = datasource.GetObjectIDsInView(datasource.GetExtents()); //Select all indexes in shapefile, loop through each feature and insert them one-by-one foreach (uint idx in indexes) { //Get feature from shapefile FeatureDataRow feature = datasource.GetFeature(idx); if (counter == 0) { //Create insert script string strSQL = " ("; foreach (DataColumn col in feature.Table.Columns) strSQL += "@" + col.ColumnName + ","; strSQL += "@WKB_Geometry,@Envelope_MinX,@Envelope_MinY, " + "@Envelope_MaxX,@Envelope_MaxY)"; strSQL = "INSERT INTO " + tablename + strSQL.Replace("@", "") + " VALUES" + strSQL; command.CommandText = strSQL; command.Parameters.Clear(); //Add datacolumn parameters foreach (DataColumn col in feature.Table.Columns) command.Parameters.Add("@" + col.ColumnName, Type2SqlType(col.DataType)); //Add geometry parameters command.Parameters.Add("@WKB_Geometry", SqlDbType.VarBinary); command.Parameters.Add("@Envelope_MinX", SqlDbType.Real); command.Parameters.Add("@Envelope_MinY", SqlDbType.Real); command.Parameters.Add("@Envelope_MaxX", SqlDbType.Real); command.Parameters.Add("@Envelope_MaxY", SqlDbType.Real); } //Set values foreach (DataColumn col in feature.Table.Columns) command.Parameters["@" + col.ColumnName].Value = feature[col]; if (feature.Geometry != null) { command.Parameters["@WKB_Geometry"].Value = feature.Geometry.AsBinary(); //Add the geometry as Well-Known Binary Envelope box = feature.Geometry.EnvelopeInternal; command.Parameters["@Envelope_MinX"].Value = box.MinX; command.Parameters["@Envelope_MinY"].Value = box.MinY; command.Parameters["@Envelope_MaxX"].Value = box.MaxX; command.Parameters["@Envelope_MaxY"].Value = box.MaxY; } else { command.Parameters["@WKB_Geometry"].Value = DBNull.Value; command.Parameters["@Envelope_MinX"].Value = DBNull.Value; command.Parameters["@Envelope_MinY"].Value = DBNull.Value; command.Parameters["@Envelope_MaxX"].Value = DBNull.Value; command.Parameters["@Envelope_MaxY"].Value = DBNull.Value; } //Insert row command.ExecuteNonQuery(); counter++; } //Create indexes command.Parameters.Clear(); command.CommandText = "CREATE INDEX [IDX_Envelope_MinX] ON " + tablename + " (Envelope_MinX)"; command.ExecuteNonQuery(); command.CommandText = "CREATE INDEX [IDX_Envelope_MinY] ON " + tablename + " (Envelope_MinY)"; command.ExecuteNonQuery(); command.CommandText = "CREATE INDEX [IDX_Envelope_MaxX] ON " + tablename + " (Envelope_MaxX)"; command.ExecuteNonQuery(); command.CommandText = "CREATE INDEX [IDX_Envelope_MaxY] ON " + tablename + " (Envelope_MaxY)"; command.ExecuteNonQuery(); conn.Close(); } datasource.Close(); return counter; } /// <summary> /// Returns the name of the SqlServer datatype based on a .NET datatype /// </summary> /// <param name="t"></param> /// <returns></returns> private static SqlDbType Type2SqlType(Type t) { switch (t.ToString()) { case "System.Boolean": return SqlDbType.Bit; case "System.Single": return SqlDbType.Real; case "System.Double": return SqlDbType.Float; case "System.Int16": return SqlDbType.SmallInt; case "System.Int32": return SqlDbType.Int; case "System.Int64": return SqlDbType.BigInt; case "System.DateTime": return SqlDbType.DateTime; case "System.Byte[]": return SqlDbType.Image; case "System.String": return SqlDbType.VarChar; default: throw (new NotSupportedException("Unsupported datatype '" + t.Name + "' found in datasource")); } } } }
using System; using UnityEngine; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { // RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = m_Camera.transform.forward * m_Input.y + m_Camera.transform.right * m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// 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.IO; using System.Linq; using FluentAssertions; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ToolPackage; using Microsoft.DotNet.Tools.Tool.Uninstall; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.Extensions.DependencyModel.Tests; using Microsoft.Extensions.EnvironmentAbstractions; using Xunit; using Parser = Microsoft.DotNet.Cli.Parser; using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Uninstall.LocalizableStrings; using Microsoft.DotNet.ToolManifest; namespace Microsoft.DotNet.Tests.Commands.Tool { public class ToolUninstallLocalCommandTests { private readonly IFileSystem _fileSystem; private readonly string _temporaryDirectoryParent; private readonly AppliedOption _appliedCommand; private readonly ParseResult _parseResult; private readonly BufferedReporter _reporter; private readonly string _temporaryDirectory; private readonly string _manifestFilePath; private readonly PackageId _packageIdDotnsay = new PackageId("dotnetsay"); private readonly ToolManifestFinder _toolManifestFinder; private readonly ToolManifestEditor _toolManifestEditor; private readonly ToolUninstallLocalCommand _defaultToolUninstallLocalCommand; public ToolUninstallLocalCommandTests() { _reporter = new BufferedReporter(); _fileSystem = new FileSystemMockBuilder().UseCurrentSystemTemporaryDirectory().Build(); _temporaryDirectoryParent = _fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; _temporaryDirectory = Path.Combine(_temporaryDirectoryParent, "sub"); _fileSystem.Directory.CreateDirectory(_temporaryDirectory); _manifestFilePath = Path.Combine(_temporaryDirectory, "dotnet-tools.json"); _fileSystem.File.WriteAllText(Path.Combine(_temporaryDirectory, _manifestFilePath), _jsonContent); _toolManifestFinder = new ToolManifestFinder(new DirectoryPath(_temporaryDirectory), _fileSystem, new FakeDangerousFileDetector()); _toolManifestEditor = new ToolManifestEditor(_fileSystem, new FakeDangerousFileDetector()); _parseResult = Parser.Instance.Parse($"dotnet tool uninstall {_packageIdDotnsay.ToString()}"); _appliedCommand = _parseResult["dotnet"]["tool"]["uninstall"]; _defaultToolUninstallLocalCommand = new ToolUninstallLocalCommand( _appliedCommand, _parseResult, _toolManifestFinder, _toolManifestEditor, _reporter); } [Fact] public void WhenRunWithPackageIdItShouldRemoveFromManifestFile() { _defaultToolUninstallLocalCommand.Execute().Should().Be(0); _fileSystem.File.ReadAllText(_manifestFilePath).Should().Be(_entryRemovedJsonContent); } [Fact] public void GivenNoManifestFileItShouldThrow() { _fileSystem.File.Delete(_manifestFilePath); Action a = () => _defaultToolUninstallLocalCommand.Execute().Should().Be(0); a.ShouldThrow<GracefulException>() .And.Message.Should() .Contain(Tools.Tool.Common.LocalizableStrings.NoManifestGuide); a.ShouldThrow<GracefulException>() .And.Message.Should() .Contain(ToolManifest.LocalizableStrings.CannotFindAManifestFile); a.ShouldThrow<GracefulException>() .And.VerboseMessage.Should().Contain(string.Format(ToolManifest.LocalizableStrings.ListOfSearched, "")); } [Fact] public void GivenNoManifestFileContainPackageIdItShouldThrow() { _fileSystem.File.Delete(_manifestFilePath); _fileSystem.File.WriteAllText(_manifestFilePath, _jsonContentContainNoPackageId); Action a = () => _defaultToolUninstallLocalCommand.Execute().Should().Be(0); a.ShouldThrow<GracefulException>() .And.Message.Should() .Contain(string.Format(LocalizableStrings.NoManifestFileContainPackageId, _packageIdDotnsay)); } [Fact] public void WhenRunWithExplicitManifestFileItShouldRemoveFromExplicitManifestFile() { var explicitManifestFilePath = Path.Combine(_temporaryDirectory, "subdirectory", "dotnet-tools.json"); _fileSystem.File.Delete(_manifestFilePath); _fileSystem.Directory.CreateDirectory(Path.Combine(_temporaryDirectory, "subdirectory")); _fileSystem.File.WriteAllText(explicitManifestFilePath, _jsonContent); var parseResult = Parser.Instance.Parse( $"dotnet tool uninstall {_packageIdDotnsay.ToString()} --tool-manifest {explicitManifestFilePath}"); var appliedCommand = parseResult["dotnet"]["tool"]["uninstall"]; var toolUninstallLocalCommand = new ToolUninstallLocalCommand( appliedCommand, parseResult, _toolManifestFinder, _toolManifestEditor, _reporter); toolUninstallLocalCommand.Execute().Should().Be(0); _fileSystem.File.ReadAllText(explicitManifestFilePath).Should().Be(_entryRemovedJsonContent); } [Fact] public void WhenRunFromToolUninstallRedirectCommandWithPackageIdItShouldRemoveFromManifestFile() { var parseResult = Parser.Instance.Parse($"dotnet tool uninstall {_packageIdDotnsay.ToString()}"); var appliedCommand = parseResult["dotnet"]["tool"]["uninstall"]; var toolUninstallLocalCommand = new ToolUninstallLocalCommand( appliedCommand, parseResult, _toolManifestFinder, _toolManifestEditor, _reporter); var toolUninstallCommand = new ToolUninstallCommand( appliedCommand, parseResult, toolUninstallLocalCommand: toolUninstallLocalCommand); toolUninstallCommand.Execute().Should().Be(0); _fileSystem.File.ReadAllText(_manifestFilePath).Should().Be(_entryRemovedJsonContent); } [Fact] public void WhenRunWithPackageIdItShouldShowSuccessMessage() { _defaultToolUninstallLocalCommand.Execute(); _reporter.Lines.Single() .Should().Contain( string.Format( LocalizableStrings.UninstallLocalToolSucceeded, _packageIdDotnsay, _manifestFilePath).Green()); } [Fact] public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShouldOnlyChangTheClosestOne() { var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); _defaultToolUninstallLocalCommand.Execute(); _fileSystem.File.ReadAllText(_manifestFilePath).Should().Be(_entryRemovedJsonContent, "Change the closest one"); _fileSystem.File.ReadAllText(parentManifestFilePath).Should().Be(_jsonContent, "Do not change the manifest layer above"); } [Fact] public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShouldOnlyChangTheClosestOne2() { var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); _defaultToolUninstallLocalCommand.Execute(); _defaultToolUninstallLocalCommand.Execute(); _fileSystem.File.ReadAllText(parentManifestFilePath).Should().Be( _entryRemovedJsonContent, "First invoke remove the one in current dir, the second invoke remove the one in parent dir."); } [Fact] public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShouldWarningTheOtherManifests() { var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); _defaultToolUninstallLocalCommand.Execute(); _reporter.Lines[0].Should().Contain(parentManifestFilePath); _reporter.Lines[0].Should().NotContain(_manifestFilePath); } private string _jsonContent = @"{ ""version"":1, ""isRoot"":false, ""tools"":{ ""t-rex"":{ ""version"":""1.0.53"", ""commands"":[ ""t-rex"" ] }, ""dotnetsay"":{ ""version"":""2.1.4"", ""commands"":[ ""dotnetsay"" ] } } }"; private string _jsonContentContainNoPackageId = @"{ ""version"":1, ""isRoot"":false, ""tools"":{} }"; private string _entryRemovedJsonContent = @"{ ""version"": 1, ""isRoot"": false, ""tools"": { ""t-rex"": { ""version"": ""1.0.53"", ""commands"": [ ""t-rex"" ] } } }"; } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Windows.Forms; using C1.Win.C1TrueDBGrid; using PCSComUtils.Common; using PCSComUtils.Framework.ReportFrame.BO; using PCSComUtils.Framework.ReportFrame.DS; using PCSComUtils.PCSExc; using PCSUtils.Log; using PCSUtils.Utils; using CancelEventArgs = System.ComponentModel.CancelEventArgs; namespace PCSUtils.Framework.ReportFrame { /// <summary> /// Summary description for DrillDownReport. /// </summary> public class DrillDownReport : Form { private TextBox txtReportName; private TextBox txtReportCode; private Label lblReportName; private Label lblReportCode; private Button btnClose; private Button btnHelp; private Button btnEdit; private Button btnSave; private Button btnDelete; /// <summary> /// Required designer variable. /// </summary> private Container components = null; private const string THIS = "PCSUtils.Framework.ReportFrame.DrillDownReport"; private const int ORDER_COLUMN_INDEX = 4; private string mMasterReportID; private EnumAction mEnumType; private DataTable tblDataSource = new DataTable(sys_ReportDrillDownTable.TABLE_NAME); private DataTable tblSourceForGrid = new DataTable(sys_ReportDrillDownTable.TABLE_NAME); private ArrayList arrMasterFields = new ArrayList(); private ArrayList arrMasterParameters = new ArrayList(); private DrillDownReportBO boDrillDownReport = new DrillDownReportBO(); private C1TrueDBGrid gridDrillDownReport; private Hashtable htDataType = new Hashtable(); private DataRow drowOldValue; public string MasterReportID { get { return this.mMasterReportID; } set { this.mMasterReportID = value; } } public EnumAction EnumType { get { return this.mEnumType; } set { this.mEnumType = value; } } //************************************************************************** /// <Description> /// Default constructor /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DrillDownReport() { // // Required for Windows Form Designer support // InitializeComponent(); #region init hashtable data type htDataType.Clear(); htDataType.Add((int)TypeCode.Boolean, TypeCode.Boolean.ToString()); htDataType.Add((int)TypeCode.Char, TypeCode.Char.ToString()); htDataType.Add((int)TypeCode.DateTime, TypeCode.DateTime.ToString()); htDataType.Add((int)TypeCode.Decimal, TypeCode.Decimal.ToString()); htDataType.Add((int)TypeCode.Double, TypeCode.Double.ToString()); htDataType.Add((int)TypeCode.Int16, TypeCode.Int16.ToString()); htDataType.Add((int)TypeCode.Int32, TypeCode.Int32.ToString()); htDataType.Add((int)TypeCode.Int64, TypeCode.Int64.ToString()); htDataType.Add((int)TypeCode.Single, TypeCode.Single.ToString()); htDataType.Add((int)TypeCode.String, TypeCode.String.ToString()); #endregion } /// <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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DrillDownReport)); this.txtReportName = new System.Windows.Forms.TextBox(); this.txtReportCode = new System.Windows.Forms.TextBox(); this.lblReportName = new System.Windows.Forms.Label(); this.lblReportCode = new System.Windows.Forms.Label(); this.btnClose = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.btnEdit = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.gridDrillDownReport = new C1.Win.C1TrueDBGrid.C1TrueDBGrid(); ((System.ComponentModel.ISupportInitialize)(this.gridDrillDownReport)).BeginInit(); this.SuspendLayout(); // // txtReportName // this.txtReportName.AccessibleDescription = resources.GetString("txtReportName.AccessibleDescription"); this.txtReportName.AccessibleName = resources.GetString("txtReportName.AccessibleName"); this.txtReportName.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtReportName.Anchor"))); this.txtReportName.AutoSize = ((bool)(resources.GetObject("txtReportName.AutoSize"))); this.txtReportName.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtReportName.BackgroundImage"))); this.txtReportName.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtReportName.Dock"))); this.txtReportName.Enabled = ((bool)(resources.GetObject("txtReportName.Enabled"))); this.txtReportName.Font = ((System.Drawing.Font)(resources.GetObject("txtReportName.Font"))); this.txtReportName.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtReportName.ImeMode"))); this.txtReportName.Location = ((System.Drawing.Point)(resources.GetObject("txtReportName.Location"))); this.txtReportName.MaxLength = ((int)(resources.GetObject("txtReportName.MaxLength"))); this.txtReportName.Multiline = ((bool)(resources.GetObject("txtReportName.Multiline"))); this.txtReportName.Name = "txtReportName"; this.txtReportName.PasswordChar = ((char)(resources.GetObject("txtReportName.PasswordChar"))); this.txtReportName.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtReportName.RightToLeft"))); this.txtReportName.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtReportName.ScrollBars"))); this.txtReportName.Size = ((System.Drawing.Size)(resources.GetObject("txtReportName.Size"))); this.txtReportName.TabIndex = ((int)(resources.GetObject("txtReportName.TabIndex"))); this.txtReportName.Text = resources.GetString("txtReportName.Text"); this.txtReportName.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtReportName.TextAlign"))); this.txtReportName.Visible = ((bool)(resources.GetObject("txtReportName.Visible"))); this.txtReportName.WordWrap = ((bool)(resources.GetObject("txtReportName.WordWrap"))); this.txtReportName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtReportName_KeyPress); // // txtReportCode // this.txtReportCode.AccessibleDescription = resources.GetString("txtReportCode.AccessibleDescription"); this.txtReportCode.AccessibleName = resources.GetString("txtReportCode.AccessibleName"); this.txtReportCode.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtReportCode.Anchor"))); this.txtReportCode.AutoSize = ((bool)(resources.GetObject("txtReportCode.AutoSize"))); this.txtReportCode.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtReportCode.BackgroundImage"))); this.txtReportCode.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtReportCode.Dock"))); this.txtReportCode.Enabled = ((bool)(resources.GetObject("txtReportCode.Enabled"))); this.txtReportCode.Font = ((System.Drawing.Font)(resources.GetObject("txtReportCode.Font"))); this.txtReportCode.ForeColor = System.Drawing.SystemColors.WindowText; this.txtReportCode.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtReportCode.ImeMode"))); this.txtReportCode.Location = ((System.Drawing.Point)(resources.GetObject("txtReportCode.Location"))); this.txtReportCode.MaxLength = ((int)(resources.GetObject("txtReportCode.MaxLength"))); this.txtReportCode.Multiline = ((bool)(resources.GetObject("txtReportCode.Multiline"))); this.txtReportCode.Name = "txtReportCode"; this.txtReportCode.PasswordChar = ((char)(resources.GetObject("txtReportCode.PasswordChar"))); this.txtReportCode.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtReportCode.RightToLeft"))); this.txtReportCode.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtReportCode.ScrollBars"))); this.txtReportCode.Size = ((System.Drawing.Size)(resources.GetObject("txtReportCode.Size"))); this.txtReportCode.TabIndex = ((int)(resources.GetObject("txtReportCode.TabIndex"))); this.txtReportCode.Text = resources.GetString("txtReportCode.Text"); this.txtReportCode.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtReportCode.TextAlign"))); this.txtReportCode.Visible = ((bool)(resources.GetObject("txtReportCode.Visible"))); this.txtReportCode.WordWrap = ((bool)(resources.GetObject("txtReportCode.WordWrap"))); this.txtReportCode.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtReportCode_KeyPress); // // lblReportName // this.lblReportName.AccessibleDescription = resources.GetString("lblReportName.AccessibleDescription"); this.lblReportName.AccessibleName = resources.GetString("lblReportName.AccessibleName"); this.lblReportName.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblReportName.Anchor"))); this.lblReportName.AutoSize = ((bool)(resources.GetObject("lblReportName.AutoSize"))); this.lblReportName.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblReportName.Dock"))); this.lblReportName.Enabled = ((bool)(resources.GetObject("lblReportName.Enabled"))); this.lblReportName.Font = ((System.Drawing.Font)(resources.GetObject("lblReportName.Font"))); this.lblReportName.Image = ((System.Drawing.Image)(resources.GetObject("lblReportName.Image"))); this.lblReportName.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblReportName.ImageAlign"))); this.lblReportName.ImageIndex = ((int)(resources.GetObject("lblReportName.ImageIndex"))); this.lblReportName.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblReportName.ImeMode"))); this.lblReportName.Location = ((System.Drawing.Point)(resources.GetObject("lblReportName.Location"))); this.lblReportName.Name = "lblReportName"; this.lblReportName.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblReportName.RightToLeft"))); this.lblReportName.Size = ((System.Drawing.Size)(resources.GetObject("lblReportName.Size"))); this.lblReportName.TabIndex = ((int)(resources.GetObject("lblReportName.TabIndex"))); this.lblReportName.Text = resources.GetString("lblReportName.Text"); this.lblReportName.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblReportName.TextAlign"))); this.lblReportName.Visible = ((bool)(resources.GetObject("lblReportName.Visible"))); // // lblReportCode // this.lblReportCode.AccessibleDescription = resources.GetString("lblReportCode.AccessibleDescription"); this.lblReportCode.AccessibleName = resources.GetString("lblReportCode.AccessibleName"); this.lblReportCode.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblReportCode.Anchor"))); this.lblReportCode.AutoSize = ((bool)(resources.GetObject("lblReportCode.AutoSize"))); this.lblReportCode.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblReportCode.Dock"))); this.lblReportCode.Enabled = ((bool)(resources.GetObject("lblReportCode.Enabled"))); this.lblReportCode.Font = ((System.Drawing.Font)(resources.GetObject("lblReportCode.Font"))); this.lblReportCode.ForeColor = System.Drawing.Color.Maroon; this.lblReportCode.Image = ((System.Drawing.Image)(resources.GetObject("lblReportCode.Image"))); this.lblReportCode.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblReportCode.ImageAlign"))); this.lblReportCode.ImageIndex = ((int)(resources.GetObject("lblReportCode.ImageIndex"))); this.lblReportCode.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblReportCode.ImeMode"))); this.lblReportCode.Location = ((System.Drawing.Point)(resources.GetObject("lblReportCode.Location"))); this.lblReportCode.Name = "lblReportCode"; this.lblReportCode.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblReportCode.RightToLeft"))); this.lblReportCode.Size = ((System.Drawing.Size)(resources.GetObject("lblReportCode.Size"))); this.lblReportCode.TabIndex = ((int)(resources.GetObject("lblReportCode.TabIndex"))); this.lblReportCode.Text = resources.GetString("lblReportCode.Text"); this.lblReportCode.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblReportCode.TextAlign"))); this.lblReportCode.Visible = ((bool)(resources.GetObject("lblReportCode.Visible"))); // // btnClose // this.btnClose.AccessibleDescription = resources.GetString("btnClose.AccessibleDescription"); this.btnClose.AccessibleName = resources.GetString("btnClose.AccessibleName"); this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnClose.Anchor"))); this.btnClose.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnClose.BackgroundImage"))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnClose.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnClose.Dock"))); this.btnClose.Enabled = ((bool)(resources.GetObject("btnClose.Enabled"))); this.btnClose.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnClose.FlatStyle"))); this.btnClose.Font = ((System.Drawing.Font)(resources.GetObject("btnClose.Font"))); this.btnClose.Image = ((System.Drawing.Image)(resources.GetObject("btnClose.Image"))); this.btnClose.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.ImageAlign"))); this.btnClose.ImageIndex = ((int)(resources.GetObject("btnClose.ImageIndex"))); this.btnClose.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnClose.ImeMode"))); this.btnClose.Location = ((System.Drawing.Point)(resources.GetObject("btnClose.Location"))); this.btnClose.Name = "btnClose"; this.btnClose.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnClose.RightToLeft"))); this.btnClose.Size = ((System.Drawing.Size)(resources.GetObject("btnClose.Size"))); this.btnClose.TabIndex = ((int)(resources.GetObject("btnClose.TabIndex"))); this.btnClose.Text = resources.GetString("btnClose.Text"); this.btnClose.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.TextAlign"))); this.btnClose.Visible = ((bool)(resources.GetObject("btnClose.Visible"))); this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnHelp // this.btnHelp.AccessibleDescription = resources.GetString("btnHelp.AccessibleDescription"); this.btnHelp.AccessibleName = resources.GetString("btnHelp.AccessibleName"); this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnHelp.Anchor"))); this.btnHelp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnHelp.BackgroundImage"))); this.btnHelp.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnHelp.Dock"))); this.btnHelp.Enabled = ((bool)(resources.GetObject("btnHelp.Enabled"))); this.btnHelp.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnHelp.FlatStyle"))); this.btnHelp.Font = ((System.Drawing.Font)(resources.GetObject("btnHelp.Font"))); this.btnHelp.Image = ((System.Drawing.Image)(resources.GetObject("btnHelp.Image"))); this.btnHelp.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.ImageAlign"))); this.btnHelp.ImageIndex = ((int)(resources.GetObject("btnHelp.ImageIndex"))); this.btnHelp.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnHelp.ImeMode"))); this.btnHelp.Location = ((System.Drawing.Point)(resources.GetObject("btnHelp.Location"))); this.btnHelp.Name = "btnHelp"; this.btnHelp.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnHelp.RightToLeft"))); this.btnHelp.Size = ((System.Drawing.Size)(resources.GetObject("btnHelp.Size"))); this.btnHelp.TabIndex = ((int)(resources.GetObject("btnHelp.TabIndex"))); this.btnHelp.Text = resources.GetString("btnHelp.Text"); this.btnHelp.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.TextAlign"))); this.btnHelp.Visible = ((bool)(resources.GetObject("btnHelp.Visible"))); // // btnEdit // this.btnEdit.AccessibleDescription = resources.GetString("btnEdit.AccessibleDescription"); this.btnEdit.AccessibleName = resources.GetString("btnEdit.AccessibleName"); this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnEdit.Anchor"))); this.btnEdit.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnEdit.BackgroundImage"))); this.btnEdit.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnEdit.Dock"))); this.btnEdit.Enabled = ((bool)(resources.GetObject("btnEdit.Enabled"))); this.btnEdit.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnEdit.FlatStyle"))); this.btnEdit.Font = ((System.Drawing.Font)(resources.GetObject("btnEdit.Font"))); this.btnEdit.Image = ((System.Drawing.Image)(resources.GetObject("btnEdit.Image"))); this.btnEdit.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnEdit.ImageAlign"))); this.btnEdit.ImageIndex = ((int)(resources.GetObject("btnEdit.ImageIndex"))); this.btnEdit.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnEdit.ImeMode"))); this.btnEdit.Location = ((System.Drawing.Point)(resources.GetObject("btnEdit.Location"))); this.btnEdit.Name = "btnEdit"; this.btnEdit.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnEdit.RightToLeft"))); this.btnEdit.Size = ((System.Drawing.Size)(resources.GetObject("btnEdit.Size"))); this.btnEdit.TabIndex = ((int)(resources.GetObject("btnEdit.TabIndex"))); this.btnEdit.Text = resources.GetString("btnEdit.Text"); this.btnEdit.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnEdit.TextAlign"))); this.btnEdit.Visible = ((bool)(resources.GetObject("btnEdit.Visible"))); this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // btnSave // this.btnSave.AccessibleDescription = resources.GetString("btnSave.AccessibleDescription"); this.btnSave.AccessibleName = resources.GetString("btnSave.AccessibleName"); this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnSave.Anchor"))); this.btnSave.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnSave.BackgroundImage"))); this.btnSave.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnSave.Dock"))); this.btnSave.Enabled = ((bool)(resources.GetObject("btnSave.Enabled"))); this.btnSave.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnSave.FlatStyle"))); this.btnSave.Font = ((System.Drawing.Font)(resources.GetObject("btnSave.Font"))); this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image"))); this.btnSave.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSave.ImageAlign"))); this.btnSave.ImageIndex = ((int)(resources.GetObject("btnSave.ImageIndex"))); this.btnSave.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnSave.ImeMode"))); this.btnSave.Location = ((System.Drawing.Point)(resources.GetObject("btnSave.Location"))); this.btnSave.Name = "btnSave"; this.btnSave.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnSave.RightToLeft"))); this.btnSave.Size = ((System.Drawing.Size)(resources.GetObject("btnSave.Size"))); this.btnSave.TabIndex = ((int)(resources.GetObject("btnSave.TabIndex"))); this.btnSave.Text = resources.GetString("btnSave.Text"); this.btnSave.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSave.TextAlign"))); this.btnSave.Visible = ((bool)(resources.GetObject("btnSave.Visible"))); this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnDelete // this.btnDelete.AccessibleDescription = resources.GetString("btnDelete.AccessibleDescription"); this.btnDelete.AccessibleName = resources.GetString("btnDelete.AccessibleName"); this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnDelete.Anchor"))); this.btnDelete.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnDelete.BackgroundImage"))); this.btnDelete.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnDelete.Dock"))); this.btnDelete.Enabled = ((bool)(resources.GetObject("btnDelete.Enabled"))); this.btnDelete.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnDelete.FlatStyle"))); this.btnDelete.Font = ((System.Drawing.Font)(resources.GetObject("btnDelete.Font"))); this.btnDelete.Image = ((System.Drawing.Image)(resources.GetObject("btnDelete.Image"))); this.btnDelete.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnDelete.ImageAlign"))); this.btnDelete.ImageIndex = ((int)(resources.GetObject("btnDelete.ImageIndex"))); this.btnDelete.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnDelete.ImeMode"))); this.btnDelete.Location = ((System.Drawing.Point)(resources.GetObject("btnDelete.Location"))); this.btnDelete.Name = "btnDelete"; this.btnDelete.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnDelete.RightToLeft"))); this.btnDelete.Size = ((System.Drawing.Size)(resources.GetObject("btnDelete.Size"))); this.btnDelete.TabIndex = ((int)(resources.GetObject("btnDelete.TabIndex"))); this.btnDelete.Text = resources.GetString("btnDelete.Text"); this.btnDelete.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnDelete.TextAlign"))); this.btnDelete.Visible = ((bool)(resources.GetObject("btnDelete.Visible"))); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // gridDrillDownReport // this.gridDrillDownReport.AccessibleDescription = resources.GetString("gridDrillDownReport.AccessibleDescription"); this.gridDrillDownReport.AccessibleName = resources.GetString("gridDrillDownReport.AccessibleName"); this.gridDrillDownReport.AllowAddNew = ((bool)(resources.GetObject("gridDrillDownReport.AllowAddNew"))); this.gridDrillDownReport.AllowArrows = ((bool)(resources.GetObject("gridDrillDownReport.AllowArrows"))); this.gridDrillDownReport.AllowColMove = ((bool)(resources.GetObject("gridDrillDownReport.AllowColMove"))); this.gridDrillDownReport.AllowColSelect = ((bool)(resources.GetObject("gridDrillDownReport.AllowColSelect"))); this.gridDrillDownReport.AllowDelete = ((bool)(resources.GetObject("gridDrillDownReport.AllowDelete"))); this.gridDrillDownReport.AllowDrag = ((bool)(resources.GetObject("gridDrillDownReport.AllowDrag"))); this.gridDrillDownReport.AllowFilter = ((bool)(resources.GetObject("gridDrillDownReport.AllowFilter"))); this.gridDrillDownReport.AllowHorizontalSplit = ((bool)(resources.GetObject("gridDrillDownReport.AllowHorizontalSplit"))); this.gridDrillDownReport.AllowRowSelect = ((bool)(resources.GetObject("gridDrillDownReport.AllowRowSelect"))); this.gridDrillDownReport.AllowSort = ((bool)(resources.GetObject("gridDrillDownReport.AllowSort"))); this.gridDrillDownReport.AllowUpdate = ((bool)(resources.GetObject("gridDrillDownReport.AllowUpdate"))); this.gridDrillDownReport.AllowUpdateOnBlur = ((bool)(resources.GetObject("gridDrillDownReport.AllowUpdateOnBlur"))); this.gridDrillDownReport.AllowVerticalSplit = ((bool)(resources.GetObject("gridDrillDownReport.AllowVerticalSplit"))); this.gridDrillDownReport.AlternatingRows = ((bool)(resources.GetObject("gridDrillDownReport.AlternatingRows"))); this.gridDrillDownReport.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("gridDrillDownReport.Anchor"))); this.gridDrillDownReport.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.BackgroundImage"))); this.gridDrillDownReport.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("gridDrillDownReport.BorderStyle"))); this.gridDrillDownReport.Caption = resources.GetString("gridDrillDownReport.Caption"); this.gridDrillDownReport.CaptionHeight = ((int)(resources.GetObject("gridDrillDownReport.CaptionHeight"))); this.gridDrillDownReport.CellTipsDelay = ((int)(resources.GetObject("gridDrillDownReport.CellTipsDelay"))); this.gridDrillDownReport.CellTipsWidth = ((int)(resources.GetObject("gridDrillDownReport.CellTipsWidth"))); this.gridDrillDownReport.ChildGrid = ((C1.Win.C1TrueDBGrid.C1TrueDBGrid)(resources.GetObject("gridDrillDownReport.ChildGrid"))); this.gridDrillDownReport.CollapseColor = ((System.Drawing.Color)(resources.GetObject("gridDrillDownReport.CollapseColor"))); this.gridDrillDownReport.ColumnFooters = ((bool)(resources.GetObject("gridDrillDownReport.ColumnFooters"))); this.gridDrillDownReport.ColumnHeaders = ((bool)(resources.GetObject("gridDrillDownReport.ColumnHeaders"))); this.gridDrillDownReport.DefColWidth = ((int)(resources.GetObject("gridDrillDownReport.DefColWidth"))); this.gridDrillDownReport.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("gridDrillDownReport.Dock"))); this.gridDrillDownReport.EditDropDown = ((bool)(resources.GetObject("gridDrillDownReport.EditDropDown"))); this.gridDrillDownReport.EmptyRows = ((bool)(resources.GetObject("gridDrillDownReport.EmptyRows"))); this.gridDrillDownReport.Enabled = ((bool)(resources.GetObject("gridDrillDownReport.Enabled"))); this.gridDrillDownReport.ExpandColor = ((System.Drawing.Color)(resources.GetObject("gridDrillDownReport.ExpandColor"))); this.gridDrillDownReport.ExposeCellMode = ((C1.Win.C1TrueDBGrid.ExposeCellModeEnum)(resources.GetObject("gridDrillDownReport.ExposeCellMode"))); this.gridDrillDownReport.ExtendRightColumn = ((bool)(resources.GetObject("gridDrillDownReport.ExtendRightColumn"))); this.gridDrillDownReport.FetchRowStyles = ((bool)(resources.GetObject("gridDrillDownReport.FetchRowStyles"))); this.gridDrillDownReport.FilterBar = ((bool)(resources.GetObject("gridDrillDownReport.FilterBar"))); this.gridDrillDownReport.FlatStyle = ((C1.Win.C1TrueDBGrid.FlatModeEnum)(resources.GetObject("gridDrillDownReport.FlatStyle"))); this.gridDrillDownReport.Font = ((System.Drawing.Font)(resources.GetObject("gridDrillDownReport.Font"))); this.gridDrillDownReport.GroupByAreaVisible = ((bool)(resources.GetObject("gridDrillDownReport.GroupByAreaVisible"))); this.gridDrillDownReport.GroupByCaption = resources.GetString("gridDrillDownReport.GroupByCaption"); this.gridDrillDownReport.Images.Add(((System.Drawing.Image)(resources.GetObject("resource")))); this.gridDrillDownReport.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("gridDrillDownReport.ImeMode"))); this.gridDrillDownReport.LinesPerRow = ((int)(resources.GetObject("gridDrillDownReport.LinesPerRow"))); this.gridDrillDownReport.Location = ((System.Drawing.Point)(resources.GetObject("gridDrillDownReport.Location"))); this.gridDrillDownReport.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder; this.gridDrillDownReport.Name = "gridDrillDownReport"; this.gridDrillDownReport.PictureAddnewRow = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureAddnewRow"))); this.gridDrillDownReport.PictureCurrentRow = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureCurrentRow"))); this.gridDrillDownReport.PictureFilterBar = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureFilterBar"))); this.gridDrillDownReport.PictureFooterRow = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureFooterRow"))); this.gridDrillDownReport.PictureHeaderRow = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureHeaderRow"))); this.gridDrillDownReport.PictureModifiedRow = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureModifiedRow"))); this.gridDrillDownReport.PictureStandardRow = ((System.Drawing.Image)(resources.GetObject("gridDrillDownReport.PictureStandardRow"))); this.gridDrillDownReport.PreviewInfo.AllowSizing = ((bool)(resources.GetObject("gridDrillDownReport.PreviewInfo.AllowSizing"))); this.gridDrillDownReport.PreviewInfo.Caption = resources.GetString("gridDrillDownReport.PreviewInfo.Caption"); this.gridDrillDownReport.PreviewInfo.Location = ((System.Drawing.Point)(resources.GetObject("gridDrillDownReport.PreviewInfo.Location"))); this.gridDrillDownReport.PreviewInfo.Size = ((System.Drawing.Size)(resources.GetObject("gridDrillDownReport.PreviewInfo.Size"))); this.gridDrillDownReport.PreviewInfo.ToolBars = ((bool)(resources.GetObject("gridDrillDownReport.PreviewInfo.ToolBars"))); this.gridDrillDownReport.PreviewInfo.UIStrings.Content = ((string[])(resources.GetObject("gridDrillDownReport.PreviewInfo.UIStrings.Content"))); this.gridDrillDownReport.PreviewInfo.ZoomFactor = ((System.Double)(resources.GetObject("gridDrillDownReport.PreviewInfo.ZoomFactor"))); this.gridDrillDownReport.PrintInfo.MaxRowHeight = ((int)(resources.GetObject("gridDrillDownReport.PrintInfo.MaxRowHeight"))); this.gridDrillDownReport.PrintInfo.OwnerDrawPageFooter = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.OwnerDrawPageFooter"))); this.gridDrillDownReport.PrintInfo.OwnerDrawPageHeader = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.OwnerDrawPageHeader"))); this.gridDrillDownReport.PrintInfo.PageFooter = resources.GetString("gridDrillDownReport.PrintInfo.PageFooter"); this.gridDrillDownReport.PrintInfo.PageFooterHeight = ((int)(resources.GetObject("gridDrillDownReport.PrintInfo.PageFooterHeight"))); this.gridDrillDownReport.PrintInfo.PageHeader = resources.GetString("gridDrillDownReport.PrintInfo.PageHeader"); this.gridDrillDownReport.PrintInfo.PageHeaderHeight = ((int)(resources.GetObject("gridDrillDownReport.PrintInfo.PageHeaderHeight"))); this.gridDrillDownReport.PrintInfo.PrintHorizontalSplits = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.PrintHorizontalSplits"))); this.gridDrillDownReport.PrintInfo.ProgressCaption = resources.GetString("gridDrillDownReport.PrintInfo.ProgressCaption"); this.gridDrillDownReport.PrintInfo.RepeatColumnFooters = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.RepeatColumnFooters"))); this.gridDrillDownReport.PrintInfo.RepeatColumnHeaders = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.RepeatColumnHeaders"))); this.gridDrillDownReport.PrintInfo.RepeatGridHeader = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.RepeatGridHeader"))); this.gridDrillDownReport.PrintInfo.RepeatSplitHeaders = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.RepeatSplitHeaders"))); this.gridDrillDownReport.PrintInfo.ShowOptionsDialog = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.ShowOptionsDialog"))); this.gridDrillDownReport.PrintInfo.ShowProgressForm = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.ShowProgressForm"))); this.gridDrillDownReport.PrintInfo.ShowSelection = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.ShowSelection"))); this.gridDrillDownReport.PrintInfo.UseGridColors = ((bool)(resources.GetObject("gridDrillDownReport.PrintInfo.UseGridColors"))); this.gridDrillDownReport.RecordSelectors = ((bool)(resources.GetObject("gridDrillDownReport.RecordSelectors"))); this.gridDrillDownReport.RecordSelectorWidth = ((int)(resources.GetObject("gridDrillDownReport.RecordSelectorWidth"))); this.gridDrillDownReport.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("gridDrillDownReport.RightToLeft"))); this.gridDrillDownReport.RowDivider.Color = ((System.Drawing.Color)(resources.GetObject("resource.Color"))); this.gridDrillDownReport.RowDivider.Style = ((C1.Win.C1TrueDBGrid.LineStyleEnum)(resources.GetObject("resource.Style"))); this.gridDrillDownReport.RowHeight = ((int)(resources.GetObject("gridDrillDownReport.RowHeight"))); this.gridDrillDownReport.RowSubDividerColor = ((System.Drawing.Color)(resources.GetObject("gridDrillDownReport.RowSubDividerColor"))); this.gridDrillDownReport.ScrollTips = ((bool)(resources.GetObject("gridDrillDownReport.ScrollTips"))); this.gridDrillDownReport.ScrollTrack = ((bool)(resources.GetObject("gridDrillDownReport.ScrollTrack"))); this.gridDrillDownReport.Size = ((System.Drawing.Size)(resources.GetObject("gridDrillDownReport.Size"))); this.gridDrillDownReport.SpringMode = ((bool)(resources.GetObject("gridDrillDownReport.SpringMode"))); this.gridDrillDownReport.TabAcrossSplits = ((bool)(resources.GetObject("gridDrillDownReport.TabAcrossSplits"))); this.gridDrillDownReport.TabIndex = ((int)(resources.GetObject("gridDrillDownReport.TabIndex"))); this.gridDrillDownReport.Text = resources.GetString("gridDrillDownReport.Text"); this.gridDrillDownReport.ViewCaptionWidth = ((int)(resources.GetObject("gridDrillDownReport.ViewCaptionWidth"))); this.gridDrillDownReport.ViewColumnWidth = ((int)(resources.GetObject("gridDrillDownReport.ViewColumnWidth"))); this.gridDrillDownReport.Visible = ((bool)(resources.GetObject("gridDrillDownReport.Visible"))); this.gridDrillDownReport.WrapCellPointer = ((bool)(resources.GetObject("gridDrillDownReport.WrapCellPointer"))); this.gridDrillDownReport.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.gridDrillDownReport_AfterColUpdate); this.gridDrillDownReport.PropBag = resources.GetString("gridDrillDownReport.PropBag"); // // DrillDownReport // this.AccessibleDescription = resources.GetString("$this.AccessibleDescription"); this.AccessibleName = resources.GetString("$this.AccessibleName"); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.CancelButton = this.btnClose; this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.Add(this.gridDrillDownReport); this.Controls.Add(this.txtReportName); this.Controls.Add(this.txtReportCode); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnEdit); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnDelete); this.Controls.Add(this.lblReportName); this.Controls.Add(this.lblReportCode); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "DrillDownReport"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.Closing += new System.ComponentModel.CancelEventHandler(this.DrillDownReport_Closing); this.Load += new System.EventHandler(this.DrillDownReport_Load); ((System.ComponentModel.ISupportInitialize)(this.gridDrillDownReport)).EndInit(); this.ResumeLayout(false); } #endregion #region Form Events //************************************************************************** /// <Description> /// Load event of form /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void DrillDownReport_Load(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".DrillDownReport_Load()"; try { #region Security //Set authorization for user Security objSecurity = new Security(); this.Name = THIS; if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0) { this.Close(); // You don't have the right to view this item PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW ,MessageBoxIcon.Warning); // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically return; } #endregion txtReportCode.Focus(); // try to get existing drill down of selected report ReportManagementBO boReportManagement = new ReportManagementBO(); DrillDownReportBO boDrillDownReport = new DrillDownReportBO(); ArrayList arrDrillDown = boReportManagement.GetDrillDownReports(MasterReportID); if (arrDrillDown.Count > 0) // already has drill down { string strDetailReportID = ((sys_ReportDrillDownVO)arrDrillDown[0]).DetailReportID; bool blnIsEdit; // get data for C1TrueDBGrid tblDataSource = boDrillDownReport.GetDataForTrueDBGrid(MasterReportID, strDetailReportID, out blnIsEdit); tblSourceForGrid = tblDataSource.Copy(); BindTrueDBGrid(tblSourceForGrid); EnableButtons(blnIsEdit); // set text for report code and report name txtReportCode.Text = strDetailReportID; txtReportName.Text = boReportManagement.GetReportName(strDetailReportID); // unable to edit report code and report name txtReportCode.Enabled = false; txtReportName.Enabled = false; } else { txtReportCode.Enabled = true; txtReportName.Enabled = true; } arrMasterFields = this.GetAllFieldsFromMaster(this.MasterReportID); arrMasterParameters = this.GetAllParametersFromMaster(this.MasterReportID); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } //************************************************************************** /// <Description> /// KeyPress Event, display the Report List form allows user select report /// then fill to report code and report name fields /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void txtReportCode_KeyPress(object sender, KeyPressEventArgs e) { const string METHOD_NAME = THIS + ".txtReportCode_KeyPress()"; if (e.KeyChar == (char)Constants.ENTER_KEY_CHAR) { try { ReportList frmReportList = new ReportList(mMasterReportID, sys_ReportTable.REPORTID_FLD); frmReportList.ShowDialog(); if (frmReportList.SelectedReport == null) { return; } txtReportCode.Text = frmReportList.SelectedReport.ReportID; // fill the coresponding report name txtReportName.Text = frmReportList.SelectedReport.ReportName; // bind data to grid if (frmReportList.SelectedReport != null) { bool blnIsEdit; tblDataSource = boDrillDownReport.GetDataForTrueDBGrid(mMasterReportID, frmReportList.SelectedReport.ReportID, out blnIsEdit); BindTrueDBGrid(tblDataSource); EnableButtons(blnIsEdit); } // move to next field } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } //************************************************************************** /// <Description> /// Keypress event, displays report list form allows user to select report /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void txtReportName_KeyPress(object sender, KeyPressEventArgs e) { const string METHOD_NAME = THIS + ".txtReportName_KeyPress()"; if (e.KeyChar == (char)Constants.ENTER_KEY_CHAR) { try { ReportList frmReportList = new ReportList(this.mMasterReportID, sys_ReportTable.REPORTNAME_FLD); frmReportList.ShowDialog(); if (frmReportList.SelectedReport == null) { return; } txtReportCode.Text = frmReportList.SelectedReport.ReportID; // fill the coresponding report name txtReportName.Text = frmReportList.SelectedReport.ReportName; // bind data to grid if (frmReportList.SelectedReport != null) { bool blnIsEdit; tblDataSource = boDrillDownReport.GetDataForTrueDBGrid(this.mMasterReportID, frmReportList.SelectedReport.ReportID, out blnIsEdit); this.BindTrueDBGrid(tblDataSource); EnableButtons(blnIsEdit); } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } //************************************************************************** /// <Description> /// Close the form /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void btnClose_Click(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically this.Close(); // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } //************************************************************************** /// <Description> /// Check whether if form mode is not equal to Default then display confirm message /// Closing the form based on user selection. /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void DrillDownReport_Closing(object sender, CancelEventArgs e) { const string METHOD_NAME = THIS + ".DrillDownReport_Closing()"; try { if (this.mEnumType != EnumAction.Default) { // display confirm message DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE,MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1); switch (dlgResult) { case DialogResult.Yes: try { if (!this.SaveData()) { e.Cancel = true; } } catch { e.Cancel = true; } break; case DialogResult.No: e.Cancel = false; break; case DialogResult.Cancel: e.Cancel = true; break; } } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } //************************************************************************** /// <Description> /// Click, Validate data and save new record /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void btnSave_Click(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".btnSave_Click()"; try { this.SaveData(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } //************************************************************************** /// <Description> /// Click event, turn form to edit mode /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void btnEdit_Click(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".btnEdit_Click()"; try { this.gridDrillDownReport.AllowDelete = true; this.gridDrillDownReport.AllowUpdate = true; btnDelete.Enabled = true; } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } //************************************************************************** /// <Description> /// Click event, delete parameter or display confirm message then delete selected record /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void btnDelete_Click(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".btnDelete_Click()"; try { // get selected row from C1TrueDBGrid SelectedRowCollection objSelectedRowCollection = gridDrillDownReport.SelectedRows; // delete parameter if (objSelectedRowCollection.Count > 0) { IEnumerator objEnum = objSelectedRowCollection.GetEnumerator(); while (objEnum.MoveNext()) { // remove the coresponding row in DataSource of grid with selected index tblDataSource.Rows.RemoveAt(int.Parse(objEnum.Current.ToString())); } } // if not select any parameter, display confirm message to delete drill down report else if (txtReportCode.Text != string.Empty) { DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (dlgResult == DialogResult.Yes) { // delete drill down report if (boDrillDownReport.Delete(this.mMasterReportID, txtReportCode.Text) <= 0) { // TODO: using PCSMessageBox to display alert } } } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } //************************************************************************** /// <Description> /// When user check/uncheck FromColumn column then disable/enable MasterPara column /// If FromColumn is checked then MasterPara will display a combo box with all fields of master report /// Else MasterPara will display a combo box with all parameters of master report /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void gridDrillDownReport_AfterColUpdate(object sender, ColEventArgs e) { const string METHOD_NAME = THIS + ".gridDrillDownReport_AfterColUpdate()"; try { C1DataColumn dcolSelected = this.gridDrillDownReport.Columns[e.ColIndex]; C1DataColumn dcolMasterPara = this.gridDrillDownReport.Columns[sys_ReportDrillDownTable.MASTERPARA_FLD]; if (dcolSelected.DataField == sys_ReportDrillDownTable.FROMCOLUMN_FLD) { drowOldValue = tblDataSource.Rows[this.gridDrillDownReport.Row]; string strOldValue = drowOldValue[sys_ReportDrillDownTable.MASTERPARA_FLD].ToString(); bool blnChecked = bool.Parse(dcolSelected.Value.ToString()); if (blnChecked) { dcolMasterPara.ValueItems.Presentation = PresentationEnum.ComboBox; // display master para as combo box with values is fields //this.gridDrillDownReport.Columns[sys_ReportDrillDownTable.MASTERPARA_FLD] dcolMasterPara.ValueItems.Values.Clear(); for (int i = 0; i < arrMasterFields.Count; i++) { sys_ReportFieldsVO voReportField = (sys_ReportFieldsVO)arrMasterFields[i]; ValueItem objValueItem = new ValueItem(voReportField.FieldName, voReportField.FieldName); dcolMasterPara.ValueItems.Values.Add(objValueItem); } } else { dcolMasterPara.ValueItems.Values.Clear(); // display master para as combo box with values is parameters dcolMasterPara.ValueItems.Presentation = PresentationEnum.ComboBox; // display master para as combo box with values is fields for (int i = 0; i < arrMasterParameters.Count; i++) { sys_ReportParaVO voReportPara = (sys_ReportParaVO)arrMasterParameters[i]; ValueItem objValueItem = new ValueItem(voReportPara.ParaName, voReportPara.ParaName); dcolMasterPara.ValueItems.Values.Add(objValueItem); } //this.gridDrillDownReport.Columns[sys_ReportDrillDownTable.MASTERPARA_FLD].ValueItems.Values. } if (drowOldValue[sys_ReportDrillDownTable.FROMCOLUMN_FLD].Equals(true.ToString())) { if (blnChecked) // return to default value { dcolMasterPara.Value = string.Empty; dcolMasterPara.Text = string.Empty; dcolMasterPara.Text = strOldValue; dcolMasterPara.Value = strOldValue; //this.gridDrillDownReport[this.gridDrillDownReport.Row, 0] = drowSelectedData[sys_ReportDrillDownTable.MASTERPARA_FLD].ToString(); } } else { if (!blnChecked) // return to default value { dcolMasterPara.Value = string.Empty; dcolMasterPara.Text = string.Empty; dcolMasterPara.Text = strOldValue; dcolMasterPara.Value = strOldValue; } } } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } #endregion #region Private Methods //************************************************************************** /// <Description> /// Get all fields from Master Report /// </Description> /// <Inputs> /// MasterReportID /// </Inputs> /// <Outputs> /// ArrayList /// </Outputs> /// <Returns> /// List of fields /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 01-Feb-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private ArrayList GetAllFieldsFromMaster(string pstrMasterReportID) { try { // get all fields of master report FieldPropertiesBO boFieldProperties = new FieldPropertiesBO(); return boFieldProperties.ListByReport(pstrMasterReportID); } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// Get all parameters from Master Report /// </Description> /// <Inputs> /// DataTable /// </Inputs> /// <Outputs> /// ArrayList /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 01-Feb-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private ArrayList GetAllParametersFromMaster(string pstrMasterReportID) { try { // get all parameters of master report ReportParameterBO boParameter = new ReportParameterBO(); return boParameter.ListByReport(pstrMasterReportID); } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// Bind the C1TrueDBGrid with specified datasource /// </Description> /// <Inputs> /// DataTable /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void BindTrueDBGrid(DataTable ptblSource) { try { // clear the data source first this.gridDrillDownReport.DataSource = null; // bind to grid this.gridDrillDownReport.DataSource = this.ConvertDataType(ptblSource); // display FromColumn as check box this.gridDrillDownReport.Columns[sys_ReportDrillDownTable.FROMCOLUMN_FLD].ValueItems.Presentation = PresentationEnum.CheckBox; // do not display ParaOrder column this.gridDrillDownReport.Columns.RemoveAt(ORDER_COLUMN_INDEX); // lock data type and detail para column this.gridDrillDownReport.Splits[0].DisplayColumns[sys_ReportParaTable.DATATYPE_FLD].Locked = true; this.gridDrillDownReport.Splits[0].DisplayColumns[sys_ReportDrillDownTable.DETAILPARA_FLD].Locked = true; } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method use to convert data type number to string, then display to user /// </Description> /// <Inputs> /// DataTable /// </Inputs> /// <Outputs> /// Changed DataTable /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private DataTable ConvertDataType(DataTable ptblSource) { try { IDictionaryEnumerator objEnum = htDataType.GetEnumerator(); foreach (DataRow drow in ptblSource.Rows) { while (objEnum.MoveNext()) { if (objEnum.Key.ToString().Equals(drow[sys_ReportParaTable.DATATYPE_FLD].ToString())) { drow[sys_ReportParaTable.DATATYPE_FLD] = objEnum.Value; break; } } } return ptblSource; } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// Enable button based on selected item /// </Description> /// <Inputs> /// boolean: is editable? /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private void EnableButtons(bool pblnIsEdit) { try { btnEdit.Enabled = (pblnIsEdit) ? true : false; } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method use to check for mandatory field(s) in the form /// </Description> /// <Inputs> /// Control to check /// </Inputs> /// <Outputs> /// bool /// </Outputs> /// <Returns> /// true if validated, false if failed /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 3-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private bool CheckMandatory(Control pobjControl) { try { if (pobjControl.Text.Trim() == string.Empty) { return false; } return true; } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method use to save data to data base /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// bool /// </Outputs> /// <Returns> /// true if successful, false if failed /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 03-Feb-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** private bool SaveData() { try { // validate data if (!CheckMandatory(txtReportCode)) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID); txtReportCode.Focus(); txtReportCode.Select(); return false; } if (!CheckMandatory(txtReportName)) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID); txtReportName.Focus(); txtReportName.Select(); return false; } // delete old drill down record first boDrillDownReport.Delete(this.MasterReportID, this.txtReportCode.Text); // for each param, we create new VO object and store to database DataTable dtblSource = (DataTable) (this.gridDrillDownReport.DataSource); int intOrder = 1; if (dtblSource.Rows.Count > 0) { foreach (DataRow drow in dtblSource.Rows) { sys_ReportDrillDownVO voDrillDown = new sys_ReportDrillDownVO(); voDrillDown.MasterReportID = this.MasterReportID; voDrillDown.DetailReportID = txtReportCode.Text.Trim(); voDrillDown.MasterPara = drow[sys_ReportDrillDownTable.MASTERPARA_FLD].ToString(); voDrillDown.DetailPara = drow[sys_ReportDrillDownTable.DETAILPARA_FLD].ToString(); voDrillDown.FromColumn = bool.Parse(drow[sys_ReportDrillDownTable.FROMCOLUMN_FLD].ToString()); voDrillDown.ParaOrder = intOrder; boDrillDownReport.Add(voDrillDown); intOrder++; } } else { // alert user that there is no parameter PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID); return false; } return true; } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } #endregion } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.Text; namespace BerkeleyDB { /// <summary> /// A class representing configuration parameters for <see cref="Database"/> /// </summary> public class DatabaseConfig { /// <summary> /// The Berkeley DB environment within which to create a database. If /// null, the database will be created stand-alone; that is, it is not /// part of any Berkeley DB environment. /// </summary> /// <remarks> /// The database access methods automatically make calls to the other /// subsystems in Berkeley DB, based on the enclosing environment. For /// example, if the environment has been configured to use locking, the /// access methods will automatically acquire the correct locks when /// reading and writing pages of the database. /// </remarks> public DatabaseEnvironment Env; /// <summary> /// The cache priority for pages referenced by the database. /// </summary> /// <remarks> /// The priority of a page biases the replacement algorithm to be more /// or less likely to discard a page when space is needed in the buffer /// pool. The bias is temporary, and pages will eventually be discarded /// if they are not referenced again. This priority is only advisory, /// and does not guarantee pages will be treated in a specific way. /// </remarks> public CachePriority Priority; /// <summary> /// The size of the shared memory buffer pool -- that is, the cache. /// </summary> /// <remarks> /// <para> /// The cache should be the size of the normal working data set of the /// application, with some small amount of additional memory for unusual /// situations. (Note: the working set is not the same as the number of /// pages accessed simultaneously, and is usually much larger.) /// </para> /// <para> /// The default cache size is 256KB, and may not be specified as less /// than 20KB. Any cache size less than 500MB is automatically increased /// by 25% to account for buffer pool overhead; cache sizes larger than /// 500MB are used as specified. The maximum size of a single cache is /// 4GB on 32-bit systems and 10TB on 64-bit systems. (All sizes are in /// powers-of-two, that is, 256KB is 2^18 not 256,000.) For information /// on tuning the Berkeley DB cache size, see Selecting a cache size in /// the Programmer's Reference Guide. /// </para> /// </remarks> public CacheInfo CacheSize; /// <summary> /// The byte order for integers in the stored database metadata. The /// host byte order of the machine where the Berkeley DB library was /// compiled is the default value. /// </summary> /// <remarks> /// <para> /// The access methods provide no guarantees about the byte ordering of /// the application data stored in the database, and applications are /// responsible for maintaining any necessary ordering. /// </para> /// <para> /// If creating additional databases in a single physical file, this /// parameter will be ignored and the byte order of the existing /// databases will be used. /// </para> /// </remarks> public ByteOrder ByteOrder = ByteOrder.MACHINE; internal bool pagesizeIsSet; private uint pgsz; /// <summary> /// The size of the pages used to hold items in the database, in bytes. /// </summary> /// <remarks> /// <para> /// The minimum page size is 512 bytes, the maximum page size is 64K /// bytes, and the page size must be a power-of-two. If the page size is /// not explicitly set, one is selected based on the underlying /// filesystem I/O block size. The automatically selected size has a /// lower limit of 512 bytes and an upper limit of 16K bytes. /// </para> /// <para> /// For information on tuning the Berkeley DB page size, see Selecting a /// page size in the Programmer's Reference Guide. /// </para> /// <para> /// If creating additional databases in a single physical file, this /// parameter will be ignored and the page size of the existing /// databases will be used. /// </para> /// </remarks> public uint PageSize { get { return pgsz; } set { pagesizeIsSet = true; pgsz = value; } } internal bool encryptionIsSet; private String encryptPwd; private bool doEncrypt; private EncryptionAlgorithm encryptAlg; /// <summary> /// Set the password and algorithm used by the Berkeley DB library to /// perform encryption and decryption. /// </summary> /// <param name="password"> /// The password used to perform encryption and decryption. /// </param> /// <param name="alg"> /// The algorithm used to perform encryption and decryption. /// </param> public void SetEncryption(String password, EncryptionAlgorithm alg) { doEncrypt = true; encryptionIsSet = true; encryptPwd = password; encryptAlg = alg; } /// <summary> /// The password used to perform encryption and decryption. /// </summary> public string EncryptionPassword { get { return encryptPwd; } } /// <summary> /// The algorithm used to perform encryption and decryption. /// </summary> public EncryptionAlgorithm EncryptAlgorithm { get { return encryptAlg; } } /// <summary> /// Encrypt the database using the cryptographic password specified by /// <see cref="DatabaseConfig.SetEncryption">DatabaseConfig.SetEncryption</see> or /// <see cref="DatabaseEnvironmentConfig.SetEncryption">DatabaseEnvironmentConfig.SetEncryption</see>. /// </summary> /// <remarks> /// <para> /// If the database already exists, the value of Encrypted must be the /// same as the existing database or an error will be returned. /// </para> /// <para> /// Encrypted databases are not portable between machines of different /// byte orders, that is, encrypted databases created on big-endian /// machines cannot be read on little-endian machines, and vice versa. /// </para> /// </remarks> public bool Encrypted { get { return doEncrypt; } set { doEncrypt = value; } } /// <summary> /// The prefix string that appears before error messages issued by /// Berkeley DB. /// </summary> public String ErrorPrefix; /// <summary> /// The mechanism for reporting error messages to the application. /// </summary> /// <remarks> /// <para> /// In some cases, when an error occurs, Berkeley DB will call /// ErrorFeedback with additional error information. It is up to the /// delegate function to display the error message in an appropriate /// manner. /// </para> /// <para> /// This error-logging enhancement does not slow performance or /// significantly increase application size, and may be run during /// normal operation as well as during application debugging. /// </para> /// <para> /// For databases opened inside of Berkeley DB environments, setting /// ErrorFeedback affects the entire environment and is equivalent to /// setting <see cref="DatabaseEnvironment.ErrorFeedback"/>. /// </para> /// </remarks> public ErrorFeedbackDelegate ErrorFeedback; /// <summary> /// /// </summary> public DatabaseFeedbackDelegate Feedback; /// <summary> /// If true, do checksum verification of pages read into the cache from /// the backing filestore. /// </summary> /// <remarks> /// <para> /// Berkeley DB uses the SHA1 Secure Hash Algorithm if encryption is /// configured and a general hash algorithm if it is not. /// </para> /// <para> /// If the database already exists, this setting will be ignored. /// </para> /// </remarks> public bool DoChecksum; /// <summary> /// If true, Berkeley DB will not write log records for this database. /// </summary> /// <remarks> /// If Berkeley DB does not write log records, updates of this database /// will exhibit the ACI (atomicity, consistency, and isolation) /// properties, but not D (durability); that is, database integrity will /// be maintained, but if the application or system fails, integrity /// will not persist. The database file must be verified and/or restored /// from backup after a failure. In order to ensure integrity after /// application shut down, the database must be synced when closed, or /// all database changes must be flushed from the database environment /// cache using either /// <see cref="DatabaseEnvironment.Checkpoint"/> or /// <see cref="DatabaseEnvironment.SyncMemPool"/>. All database objects /// for a single physical file must set NonDurableTxns, including /// database objects for different databases in a physical file. /// </remarks> public bool NonDurableTxns; /// <summary> /// Configuration of <see cref="BaseDatabase"/> handle to obtain a write /// lock on the entire database. /// </summary> /// <remarks> /// <para> /// If true, configure the <see cref="BaseDatabase"/> handle to obtain a /// write lock on the entire database. When the database is opened it /// will immediately throw <see cref="LockNotGrantedException"/> if it /// cannot obtain the exclusive lock immediately. If False, configure /// the <see cref="BaseDatabase"/> handle to obtain a write lock on the /// entire database. When the database is opened, it will block until it /// can obtain the exclusive lock. If null, do not configure the /// <see cref="BaseDatabase"/> handle to obtain a write lock on the /// entire database. /// </para> /// </remarks> public bool? NoWaitDbExclusiveLock; internal uint flags { get { uint ret = 0; ret |= DoChecksum ? Internal.DbConstants.DB_CHKSUM : 0; ret |= Encrypted ? Internal.DbConstants.DB_ENCRYPT : 0; ret |= NonDurableTxns ? Internal.DbConstants.DB_TXN_NOT_DURABLE : 0; return ret; } } /// <summary> /// Enclose the open call within a transaction. If the call succeeds, /// the open operation will be recoverable and all subsequent database /// modification operations based on this handle will be transactionally /// protected. If the call fails, no database will have been created. /// </summary> public bool AutoCommit; /// <summary> /// Cause the database object to be free-threaded; that is, concurrently /// usable by multiple threads in the address space. /// </summary> public bool FreeThreaded; /// <summary> /// Do not map this database into process memory. /// </summary> public bool NoMMap; /// <summary> /// Open the database for reading only. Any attempt to modify items in /// the database will fail, regardless of the actual permissions of any /// underlying files. /// </summary> public bool ReadOnly; /// <summary> /// Support transactional read operations with degree 1 isolation. /// </summary> /// <remarks> /// Read operations on the database may request the return of modified /// but not yet committed data. This flag must be specified on all /// database objects used to perform dirty reads or database updates, /// otherwise requests for dirty reads may not be honored and the read /// may block. /// </remarks> public bool ReadUncommitted; /// <summary> /// Physically truncate the underlying file, discarding all previous databases it might have held. /// </summary> /// <remarks> /// <para> /// Underlying filesystem primitives are used to implement this flag. /// For this reason, it is applicable only to the file and cannot be /// used to discard databases within a file. /// </para> /// <para> /// This setting cannot be lock or transaction-protected, and it is an /// error to specify it in a locking or transaction-protected /// environment. /// </para> /// </remarks> public bool Truncate; /// <summary> /// Open the database with support for multiversion concurrency control. /// </summary> /// <remarks> /// This will cause updates to the database to follow a copy-on-write /// protocol, which is required to support snapshot isolation. This /// settting requires that the database be transactionally protected /// during its open and is not supported by the queue format. /// </remarks> public bool UseMVCC; internal uint openFlags { get { uint ret = 0; ret |= AutoCommit ? Internal.DbConstants.DB_AUTO_COMMIT : 0; ret |= FreeThreaded ? Internal.DbConstants.DB_THREAD : 0; ret |= NoMMap ? Internal.DbConstants.DB_NOMMAP : 0; ret |= ReadOnly ? Internal.DbConstants.DB_RDONLY : 0; ret |= ReadUncommitted ? Internal.DbConstants.DB_READ_UNCOMMITTED : 0; ret |= Truncate ? Internal.DbConstants.DB_TRUNCATE : 0; ret |= UseMVCC ? Internal.DbConstants.DB_MULTIVERSION : 0; return ret; } } /// <summary> /// Instantiate a new DatabaseConfig object /// </summary> public DatabaseConfig() { Env = null; Priority = CachePriority.DEFAULT; pagesizeIsSet = false; encryptionIsSet = false; ErrorPrefix = null; Feedback = null; DoChecksum = false; NonDurableTxns = false; NoWaitDbExclusiveLock = null; AutoCommit = false; FreeThreaded = false; NoMMap = false; ReadOnly = false; ReadUncommitted = false; Truncate = false; UseMVCC = false; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geodatabase; namespace HookActions { [Guid("7DA9C483-ABDC-4e42-AA9F-530B33980D15")] [ClassInterface(ClassInterfaceType.None)] [ProgId("HookActions.hookActionsZoom")] public sealed class hookActionsZoom : BaseCommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); GMxCommands.Register(regKey); MxCommands.Register(regKey); ControlsCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); GMxCommands.Unregister(regKey); MxCommands.Unregister(regKey); ControlsCommands.Unregister(regKey); } #endregion #endregion private IHookHelper m_hookHelper = null; private IGlobeHookHelper m_globeHookHelper = null; public hookActionsZoom() { base.m_category = "HookActions"; base.m_caption = "Zoom selected features"; base.m_message = "Zoom selected features"; base.m_toolTip = "Zoom selected features"; base.m_name = "HookActions_Zoom"; } public override void OnCreate(object hook) { // Test the hook that calls this command and disable if nothing valid try { m_hookHelper = new HookHelperClass(); m_hookHelper.Hook = hook; if (m_hookHelper.ActiveView == null) { m_hookHelper = null; } } catch { m_hookHelper = null; } if (m_hookHelper == null) { //Can be globe try { m_globeHookHelper = new GlobeHookHelperClass(); m_globeHookHelper.Hook = hook; if (m_globeHookHelper.ActiveViewer == null) { //Nothing valid! m_globeHookHelper = null; } } catch { m_globeHookHelper = null; } } if (m_globeHookHelper == null && m_hookHelper == null) base.m_enabled = false; else base.m_enabled = true; } public override bool Enabled { get { IHookActions hookActions = null; IBasicMap basicMap = null; //Get basic map and set hook actions if (m_hookHelper != null) { basicMap = m_hookHelper.FocusMap as IBasicMap; hookActions = m_hookHelper as IHookActions; } else if (m_globeHookHelper != null) { basicMap = m_globeHookHelper.Globe as IBasicMap; hookActions = m_globeHookHelper as IHookActions; } //Disable if no features selected IEnumFeature enumFeature = basicMap.FeatureSelection as IEnumFeature; IFeature feature = enumFeature.Next(); if (feature == null) return false; //Enable if action supported on first selected feature if (hookActions.get_ActionSupported(feature.Shape, esriHookActions.esriHookActionsZoom)) return true; else return false; } } public override void OnClick() { IHookActions hookActions = null; IBasicMap basicMap = null; //Get basic map and set hook actions if (m_hookHelper != null) { basicMap = m_hookHelper.FocusMap as IBasicMap; hookActions = m_hookHelper as IHookActions; } else if (m_globeHookHelper != null) { basicMap = m_globeHookHelper.Globe as IBasicMap; hookActions = m_globeHookHelper as IHookActions; } //Get feature selection ISelection selection = basicMap.FeatureSelection; //Get enumerator IEnumFeature enumFeature = selection as IEnumFeature; enumFeature.Reset(); //Set first feature IFeature feature; feature = enumFeature.Next(); //Loop though the features IArray array = new ESRI.ArcGIS.esriSystem.Array(); while (feature != null) { //Add feature to array array.Add(feature.Shape); //Set next feature feature = enumFeature.Next(); } //If the action is supported perform the action if (hookActions.get_ActionSupportedOnMultiple(array, esriHookActions.esriHookActionsZoom)) hookActions.DoActionOnMultiple(array, esriHookActions.esriHookActionsZoom); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; using System.Xml; using ConfigDataInfo; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.ServiceManagement.Extensions; using Microsoft.WindowsAzure.Management.Utilities.Common; using Model; using WindowsAzure.ServiceManagement; using Microsoft.WindowsAzure.Storage.Blob; using IaasCmdletInfo; using PaasCmdletInfo; using PIRCmdletInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.PlatformImageRepository.Model; public class ServiceManagementCmdletTestHelper { /// <summary> /// Run a powershell cmdlet that returns the first PSObject as a return value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet"></param> /// <returns></returns> private T RunPSCmdletAndReturnFirst<T>(PowershellCore.CmdletsInfo cmdlet) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { try { var operation = (ManagementOperationContext)result[0].BaseObject; Console.WriteLine("Operation ID: {0}", operation.OperationId); } catch { } return (T) result[0].BaseObject; } return default(T); } /// <summary> /// Run a powershell cmdlet that returns a collection of PSObjects as a return value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet"></param> /// <returns></returns> private Collection<T> RunPSCmdletAndReturnAll<T>(PowershellCore.CmdletsInfo cmdlet) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<T> resultCollection = new Collection<T>(); foreach (PSObject re in result) { resultCollection.Add((T)re.BaseObject); } try { var operation = (ManagementOperationContext)result[0].BaseObject; Console.WriteLine("Operation ID: {0}", operation.OperationId); } catch { } return resultCollection; } public Collection <PSObject> RunPSScript(string script) { List<string> st = new List<string>(); st.Add(script); WindowsAzurePowershellScript azurePowershellCmdlet = new WindowsAzurePowershellScript(st); return azurePowershellCmdlet.Run(); } public CopyState CheckCopyBlobStatus(string destContainer, string destBlob) { List<string> st = new List<string>(); st.Add(string.Format("Get-AzureStorageBlobCopyState -Container {0} -Blob {1}", destContainer, destBlob)); WindowsAzurePowershellScript azurePowershellCmdlet = new WindowsAzurePowershellScript(st); return (CopyState)azurePowershellCmdlet.Run()[0].BaseObject; } public bool TestAzureServiceName(string serviceName) { return RunPSCmdletAndReturnFirst<bool>(new TestAzureNameCmdletInfo("Service", serviceName)); } public Collection<LocationsContext> GetAzureLocation() { return RunPSCmdletAndReturnAll<LocationsContext>(new GetAzureLocationCmdletInfo()); } public string GetAzureLocationName(string[] keywords) { Collection<LocationsContext> locations = GetAzureLocation(); if (keywords != null) { foreach (LocationsContext location in locations) { if (MatchExactWords(location.Name, keywords) >= 0) { return location.Name; } } } else { if (locations.Count == 1) { return locations[0].Name; } } return null; } private static int MatchExactWords(string input, string[] keywords) { //returns -1 for no match, 0 for exact match, and a positive number for how many keywords are matched. int result = 0; if (string.IsNullOrEmpty(input) || keywords.Length == 0) return -1; foreach (string keyword in keywords) { //For whole word match, modify pattern to be "\b{0}\b" if (!string.IsNullOrEmpty(keyword) && keyword.ToLowerInvariant().Equals(input.ToLowerInvariant())) { result++; } } if (result == keywords.Length) { return 0; } else if (result == 0) { return -1; } else { return result; } } public Collection<OSVersionsContext> GetAzureOSVersion() { return RunPSCmdletAndReturnAll<OSVersionsContext>(new GetAzureOSVersionCmdletInfo()); } #region CertificateSetting, VMConifig, ProvisioningConfig public CertificateSetting NewAzureCertificateSetting(string store, string thumbprint) { return RunPSCmdletAndReturnFirst<CertificateSetting>(new NewAzureCertificateSettingCmdletInfo(store, thumbprint)); } public PersistentVM NewAzureVMConfig(AzureVMConfigInfo vmConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new NewAzureVMConfigCmdletInfo(vmConfig)); } public PersistentVM AddAzureProvisioningConfig(AzureProvisioningConfigInfo provConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureProvisioningConfigCmdletInfo(provConfig)); } #endregion #region AzureAffinityGroup public ManagementOperationContext NewAzureAffinityGroup(string name, string location, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext> (new NewAzureAffinityGroupCmdletInfo(name, location, label, description)); } public Collection<AffinityGroupContext> GetAzureAffinityGroup(string name) { return RunPSCmdletAndReturnAll<AffinityGroupContext>(new GetAzureAffinityGroupCmdletInfo(name)); } public ManagementOperationContext SetAzureAffinityGroup(string name, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext> (new SetAzureAffinityGroupCmdletInfo(name, label, description)); } public ManagementOperationContext RemoveAzureAffinityGroup(string name) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureAffinityGroupCmdletInfo(name)); } #endregion #region AzureAvailabilitySet public PersistentVM SetAzureAvailabilitySet(string availabilitySetName, PersistentVM vm) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureAvailabilitySetCmdletInfo(availabilitySetName, vm)); } public PersistentVM SetAzureAvailabilitySet(string vmName, string serviceName, string availabilitySetName) { if (!string.IsNullOrEmpty(availabilitySetName)) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureAvailabilitySetCmdletInfo(availabilitySetName, vm)); } else { return null; } } #endregion AzureAvailabilitySet #region AzureCertificate public ManagementOperationContext AddAzureCertificate(string serviceName, PSObject cert, string password = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new AddAzureCertificateCmdletInfo(serviceName, cert, password)); } public Collection <CertificateContext> GetAzureCertificate(string serviceName, string thumbprint = null, string algorithm = null) { return RunPSCmdletAndReturnAll<CertificateContext> (new GetAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm)); } public ManagementOperationContext RemoveAzureCertificate(string serviceName, string thumbprint, string algorithm) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm)); } #endregion #region AzureDataDisk public PersistentVM AddAzureDataDisk(AddAzureDataDiskConfig diskConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureDataDiskCmdletInfo(diskConfig)); } public void AddDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig [] diskConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AddAzureDataDiskConfig config in diskConfigs) { config.Vm = vm; vm = AddAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } public PersistentVM SetAzureDataDisk(SetAzureDataDiskConfig discCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureDataDiskCmdletInfo(discCfg)); } public void SetDataDisk(string vmName, string serviceName, HostCaching hc, int lun) { SetAzureDataDiskConfig config = new SetAzureDataDiskConfig(hc, lun); config.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureDataDisk(config)); } public Collection<DataVirtualHardDisk> GetAzureDataDisk(string vmName, string serviceName) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); return RunPSCmdletAndReturnAll<DataVirtualHardDisk>(new GetAzureDataDiskCmdletInfo(vmRolectx.VM)); } public Collection<DataVirtualHardDisk> GetAzureDataDisk(PersistentVM vm) { return RunPSCmdletAndReturnAll<DataVirtualHardDisk>(new GetAzureDataDiskCmdletInfo(vm)); } public PersistentVM RemoveAzureDataDisk(RemoveAzureDataDiskConfig discCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new RemoveAzureDataDiskCmdletInfo(discCfg)); } public void RemoveDataDisk(string vmName, string serviceName, int [] lunSlots) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (int lun in lunSlots) { RemoveAzureDataDiskConfig config = new RemoveAzureDataDiskConfig(lun, vm); RemoveAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } #endregion #region AzureDeployment public ManagementOperationContext NewAzureDeployment(string serviceName, string packagePath, string configPath, string slot, string label, string name, bool doNotStart, bool warning, ExtensionConfigurationInput config = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureDeploymentCmdletInfo(serviceName, packagePath, configPath, slot, label, name, doNotStart, warning, config)); } public DeploymentInfoContext GetAzureDeployment(string serviceName, string slot) { return RunPSCmdletAndReturnFirst<DeploymentInfoContext>(new GetAzureDeploymentCmdletInfo(serviceName, slot)); } public DeploymentInfoContext GetAzureDeployment(string serviceName) { return GetAzureDeployment(serviceName, DeploymentSlotType.Production); } private ManagementOperationContext SetAzureDeployment(SetAzureDeploymentCmdletInfo cmdletInfo) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(cmdletInfo); } public ManagementOperationContext SetAzureDeploymentStatus(string serviceName, string slot, string newStatus) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentStatusCmdletInfo(serviceName, slot, newStatus)); } public ManagementOperationContext SetAzureDeploymentConfig(string serviceName, string slot, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentConfigCmdletInfo(serviceName, slot, configPath)); } public ManagementOperationContext SetAzureDeploymentUpgrade(string serviceName, string slot, string mode, string packagePath, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentUpgradeCmdletInfo(serviceName, slot, mode, packagePath, configPath)); } public ManagementOperationContext SetAzureDeployment(string option, string serviceName, string packagePath, string newStatus, string configName, string slot, string mode, string label, string roleName, bool force) { return SetAzureDeployment(new SetAzureDeploymentCmdletInfo(option, serviceName, packagePath, newStatus, configName, slot, mode, label, roleName, force)); } public ManagementOperationContext RemoveAzureDeployment(string serviceName, string slot, bool force) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureDeploymentCmdletInfo(serviceName, slot, force)); } public ManagementOperationContext MoveAzureDeployment(string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new MoveAzureDeploymentCmdletInfo(serviceName)); } public ManagementOperationContext SetAzureWalkUpgradeDomain(string serviceName, string slot, int domainNumber) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureWalkUpgradeDomainCmdletInfo(serviceName, slot, domainNumber)); } #endregion #region AzureDisk // Add-AzureDisk public DiskContext AddAzureDisk(string diskName, string mediaPath, string label, string os) { DiskContext result = new DiskContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<DiskContext>(new AddAzureDiskCmdletInfo(diskName, mediaPath, label, os)), "409", 3, 60); return result; } // Get-AzureDisk public Collection<DiskContext> GetAzureDisk(string diskName) { return GetAzureDisk(new GetAzureDiskCmdletInfo(diskName)); } public Collection<DiskContext> GetAzureDisk() { return GetAzureDisk(new GetAzureDiskCmdletInfo((string)null)); } private Collection<DiskContext> GetAzureDisk(GetAzureDiskCmdletInfo getAzureDiskCmdletInfo) { return RunPSCmdletAndReturnAll<DiskContext>(getAzureDiskCmdletInfo); } public Collection<DiskContext> GetAzureDiskAttachedToRoleName(string[] roleName, bool exactMatch = true) { Collection<DiskContext> retDisks = new Collection<DiskContext>(); Collection<DiskContext> disks = GetAzureDisk(); foreach (DiskContext disk in disks) { if (disk.AttachedTo != null && disk.AttachedTo.RoleName != null) { if (Utilities.MatchKeywords(disk.AttachedTo.RoleName, roleName, exactMatch) >= 0) retDisks.Add(disk); } } return retDisks; } // Remove-AzureDisk public ManagementOperationContext RemoveAzureDisk(string diskName, bool deleteVhd) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureDiskCmdletInfo(diskName, deleteVhd)); } // Update-AzureDisk public DiskContext UpdateAzureDisk(string diskName, string label) { return RunPSCmdletAndReturnFirst<DiskContext>(new UpdateAzureDiskCmdletInfo(diskName, label)); } #endregion #region AzureDns public DnsServer NewAzureDns(string name, string ipAddress) { return RunPSCmdletAndReturnFirst<DnsServer>(new NewAzureDnsCmdletInfo(name, ipAddress)); } public DnsServerList GetAzureDns(DnsSettings settings) { GetAzureDnsCmdletInfo getAzureDnsCmdletInfo = new GetAzureDnsCmdletInfo(settings); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDnsCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); DnsServerList dnsList = new DnsServerList(); foreach (PSObject re in result) { dnsList.Add((DnsServer)re.BaseObject); } return dnsList; } #endregion #region AzureEndpoint public PersistentVM AddAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureEndpointCmdletInfo(endPointConfig)); } public void AddEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo [] endPointConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AzureEndPointConfigInfo config in endPointConfigs) { config.Vm = vm; vm = AddAzureEndPoint(config); } UpdateAzureVM(vmName, serviceName, vm); } public Collection <InputEndpointContext> GetAzureEndPoint(PersistentVMRoleContext vmRoleCtxt) { return RunPSCmdletAndReturnAll<InputEndpointContext>(new GetAzureEndpointCmdletInfo(vmRoleCtxt)); } public Collection<InputEndpointContext> GetAzureEndPoint(PersistentVM vm) { return RunPSCmdletAndReturnAll<InputEndpointContext>(new GetAzureEndpointCmdletInfo(vm)); } public void SetEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo endPointConfig) { endPointConfig.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureEndPoint(endPointConfig)); } public PersistentVM SetAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { if (null != endPointConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureEndpointCmdletInfo(endPointConfig)); } return null; } public void SetLBEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo endPointConfig, AzureEndPointConfigInfo.ParameterSet paramset) { endPointConfig.Vm = GetAzureVM(vmName, serviceName).VM; SetAzureLoadBalancedEndPoint(endPointConfig, paramset); //UpdateAzureVM(vmName, serviceName, SetAzureLoadBalancedEndPoint(endPointConfig, paramset)); } private ManagementOperationContext SetAzureLoadBalancedEndPoint(AzureEndPointConfigInfo endPointConfig, AzureEndPointConfigInfo.ParameterSet paramset) { if (null != endPointConfig) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureLoadBalancedEndpointCmdletInfo(endPointConfig, paramset)); } return null; } public PersistentVMRoleContext RemoveAzureEndPoint(string epName, PersistentVMRoleContext vmRoleCtxt) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new RemoveAzureEndpointCmdletInfo(epName, vmRoleCtxt)); } public PersistentVM RemoveAzureEndPoint(string epName, PersistentVM vm) { return RunPSCmdletAndReturnFirst<PersistentVM>(new RemoveAzureEndpointCmdletInfo(epName, vm)); } public void RemoveEndPoint(string vmName, string serviceName, string [] epNames) { PersistentVMRoleContext vmRoleCtxt = GetAzureVM(vmName, serviceName); foreach (string ep in epNames) { vmRoleCtxt.VM = RemoveAzureEndPoint(ep, vmRoleCtxt).VM; } UpdateAzureVM(vmName, serviceName, vmRoleCtxt.VM); } #endregion #region AzureOSDisk public PersistentVM SetAzureOSDisk(HostCaching hc, PersistentVM vm) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureOSDiskCmdletInfo(hc, vm)); } public OSVirtualHardDisk GetAzureOSDisk(PersistentVM vm) { return RunPSCmdletAndReturnFirst<OSVirtualHardDisk>(new GetAzureOSDiskCmdletInfo(vm)); } #endregion #region AzureRole public ManagementOperationContext SetAzureRole(string serviceName, string slot, string roleName, int count) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureRoleCmdletInfo(serviceName, slot, roleName, count)); } public Collection<RoleContext> GetAzureRole(string serviceName, string slot, string roleName, bool details) { return RunPSCmdletAndReturnAll<RoleContext>(new GetAzureRoleCmdletInfo(serviceName, slot, roleName, details)); } #endregion #region AzureQuickVM public ManagementOperationContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName, InstanceSize? instanceSize) { ManagementOperationContext result = new ManagementOperationContext(); try { result = RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureQuickVMCmdletInfo(os, name, serviceName, imageName, userName, password, locationName, instanceSize)); } catch (Exception e) { if (e.ToString().Contains("409")) { Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureQuickVMCmdletInfo(os, name, serviceName, imageName, userName, password, null, instanceSize)), "409", 4, 60); } else { Console.WriteLine(e.InnerException.ToString()); throw; } } return result; } public ManagementOperationContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName = null) { return NewAzureQuickVM(os, name, serviceName, imageName, userName, password, locationName, null); } #endregion #region AzurePlatformVMImage internal ManagementOperationContext SetAzurePlatformVMImageReplicate(string imageName, string[] locations) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzurePlatformVMImageCmdletInfo(imageName, null, locations)); } internal ManagementOperationContext SetAzurePlatformVMImagePublic(string imageName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzurePlatformVMImageCmdletInfo(imageName, "Public", null)); } internal ManagementOperationContext SetAzurePlatformVMImagePrivate(string imageName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzurePlatformVMImageCmdletInfo(imageName, "Private", null)); } internal OSImageDetailsContext GetAzurePlatformVMImage(string imageName) { return RunPSCmdletAndReturnFirst<OSImageDetailsContext>(new GetAzurePlatformVMImageCmdletInfo(imageName)); } internal ManagementOperationContext RemoveAzurePlatformVMImage(string imageName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzurePlatformVMImageCmdletInfo(imageName)); } #endregion #region AzurePublishSettingsFile internal void ImportAzurePublishSettingsFile() { this.ImportAzurePublishSettingsFile(CredentialHelper.PublishSettingsFile); } internal void ImportAzurePublishSettingsFile(string publishSettingsFile) { ImportAzurePublishSettingsFileCmdletInfo importAzurePublishSettingsFileCmdlet = new ImportAzurePublishSettingsFileCmdletInfo(publishSettingsFile); WindowsAzurePowershellCmdlet importAzurePublishSettingsFile = new WindowsAzurePowershellCmdlet(importAzurePublishSettingsFileCmdlet); var i = importAzurePublishSettingsFile.Run(); Console.WriteLine(i.ToString()); } #endregion #region AzureSubscription public Collection<SubscriptionData> GetAzureSubscription() { return RunPSCmdletAndReturnAll<SubscriptionData>(new GetAzureSubscriptionCmdletInfo()); } public SubscriptionData GetCurrentAzureSubscription() { Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.IsDefault) { return subscription; } } return null; } public SubscriptionData SetAzureSubscription(string subscriptionName, string currentStorageAccount) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName, currentStorageAccount); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } public SubscriptionData SetDefaultAzureSubscription(string subscriptionName) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } public bool SelectAzureSubscription(string subscriptionName, bool clear = false, string subscriptionDataFile = null) { return RunPSCmdletAndReturnFirst<bool>(new SelectAzureSubscriptionCmdletInfo(subscriptionName, clear, subscriptionDataFile)); } #endregion #region AzureSubnet public SubnetNamesCollection GetAzureSubnet(PersistentVM vm) { GetAzureSubnetCmdletInfo getAzureSubnetCmdlet = new GetAzureSubnetCmdletInfo(vm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureSubnetCmdlet); Collection <PSObject> result = azurePowershellCmdlet.Run(); SubnetNamesCollection subnets = new SubnetNamesCollection(); foreach (PSObject re in result) { subnets.Add((string)re.BaseObject); } return subnets; } public PersistentVM SetAzureSubnet(PersistentVM vm, string [] subnetNames) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureSubnetCmdletInfo(vm, subnetNames)); } #endregion #region AzureStorageAccount public ManagementOperationContext NewAzureStorageAccount(string storageName, string locationName, string affinity, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureStorageAccountCmdletInfo(storageName, locationName, affinity, label, description)); } public StorageServicePropertiesOperationContext NewAzureStorageAccount(string storageName, string locationName) { NewAzureStorageAccount(storageName, locationName, null, null, null); Collection<StorageServicePropertiesOperationContext> storageAccounts = GetAzureStorageAccount(null); foreach (StorageServicePropertiesOperationContext storageAccount in storageAccounts) { if (storageAccount.StorageAccountName == storageName) return storageAccount; } return null; } public Collection<StorageServicePropertiesOperationContext> GetAzureStorageAccount(string accountName) { return RunPSCmdletAndReturnAll<StorageServicePropertiesOperationContext>(new GetAzureStorageAccountCmdletInfo(accountName)); } public ManagementOperationContext SetAzureStorageAccount(string accountName, string label, string description, bool? geoReplication) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureStorageAccountCmdletInfo(accountName, label, description, geoReplication)); } public void RemoveAzureStorageAccount(string storageAccountName) { Utilities.RetryActionUntilSuccess( () => RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureStorageAccountCmdletInfo(storageAccountName)), "409", 3, 60); } #endregion #region AzureStorageKey public StorageServiceKeyOperationContext GetAzureStorageAccountKey(string stroageAccountName) { return RunPSCmdletAndReturnFirst<StorageServiceKeyOperationContext>(new GetAzureStorageKeyCmdletInfo(stroageAccountName)); } public StorageServiceKeyOperationContext NewAzureStorageAccountKey(string stroageAccountName, string keyType) { return RunPSCmdletAndReturnFirst<StorageServiceKeyOperationContext>(new NewAzureStorageKeyCmdletInfo(stroageAccountName, keyType)); } #endregion #region AzureService public ManagementOperationContext NewAzureService(string serviceName, string location) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureServiceCmdletInfo(serviceName, location)); } internal void NewAzureService(string serviceName, string serviceLabel, string locationName) { NewAzureServiceCmdletInfo newAzureServiceCmdletInfo = new NewAzureServiceCmdletInfo(serviceName, serviceLabel, locationName); WindowsAzurePowershellCmdlet newAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(newAzureServiceCmdletInfo); Collection<PSObject> result = newAzureServiceCmdlet.Run(); } public bool RemoveAzureService(string serviceName) { bool result = false; Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<bool>(new RemoveAzureServiceCmdletInfo(serviceName)), "ConflictError", 3, 60); return result; } public HostedServiceDetailedContext GetAzureService(string serviceName) { return RunPSCmdletAndReturnFirst<HostedServiceDetailedContext>(new GetAzureServiceCmdletInfo(serviceName)); } #endregion #region AzureServiceDiagnosticsExtension // New-AzureServiceDiagnosticsExtensionConfig public ExtensionConfigurationInput NewAzureServiceDiagnosticsExtensionConfig(string storage, XmlDocument config = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(storage, config, roles)); } public ExtensionConfigurationInput NewAzureServiceDiagnosticsExtensionConfig (string storage, X509Certificate2 cert, XmlDocument config = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput> (new NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(storage, cert, config, roles)); } public ExtensionConfigurationInput NewAzureServiceDiagnosticsExtensionConfig (string storage, string thumbprint, string algorithm = null, XmlDocument config = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput> (new NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(storage, thumbprint, algorithm, config, roles)); } // Set-AzureServiceDiagnosticsExtension public ManagementOperationContext SetAzureServiceDiagnosticsExtension (string service, string storage, XmlDocument config = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceDiagnosticsExtensionCmdletInfo(service, storage, config, roles, slot)); } public ManagementOperationContext SetAzureServiceDiagnosticsExtension(string service, string storage, X509Certificate2 cert, XmlDocument config = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceDiagnosticsExtensionCmdletInfo(service, storage, cert, config, roles, slot)); } public ManagementOperationContext SetAzureServiceDiagnosticsExtension(string service, string storage, string thumbprint, string algorithm = null, XmlDocument config = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceDiagnosticsExtensionCmdletInfo(service, storage, thumbprint, algorithm, config, roles, slot)); } // Get-AzureServiceDiagnosticsExtension public Collection <DiagnosticExtensionContext> GetAzureServiceDiagnosticsExtension(string serviceName, string slot = null) { return RunPSCmdletAndReturnAll<DiagnosticExtensionContext>(new GetAzureServiceDiagnosticsExtensionCmdletInfo(serviceName, slot)); } // Remove-AzureServiceDiagnosticsExtension public ManagementOperationContext RemoveAzureServiceDiagnosticsExtension(string serviceName, bool uninstall = false, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureServiceDiagnosticsExtensionCmdletInfo(serviceName, uninstall, roles, slot)); } #endregion #region AzureServiceRemoteDesktopExtension // New-AzureServiceRemoteDesktopExtensionConfig public ExtensionConfigurationInput NewAzureServiceRemoteDesktopExtensionConfig(PSCredential cred, DateTime? exp = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(cred, exp, roles)); } public ExtensionConfigurationInput NewAzureServiceRemoteDesktopExtensionConfig(PSCredential cred, X509Certificate2 cert, string alg = null, DateTime? exp = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(cred, cert, alg, exp, roles)); } public ExtensionConfigurationInput NewAzureServiceRemoteDesktopExtensionConfig(PSCredential cred, string thumbprint, string algorithm = null, DateTime? exp = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(cred, thumbprint, algorithm, exp, roles)); } // Set-AzureServiceRemoteDesktopExtension public ManagementOperationContext SetAzureServiceRemoteDesktopExtension(string serviceName, PSCredential cred, DateTime? exp = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, cred, exp, roles, slot)); } public ManagementOperationContext SetAzureServiceRemoteDesktopExtension(string serviceName, PSCredential credential, X509Certificate2 cert, DateTime? expiration = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, credential, cert, expiration, roles, slot)); } public ManagementOperationContext SetAzureServiceRemoteDesktopExtension(string serviceName, PSCredential credential, string thumbprint, string algorithm = null, DateTime? expiration = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, credential, thumbprint, algorithm, expiration, roles, slot)); } // Get-AzureServiceRemoteDesktopExtension public Collection <RemoteDesktopExtensionContext> GetAzureServiceRemoteDesktopExtension(string serviceName, string slot = null) //public RemoteDesktopExtensionContext GetAzureServiceRemoteDesktopExtension(string serviceName, string slot = null) { return RunPSCmdletAndReturnAll<RemoteDesktopExtensionContext>(new GetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, slot)); //return RunPSCmdletAndReturnFirst<RemoteDesktopExtensionContext>(new GetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, slot)); } // Remove-AzureServiceRemoteDesktopExtension public ManagementOperationContext RemoveAzureServiceRemoteDesktopExtension(string serviceName, bool uninstall = false, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, uninstall, roles, slot)); } #endregion #region AzureVM internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] VMs, string location = null) { return NewAzureVM(serviceName, VMs, null, null, null, null, null, null, location); } internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] vms, string vnetName, DnsServer[] dnsSettings, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentDescription, string location =null, string affinityGroup = null) { Collection<ManagementOperationContext> result = new Collection<ManagementOperationContext>(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnAll<ManagementOperationContext>(new NewAzureVMCmdletInfo(serviceName, vms, vnetName, dnsSettings, serviceLabel, serviceDescription, deploymentLabel, deploymentDescription, location, affinityGroup)), "409", 5, 60); return result; } public PersistentVMRoleContext GetAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new GetAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext RemoveAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext StartAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new StartAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext StopAzureVM(PersistentVM vm, string serviceName, bool stay = false, bool force = false) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new StopAzureVMCmdletInfo(vm, serviceName, stay, force)); } public ManagementOperationContext StopAzureVM(string vmName, string serviceName, bool stay = false, bool force = false) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new StopAzureVMCmdletInfo(vmName, serviceName, stay, force)); } public void RestartAzureVM(string vmName, string serviceName) { RestartAzureVMCmdletInfo restartAzureVMCmdlet = new RestartAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(restartAzureVMCmdlet); azurePowershellCmdlet.Run(); } public PersistentVMRoleContext ExportAzureVM(string vmName, string serviceName, string path) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new ExportAzureVMCmdletInfo(vmName, serviceName, path)); } public Collection<PersistentVM> ImportAzureVM(string path) { return RunPSCmdletAndReturnAll<PersistentVM>(new ImportAzureVMCmdletInfo(path)); } public ManagementOperationContext UpdateAzureVM(string vmName, string serviceName, PersistentVM persistentVM) { ManagementOperationContext result = new ManagementOperationContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<ManagementOperationContext>(new UpdateAzureVMCmdletInfo(vmName, serviceName, persistentVM)), "409", 3, 60); return result; } #endregion #region AzureVMImage public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OS os, string label = null) { OSImageContext result = new OSImageContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<OSImageContext>(new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, label)), "409", 3, 60); return result; } public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OS os, InstanceSize recommendedSize) { OSImageContext result = new OSImageContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<OSImageContext>(new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, null, recommendedSize)), "409", 3, 60); return result; } public OSImageContext UpdateAzureVMImage(string imageName, string label) { return RunPSCmdletAndReturnFirst<OSImageContext>(new UpdateAzureVMImageCmdletInfo(imageName, label)); } public OSImageContext UpdateAzureVMImage(string imageName, InstanceSize recommendedSize) { return RunPSCmdletAndReturnFirst<OSImageContext>(new UpdateAzureVMImageCmdletInfo(imageName, null, recommendedSize)); } public ManagementOperationContext RemoveAzureVMImage(string imageName, bool deleteVhd = false) { ManagementOperationContext result = new ManagementOperationContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVMImageCmdletInfo(imageName, deleteVhd)), "409", 3, 60); return result; } public void SaveAzureVMImage(string serviceName, string vmName, string newVmName, string newImageName = null) { RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SaveAzureVMImageCmdletInfo(serviceName, vmName, newVmName, newImageName)); } public Collection<OSImageContext> GetAzureVMImage(string imageName = null) { return RunPSCmdletAndReturnAll<OSImageContext>(new GetAzureVMImageCmdletInfo(imageName)); } public string GetAzureVMImageName(string[] keywords, bool exactMatch = true) { Collection<OSImageContext> vmImages = GetAzureVMImage(); foreach (OSImageContext image in vmImages) { if (Utilities.MatchKeywords(image.ImageName, keywords, exactMatch) >= 0) return image.ImageName; } foreach (OSImageContext image in vmImages) { if (Utilities.MatchKeywords(image.OS, keywords, exactMatch) >= 0) return image.ImageName; } return null; } #endregion #region AzureVhd public string AddAzureVhdStop(FileInfo localFile, string destination, int ms) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, null)); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination) { return AddAzureVhd(localFile, destination, null); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, string baseImage) { return AddAzureVhd(localFile, destination, null, false, baseImage); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, bool overwrite) { return AddAzureVhd(localFile, destination, null, overwrite); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, int? numberOfUploaderThreads, bool overWrite = false, string baseImage = null) { VhdUploadContext result = new VhdUploadContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, numberOfUploaderThreads, overWrite, baseImage)), "pipeline is already running", 3, 30); return result; } public VhdDownloadContext SaveAzureVhd(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite) { VhdDownloadContext result = new VhdDownloadContext(); Utilities.RetryActionUntilSuccess( () => result = RunPSCmdletAndReturnFirst<VhdDownloadContext>(new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite)), "pipeline is already running", 3, 30); return result; } public string SaveAzureVhdStop(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite, int ms) { SaveAzureVhdCmdletInfo saveAzureVhdCmdletInfo = new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(saveAzureVhdCmdletInfo); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } #endregion #region AzureVnetConfig public Collection<VirtualNetworkConfigContext> GetAzureVNetConfig(string filePath) { return RunPSCmdletAndReturnAll<VirtualNetworkConfigContext>(new GetAzureVNetConfigCmdletInfo(filePath)); } public ManagementOperationContext SetAzureVNetConfig(string filePath) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureVNetConfigCmdletInfo(filePath)); } public ManagementOperationContext RemoveAzureVNetConfig() { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVNetConfigCmdletInfo()); } #endregion #region AzureVNetGateway public ManagementOperationContext NewAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureVNetGatewayCmdletInfo(vnetName)); } public Collection <VirtualNetworkGatewayContext> GetAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnAll<VirtualNetworkGatewayContext>(new GetAzureVNetGatewayCmdletInfo(vnetName)); } public ManagementOperationContext SetAzureVNetGateway(string option, string vnetName, string localNetwork) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureVNetGatewayCmdletInfo(option, vnetName, localNetwork)); } public ManagementOperationContext RemoveAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVNetGatewayCmdletInfo(vnetName)); } public SharedKeyContext GetAzureVNetGatewayKey(string vnetName, string localnet) { return RunPSCmdletAndReturnFirst<SharedKeyContext>(new GetAzureVNetGatewayKeyCmdletInfo(vnetName, localnet)); } #endregion #region AzureVNet public Collection<GatewayConnectionContext> GetAzureVNetConnection(string vnetName) { return RunPSCmdletAndReturnAll<GatewayConnectionContext>(new GetAzureVNetConnectionCmdletInfo(vnetName)); } public Collection<VirtualNetworkSiteContext> GetAzureVNetSite(string vnetName) { return RunPSCmdletAndReturnAll<VirtualNetworkSiteContext>(new GetAzureVNetSiteCmdletInfo(vnetName)); } #endregion public ManagementOperationContext GetAzureRemoteDesktopFile(string vmName, string serviceName, string localPath, bool launch) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new GetAzureRemoteDesktopFileCmdletInfo(vmName, serviceName, localPath, launch)); } internal PersistentVM GetPersistentVM(PersistentVMConfigInfo configInfo) { PersistentVM vm = null; if (null != configInfo) { if (configInfo.VmConfig != null) { vm = NewAzureVMConfig(configInfo.VmConfig); } if (configInfo.ProvConfig != null) { configInfo.ProvConfig.Vm = vm; vm = AddAzureProvisioningConfig(configInfo.ProvConfig); } if (configInfo.DiskConfig != null) { configInfo.DiskConfig.Vm = vm; vm = AddAzureDataDisk(configInfo.DiskConfig); } if (configInfo.EndPointConfig != null) { configInfo.EndPointConfig.Vm = vm; vm = AddAzureEndPoint(configInfo.EndPointConfig); } } return vm; } internal void AddVMDataDisks(string vmName, string serviceName, AddAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (AddAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = AddAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMDataDisks(string vmName, string serviceName, SetAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (SetAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMSize(string vmName, string serviceName, SetAzureVMSizeConfig vmSizeConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); vmSizeConfig.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureVMSize(vmSizeConfig); UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } public PersistentVM SetAzureVMSize(SetAzureVMSizeConfig sizeCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureVMSizeCmdletInfo(sizeCfg)); } internal void AddVMDataDisksAndEndPoint(string vmName, string serviceName, AddAzureDataDiskConfig[] dataDiskConfig, AzureEndPointConfigInfo endPointConfig) { AddVMDataDisks(vmName, serviceName, dataDiskConfig); AddEndPoint(vmName, serviceName, new [] {endPointConfig}); } public void RemoveAzureSubscriptions() { // Remove all subscriptions. SAS Uri should work without a subscription. try { RunPSScript("Get-AzureSubscription | Remove-AzureSubscription -Force"); } catch { Console.WriteLine("Subscriptions cannot be removed"); } // Check if all subscriptions are removed. try { GetAzureSubscription(); Assert.Fail("Subscription was not removed!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } } } public void RemoveAzureSubscription(string subscriptionName, bool force) { RemoveAzureSubscriptionCmdletInfo removeAzureSubscriptionCmdletInfo = new RemoveAzureSubscriptionCmdletInfo(subscriptionName, null, force); WindowsAzurePowershellCmdlet removeAzureSubscriptionCmdlet = new WindowsAzurePowershellCmdlet(removeAzureSubscriptionCmdletInfo); var result = removeAzureSubscriptionCmdlet.Run(); } internal NetworkAclObject NewAzureAclConfig() { return RunPSCmdletAndReturnFirst<NetworkAclObject>(new NewAzureAclConfigCmdletInfo()); } // Set-AzureAclConfig -AddRule -ACL $acl2 -Order 100 -Action Deny -RemoteSubnet "172.0.0.0/8" -Description "notes3" // vmPowershellCmdlets.SetAzureAclConfig(SetACLConfig.AddRule, aclObj, 100, ACLAction.Permit, "172.0.0.0//8", "Desc"); internal void SetAzureAclConfig(SetACLConfig aclConfig, NetworkAclObject aclObj, int order, ACLAction aclAction, string remoteSubnet, string desc) { SetAzureAclConfigCmdletInfo setAzureAclConfigCmdletInfo = new SetAzureAclConfigCmdletInfo(aclConfig.ToString(), aclObj, order, aclAction.ToString(), remoteSubnet, desc, null); WindowsAzurePowershellCmdlet setAzureAclConfigCmdlet = new WindowsAzurePowershellCmdlet(setAzureAclConfigCmdletInfo); var result = setAzureAclConfigCmdlet.Run(); } } }
// // File.cs: // // Author: // Ruben Vermeersch (ruben@savanne.be) // // Copyright (C) 2009 Ruben Vermeersch // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; using System.Collections.Generic; using System.IO; using TagLib.Image; using TagLib.IFD; using TagLib.IFD.Entries; using TagLib.IFD.Tags; using TagLib.Xmp; namespace TagLib.Tiff { /// <summary> /// This class extends <see cref="TagLib.File" /> to provide tagging /// and properties support for Tiff files. /// </summary> [SupportedMimeType("taglib/tiff", "tiff")] [SupportedMimeType("taglib/tif", "tif")] [SupportedMimeType("image/tiff")] public class File : TagLib.Image.File { #region Private Fields /// <summary> /// Contains the media properties. /// </summary> private Properties properties; /// <summary> /// Whether or not the file is big-endian. /// </summary> private bool is_bigendian; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified path in the local file /// system and specified read style. /// </summary> /// <param name="path"> /// A <see cref="string" /> object containing the path of the /// file to use in the new instance. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" />. /// </exception> public File (string path, ReadStyle propertiesStyle) : this (new File.LocalFileAbstraction (path), propertiesStyle) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified path in the local file /// system. /// </summary> /// <param name="path"> /// A <see cref="string" /> object containing the path of the /// file to use in the new instance. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" />. /// </exception> public File (string path) : base (path) { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified file abstraction and /// specified read style. /// </summary> /// <param name="abstraction"> /// A <see cref="IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> public File (File.IFileAbstraction abstraction, ReadStyle propertiesStyle) : base (abstraction) { ImageTag = new CombinedImageTag (TagTypes.TiffIFD | TagTypes.XMP); Mode = AccessMode.Read; try { Read (propertiesStyle); TagTypesOnDisk = TagTypes; } finally { Mode = AccessMode.Closed; } } /// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified file abstraction. /// </summary> /// <param name="abstraction"> /// A <see cref="IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> protected File (IFileAbstraction abstraction) : base (abstraction) { } #endregion #region Public Properties /// <summary> /// Gets the media properties of the file represented by the /// current instance. /// </summary> /// <value> /// A <see cref="TagLib.Properties" /> object containing the /// media properties of the file represented by the current /// instance. /// </value> public override TagLib.Properties Properties { get { return properties; } } #endregion #region Public Methods /// <summary> /// Saves the changes made in the current instance to the /// file it represents. /// </summary> public override void Save () { Mode = AccessMode.Write; try { WriteFile (); TagTypesOnDisk = TagTypes; } finally { Mode = AccessMode.Closed; } } #endregion #region Private Methods /// <summary> /// Render the whole file and write it back. /// </summary> private void WriteFile () { // Check, if IFD0 is contained IFDTag exif = ImageTag.Exif; if (exif == null) throw new Exception ("Tiff file without tags"); UpdateTags (exif); // first IFD starts at 8 uint first_ifd_offset = 8; ByteVector data = new ByteVector (); if (is_bigendian) data.Add ("MM"); else data.Add ("II"); data.Add (ByteVector.FromUShort (42, is_bigendian)); data.Add (ByteVector.FromUInt (first_ifd_offset, is_bigendian)); var renderer = new IFDRenderer (is_bigendian, exif.Structure, first_ifd_offset); data.Add (renderer.Render ()); Insert (data, 0, Length); } /// <summary> /// Update the XMP stored in the Tiff IFD /// </summary> /// <param name="exif"> /// A <see cref="IFDTag"/> The Tiff IFD to update the entries /// </param> private void UpdateTags (IFDTag exif) { // update the XMP entry exif.Structure.RemoveTag (0, (ushort) IFDEntryTag.XMP); XmpTag xmp = ImageTag.Xmp; if (xmp != null) exif.Structure.AddEntry (0, new ByteVectorIFDEntry ((ushort) IFDEntryTag.XMP, xmp.Render ())); } /// <summary> /// Starts parsing the TIFF header of the file from beginning /// and sets <see cref="is_bigendian"/> according to the header. /// The method returns the offset to the first IFD. /// </summary> /// <returns> /// A <see cref="System.UInt32"/> representing the offset to first /// IFD of this file. /// </returns> private uint ReadFirstIFDOffset () { // 2 + 2 + 4 (Byte Order + TIFF Magic Number + Offset) int tiff_header_size = 8; Seek (0, SeekOrigin.Begin); ByteVector header = ReadBlock (tiff_header_size); is_bigendian = header.Mid (0, 2).ToString ().Equals ("MM"); ushort magic = header.Mid (2, 2).ToUShort (is_bigendian); if (magic != 42) throw new Exception (String.Format ("Invalid TIFF magic: {0}", magic)); return header.Mid (4, 4).ToUInt (is_bigendian); } /// <summary> /// Reads the file with a specified read style. /// </summary> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> private void Read (ReadStyle propertiesStyle) { Mode = AccessMode.Read; try { uint offset = ReadFirstIFDOffset (); var ifd_tag = new IFDTag (); var reader = new IFDReader (this, is_bigendian, ifd_tag.Structure, 0, offset, (uint) Length); reader.Read (); ImageTag.AddTag (ifd_tag); // Find XMP data var xmp_entry = ifd_tag.Structure.GetEntry (0, (ushort) IFDEntryTag.XMP) as ByteVectorIFDEntry; if (xmp_entry != null) { ImageTag.AddTag (new XmpTag (xmp_entry.Data.ToString ())); } if (propertiesStyle == ReadStyle.None) return; properties = ExtractProperties (); } finally { Mode = AccessMode.Closed; } } /// <summary> /// Attempts to extract the media properties of the main /// photo. /// </summary> /// <returns> /// A <see cref="Properties" /> object with a best effort guess /// at the right values. When no guess at all can be made, /// <see langword="null" /> is returned. /// </returns> private Properties ExtractProperties () { int width = 0, height = 0; IFDTag tag = GetTag (TagTypes.TiffIFD) as IFDTag; IFDStructure structure = tag.Structure; width = (int) (structure.GetLongValue (0, (ushort) IFDEntryTag.ImageWidth) ?? 0); height = (int) (structure.GetLongValue (0, (ushort) IFDEntryTag.ImageLength) ?? 0); if (width > 0 && height > 0) { return new Properties (TimeSpan.Zero, new Codec (width, height)); } return null; } #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 Leap.Unity.Attributes; namespace Leap.Unity { /** * A base class for implementing detectors that detect a holding pose of a hand. * * Such detectors might use the PinchStrength, PinchDistance, GrabStrength, or GrabAngle * properties of the Hand or might use a more complex heuristic. */ public abstract class AbstractHoldDetector : Detector { /** Implementations must implement this method. */ protected abstract void ensureUpToDate(); [SerializeField] protected IHandModel _handModel; public IHandModel HandModel { get { return _handModel; } set { _handModel = value; } } /** * Whether the Transform of the object containing this Detector script * is transformed by the Position and Rotation of the hand when IsHolding is true. * * If false, the Transform is not affected. */ [Tooltip("Whether to change the transform of the parent object.")] public bool ControlsTransform = true; /** Whether to draw the detector's Gizmos for debugging. (Not every detector provides gizmos.) * @since 4.1.2 */ [Tooltip("Draw this detector's Gizmos, if any. (Gizmos must be on in Unity edtor, too.)")] public bool ShowGizmos = true; protected int _lastUpdateFrame = -1; protected bool _didChange = false; protected Vector3 _position; protected Quaternion _rotation; protected Vector3 _direction = Vector3.forward; protected Vector3 _normal = Vector3.up; protected float _distance; protected float _lastHoldTime = 0.0f; protected float _lastReleaseTime = 0.0f; protected Vector3 _lastPosition = Vector3.zero; protected Quaternion _lastRotation = Quaternion.identity; protected Vector3 _lastDirection = Vector3.forward; protected Vector3 _lastNormal = Vector3.up; protected float _lastDistance = 1.0f; protected virtual void Awake() { if (GetComponent<IHandModel>() != null && ControlsTransform == true) { Debug.LogWarning("Detector should not be control the IHandModel's transform. Either attach it to its own transform or set ControlsTransform to false."); } if (_handModel == null) { _handModel = GetComponentInParent<IHandModel>(); if (_handModel == null) { Debug.LogWarning("The HandModel field of Detector was unassigned and the detector has been disabled."); enabled = false; } } } protected virtual void Update() { //We ensure the data is up to date at all times because //there are some values (like LastPinchTime) that cannot //be updated on demand ensureUpToDate(); } /// <summary> /// Returns whether or not the dectector is currently detecting a pinch or grab. /// </summary> public virtual bool IsHolding { get { ensureUpToDate(); return IsActive; } } /// <summary> /// Returns whether or not the value of IsPinching is different than the value reported during /// the previous frame. /// </summary> public virtual bool DidChangeFromLastFrame { get { ensureUpToDate(); return _didChange; } } /// <summary> /// Returns whether or not the value of IsHolding changed to true between this frame and the previous. /// </summary> public virtual bool DidStartHold { get { ensureUpToDate(); return DidChangeFromLastFrame && IsHolding; } } /// <summary> /// Returns whether or not the value of IsHolding changed to false between this frame and the previous. /// </summary> public virtual bool DidRelease { get { ensureUpToDate(); return DidChangeFromLastFrame && !IsHolding; } } /// <summary> /// Returns the value of Time.time during the most recent pinch event. /// </summary> public float LastHoldTime { get { ensureUpToDate(); return _lastHoldTime; } } /// <summary> /// Returns the value of Time.time during the most recent unpinch event. /// </summary> public float LastReleaseTime { get { ensureUpToDate(); return _lastReleaseTime; } } /// <summary> /// Returns the position value of the detected pinch or grab. If a pinch or grab is not currently being /// detected, returns the most recent position value. /// </summary> public Vector3 Position { get { ensureUpToDate(); return _position; } } public Vector3 LastActivePosition { get { return _lastPosition; } } /// <summary> /// Returns the rotation value of the detected pinch or grab. If a pinch or grab is not currently being /// detected, returns the most recent rotation value. /// </summary> public Quaternion Rotation { get { ensureUpToDate(); return _rotation; } } public Quaternion LastActiveRotation { get { return _lastRotation; } } public Vector3 Direction { get { return _direction; } } public Vector3 LastActiveDirection { get { return _lastDirection; } } public Vector3 Normal { get { return _normal; } } public Vector3 LastActiveNormal { get { return _lastNormal; } } public float Distance { get { return _distance; } } public float LastActiveDistance { get { return _lastDistance; } } protected virtual void changeState(bool shouldBeActive) { bool currentState = IsActive; if (shouldBeActive) { _lastHoldTime = Time.time; Activate(); } else { _lastReleaseTime = Time.time; Deactivate(); } if (currentState != IsActive) { _didChange = true; } } #if UNITY_EDITOR protected virtual void OnDrawGizmos () { if (ShowGizmos) { ensureUpToDate(); Color centerColor; Vector3 centerPosition = _position; Quaternion circleRotation = _rotation; if (IsHolding) { centerColor = OnColor; } else { centerColor = OffColor; } Vector3 axis; float angle; circleRotation.ToAngleAxis(out angle, out axis); Utils.DrawCircle(centerPosition, Normal, Distance / 2, centerColor); Gizmos.color = NormalColor; Gizmos.DrawLine(centerPosition, centerPosition + Direction * Distance / 2); Gizmos.color = DirectionColor; Gizmos.DrawLine(centerPosition, centerPosition + Normal * Distance / 2); } } #endif } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using ViewBinder.WebAPISample.Areas.HelpPage.Models; namespace ViewBinder.WebAPISample.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* Copyright 2014 Google 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 DriveProxy.Utils; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; namespace DriveProxy.API { partial class DriveService { public class RenameStream : Stream { protected string _MimeType = ""; protected string _TempFilePath; protected string _Title = ""; public override StreamType Type { get { return StreamType.Rename; } } public override string Title { get { return _Title; } } public override string MimeType { get { return _MimeType; } } public void Init(FileInfo fileInfo, string title, string mimeType = null) { try { if (Status == StatusType.Queued) { throw new Exception("Stream has already been queued."); } if (Status != StatusType.NotStarted) { throw new Exception("Stream has already been started."); } if (fileInfo == null) { throw new Exception("File is null."); } if (fileInfo.IsRoot) { throw new Exception("Cannot trash root folder."); } if (String.IsNullOrEmpty(title)) { throw new Exception("Title is blank."); } if (fileInfo.IsFolder) { mimeType = fileInfo.MimeType; } else if (String.IsNullOrEmpty(mimeType)) { mimeType = API.DriveService.GetMimeType(title); } _FileId = fileInfo.Id; _FileInfo = fileInfo; _Title = title; _MimeType = mimeType; _TempFilePath = _FileInfo.FilePath; base.Init(); } catch (Exception exception) { Log.Error(exception); } } protected override void Start() { try { if (Status != StatusType.Queued) { throw new Exception("Stream has not been queued."); } base.Start(); _FileInfo = _DriveService.GetFile(FileId); if (_FileInfo == null) { throw new Exception("File '" + FileId + "' no longer exists."); } Lock(); using (API.DriveService.Connection connection = API.DriveService.Connection.Create()) { Google.Apis.Drive.v2.Data.File file = _FileInfo._file; file = connection.Service.Files.Get(file.Id).Execute(); file.Title = Title; if (!String.IsNullOrEmpty(MimeType)) { file.MimeType = MimeType; } FilesResource.UpdateRequest request = connection.Service.Files.Update(file, FileId); file = request.Execute(); _FileInfo = GetFileInfo(file); DriveService_ProgressChanged(StatusType.Completed, null); } } catch (Exception exception) { try { _Status = StatusType.Failed; _ExceptionMessage = exception.Message; DriveService_ProgressChanged(StatusType.Failed, exception); } catch { Debugger.Break(); } Log.Error(exception); } } protected override void Dispose() { try { base.Dispose(); } catch (Exception exception) { Log.Error(exception, false); } } protected void DriveService_ProgressChanged(System.Threading.Tasks.Task<File> task) { try { if (task.IsCanceled) { DriveService_ProgressChanged(StatusType.Cancelled, null); } else if (task.IsFaulted) { DriveService_ProgressChanged(StatusType.Failed, task.Exception); } else if (task.IsCompleted) { _FileInfo = API.DriveService.GetFileInfo(task.Result); DriveService_ProgressChanged(StatusType.Completed, null); } } catch (Exception exception) { Log.Error(exception, false); } } protected void DriveService_ProgressChanged(StatusType status, Exception processException) { try { UpdateProgress(status, BytesProcessed, TotalBytes, processException); if (Processed) { try { if (Completed) { if (!String.Equals(_FileInfo.OriginalFilename, Title, StringComparison.CurrentCultureIgnoreCase)) { throw new Exception("File in cloud was not renamed."); } API.DriveService.FileTitles.Remove(_FileInfo._file); if (API.DriveService.FileExists(_TempFilePath)) { if (!String.Equals(_TempFilePath, FilePath, StringComparison.CurrentCultureIgnoreCase)) { API.DriveService.MoveFile(_TempFilePath, FilePath); API.DriveService.SetFileLastWriteTime(FilePath, _FileInfo.ModifiedDate); } } } } catch (Exception exception) { Log.Error(exception, false); if (!Failed) { _ExceptionMessage = exception.Message; _Status = StatusType.Failed; } } } InvokeOnProgressEvent(); } catch (Exception exception) { Log.Error(exception, false); } } } } }
// /******************************************************************************* // * Copyright 2012-2018 Esri // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // ******************************************************************************/ using System.ComponentModel; using Esri.ArcGISRuntime.Toolkit.UI.Controls; using Xamarin.Forms; using Grid = Xamarin.Forms.Grid; using XForms = Xamarin.Forms.Xaml; namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms { public partial class SearchView : TemplatedView, INotifyPropertyChanged { #pragma warning disable SA1306, SA1310, SX1309 // Field names should begin with lower-case letter private Entry? PART_Entry; private ImageButton? PART_CancelButton; private ImageButton? PART_SearchButton; private ImageButton? PART_SourceSelectButton; private Label? PART_ResultLabel; private ListView? PART_SuggestionsView; private ListView? PART_ResultView; private ListView? PART_SourcesView; private Button? PART_RepeatButton; private Grid? PART_ResultContainer; private Grid? PART_RepeatButtonContainer; #pragma warning restore SA1306, SA1310, SX1309 // Field names should begin with lower-case letter private static readonly DataTemplate DefaultResultTemplate; private static readonly DataTemplate DefaultSuggestionTemplate; private static readonly DataTemplate DefaultSuggestionGroupHeaderTemplate; private static readonly ControlTemplate DefaultControlTemplate; private static readonly ByteArrayToImageSourceConverter ImageSourceConverter; private static readonly BoolToCollectionIconImageConverter CollectionIconConverter; private static readonly EmptyStringToBoolConverter EmptyStringConverter; static SearchView() { ImageSourceConverter = new ByteArrayToImageSourceConverter(); CollectionIconConverter = new BoolToCollectionIconImageConverter(); EmptyStringConverter = new EmptyStringToBoolConverter(); DefaultSuggestionGroupHeaderTemplate = new DataTemplate(() => { var viewcell = new ViewCell(); Grid containingGrid = new Grid(); containingGrid.BackgroundColor = Color.FromHex("#4e4e4e"); Label textLabel = new Label(); textLabel.SetBinding(Label.TextProperty, "Key.DisplayName"); textLabel.Margin = new Thickness(4); textLabel.TextColor = Color.White; textLabel.FontSize = 14; textLabel.VerticalTextAlignment = TextAlignment.Center; containingGrid.Children.Add(textLabel); viewcell.View = containingGrid; return viewcell; }); DefaultSuggestionTemplate = new DataTemplate(() => { var viewCell = new ViewCell(); Grid containingGrid = new Grid(); containingGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); containingGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star }); containingGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); Grid textStack = new Grid(); textStack.VerticalOptions = LayoutOptions.Center; textStack.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); textStack.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); Image imageView = new Image(); imageView.SetBinding(Image.SourceProperty, nameof(SearchSuggestion.IsCollection), converter: CollectionIconConverter); imageView.WidthRequest = 16; imageView.HeightRequest = 16; imageView.Margin = new Thickness(4); imageView.VerticalOptions = LayoutOptions.Center; Label titleLabel = new Label(); titleLabel.SetBinding(Label.TextProperty, nameof(SearchSuggestion.DisplayTitle)); titleLabel.VerticalOptions = LayoutOptions.End; titleLabel.VerticalTextAlignment = TextAlignment.End; titleLabel.TextColor = Color.Black; Label subtitleLabel = new Label(); subtitleLabel.SetBinding(Label.TextProperty, nameof(SearchSuggestion.DisplaySubtitle)); subtitleLabel.SetBinding(Label.IsVisibleProperty, nameof(SearchSuggestion.DisplaySubtitle), converter: EmptyStringConverter); subtitleLabel.VerticalOptions = LayoutOptions.Start; subtitleLabel.VerticalTextAlignment = TextAlignment.Start; subtitleLabel.TextColor = Color.Black; textStack.Children.Add(titleLabel); textStack.Children.Add(subtitleLabel); Grid.SetRow(titleLabel, 0); Grid.SetRow(subtitleLabel, 1); containingGrid.Children.Add(imageView); containingGrid.Children.Add(textStack); Grid.SetColumn(textStack, 1); Grid.SetColumn(imageView, 0); viewCell.View = containingGrid; return viewCell; }); DefaultResultTemplate = new DataTemplate(() => { var viewCell = new ViewCell(); Grid containingGrid = new Grid(); containingGrid.Padding = new Thickness(2, 4, 2, 4); containingGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); containingGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star }); containingGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); Grid textStack = new Grid(); textStack.VerticalOptions = LayoutOptions.Center; textStack.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); textStack.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); Image imageView = new Image(); imageView.SetBinding(Image.SourceProperty, nameof(SearchResult.MarkerImageData), converter: ImageSourceConverter); imageView.WidthRequest = 24; imageView.HeightRequest = 24; imageView.Margin = new Thickness(4); imageView.VerticalOptions = LayoutOptions.Center; Label titleLabel = new Label(); titleLabel.SetBinding(Label.TextProperty, nameof(SearchResult.DisplayTitle)); titleLabel.FontAttributes = FontAttributes.Bold; titleLabel.VerticalOptions = LayoutOptions.End; titleLabel.VerticalTextAlignment = TextAlignment.End; titleLabel.TextColor = Color.Black; Label subtitleLabel = new Label(); subtitleLabel.SetBinding(Label.TextProperty, nameof(SearchResult.DisplaySubtitle)); subtitleLabel.SetBinding(Label.IsVisibleProperty, nameof(SearchResult.DisplaySubtitle), converter: EmptyStringConverter); subtitleLabel.TextColor = Color.Black; subtitleLabel.VerticalOptions = LayoutOptions.Start; subtitleLabel.VerticalTextAlignment = TextAlignment.Start; textStack.Children.Add(titleLabel); textStack.Children.Add(subtitleLabel); Grid.SetRow(titleLabel, 0); Grid.SetRow(subtitleLabel, 1); containingGrid.Children.Add(imageView); containingGrid.Children.Add(textStack); Grid.SetColumn(textStack, 1); Grid.SetColumn(imageView, 0); viewCell.View = containingGrid; return viewCell; }); string template = $@"<ControlTemplate xmlns=""http://xamarin.com/schemas/2014/forms"" xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"" xmlns:esriTK=""clr-namespace:Esri.ArcGISRuntime.Toolkit.Xamarin.Forms""> <Grid RowSpacing=""0"" ColumnSpacing=""0"" > <Grid.ColumnDefinitions> <ColumnDefinition Width=""Auto"" /> <ColumnDefinition Width=""*"" /> <ColumnDefinition Width=""32"" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height=""Auto"" /> <RowDefinition Height=""Auto"" /> <RowDefinition Height=""Auto"" /> </Grid.RowDefinitions> <Grid Grid.Row=""0"" Grid.ColumnSpan=""3"" BackgroundColor=""White"" /> <ImageButton x:Name=""{nameof(PART_SourceSelectButton)}"" Grid.Column=""0"" WidthRequest=""32"" HeightRequest=""32"" Padding=""4"" BackgroundColor=""Transparent"" Margin=""0"" /> <Entry x:Name=""{nameof(PART_Entry)}"" Grid.Column=""1"" Grid.Row=""0"" BackgroundColor=""White"" TextColor=""Black"" /> <ImageButton x:Name=""{nameof(PART_CancelButton)}"" Grid.Column=""1"" HorizontalOptions=""End"" WidthRequest=""32"" HeightRequest=""32"" Padding=""4"" BackgroundColor=""Transparent"" /> <ImageButton x:Name=""{nameof(PART_SearchButton)}"" Grid.Column=""2"" WidthRequest=""32"" HeightRequest=""32"" Padding=""4"" BackgroundColor=""Transparent"" /> <ListView x:Name=""{nameof(PART_SuggestionsView)}"" Grid.Column=""0"" Grid.ColumnSpan=""3"" Grid.Row=""1"" Grid.RowSpan=""2"" HasUnevenRows=""true"" BackgroundColor=""White"" HeightRequest=""175"" /> <ListView x:Name=""{nameof(PART_ResultView)}"" Grid.Column=""0"" Grid.ColumnSpan=""3"" Grid.Row=""1"" Grid.RowSpan=""1"" HasUnevenRows=""true"" BackgroundColor=""White"" HeightRequest=""200"" /> <ListView x:Name=""{nameof(PART_SourcesView)}"" Grid.Column=""0"" Grid.ColumnSpan=""3"" Grid.Row=""1"" BackgroundColor=""White"" HeightRequest=""150"" /> <Grid x:Name=""{nameof(PART_ResultContainer)}"" BackgroundColor=""White"" Grid.ColumnSpan=""3"" Grid.Row=""1"" Padding=""8""><Label x:Name=""{nameof(PART_ResultLabel)}"" HorizontalOptions=""Center"" VerticalOptions=""Center"" FontAttributes=""Bold"" /></Grid> <Grid x:Name=""{nameof(PART_RepeatButtonContainer)}"" BackgroundColor=""White"" Grid.Column=""0"" Grid.ColumnSpan=""3"" Grid.Row=""2""> <Button x:Name=""{nameof(PART_RepeatButton)}"" BackgroundColor=""#007AC2"" TextColor=""White"" CornerRadius=""0"" /> </Grid> </Grid> </ControlTemplate>"; DefaultControlTemplate = XForms.Extensions.LoadFromXaml(new ControlTemplate(), template); } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Xml.Transform.Sax.cs // // 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. #pragma warning disable 1717 namespace Javax.Xml.Transform.Sax { /// <summary> /// <para>Acts as an holder for a transformation Result.</para><para><para> </para></para> /// </summary> /// <java-name> /// javax/xml/transform/sax/SAXResult /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/SAXResult", AccessFlags = 33)] public partial class SAXResult : global::Javax.Xml.Transform.IResult /* scope: __dot42__ */ { /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Result output of this type. </para> /// </summary> /// <java-name> /// FEATURE /// </java-name> [Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE = "http://javax.xml.transform.sax.SAXResult/feature"; /// <summary> /// <para>Zero-argument default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SAXResult() /* MethodBuilder.Create */ { } /// <summary> /// <para>Create a SAXResult that targets a SAX2 org.xml.sax.ContentHandler.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Lorg/xml/sax/ContentHandler;)V", AccessFlags = 1)] public SAXResult(global::Org.Xml.Sax.IContentHandler handler) /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the target to be a SAX2 org.xml.sax.ContentHandler.</para><para></para> /// </summary> /// <java-name> /// setHandler /// </java-name> [Dot42.DexImport("setHandler", "(Lorg/xml/sax/ContentHandler;)V", AccessFlags = 1)] public virtual void SetHandler(global::Org.Xml.Sax.IContentHandler handler) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the org.xml.sax.ContentHandler that is the Result.</para><para></para> /// </summary> /// <returns> /// <para>The ContentHandler that is to be transformation output. </para> /// </returns> /// <java-name> /// getHandler /// </java-name> [Dot42.DexImport("getHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.IContentHandler GetHandler() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.IContentHandler); } /// <summary> /// <para>Set the SAX2 org.xml.sax.ext.LexicalHandler for the output.</para><para>This is needed to handle XML comments and the like. If the lexical handler is not set, an attempt should be made by the transformer to cast the org.xml.sax.ContentHandler to a <code>LexicalHandler</code>.</para><para></para> /// </summary> /// <java-name> /// setLexicalHandler /// </java-name> [Dot42.DexImport("setLexicalHandler", "(Lorg/xml/sax/ext/LexicalHandler;)V", AccessFlags = 1)] public virtual void SetLexicalHandler(global::Org.Xml.Sax.Ext.ILexicalHandler handler) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get a SAX2 org.xml.sax.ext.LexicalHandler for the output.</para><para></para> /// </summary> /// <returns> /// <para>A <code>LexicalHandler</code>, or null. </para> /// </returns> /// <java-name> /// getLexicalHandler /// </java-name> [Dot42.DexImport("getLexicalHandler", "()Lorg/xml/sax/ext/LexicalHandler;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.Ext.ILexicalHandler GetLexicalHandler() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.Ext.ILexicalHandler); } /// <summary> /// <para>Method setSystemId Set the systemID that may be used in association with the org.xml.sax.ContentHandler.</para><para></para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSystemId(string systemId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the system identifier that was set with setSystemId.</para><para></para> /// </summary> /// <returns> /// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSystemId() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Get the org.xml.sax.ContentHandler that is the Result.</para><para></para> /// </summary> /// <returns> /// <para>The ContentHandler that is to be transformation output. </para> /// </returns> /// <java-name> /// getHandler /// </java-name> public global::Org.Xml.Sax.IContentHandler Handler { [Dot42.DexImport("getHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] get{ return GetHandler(); } [Dot42.DexImport("setHandler", "(Lorg/xml/sax/ContentHandler;)V", AccessFlags = 1)] set{ SetHandler(value); } } /// <summary> /// <para>Get a SAX2 org.xml.sax.ext.LexicalHandler for the output.</para><para></para> /// </summary> /// <returns> /// <para>A <code>LexicalHandler</code>, or null. </para> /// </returns> /// <java-name> /// getLexicalHandler /// </java-name> public global::Org.Xml.Sax.Ext.ILexicalHandler LexicalHandler { [Dot42.DexImport("getLexicalHandler", "()Lorg/xml/sax/ext/LexicalHandler;", AccessFlags = 1)] get{ return GetLexicalHandler(); } [Dot42.DexImport("setLexicalHandler", "(Lorg/xml/sax/ext/LexicalHandler;)V", AccessFlags = 1)] set{ SetLexicalHandler(value); } } /// <summary> /// <para>Get the system identifier that was set with setSystemId.</para><para></para> /// </summary> /// <returns> /// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> public string SystemId { [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSystemId(); } [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSystemId(value); } } } /// <summary> /// <para>Acts as an holder for SAX-style Source.</para><para>Note that XSLT requires namespace support. Attempting to transform an input source that is not generated with a namespace-aware parser may result in errors. Parsers can be made namespace aware by calling the javax.xml.parsers.SAXParserFactory#setNamespaceAware(boolean awareness) method.</para><para><para> </para><para></para><title>Revision:</title><para>446598 </para>, <title>Date:</title><para>2006-09-15 05:55:40 -0700 (Fri, 15 Sep 2006) </para></para> /// </summary> /// <java-name> /// javax/xml/transform/sax/SAXSource /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/SAXSource", AccessFlags = 33)] public partial class SAXSource : global::Javax.Xml.Transform.ISource /* scope: __dot42__ */ { /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Source input of this type. </para> /// </summary> /// <java-name> /// FEATURE /// </java-name> [Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE = "http://javax.xml.transform.sax.SAXSource/feature"; /// <summary> /// <para>Zero-argument default constructor. If this constructor is used, and no SAX source is set using setInputSource(InputSource inputSource) , then the <code>Transformer</code> will create an empty source org.xml.sax.InputSource using new InputSource().</para><para><para>javax.xml.transform.Transformer::transform(Source xmlSource, Result outputTarget) </para></para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SAXSource() /* MethodBuilder.Create */ { } /// <summary> /// <para>Create a <code>SAXSource</code>, using an org.xml.sax.XMLReader and a SAX InputSource. The javax.xml.transform.Transformer or javax.xml.transform.sax.SAXTransformerFactory will set itself to be the reader's org.xml.sax.ContentHandler, and then will call reader.parse(inputSource).</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Lorg/xml/sax/XMLReader;Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] public SAXSource(global::Org.Xml.Sax.IXMLReader reader, global::Org.Xml.Sax.InputSource inputSource) /* MethodBuilder.Create */ { } /// <summary> /// <para>Create a <code>SAXSource</code>, using a SAX <code>InputSource</code>. The javax.xml.transform.Transformer or javax.xml.transform.sax.SAXTransformerFactory creates a reader via org.xml.sax.helpers.XMLReaderFactory (if setXMLReader is not used), sets itself as the reader's org.xml.sax.ContentHandler, and calls reader.parse(inputSource).</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] public SAXSource(global::Org.Xml.Sax.InputSource inputSource) /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the XMLReader to be used for the Source.</para><para></para> /// </summary> /// <java-name> /// setXMLReader /// </java-name> [Dot42.DexImport("setXMLReader", "(Lorg/xml/sax/XMLReader;)V", AccessFlags = 1)] public virtual void SetXMLReader(global::Org.Xml.Sax.IXMLReader reader) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the XMLReader to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid XMLReader or XMLFilter reference, or null. </para> /// </returns> /// <java-name> /// getXMLReader /// </java-name> [Dot42.DexImport("getXMLReader", "()Lorg/xml/sax/XMLReader;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.IXMLReader GetXMLReader() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.IXMLReader); } /// <summary> /// <para>Set the SAX InputSource to be used for the Source.</para><para></para> /// </summary> /// <java-name> /// setInputSource /// </java-name> [Dot42.DexImport("setInputSource", "(Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] public virtual void SetInputSource(global::Org.Xml.Sax.InputSource inputSource) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the SAX InputSource to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid InputSource reference, or null. </para> /// </returns> /// <java-name> /// getInputSource /// </java-name> [Dot42.DexImport("getInputSource", "()Lorg/xml/sax/InputSource;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.InputSource GetInputSource() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.InputSource); } /// <summary> /// <para>Set the system identifier for this Source. If an input source has already been set, it will set the system ID or that input source, otherwise it will create a new input source.</para><para>The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if no byte stream or character stream is specified).</para><para></para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetSystemId(string systemId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Get the base ID (URI or system ID) from where URIs will be resolved.</para><para></para> /// </summary> /// <returns> /// <para>Base URL for the <code>Source</code>, or <code>null</code>. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetSystemId() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Attempt to obtain a SAX InputSource object from a Source object.</para><para></para> /// </summary> /// <returns> /// <para>An InputSource, or null if Source can not be converted. </para> /// </returns> /// <java-name> /// sourceToInputSource /// </java-name> [Dot42.DexImport("sourceToInputSource", "(Ljavax/xml/transform/Source;)Lorg/xml/sax/InputSource;", AccessFlags = 9)] public static global::Org.Xml.Sax.InputSource SourceToInputSource(global::Javax.Xml.Transform.ISource source) /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.InputSource); } /// <summary> /// <para>Get the XMLReader to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid XMLReader or XMLFilter reference, or null. </para> /// </returns> /// <java-name> /// getXMLReader /// </java-name> public global::Org.Xml.Sax.IXMLReader XMLReader { [Dot42.DexImport("getXMLReader", "()Lorg/xml/sax/XMLReader;", AccessFlags = 1)] get{ return GetXMLReader(); } [Dot42.DexImport("setXMLReader", "(Lorg/xml/sax/XMLReader;)V", AccessFlags = 1)] set{ SetXMLReader(value); } } /// <summary> /// <para>Get the SAX InputSource to be used for the Source.</para><para></para> /// </summary> /// <returns> /// <para>A valid InputSource reference, or null. </para> /// </returns> /// <java-name> /// getInputSource /// </java-name> public global::Org.Xml.Sax.InputSource InputSource { [Dot42.DexImport("getInputSource", "()Lorg/xml/sax/InputSource;", AccessFlags = 1)] get{ return GetInputSource(); } [Dot42.DexImport("setInputSource", "(Lorg/xml/sax/InputSource;)V", AccessFlags = 1)] set{ SetInputSource(value); } } /// <summary> /// <para>Get the base ID (URI or system ID) from where URIs will be resolved.</para><para></para> /// </summary> /// <returns> /// <para>Base URL for the <code>Source</code>, or <code>null</code>. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> public string SystemId { [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetSystemId(); } [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetSystemId(value); } } } /// <summary> /// <para>A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.</para><para>Note that TemplatesHandler does not need to implement LexicalHandler.</para> /// </summary> /// <java-name> /// javax/xml/transform/sax/TemplatesHandler /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/TemplatesHandler", AccessFlags = 1537)] public partial interface ITemplatesHandler : global::Org.Xml.Sax.IContentHandler /* scope: __dot42__ */ { /// <summary> /// <para>When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.</para><para></para> /// </summary> /// <returns> /// <para>The Templates object that was created during the SAX event process, or null if no Templates object has been created. </para> /// </returns> /// <java-name> /// getTemplates /// </java-name> [Dot42.DexImport("getTemplates", "()Ljavax/xml/transform/Templates;", AccessFlags = 1025)] global::Javax.Xml.Transform.ITemplates GetTemplates() /* MethodBuilder.Create */ ; /// <summary> /// <para>Set the base ID (URI or system ID) for the Templates object created by this builder. This must be set in order to resolve relative URIs in the stylesheet. This must be called before the startDocument event.</para><para></para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetSystemId(string systemID) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the base ID (URI or system ID) from where relative URLs will be resolved. </para> /// </summary> /// <returns> /// <para>The systemID that was set with setSystemId. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1025)] string GetSystemId() /* MethodBuilder.Create */ ; } /// <summary> /// <para>A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result. </para> /// </summary> /// <java-name> /// javax/xml/transform/sax/TransformerHandler /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/TransformerHandler", AccessFlags = 1537)] public partial interface ITransformerHandler : global::Org.Xml.Sax.IContentHandler, global::Org.Xml.Sax.Ext.ILexicalHandler, global::Org.Xml.Sax.IDTDHandler /* scope: __dot42__ */ { /// <summary> /// <para>Set the <code>Result</code> associated with this <code>TransformerHandler</code> to be used for the transformation.</para><para></para> /// </summary> /// <java-name> /// setResult /// </java-name> [Dot42.DexImport("setResult", "(Ljavax/xml/transform/Result;)V", AccessFlags = 1025)] void SetResult(global::Javax.Xml.Transform.IResult result) /* MethodBuilder.Create */ ; /// <summary> /// <para>Set the base ID (URI or system ID) from where relative URLs will be resolved. </para> /// </summary> /// <java-name> /// setSystemId /// </java-name> [Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1025)] void SetSystemId(string systemID) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the base ID (URI or system ID) from where relative URLs will be resolved. </para> /// </summary> /// <returns> /// <para>The systemID that was set with setSystemId. </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1025)] string GetSystemId() /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the <code>Transformer</code> associated with this handler, which is needed in order to set parameters and output properties.</para><para></para> /// </summary> /// <returns> /// <para><code>Transformer</code> associated with this <code>TransformerHandler</code>. </para> /// </returns> /// <java-name> /// getTransformer /// </java-name> [Dot42.DexImport("getTransformer", "()Ljavax/xml/transform/Transformer;", AccessFlags = 1025)] global::Javax.Xml.Transform.Transformer GetTransformer() /* MethodBuilder.Create */ ; } /// <summary> /// <para>This class extends TransformerFactory to provide SAX-specific factory methods. It provides two types of ContentHandlers, one for creating Transformers, the other for creating Templates objects.</para><para>If an application wants to set the ErrorHandler or EntityResolver for an XMLReader used during a transformation, it should use a URIResolver to return the SAXSource which provides (with getXMLReader) a reference to the XMLReader.</para> /// </summary> /// <java-name> /// javax/xml/transform/sax/SAXTransformerFactory /// </java-name> [Dot42.DexImport("javax/xml/transform/sax/SAXTransformerFactory", AccessFlags = 1057)] public abstract partial class SAXTransformerFactory : global::Javax.Xml.Transform.TransformerFactory /* scope: __dot42__ */ { /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the TransformerFactory returned from javax.xml.transform.TransformerFactory#newInstance may be safely cast to a SAXTransformerFactory. </para> /// </summary> /// <java-name> /// FEATURE /// </java-name> [Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE = "http://javax.xml.transform.sax.SAXTransformerFactory/feature"; /// <summary> /// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the newXMLFilter(Source src) and newXMLFilter(Templates templates) methods are supported. </para> /// </summary> /// <java-name> /// FEATURE_XMLFILTER /// </java-name> [Dot42.DexImport("FEATURE_XMLFILTER", "Ljava/lang/String;", AccessFlags = 25)] public const string FEATURE_XMLFILTER = "http://javax.xml.transform.sax.SAXTransformerFactory/feature/xmlfilter"; /// <summary> /// <para>The default constructor is protected on purpose. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal SAXTransformerFactory() /* MethodBuilder.Create */ { } /// <summary> /// <para>Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.</para><para></para> /// </summary> /// <returns> /// <para>TransformerHandler ready to transform SAX events.</para> /// </returns> /// <java-name> /// newTransformerHandler /// </java-name> [Dot42.DexImport("newTransformerHandler", "(Ljavax/xml/transform/Source;)Ljavax/xml/transform/sax/TransformerHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITransformerHandler NewTransformerHandler(global::Javax.Xml.Transform.ISource src) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.</para><para></para> /// </summary> /// <returns> /// <para>TransformerHandler ready to transform SAX events.</para> /// </returns> /// <java-name> /// newTransformerHandler /// </java-name> [Dot42.DexImport("newTransformerHandler", "(Ljavax/xml/transform/Templates;)Ljavax/xml/transform/sax/TransformerHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITransformerHandler NewTransformerHandler(global::Javax.Xml.Transform.ITemplates src) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get a TransformerHandler object that can process SAX ContentHandler events into a Result. The transformation is defined as an identity (or copy) transformation, for example to copy a series of SAX parse events into a DOM tree.</para><para></para> /// </summary> /// <returns> /// <para>A non-null reference to a TransformerHandler, that may be used as a ContentHandler for SAX parse events.</para> /// </returns> /// <java-name> /// newTransformerHandler /// </java-name> [Dot42.DexImport("newTransformerHandler", "()Ljavax/xml/transform/sax/TransformerHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITransformerHandler NewTransformerHandler() /* MethodBuilder.Create */ ; /// <summary> /// <para>Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.</para><para></para> /// </summary> /// <returns> /// <para>A non-null reference to a TransformerHandler, that may be used as a ContentHandler for SAX parse events.</para> /// </returns> /// <java-name> /// newTemplatesHandler /// </java-name> [Dot42.DexImport("newTemplatesHandler", "()Ljavax/xml/transform/sax/TemplatesHandler;", AccessFlags = 1025)] public abstract global::Javax.Xml.Transform.Sax.ITemplatesHandler NewTemplatesHandler() /* MethodBuilder.Create */ ; /// <summary> /// <para>Create an XMLFilter that uses the given Source as the transformation instructions.</para><para></para> /// </summary> /// <returns> /// <para>An XMLFilter object, or null if this feature is not supported.</para> /// </returns> /// <java-name> /// newXMLFilter /// </java-name> [Dot42.DexImport("newXMLFilter", "(Ljavax/xml/transform/Source;)Lorg/xml/sax/XMLFilter;", AccessFlags = 1025)] public abstract global::Org.Xml.Sax.IXMLFilter NewXMLFilter(global::Javax.Xml.Transform.ISource src) /* MethodBuilder.Create */ ; /// <summary> /// <para>Create an XMLFilter that uses the given Source as the transformation instructions.</para><para></para> /// </summary> /// <returns> /// <para>An XMLFilter object, or null if this feature is not supported.</para> /// </returns> /// <java-name> /// newXMLFilter /// </java-name> [Dot42.DexImport("newXMLFilter", "(Ljavax/xml/transform/Templates;)Lorg/xml/sax/XMLFilter;", AccessFlags = 1025)] public abstract global::Org.Xml.Sax.IXMLFilter NewXMLFilter(global::Javax.Xml.Transform.ITemplates src) /* MethodBuilder.Create */ ; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.Unicode; namespace System.Text { public readonly ref partial struct Utf8Span { [StackTraceHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CheckSplitOptions(Utf8StringSplitOptions options) { if ((uint)options > (uint)(Utf8StringSplitOptions.RemoveEmptyEntries | Utf8StringSplitOptions.TrimEntries)) { CheckSplitOptions_Throw(options); } } [StackTraceHidden] private static void CheckSplitOptions_Throw(Utf8StringSplitOptions options) { throw new ArgumentOutOfRangeException( paramName: nameof(options), message: SR.Format(SR.Arg_EnumIllegalVal, (int)options)); } public SplitResult Split(char separator, Utf8StringSplitOptions options = Utf8StringSplitOptions.None) { if (!Rune.TryCreate(separator, out Rune rune)) { throw new ArgumentOutOfRangeException( paramName: nameof(separator), message: SR.ArgumentOutOfRange_Utf16SurrogatesDisallowed); } CheckSplitOptions(options); return new SplitResult(this, rune, options); } public SplitResult Split(Rune separator, Utf8StringSplitOptions options = Utf8StringSplitOptions.None) { CheckSplitOptions(options); return new SplitResult(this, separator, options); } public SplitResult Split(Utf8Span separator, Utf8StringSplitOptions options = Utf8StringSplitOptions.None) { if (separator.IsEmpty) { throw new ArgumentException( paramName: nameof(separator), message: SR.Argument_CannotBeEmptySpan); } CheckSplitOptions(options); return new SplitResult(this, separator, options); } /// <summary> /// Locates <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// An ordinal search is performed. /// </remarks> public SplitOnResult SplitOn(char separator) { return TryFind(separator, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// The search is performed using the specified <paramref name="comparisonType"/>. /// </remarks> public SplitOnResult SplitOn(char separator, StringComparison comparisonType) { return TryFind(separator, comparisonType, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// An ordinal search is performed. /// </remarks> public SplitOnResult SplitOn(Rune separator) { return TryFind(separator, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// The search is performed using the specified <paramref name="comparisonType"/>. /// </remarks> public SplitOnResult SplitOn(Rune separator, StringComparison comparisonType) { return TryFind(separator, comparisonType, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// An ordinal search is performed. /// </remarks> public SplitOnResult SplitOn(Utf8Span separator) { return TryFind(separator, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Utf8Span)". /// </summary> /// <remarks> /// The search is performed using the specified <paramref name="comparisonType"/>. /// </remarks> public SplitOnResult SplitOn(Utf8Span separator, StringComparison comparisonType) { return TryFind(separator, comparisonType, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// An ordinal search is performed. /// </remarks> public SplitOnResult SplitOnLast(char separator) { return TryFindLast(separator, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// The search is performed using the specified <paramref name="comparisonType"/>. /// </remarks> public SplitOnResult SplitOnLast(char separator, StringComparison comparisonType) { return TryFindLast(separator, comparisonType, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// An ordinal search is performed. /// </remarks> public SplitOnResult SplitOnLast(Rune separator) { return TryFindLast(separator, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// The search is performed using the specified <paramref name="comparisonType"/>. /// </remarks> public SplitOnResult SplitOnLast(Rune separator, StringComparison comparisonType) { return TryFindLast(separator, comparisonType, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// An ordinal search is performed. /// </remarks> public SplitOnResult SplitOnLast(Utf8Span separator) { return TryFindLast(separator, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Locates the last occurrence of <paramref name="separator"/> within this <see cref="Utf8Span"/> instance, creating <see cref="Utf8Span"/> /// instances which represent the data on either side of the separator. If <paramref name="separator"/> is not found /// within this <see cref="Utf8Span"/> instance, returns the tuple "(this, Empty)". /// </summary> /// <remarks> /// The search is performed using the specified <paramref name="comparisonType"/>. /// </remarks> public SplitOnResult SplitOnLast(Utf8Span separator, StringComparison comparisonType) { return TryFindLast(separator, comparisonType, out Range range) ? new SplitOnResult(this, range) : new SplitOnResult(this); } /// <summary> /// Trims whitespace from the beginning and the end of this <see cref="Utf8Span"/>, /// returning a new <see cref="Utf8Span"/> containing the resulting slice. /// </summary> public Utf8Span Trim() => TrimHelper(TrimType.Both); /// <summary> /// Trims whitespace from only the end of this <see cref="Utf8Span"/>, /// returning a new <see cref="Utf8Span"/> containing the resulting slice. /// </summary> public Utf8Span TrimEnd() => TrimHelper(TrimType.Tail); internal Utf8Span TrimHelper(TrimType trimType) { ReadOnlySpan<byte> retSpan = Bytes; if ((trimType & TrimType.Head) != 0) { int indexOfFirstNonWhiteSpaceChar = Utf8Utility.GetIndexOfFirstNonWhiteSpaceChar(retSpan); Debug.Assert((uint)indexOfFirstNonWhiteSpaceChar <= (uint)retSpan.Length); // TODO_UTF8STRING: Can use an unsafe slicing routine below if we need a perf boost. retSpan = retSpan.Slice(indexOfFirstNonWhiteSpaceChar); } if ((trimType & TrimType.Tail) != 0) { int indexOfTrailingWhiteSpaceSequence = Utf8Utility.GetIndexOfTrailingWhiteSpaceSequence(retSpan); Debug.Assert((uint)indexOfTrailingWhiteSpaceSequence <= (uint)retSpan.Length); // TODO_UTF8STRING: Can use an unsafe slicing routine below if we need a perf boost. retSpan = retSpan.Slice(0, indexOfTrailingWhiteSpaceSequence); } return UnsafeCreateWithoutValidation(retSpan); } /// <summary> /// Trims whitespace from only the beginning of this <see cref="Utf8Span"/>, /// returning a new <see cref="Utf8Span"/> containing the resulting slice. /// </summary> public Utf8Span TrimStart() => TrimHelper(TrimType.Head); [StructLayout(LayoutKind.Auto)] public readonly ref struct SplitResult { private readonly State _state; internal SplitResult(Utf8Span source, Rune searchRune, Utf8StringSplitOptions splitOptions) { _state = new State { RemainingSearchSpace = source, SearchRune = searchRune.Value, SearchTerm = default, SplitOptions = splitOptions }; } internal SplitResult(Utf8Span source, Utf8Span searchTerm, Utf8StringSplitOptions splitOptions) { _state = new State { RemainingSearchSpace = source, SearchRune = -1, SearchTerm = searchTerm, SplitOptions = splitOptions }; } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out item2); TrimIfNeeded(ref item2); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2, out Utf8Span item3) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out Utf8Span remainder); _state.DeconstructHelper(in remainder, out item2, out item3); TrimIfNeeded(ref item3); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2, out Utf8Span item3, out Utf8Span item4) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out Utf8Span remainder); _state.DeconstructHelper(in remainder, out item2, out remainder); _state.DeconstructHelper(in remainder, out item3, out item4); TrimIfNeeded(ref item4); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2, out Utf8Span item3, out Utf8Span item4, out Utf8Span item5) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out Utf8Span remainder); _state.DeconstructHelper(in remainder, out item2, out remainder); _state.DeconstructHelper(in remainder, out item3, out remainder); _state.DeconstructHelper(in remainder, out item4, out item5); TrimIfNeeded(ref item5); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2, out Utf8Span item3, out Utf8Span item4, out Utf8Span item5, out Utf8Span item6) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out Utf8Span remainder); _state.DeconstructHelper(in remainder, out item2, out remainder); _state.DeconstructHelper(in remainder, out item3, out remainder); _state.DeconstructHelper(in remainder, out item4, out remainder); _state.DeconstructHelper(in remainder, out item5, out item6); TrimIfNeeded(ref item6); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2, out Utf8Span item3, out Utf8Span item4, out Utf8Span item5, out Utf8Span item6, out Utf8Span item7) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out Utf8Span remainder); _state.DeconstructHelper(in remainder, out item2, out remainder); _state.DeconstructHelper(in remainder, out item3, out remainder); _state.DeconstructHelper(in remainder, out item4, out remainder); _state.DeconstructHelper(in remainder, out item5, out remainder); _state.DeconstructHelper(in remainder, out item6, out item7); TrimIfNeeded(ref item7); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span item1, out Utf8Span item2, out Utf8Span item3, out Utf8Span item4, out Utf8Span item5, out Utf8Span item6, out Utf8Span item7, out Utf8Span item8) { _state.DeconstructHelper(in _state.RemainingSearchSpace, out item1, out Utf8Span remainder); _state.DeconstructHelper(in remainder, out item2, out remainder); _state.DeconstructHelper(in remainder, out item3, out remainder); _state.DeconstructHelper(in remainder, out item4, out remainder); _state.DeconstructHelper(in remainder, out item5, out remainder); _state.DeconstructHelper(in remainder, out item6, out remainder); _state.DeconstructHelper(in remainder, out item7, out item8); TrimIfNeeded(ref item8); } public Enumerator GetEnumerator() => new Enumerator(this); private void TrimIfNeeded(ref Utf8Span span) { if ((_state.SplitOptions & Utf8StringSplitOptions.TrimEntries) != 0) { span = span.Trim(); } } [StructLayout(LayoutKind.Auto)] public ref struct Enumerator { private const Utf8StringSplitOptions HALT_ENUMERATION = (Utf8StringSplitOptions)int.MinValue; private Utf8Span _current; private State _state; internal Enumerator(SplitResult result) { _current = default; _state = result._state; // copy by value } public Utf8Span Current => _current; public bool MoveNext() { // Happy path: if the search term was found, then the two 'out' fields below are overwritten with // the contents of the (before, after) tuple, and we can return right away. if (_state.DeconstructHelper(in _state.RemainingSearchSpace, out _current, out _state.RemainingSearchSpace)) { return true; } // At this point, the search term was not found within the search space. '_current' contains the last // bit of data after the final occurrence of the search term. We'll also set a flag saying that we've // completed enumeration. if (_current.IsEmpty && (_state.SplitOptions & Utf8StringSplitOptions.RemoveEmptyEntries) != 0) { return false; } if ((_state.SplitOptions & HALT_ENUMERATION) != 0) { return false; } _state.SplitOptions |= HALT_ENUMERATION; // prevents yielding <empty> forever at end of split return true; } } [StructLayout(LayoutKind.Auto)] private ref struct State // fully mutable { internal Utf8Span RemainingSearchSpace; internal int SearchRune; // -1 if not specified, takes less space than "Rune?" internal Utf8Span SearchTerm; internal Utf8StringSplitOptions SplitOptions; // Returns 'true' if a match was found, 'false' otherwise. internal readonly bool DeconstructHelper(in Utf8Span source, out Utf8Span firstItem, out Utf8Span remainder) { // n.b. Our callers might pass the same reference for 'source' and 'remainder'. // We need to take care not to read 'source' after writing 'remainder'. bool wasMatchFound; ref readonly Utf8Span searchSpan = ref source; while (true) { if (searchSpan.IsEmpty) { firstItem = searchSpan; remainder = default; wasMatchFound = false; break; } Range matchRange; if (SearchRune >= 0) { wasMatchFound = searchSpan.TryFind(Rune.UnsafeCreate((uint)SearchRune), out matchRange); } else { wasMatchFound = searchSpan.TryFind(SearchTerm, out matchRange); } if (!wasMatchFound) { // If no match was found, we move 'source' to 'firstItem', trim if necessary, and return right away. firstItem = searchSpan; if ((SplitOptions & Utf8StringSplitOptions.TrimEntries) != 0) { firstItem = firstItem.Trim(); } remainder = default; } else { // Otherwise, if a match was found, split the result across 'firstItem' and 'remainder', // applying trimming if necessary. firstItem = searchSpan[..matchRange.Start]; // TODO_UTF8STRING: Could use unsafe slicing as optimization remainder = searchSpan[matchRange.End..]; // TODO_UTF8STRING: Could use unsafe slicing as optimization if ((SplitOptions & Utf8StringSplitOptions.TrimEntries) != 0) { firstItem = firstItem.Trim(); } // If we're asked to remove empty entries, loop until there's a real value in 'firstItem'. if ((SplitOptions & Utf8StringSplitOptions.RemoveEmptyEntries) != 0 && firstItem.IsEmpty) { searchSpan = ref remainder; continue; } } break; // loop only if explicit 'continue' statement was hit } return wasMatchFound; } } } [StructLayout(LayoutKind.Auto)] public readonly ref struct SplitOnResult { // Used when there is no match. internal SplitOnResult(Utf8Span originalSearchSpace) { Before = originalSearchSpace; After = Empty; } // Used when a match is found. internal SplitOnResult(Utf8Span originalSearchSpace, Range searchTermMatchRange) { (int startIndex, int length) = searchTermMatchRange.GetOffsetAndLength(originalSearchSpace.Length); // TODO_UTF8STRING: The below indexer performs correctness checks. We can skip these checks (and even the // bounds checks more generally) since we know the inputs are all valid and the containing struct is not // subject to tearing. Before = originalSearchSpace[..startIndex]; After = originalSearchSpace[(startIndex + length)..]; } public Utf8Span After { get; } public Utf8Span Before { get; } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out Utf8Span before, out Utf8Span after) { before = Before; after = After; } } } }
using System; using System.Collections.Generic; using System.Text; namespace OEIS { class Program { static void Main(string[] args) { int simulateN = 6; int iterations = 10000; int maxN = 12; JengaTower j = new JengaTower(); Console.WriteLine("Simulating a random set of Jenga towers with " + simulateN + " blocks..."); j.simulate(simulateN, iterations); Console.ReadLine(); j.count(maxN); Console.ReadLine(); } } class JengaTower { Random rand; int maxN; public JengaTower() { rand = new Random(); } public void count(int N) { maxN = N; // populate num1Tower[n], the number of ways to build 1 tower of n blocks // for towers which have either 1 or 2 blocks at each level, this is just Fibonacci(n) count1Tower(); // populate numSameTowers[m, n], the number of ways to build m towers each with exactly n blocks // this is just num1Tower[n]+m-1 choose m countSameTowers(); // populate numSetTowers[m, n], the number of ways to build m towers with a total of n blocks // here is where the interesting work is done countSetTowers(); // populate numTowers[n], the number of ways to build towers with a total of n blocks. // this is just a sum over "how many towers?" of numSetTowers countTowers(); for (int n = 0; n <= maxN; n++) { Console.Write(numTowers[n] + ", "); } Console.WriteLine(); } // how many distinct ways can we build towers with N blocks? int[] numTowers; public void countTowers() { numTowers = new int[maxN + 1]; numTowers[0] = 1; for (int n = 1; n <= maxN; n++) { // sum of ways to build m towers, m=1..n for (int m = 1; m <= n; m++) { numTowers[n] += numSetTowers[m, n]; } } } // how many distinct ways can we build M towers with N blocks? int[,] numSetTowers; public void countSetTowers() { numSetTowers = new int[maxN + 1, maxN + 1]; // there is exactly 1 way to build 0 towers with 0 blocks numSetTowers[0, 0] = 1; // there are 0 ways to build m towers with < m blocks // M towers, N blocks, no tower has more than S blocks in it int[, ,] numSetTowersMaxSize = new int[maxN + 1, maxN + 1, maxN + 1]; // there is exactly 1 way to build 0 towers with 0 blocks for (int s = 0; s <= maxN; s++) { numSetTowersMaxSize[0, 0, s] = 1; } // there are 0 ways to build m towers with < m blocks // there are 0 ways to build m towers with n + 1 blocks when no tower has more than n/m blocks in it // for each number of total blocks, for (int n = 1; n <= maxN; n++) { // for each number of total towers, for (int m = 1; m <= n; m++) { // suppose the largest number of blocks in any of the towers is s, // (we have n-m extra blocks, so the largest tower can have at most n-m+1 blocks) for (int s = 1; s <= (n - m + 1); s++) { // for each number d of towers that all have s blocks, for (int d = 1; d * s <= n && d <= m; d++) { // there are w ways to build m towers from n blocks with d of the towers having s blocks // and no tower having more than s blocks int w = numSameTowers[d, s] * numSetTowersMaxSize[m - d, n - d * s, s - 1]; // if a tower arrangement has no tower with more than s blocks, then it also // has no tower with more than s+1, s+2, etc. blocks for (int x = s; x <= maxN; x++) { numSetTowersMaxSize[m, n, x] += w; } } } numSetTowers[m, n] = numSetTowersMaxSize[m, n, maxN]; } } Console.WriteLine("Number of ways to build M towers with N blocks"); Console.WriteLine("------------------------------------------------"); for (int i = 0; i <= maxN; i++) { Console.Write(i + ":\t"); for (int j = 0; j <= maxN; j++) { Console.Write(numSetTowers[i, j] + " "); } Console.WriteLine(""); } Console.WriteLine(""); } // how many distinct ways can we build M towers with N blocks in each? // numSameTowers[i, j] is how many ways to build i towers with j blocks in each // this is just choosing M times with repetition from num1Tower(N) tower choices // which is ((num1Tower(N), M)) = (num1Tower(N)+M-1,M) int[,] numSameTowers; public void countSameTowers() { numSameTowers = new int[maxN + 1, maxN + 1]; for (int n = 0; n <= maxN; n++) { for (int m = 0; m <= maxN; m++) { numSameTowers[m, n] = choose(num1Tower[n] + m - 1, m); } } } private int choose(int n, int m) { if (n < m) return 0; int r = 1; for (int i = 0; i < m; i++) { r *= n - i; r /= i + 1; } return r; } // how many distinct ways can we build 1 tower with N blocks in it? // if we can use up to k blocks in each level, then picture a tower // whose top level has j blocks - the number of such towers is the same // as the number of towers with N-j blocks in it. int[] num1Tower; public void count1Tower() { int k = 2; num1Tower = new int[maxN + 1]; num1Tower[0] = 1; num1Tower[1] = 1; num1Tower[2] = 2; // assert initial fills are at least as many as k for (int i = 3; i <= maxN; i++) { //num1Tower[i] = num1Tower[i - 1] + num1Tower[i - 2] + num1Tower[i - 3]; for (int j = 1; j <= k; j++) { num1Tower[i] += num1Tower[i - j]; } } Console.WriteLine("Number of ways to build 1 tower with N blocks"); Console.WriteLine("==="); Console.WriteLine("\t0\t1\t2\t3\t4\t5\t6\t7\t8"); Console.WriteLine("------------------------------------------------"); for (int i = 0; i <= maxN; i++) Console.Write("\t" + num1Tower[i]); Console.WriteLine(""); Console.WriteLine(""); } public void simulate(int n, int T) { HashSet<string> first = new HashSet<string>(); HashSet<string> second = new HashSet<string>(); for (int multiply = 1; multiply <= 10; multiply *= 10) { HashSet<string> found = new HashSet<string>(); for (int t = 0; t < T * multiply; t++) { List<List<int>> towers = new List<List<int>>(); int numTowers = 0; int howManyTowers = rand.Next(1, ((n + 1) * n) / 2 + 1); for (int i = 0; i < n; i++) { if (howManyTowers >= n - i) { howManyTowers -= (n - i); towers.Add(new List<int>() { 1 }); numTowers++; } } double[] prob = new double[numTowers]; double sum = 0; for (int i = 0; i < numTowers; i++) { prob[i] = rand.NextDouble(); if (i == 0) prob[i] = 1 - prob[i] * prob[i]; sum += prob[i]; } for (int i = 0; i < numTowers; i++) { prob[i] /= sum; } for (int i = 0; i < n - numTowers; i++) { double towerToChangeRandom = rand.NextDouble(); List<int> towerToChange = towers[0]; for (int j = 0; j < numTowers; j++) { if (towerToChangeRandom < prob[j]) { towerToChange = towers[j]; break; } towerToChangeRandom -= prob[j]; } if (towerToChange[towerToChange.Count - 1] == 2 || rand.Next(0, 5) <= 2) { towerToChange.Add(1); } else { towerToChange[towerToChange.Count - 1] = 2; } } found.Add(canonical(towers)); } int total = found.Count; printHashSet(found, total); if (multiply == 1) { first.UnionWith(found); } else { second.UnionWith(found); } } second.SymmetricExceptWith(first); printHashSet(second, second.Count); } private static void printHashSet(HashSet<string> found, int total) { string[] instances = new string[found.Count]; found.CopyTo(instances); Array.Sort<string>(instances); foreach (string instance in instances) { Console.WriteLine(instance); } Console.WriteLine(total); } public string canonical(List<List<int>> towerset) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < towerset.Count; i++) { if (i != 0) sb.Append(","); sb.Append(string.Join<int>("/", towerset[i])); } string towersstring = sb.ToString(); string[] towers = towersstring.Split(new char[] { ',' }); Array.Sort<string>(towers); return string.Join<string>(",", towers); } } }
/* * 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; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace ZXing.Client.Result { /// <summary> /// Parses contact information formatted according to the VCard (2.1) format. This is not a complete /// implementation but should parse information as commonly encoded in 2D barcodes. /// </summary> /// <author>Sean Owen</author> sealed class VCardResultParser : ResultParser { #if SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE || NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 private static readonly Regex BEGIN_VCARD = new Regex("BEGIN:VCARD", RegexOptions.IgnoreCase); private static readonly Regex VCARD_LIKE_DATE = new Regex(@"\A(?:" + "\\d{4}-?\\d{2}-?\\d{2}" + @")\z"); private static readonly Regex CR_LF_SPACE_TAB = new Regex("\r\n[ \t]"); private static readonly Regex NEWLINE_ESCAPE = new Regex("\\\\[nN]"); private static readonly Regex VCARD_ESCAPES = new Regex("\\\\([,;\\\\])"); private static readonly Regex EQUALS = new Regex("="); private static readonly Regex SEMICOLON = new Regex(";"); private static readonly Regex UNESCAPED_SEMICOLONS = new Regex("(?<!\\\\);+"); private static readonly Regex COMMA = new Regex(","); private static readonly Regex SEMICOLON_OR_COMMA = new Regex("[;,]"); #else private static readonly Regex BEGIN_VCARD = new Regex("BEGIN:VCARD", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex VCARD_LIKE_DATE = new Regex(@"\A(?:" + "\\d{4}-?\\d{2}-?\\d{2}" + @")\z", RegexOptions.Compiled); private static readonly Regex CR_LF_SPACE_TAB = new Regex("\r\n[ \t]", RegexOptions.Compiled); private static readonly Regex NEWLINE_ESCAPE = new Regex("\\\\[nN]", RegexOptions.Compiled); private static readonly Regex VCARD_ESCAPES = new Regex("\\\\([,;\\\\])", RegexOptions.Compiled); private static readonly Regex EQUALS = new Regex("=", RegexOptions.Compiled); private static readonly Regex SEMICOLON = new Regex(";", RegexOptions.Compiled); private static readonly Regex UNESCAPED_SEMICOLONS = new Regex("(?<!\\\\);+", RegexOptions.Compiled); private static readonly Regex COMMA = new Regex(",", RegexOptions.Compiled); private static readonly Regex SEMICOLON_OR_COMMA = new Regex("[;,]", RegexOptions.Compiled); #endif override public ParsedResult parse(ZXing.Result result) { // Although we should insist on the raw text ending with "END:VCARD", there's no reason // to throw out everything else we parsed just because this was omitted. In fact, Eclair // is doing just that, and we can't parse its contacts without this leniency. String rawText = result.Text; var m = BEGIN_VCARD.Match(rawText); if (!m.Success || m.Index != 0) { return null; } List<List<String>> names = matchVCardPrefixedField("FN", rawText, true, false); if (names == null) { // If no display names found, look for regular name fields and format them names = matchVCardPrefixedField("N", rawText, true, false); formatNames(names); } List<String> nicknameString = matchSingleVCardPrefixedField("NICKNAME", rawText, true, false); String[] nicknames = nicknameString == null ? null : COMMA.Split(nicknameString[0]); List<List<String>> phoneNumbers = matchVCardPrefixedField("TEL", rawText, true, false); List<List<String>> emails = matchVCardPrefixedField("EMAIL", rawText, true, false); List<String> note = matchSingleVCardPrefixedField("NOTE", rawText, false, false); List<List<String>> addresses = matchVCardPrefixedField("ADR", rawText, true, true); List<String> org = matchSingleVCardPrefixedField("ORG", rawText, true, true); List<String> birthday = matchSingleVCardPrefixedField("BDAY", rawText, true, false); if (birthday != null && !isLikeVCardDate(birthday[0])) { birthday = null; } List<String> title = matchSingleVCardPrefixedField("TITLE", rawText, true, false); List<List<String>> urls = matchVCardPrefixedField("URL", rawText, true, false); List<String> instantMessenger = matchSingleVCardPrefixedField("IMPP", rawText, true, false); List<String> geoString = matchSingleVCardPrefixedField("GEO", rawText, true, false); String[] geo = geoString == null ? null : SEMICOLON_OR_COMMA.Split(geoString[0]); if (geo != null && geo.Length != 2) { geo = null; } return new AddressBookParsedResult(toPrimaryValues(names), nicknames, null, toPrimaryValues(phoneNumbers), toTypes(phoneNumbers), toPrimaryValues(emails), toTypes(emails), toPrimaryValue(instantMessenger), toPrimaryValue(note), toPrimaryValues(addresses), toTypes(addresses), toPrimaryValue(org), toPrimaryValue(birthday), toPrimaryValue(title), toPrimaryValues(urls), geo); } public static List<List<String>> matchVCardPrefixedField(String prefix, String rawText, bool trim, bool parseFieldDivider) { List<List<String>> matches = null; int i = 0; int max = rawText.Length; while (i < max) { // At start or after newline, match prefix, followed by optional metadata // (led by ;) ultimately ending in colon var matcher = new Regex("(?:^|\n)" + prefix + "(?:;([^:]*))?:", RegexOptions.IgnoreCase); if (i > 0) { i--; // Find from i-1 not i since looking at the preceding character } var match = matcher.Match(rawText, i); if (!match.Success) { break; } i = match.Index + match.Length; String metadataString = match.Groups[1].Value; // group 1 = metadata substring List<String> metadata = null; bool quotedPrintable = false; String quotedPrintableCharset = null; if (metadataString != null) { foreach (String metadatum in SEMICOLON.Split(metadataString)) { if (metadata == null) { metadata = new List<String>(1); } metadata.Add(metadatum); String[] metadatumTokens = EQUALS.Split(metadatum, 2); if (metadatumTokens.Length > 1) { String key = metadatumTokens[0]; String value = metadatumTokens[1]; if (String.Compare("ENCODING", key, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare("QUOTED-PRINTABLE", value, StringComparison.OrdinalIgnoreCase) == 0) { quotedPrintable = true; } else if (String.Compare("CHARSET", key, StringComparison.OrdinalIgnoreCase) == 0) { quotedPrintableCharset = value; } } } } int matchStart = i; // Found the start of a match here while ((i = rawText.IndexOf('\n', i)) >= 0) { // Really, end in \r\n if (i < rawText.Length - 1 && // But if followed by tab or space, (rawText[i + 1] == ' ' || // this is only a continuation rawText[i + 1] == '\t')) { i += 2; // Skip \n and continutation whitespace } else if (quotedPrintable && // If preceded by = in quoted printable ((i >= 1 && rawText[i - 1] == '=') || // this is a continuation (i >= 2 && rawText[i - 2] == '='))) { i++; // Skip \n } else { break; } } if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = max; } else if (i > matchStart) { // found a match if (matches == null) { matches = new List<List<String>>(1); // lazy init } if (i >= 1 && rawText[i - 1] == '\r') { i--; // Back up over \r, which really should be there } String element = rawText.Substring(matchStart, i - matchStart); if (trim) { element = element.Trim(); } if (quotedPrintable) { element = decodeQuotedPrintable(element, quotedPrintableCharset); if (parseFieldDivider) { element = UNESCAPED_SEMICOLONS.Replace(element, "\n").Trim(); } } else { if (parseFieldDivider) { element = UNESCAPED_SEMICOLONS.Replace(element, "\n").Trim(); } element = CR_LF_SPACE_TAB.Replace(element, ""); element = NEWLINE_ESCAPE.Replace(element, "\n"); element = VCARD_ESCAPES.Replace(element, "$1"); } if (metadata == null) { var matched = new List<String>(1); matched.Add(element); matches.Add(matched); } else { metadata.Insert(0, element); matches.Add(metadata); } i++; } else { i++; } } return matches; } private static String decodeQuotedPrintable(String value, String charset) { int length = value.Length; var result = new StringBuilder(length); var fragmentBuffer = new MemoryStream(); for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '\r': case '\n': break; case '=': if (i < length - 2) { char nextChar = value[i + 1]; if (nextChar == '\r' || nextChar == '\n') { // Ignore, it's just a continuation symbol } else { char nextNextChar = value[i + 2]; int firstDigit = parseHexDigit(nextChar); int secondDigit = parseHexDigit(nextNextChar); if (firstDigit >= 0 && secondDigit >= 0) { fragmentBuffer.WriteByte((byte)((firstDigit << 4) | secondDigit)); } // else ignore it, assume it was incorrectly encoded i += 2; } } break; default: maybeAppendFragment(fragmentBuffer, charset, result); result.Append(c); break; } } maybeAppendFragment(fragmentBuffer, charset, result); return result.ToString(); } private static void maybeAppendFragment(MemoryStream fragmentBuffer, String charset, StringBuilder result) { if (fragmentBuffer.Length > 0) { byte[] fragmentBytes = fragmentBuffer.ToArray(); String fragment; if (charset == null) { #if WindowsCE fragment = Encoding.Default.GetString(fragmentBytes, 0, fragmentBytes.Length); #else fragment = Encoding.UTF8.GetString(fragmentBytes, 0, fragmentBytes.Length); #endif } else { try { fragment = Encoding.GetEncoding(charset).GetString(fragmentBytes, 0, fragmentBytes.Length); } catch (Exception ) { #if WindowsCE // WindowsCE doesn't support all encodings. But it is device depended. // So we try here the some different ones if (charset == "ISO-8859-1") { fragment = Encoding.GetEncoding(1252).GetString(fragmentBytes, 0, fragmentBytes.Length); } else { fragment = Encoding.Default.GetString(fragmentBytes, 0, fragmentBytes.Length); } fragment = Encoding.Default.GetString(fragmentBytes, 0, fragmentBytes.Length); #else fragment = Encoding.UTF8.GetString(fragmentBytes, 0, fragmentBytes.Length); #endif } } fragmentBuffer.Seek(0, SeekOrigin.Begin); fragmentBuffer.SetLength(0); result.Append(fragment); } } internal static List<String> matchSingleVCardPrefixedField(String prefix, String rawText, bool trim, bool parseFieldDivider) { List<List<String>> values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider); return values == null || values.Count == 0 ? null : values[0]; } private static String toPrimaryValue(List<String> list) { return list == null || list.Count == 0 ? null : list[0]; } private static String[] toPrimaryValues(ICollection<List<String>> lists) { if (lists == null || lists.Count == 0) { return null; } var result = new List<String>(lists.Count); foreach (var list in lists) { String value = list[0]; if (!String.IsNullOrEmpty(value)) { result.Add(value); } } return SupportClass.toStringArray(result); } private static String[] toTypes(ICollection<List<String>> lists) { if (lists == null || lists.Count == 0) { return null; } List<String> result = new List<String>(lists.Count); foreach (var list in lists) { String value = list[0]; if (!String.IsNullOrEmpty(value)) { String type = null; for (int i = 1; i < list.Count; i++) { String metadatum = list[i]; int equals = metadatum.IndexOf('='); if (equals < 0) { // take the whole thing as a usable label type = metadatum; break; } if (String.Compare("TYPE", metadatum.Substring(0, equals), StringComparison.OrdinalIgnoreCase) == 0) { type = metadatum.Substring(equals + 1); break; } } result.Add(type); } } return SupportClass.toStringArray(result); } private static bool isLikeVCardDate(String value) { return value == null || VCARD_LIKE_DATE.Match(value).Success; } /** * Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like * "Reverend John Q. Public III". * * @param names name values to format, in place */ private static void formatNames(IEnumerable<List<String>> names) { if (names != null) { foreach (var list in names) { String name = list[0]; String[] components = new String[5]; int start = 0; int end; int componentIndex = 0; while (componentIndex < components.Length - 1 && (end = name.IndexOf(';', start)) >= 0) { components[componentIndex] = name.Substring(start, end - start); componentIndex++; start = end + 1; } components[componentIndex] = name.Substring(start); StringBuilder newName = new StringBuilder(100); maybeAppendComponent(components, 3, newName); maybeAppendComponent(components, 1, newName); maybeAppendComponent(components, 2, newName); maybeAppendComponent(components, 0, newName); maybeAppendComponent(components, 4, newName); list.Insert(0, newName.ToString().Trim()); } } } private static void maybeAppendComponent(String[] components, int i, StringBuilder newName) { if (!String.IsNullOrEmpty(components[i])) { if (newName.Length > 0) { newName.Append(' '); } newName.Append(components[i]); } } } }
#if MONO_COM #define FEATURE_COMINTEROP #endif // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices{ using System; using System.Reflection; using System.Diagnostics.Contracts; [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class UnmanagedFunctionPointerAttribute : Attribute { CallingConvention m_callingConvention; public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention) { m_callingConvention = callingConvention; } public CallingConvention CallingConvention { get { return m_callingConvention; } } public CharSet CharSet; public bool BestFitMapping; public bool ThrowOnUnmappableChar; // This field is ignored and marshaling behaves as if it was true (for historical reasons). public bool SetLastError; // P/Invoke via delegate always preserves signature, HRESULT swapping is not supported. //public bool PreserveSig; } [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [System.Runtime.InteropServices.ComVisible(false)] public sealed class TypeIdentifierAttribute : Attribute { public TypeIdentifierAttribute() { } public TypeIdentifierAttribute(string scope, string identifier) { Scope_ = scope; Identifier_ = identifier; } public String Scope { get { return Scope_; } } public String Identifier { get { return Identifier_; } } internal String Scope_; internal String Identifier_; } // To be used on methods that sink reverse P/Invoke calls. // This attribute is a CoreCLR-only security measure, currently ignored by the desktop CLR. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class AllowReversePInvokeCallsAttribute : Attribute { public AllowReversePInvokeCallsAttribute() { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class DispIdAttribute : Attribute { internal int _val; public DispIdAttribute(int dispId) { _val = dispId; } public int Value { get { return _val; } } } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum ComInterfaceType { InterfaceIsDual = 0, InterfaceIsIUnknown = 1, InterfaceIsIDispatch = 2, [System.Runtime.InteropServices.ComVisible(false)] InterfaceIsIInspectable = 3, } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class InterfaceTypeAttribute : Attribute { internal ComInterfaceType _val; public InterfaceTypeAttribute(ComInterfaceType interfaceType) { _val = interfaceType; } public InterfaceTypeAttribute(short interfaceType) { _val = (ComInterfaceType)interfaceType; } public ComInterfaceType Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComDefaultInterfaceAttribute : Attribute { internal Type _val; public ComDefaultInterfaceAttribute(Type defaultInterface) { _val = defaultInterface; } public Type Value { get { return _val; } } } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum ClassInterfaceType { None = 0, AutoDispatch = 1, AutoDual = 2 } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ClassInterfaceAttribute : Attribute { internal ClassInterfaceType _val; public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType) { _val = classInterfaceType; } public ClassInterfaceAttribute(short classInterfaceType) { _val = (ClassInterfaceType)classInterfaceType; } public ClassInterfaceType Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComVisibleAttribute : Attribute { internal bool _val; public ComVisibleAttribute(bool visibility) { _val = visibility; } public bool Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibImportClassAttribute : Attribute { internal String _importClassName; public TypeLibImportClassAttribute(Type importClass) { _importClassName = importClass.ToString(); } public String Value { get { return _importClassName; } } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class LCIDConversionAttribute : Attribute { internal int _val; public LCIDConversionAttribute(int lcid) { _val = lcid; } public int Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComRegisterFunctionAttribute : Attribute { public ComRegisterFunctionAttribute() { } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComUnregisterFunctionAttribute : Attribute { public ComUnregisterFunctionAttribute() { } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ProgIdAttribute : Attribute { internal String _val; public ProgIdAttribute(String progId) { _val = progId; } public String Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ImportedFromTypeLibAttribute : Attribute { internal String _val; public ImportedFromTypeLibAttribute(String tlbFile) { _val = tlbFile; } public String Value { get {return _val;} } } [Obsolete("The IDispatchImplAttribute is deprecated.", false)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum IDispatchImplType { SystemDefinedImpl = 0, InternalImpl = 1, CompatibleImpl = 2, } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false)] [Obsolete("This attribute is deprecated and will be removed in a future version.", false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class IDispatchImplAttribute : Attribute { internal IDispatchImplType _val; public IDispatchImplAttribute(IDispatchImplType implType) { _val = implType; } public IDispatchImplAttribute(short implType) { _val = (IDispatchImplType)implType; } public IDispatchImplType Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Class, Inherited = true)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComSourceInterfacesAttribute : Attribute { internal String _val; public ComSourceInterfacesAttribute(String sourceInterfaces) { _val = sourceInterfaces; } public ComSourceInterfacesAttribute(Type sourceInterface) { _val = sourceInterface.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3, Type sourceInterface4) { _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName; } public String Value { get {return _val;} } } #if FEATURE_COMINTEROP || MOBILE_LEGACY [AttributeUsage(AttributeTargets.All, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComConversionLossAttribute : Attribute { public ComConversionLossAttribute() { } } #endif #if FEATURE_COMINTEROP || MOBILE_LEGACY [Serializable] [Flags()] [System.Runtime.InteropServices.ComVisible(true)] public enum TypeLibTypeFlags { FAppObject = 0x0001, FCanCreate = 0x0002, FLicensed = 0x0004, FPreDeclId = 0x0008, FHidden = 0x0010, FControl = 0x0020, FDual = 0x0040, FNonExtensible = 0x0080, FOleAutomation = 0x0100, FRestricted = 0x0200, FAggregatable = 0x0400, FReplaceable = 0x0800, FDispatchable = 0x1000, FReverseBind = 0x2000, } [Serializable] [Flags()] [System.Runtime.InteropServices.ComVisible(true)] public enum TypeLibFuncFlags { FRestricted = 0x0001, FSource = 0x0002, FBindable = 0x0004, FRequestEdit = 0x0008, FDisplayBind = 0x0010, FDefaultBind = 0x0020, FHidden = 0x0040, FUsesGetLastError = 0x0080, FDefaultCollelem = 0x0100, FUiDefault = 0x0200, FNonBrowsable = 0x0400, FReplaceable = 0x0800, FImmediateBind = 0x1000, } [Serializable] [Flags()] [System.Runtime.InteropServices.ComVisible(true)] public enum TypeLibVarFlags { FReadOnly = 0x0001, FSource = 0x0002, FBindable = 0x0004, FRequestEdit = 0x0008, FDisplayBind = 0x0010, FDefaultBind = 0x0020, FHidden = 0x0040, FRestricted = 0x0080, FDefaultCollelem = 0x0100, FUiDefault = 0x0200, FNonBrowsable = 0x0400, FReplaceable = 0x0800, FImmediateBind = 0x1000, } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibTypeAttribute : Attribute { internal TypeLibTypeFlags _val; public TypeLibTypeAttribute(TypeLibTypeFlags flags) { _val = flags; } public TypeLibTypeAttribute(short flags) { _val = (TypeLibTypeFlags)flags; } public TypeLibTypeFlags Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibFuncAttribute : Attribute { internal TypeLibFuncFlags _val; public TypeLibFuncAttribute(TypeLibFuncFlags flags) { _val = flags; } public TypeLibFuncAttribute(short flags) { _val = (TypeLibFuncFlags)flags; } public TypeLibFuncFlags Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Field, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibVarAttribute : Attribute { internal TypeLibVarFlags _val; public TypeLibVarAttribute(TypeLibVarFlags flags) { _val = flags; } public TypeLibVarAttribute(short flags) { _val = (TypeLibVarFlags)flags; } public TypeLibVarFlags Value { get {return _val;} } } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000 } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] // Note that this enum should remain in-[....] with the CorNativeType enum in corhdr.h public enum UnmanagedType { Bool = 0x2, // 4 byte boolean value (true != 0, false == 0) I1 = 0x3, // 1 byte signed value U1 = 0x4, // 1 byte unsigned value I2 = 0x5, // 2 byte signed value U2 = 0x6, // 2 byte unsigned value I4 = 0x7, // 4 byte signed value U4 = 0x8, // 4 byte unsigned value I8 = 0x9, // 8 byte signed value U8 = 0xa, // 8 byte unsigned value R4 = 0xb, // 4 byte floating point R8 = 0xc, // 8 byte floating point Currency = 0xf, // A currency BStr = 0x13, // OLE Unicode BSTR LPStr = 0x14, // Ptr to SBCS string LPWStr = 0x15, // Ptr to Unicode string LPTStr = 0x16, // Ptr to OS preferred (SBCS/Unicode) string ByValTStr = 0x17, // OS preferred (SBCS/Unicode) inline string (only valid in structs) IUnknown = 0x19, // COM IUnknown pointer. IDispatch = 0x1a, // COM IDispatch pointer Struct = 0x1b, // Structure Interface = 0x1c, // COM interface SafeArray = 0x1d, // OLE SafeArray ByValArray = 0x1e, // Array of fixed size (only valid in structs) SysInt = 0x1f, // Hardware natural sized signed integer SysUInt = 0x20, VBByRefStr = 0x22, AnsiBStr = 0x23, // OLE BSTR containing SBCS characters TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0) FunctionPtr = 0x26, // Function pointer AsAny = 0x28, // Paired with Object type and does runtime marshalling determination LPArray = 0x2a, // C style array LPStruct = 0x2b, // Pointer to a structure CustomMarshaler = 0x2c, Error = 0x2d, [System.Runtime.InteropServices.ComVisible(false)] IInspectable = 0x2e, [System.Runtime.InteropServices.ComVisible(false)] HString = 0x2f, // Windows Runtime HSTRING } #if !MONO [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class MarshalAsAttribute : Attribute { #if MONO internal MarshalAsAttribute Copy () { return (MarshalAsAttribute)this.MemberwiseClone (); } #else [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return GetCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()); } [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeParameterInfo parameter) { return GetCustomAttribute(parameter) != null; } [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeFieldInfo field) { return GetCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); ; } [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field) { return GetCustomAttribute(field) != null; } [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(int token, RuntimeModule scope) { UnmanagedType unmanagedType, arraySubType; VarEnum safeArraySubType; int sizeParamIndex = 0, sizeConst = 0; string marshalTypeName = null, marshalCookie = null, safeArrayUserDefinedTypeName = null; int iidParamIndex = 0; ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token); if (nativeType.Length == 0) return null; MetadataImport.GetMarshalAs(nativeType, out unmanagedType, out safeArraySubType, out safeArrayUserDefinedTypeName, out arraySubType, out sizeParamIndex, out sizeConst, out marshalTypeName, out marshalCookie, out iidParamIndex); RuntimeType safeArrayUserDefinedType = safeArrayUserDefinedTypeName == null || safeArrayUserDefinedTypeName.Length == 0 ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope); RuntimeType marshalTypeRef = null; try { marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalTypeName, scope); } catch (System.TypeLoadException) { // The user may have supplied a bad type name string causing this TypeLoadException // Regardless, we return the bad type name Contract.Assert(marshalTypeName != null); } return new MarshalAsAttribute( unmanagedType, safeArraySubType, safeArrayUserDefinedType, arraySubType, (short)sizeParamIndex, sizeConst, marshalTypeName, marshalTypeRef, marshalCookie, iidParamIndex); } internal MarshalAsAttribute(UnmanagedType val, VarEnum safeArraySubType, RuntimeType safeArrayUserDefinedSubType, UnmanagedType arraySubType, short sizeParamIndex, int sizeConst, string marshalType, RuntimeType marshalTypeRef, string marshalCookie, int iidParamIndex) { _val = val; SafeArraySubType = safeArraySubType; SafeArrayUserDefinedSubType = safeArrayUserDefinedSubType; IidParameterIndex = iidParamIndex; ArraySubType = arraySubType; SizeParamIndex = sizeParamIndex; SizeConst = sizeConst; MarshalType = marshalType; MarshalTypeRef = marshalTypeRef; MarshalCookie = marshalCookie; } #endif internal UnmanagedType _val; public MarshalAsAttribute(UnmanagedType unmanagedType) { _val = unmanagedType; } public MarshalAsAttribute(short unmanagedType) { _val = (UnmanagedType)unmanagedType; } public UnmanagedType Value { get { return _val; } } // Fields used with SubType = SafeArray. public VarEnum SafeArraySubType; public Type SafeArrayUserDefinedSubType; // Field used with iid_is attribute (interface pointers). public int IidParameterIndex; // Fields used with SubType = ByValArray and LPArray. // Array size = parameter(PI) * PM + C public UnmanagedType ArraySubType; public short SizeParamIndex; // param index PI public int SizeConst; // constant C // Fields used with SubType = CustomMarshaler [System.Runtime.InteropServices.ComVisible(true)] public String MarshalType; // Name of marshaler class [System.Runtime.InteropServices.ComVisible(true)] public Type MarshalTypeRef; // Type of marshaler class public String MarshalCookie; // cookie to pass to marshaler } #endif [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] #if !MONOTOUCH public #endif sealed class ComImportAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeType type) { if ((type.Attributes & TypeAttributes.Import) == 0) return null; return new ComImportAttribute(); } internal static bool IsDefined(RuntimeType type) { return (type.Attributes & TypeAttributes.Import) != 0; } public ComImportAttribute() { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class GuidAttribute : Attribute { internal String _val; public GuidAttribute(String guid) { _val = guid; } public String Value { get { return _val; } } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class PreserveSigAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeMethodInfo method) { if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) == 0) return null; return new PreserveSigAttribute(); } internal static bool IsDefined(RuntimeMethodInfo method) { return (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; } public PreserveSigAttribute() { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class InAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return parameter.IsIn ? new InAttribute() : null; } internal static bool IsDefined(RuntimeParameterInfo parameter) { return parameter.IsIn; } public InAttribute() { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class OutAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return parameter.IsOut ? new OutAttribute() : null; } internal static bool IsDefined(RuntimeParameterInfo parameter) { return parameter.IsOut; } public OutAttribute() { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class OptionalAttribute : Attribute { internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter) { return parameter.IsOptional ? new OptionalAttribute() : null; } internal static bool IsDefined(RuntimeParameterInfo parameter) { return parameter.IsOptional; } public OptionalAttribute() { } } [Flags] public enum DllImportSearchPath { UseDllDirectoryForDependencies = 0x100, ApplicationDirectory = 0x200, UserDirectories = 0x400, System32 = 0x800, SafeDirectories = 0x1000, AssemblyDirectory = 0x2, LegacyBehavior = 0x0 } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)] [System.Runtime.InteropServices.ComVisible(false)] public sealed class DefaultDllImportSearchPathsAttribute : Attribute { internal DllImportSearchPath _paths; public DefaultDllImportSearchPathsAttribute(DllImportSearchPath paths) { _paths = paths; } public DllImportSearchPath Paths { get { return _paths; } } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class DllImportAttribute : Attribute { [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) return null; #if !MONO MetadataImport scope = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule()); #endif string entryPoint, dllName = null; int token = method.MetadataToken; PInvokeAttributes flags = 0; #if MONO ((MonoMethod)method).GetPInvoke(out flags, out entryPoint, out dllName); #else scope.GetPInvokeMap(token, out flags, out entryPoint, out dllName); #endif CharSet charSet = CharSet.None; switch (flags & PInvokeAttributes.CharSetMask) { case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break; case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break; // Invalid: default to CharSet.None default: break; } CallingConvention callingConvention = CallingConvention.Cdecl; switch (flags & PInvokeAttributes.CallConvMask) { case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break; case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break; case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break; case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break; case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break; // Invalid: default to CallingConvention.Cdecl default: break; } bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; bool preserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; return new DllImportAttribute( dllName, entryPoint, charSet, exactSpelling, setLastError, preserveSig, callingConvention, bestFitMapping, throwOnUnmappableChar); } internal static bool IsDefined(RuntimeMethodInfo method) { return (method.Attributes & MethodAttributes.PinvokeImpl) != 0; } internal DllImportAttribute( string dllName, string entryPoint, CharSet charSet, bool exactSpelling, bool setLastError, bool preserveSig, CallingConvention callingConvention, bool bestFitMapping, bool throwOnUnmappableChar) { _val = dllName; EntryPoint = entryPoint; CharSet = charSet; ExactSpelling = exactSpelling; SetLastError = setLastError; PreserveSig = preserveSig; CallingConvention = callingConvention; BestFitMapping = bestFitMapping; ThrowOnUnmappableChar = throwOnUnmappableChar; } internal String _val; public DllImportAttribute(String dllName) { _val = dllName; } public String Value { get { return _val; } } public String EntryPoint; public CharSet CharSet; public bool SetLastError; public bool ExactSpelling; public bool PreserveSig; public CallingConvention CallingConvention; public bool BestFitMapping; public bool ThrowOnUnmappableChar; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class StructLayoutAttribute : Attribute { private const int DEFAULT_PACKING_SIZE = 8; [System.Security.SecurityCritical] // auto-generated internal static StructLayoutAttribute GetCustomAttribute(RuntimeType type) { if (!IsDefined(type)) return null; int pack = 0, size = 0; LayoutKind layoutKind = LayoutKind.Auto; switch (type.Attributes & TypeAttributes.LayoutMask) { case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; default: Contract.Assume(false); break; } CharSet charSet = CharSet.None; switch (type.Attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; default: Contract.Assume(false); break; } #if MONO type.GetPacking (out pack, out size); #else type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out pack, out size); #endif // Metadata parameter checking should not have allowed 0 for packing size. // The runtime later converts a packing size of 0 to 8 so do the same here // because it's more useful from a user perspective. if (pack == 0) pack = DEFAULT_PACKING_SIZE; return new StructLayoutAttribute(layoutKind, pack, size, charSet); } internal static bool IsDefined(RuntimeType type) { if (type.IsInterface || type.HasElementType || type.IsGenericParameter) return false; return true; } internal LayoutKind _val; internal StructLayoutAttribute(LayoutKind layoutKind, int pack, int size, CharSet charSet) { _val = layoutKind; Pack = pack; Size = size; CharSet = charSet; } public StructLayoutAttribute(LayoutKind layoutKind) { _val = layoutKind; } public StructLayoutAttribute(short layoutKind) { _val = (LayoutKind)layoutKind; } public LayoutKind Value { get { return _val; } } public int Pack; public int Size; public CharSet CharSet; } [AttributeUsage(AttributeTargets.Field, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class FieldOffsetAttribute : Attribute { [System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeFieldInfo field) { int fieldOffset; if (field.DeclaringType != null && #if MONO (fieldOffset = field.GetFieldOffset ()) >= 0) #else field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out fieldOffset)) #endif return new FieldOffsetAttribute(fieldOffset); return null; } [System.Security.SecurityCritical] // auto-generated internal static bool IsDefined(RuntimeFieldInfo field) { return GetCustomAttribute(field) != null; } internal int _val; public FieldOffsetAttribute(int offset) { _val = offset; } public int Value { get { return _val; } } } #if FEATURE_COMINTEROP || MOBILE_LEGACY [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComAliasNameAttribute : Attribute { internal String _val; public ComAliasNameAttribute(String alias) { _val = alias; } public String Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AutomationProxyAttribute : Attribute { internal bool _val; public AutomationProxyAttribute(bool val) { _val = val; } public bool Value { get {return _val;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class PrimaryInteropAssemblyAttribute : Attribute { internal int _major; internal int _minor; public PrimaryInteropAssemblyAttribute(int major, int minor) { _major = major; _minor = minor; } public int MajorVersion { get {return _major;} } public int MinorVersion { get {return _minor;} } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class CoClassAttribute : Attribute { internal Type _CoClass; public CoClassAttribute(Type coClass) { _CoClass = coClass; } public Type CoClass { get { return _CoClass; } } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComEventInterfaceAttribute : Attribute { internal Type _SourceInterface; internal Type _EventProvider; public ComEventInterfaceAttribute(Type SourceInterface, Type EventProvider) { _SourceInterface = SourceInterface; _EventProvider = EventProvider; } public Type SourceInterface { get {return _SourceInterface;} } public Type EventProvider { get {return _EventProvider;} } } #endif #if FEATURE_COMINTEROP || MOBILE_LEGACY [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeLibVersionAttribute : Attribute { internal int _major; internal int _minor; public TypeLibVersionAttribute(int major, int minor) { _major = major; _minor = minor; } public int MajorVersion { get {return _major;} } public int MinorVersion { get {return _minor;} } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ComCompatibleVersionAttribute : Attribute { internal int _major; internal int _minor; internal int _build; internal int _revision; public ComCompatibleVersionAttribute(int major, int minor, int build, int revision) { _major = major; _minor = minor; _build = build; _revision = revision; } public int MajorVersion { get {return _major;} } public int MinorVersion { get {return _minor;} } public int BuildNumber { get {return _build;} } public int RevisionNumber { get {return _revision;} } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class BestFitMappingAttribute : Attribute { internal bool _bestFitMapping; public BestFitMappingAttribute(bool BestFitMapping) { _bestFitMapping = BestFitMapping; } public bool BestFitMapping { get { return _bestFitMapping; } } public bool ThrowOnUnmappableChar; } [AttributeUsage(AttributeTargets.Module, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class DefaultCharSetAttribute : Attribute { internal CharSet _CharSet; public DefaultCharSetAttribute(CharSet charSet) { _CharSet = charSet; } public CharSet CharSet { get { return _CharSet; } } } [Obsolete("This attribute has been deprecated. Application Domains no longer respect Activation Context boundaries in IDispatch calls.", false)] [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class SetWin32ContextInIDispatchAttribute : Attribute { public SetWin32ContextInIDispatchAttribute() { } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] [System.Runtime.InteropServices.ComVisible(false)] public sealed class ManagedToNativeComInteropStubAttribute : Attribute { internal Type _classType; internal String _methodName; public ManagedToNativeComInteropStubAttribute(Type classType, String methodName) { _classType = classType; _methodName = methodName; } public Type ClassType { get { return _classType; } } public String MethodName { get { return _methodName; } } } #endif #endif }
using System.Diagnostics; using System.Text; namespace IronAHK.Scripting { partial class Parser { [Conditional(Legacy)] void Translate(ref string code) { #region Variables var delim = new char[Spaces.Length + 1]; delim[0] = Multicast; Spaces.CopyTo(delim, 1); int z = code.IndexOfAny(delim); string cmd, param; if (z == -1) { cmd = code; param = string.Empty; } else { cmd = code.Substring(0, z); param = code.Substring(z).TrimStart(delim); } var replaced = new StringBuilder(code.Length); #endregion #region Parameters string[] parts = SplitCommandParameters(param); if (parts.Length > 0) parts[parts.Length - 1] = StripCommentSingle(parts[parts.Length - 1]); for (int i = 0; i < parts.Length; i++) { if (IsExpressionParameter(parts[i])) { int e = parts[i].IndexOf(Resolve) + 1; if (e < parts[i].Length) parts[i] = parts[i].Substring(e); else parts[i] = new string(StringBound, 2); } else { parts[i] = parts[i].TrimStart(Spaces); int l = parts[i].Length; if (l > 1 && parts[i][0] == Resolve && parts[i][l - 1] == Resolve) parts[i] = parts[i].Substring(1, l - 2); else { string str = StringBound.ToString(); parts[i] = string.Concat(str, parts[i], str); } } } #endregion switch (cmd.ToLowerInvariant()) { #region Repeat case "repeat": param = StripCommentSingle(param); if (param.Length > 0 && !IsPrimativeObject(param)) param = string.Empty; replaced.Append("Loop "); replaced.Append(param); replaced.Append(SingleSpace); replaced.Append(BlockOpen); break; case "endrepeat": replaced.Append(BlockClose); replaced.Append(param); break; #endregion #region Setters case "setbatchlines": case "setcontroldelay": case "setdefaultmousespeed": case "setkeydelay": case "setmousedelay": case "setstorecapslockmode": case "settitlematchmode": case "setwindelay": case "setworkingdir": replaced.Append("A_"); replaced.Append(cmd, 3, cmd.Length - 3); replaced.Append(Equal); replaced.Append(param); break; case "setenv": replaced.Append(parts[0].Substring(1, parts[0].Length - 2)); replaced.Append(AssignPre); replaced.Append(Equal); if (parts.Length > 1) replaced.Append(parts[1]); else replaced.Append(NullTxt); break; case "setformat": if (parts.Length != 2) throw new ParseException(ExTooFewParams); replaced.Append("A_Format"); const string fast = "fast"; parts[0] = parts[0].Substring(1, parts[0].Length - 2); if (parts[0].EndsWith(fast, System.StringComparison.OrdinalIgnoreCase)) parts[0] = parts[0].Substring(0, parts[0].Length - fast.Length); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append(parts[1]); break; case "autotrim": case "detecthiddentext": case "detecthiddenwindows": case "stringcasesense": replaced.Append("A_"); replaced.Append(cmd); replaced.Append(Equal); replaced.Append(param); break; #endregion #region If #region Equality // TODO: push single conditional command on same line as legacy converted equality-if statements case "ifequal": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(parts[0]); replaced.Append(Equal); if (parts.Length > 1) replaced.Append(parts[1]); break; case "ifnotequal": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(parts[0]); replaced.Append(Not); replaced.Append(Equal); if (parts.Length > 1) replaced.Append(parts[1]); break; case "ifgreater": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(parts[0]); replaced.Append(Greater); if (parts.Length > 1) replaced.Append(parts[1]); break; case "ifgreaterorequal": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(parts[0]); replaced.Append(Greater); replaced.Append(Equal); if (parts.Length > 1) replaced.Append(parts[1]); break; case "ifless": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(parts[0]); replaced.Append(Less); if (parts.Length > 1) replaced.Append(parts[1]); break; case "iflessorequal": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(parts[0]); replaced.Append(Less); replaced.Append(Equal); if (parts.Length > 1) replaced.Append(parts[1]); break; #endregion case "ifexist": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append("FileExist"); replaced.Append(ParenOpen); replaced.Append(parts[0]); replaced.Append(ParenClose, 2); break; case "ifnotexist": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append(Not); replaced.Append("FileExist"); replaced.Append(ParenOpen); replaced.Append(parts[0]); replaced.Append(ParenClose, 2); break; case "ifinstring": if (parts.Length < 2) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append("InStr"); replaced.Append(ParenOpen); replaced.Append(parts[0]); replaced.Append(Multicast); replaced.Append(parts[1]); replaced.Append(ParenClose, 2); break; case "ifnotinstring": if (parts.Length < 2) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append(Not); replaced.Append("InStr"); replaced.Append(ParenOpen); replaced.Append(parts[0]); replaced.Append(Multicast); replaced.Append(parts[1]); replaced.Append(ParenClose, 2); break; case "ifmsgbox": if (parts.Length < 1) throw new ParseException(ExTooFewParams); replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append("A_MsgBox"); replaced.Append(Equal); replaced.Append(parts[0]); replaced.Append(ParenClose); break; case "ifwinactive": replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append("WinActive"); replaced.Append(ParenOpen); foreach (var part in parts) { replaced.Append(part); replaced.Append(Multicast); } if (parts.Length > 1) replaced.Remove(replaced.Length - 1, 1); replaced.Append(ParenClose, 2); break; case "ifwinexist": replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append("WinExist"); replaced.Append(ParenOpen); foreach (var part in parts) { replaced.Append(part); replaced.Append(Multicast); } if (parts.Length > 1) replaced.Remove(replaced.Length - 1, 1); replaced.Append(ParenClose, 2); break; case "ifwinnotactive": replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append(Not); replaced.Append("WinActive"); replaced.Append(ParenOpen); foreach (var part in parts) { replaced.Append(part); replaced.Append(Multicast); } if (parts.Length > 1) replaced.Remove(replaced.Length - 1, 1); replaced.Append(ParenClose, 2); break; case "ifwinnotexist": replaced.Append(FlowIf); replaced.Append(SingleSpace); replaced.Append(ParenOpen); replaced.Append(Not); replaced.Append("WinExist"); replaced.Append(ParenOpen); foreach (var part in parts) { replaced.Append(part); replaced.Append(Multicast); } if (parts.Length > 1) replaced.Remove(replaced.Length - 1, 1); replaced.Append(ParenClose, 2); break; #endregion #region Strings // HACK: convert L/R paramter for legacy StringGetPos command case "stringgetpos": if (parts.Length < 3) throw new ParseException(ExTooFewParams); replaced.Append(parts[0].Trim(StringBound)); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("InStr"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(Multicast); replaced.Append(parts[2]); replaced.Append(Multicast); replaced.Append(FalseTxt); replaced.Append(Multicast); replaced.Append(parts.Length > 4 ? parts[4] : "0"); replaced.Append(ParenClose); break; case "stringleft": if (parts.Length < 3) throw new ParseException(ExTooFewParams); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("SubStr"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(Multicast); replaced.Append("1"); replaced.Append(Multicast); replaced.Append(parts[2]); replaced.Append(ParenClose); break; case "stringlen": if (parts.Length < 2) throw new ParseException(ExTooFewParams); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("StrLen"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(ParenClose); break; case "stringmid": if (parts.Length < 3) throw new ParseException(ExTooFewParams); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("SubStr"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(Multicast); replaced.Append(parts[2]); if (parts.Length > 3) { replaced.Append(Multicast); replaced.Append(parts[3]); } if (parts.Length > 4) { replaced.Append(Multicast); replaced.Append(parts[4]); } replaced.Append(ParenClose); break; case "stringright": if (parts.Length < 3) throw new ParseException(ExTooFewParams); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("SubStr"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(Multicast); replaced.Append("1"); replaced.Append(Add); replaced.Append(Minus); replaced.Append(ParenOpen); replaced.Append(parts[2]); replaced.Append(ParenClose); replaced.Append(ParenClose); break; case "stringtrimleft": if (parts.Length < 3) throw new ParseException(ExTooFewParams); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("SubStr"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(Multicast); replaced.Append("1"); replaced.Append(Add); replaced.Append(parts[2]); replaced.Append(ParenClose); break; case "stringtrimright": if (parts.Length < 3) throw new ParseException(ExTooFewParams); replaced.Append(parts[0]); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("SubStr"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(Multicast); replaced.Append("1"); replaced.Append(Multicast); replaced.Append(Minus); replaced.Append(ParenOpen); replaced.Append(parts[2]); replaced.Append(ParenClose); replaced.Append(ParenClose); break; #endregion #region Arithmetic // TODO: translate legacy EnvMult, EnvDiv etc #endregion #region Send case "sendevent": case "sendinput": case "sendplay": replaced.Append("Send"); replaced.Append(Multicast); replaced.Append(SingleSpace); replaced.Append(param); break; case "sendraw": replaced.Append("Send"); replaced.Append(Multicast); replaced.Append(SingleSpace); ParameterPrepend(ref param, "{Raw}"); replaced.Append(param); break; case "controlsendraw": replaced.Append("ControlSend"); replaced.Append(Multicast); replaced.Append(SingleSpace); ParameterPrepend(ref param, "{Raw}"); replaced.Append(param); break; case "sendmode": code = string.Empty; break; case "setcapslockstate": case "setnumlockstate": case "setscrolllockstate": replaced.Append("SetLockState"); replaced.Append(Multicast); replaced.Append(SingleSpace); replaced.Append(cmd, 3, cmd.Length - 3 - 5); replaced.Append(Multicast); replaced.Append(SingleSpace); replaced.Append(param); break; #endregion #region Mouse case "leftclick": case "mouseclick": replaced.Append("Click"); replaced.Append(Multicast); replaced.Append(param); break; case "leftclickdrag": replaced.Append("MouseClickDrag"); replaced.Append(Multicast); replaced.Append("Left"); replaced.Append(Multicast); replaced.Append(param); break; case "mousemove": replaced.Append("Click"); replaced.Append(Multicast); replaced.Append(param); replaced.Append(Multicast); replaced.Append("0"); break; #endregion #region Debug case "edit": case "listlines": case "listvars": replaced = null; break; #endregion #region Other case "filegetattrib": if (parts.Length != 2) replaced = null; else { replaced.Append(parts[0].Substring(1, parts[0].Length - 2)); replaced.Append(AssignPre); replaced.Append(Equal); replaced.Append("FileExist"); replaced.Append(ParenOpen); replaced.Append(parts[1]); replaced.Append(ParenClose); } break; #endregion } if (replaced == null) code = string.Empty; else if (replaced.Length > 0) code = replaced.ToString(); } [Conditional(Legacy)] void ParameterPrepend(ref string param, string insert) { if (IsExpressionParameter(param)) { var buffer = new StringBuilder(param.Length + insert.Length + 2); buffer.Append(Resolve); buffer.Append(SingleSpace); buffer.Append(StringBound); buffer.Append(insert); buffer.Append(StringBound); buffer.Append(SingleSpace); buffer.Append(Concatenate); buffer.Append(SingleSpace); buffer.Append(param, 2, param.Length - 2); param = buffer.ToString(); } else param = string.Concat(insert, param); } } }
//----------------------------------------------------------------------------- // Torque3D - postFXManager.gui.cs - Contains the code for the implementation // of the gui controls used in postFXManager.gui. // // // Copyright (C) Luma Arcade 2010 // Written By Sven Bergstrom | Luma Arcade //----------------------------------------------------------------------------- $PostFXManager::vebose = true; function postVerbose(%string) { if($PostFXManager::vebose == true) { echo(%string); } } function PostFXManager::onDialogPush( %this ) { //Apply the settings to the controls postVerbose("% - PostFX Manager - Loading GUI."); %this.settingsRefreshAll(); } // :: Controls for the overall postFX manager dialog function ppOptionsEnable::onAction(%this) { //Disable / Enable all PostFX if(ppOptionsEnable.getValue()) { %toEnable = true; } else { %toEnable = false; } PostFXManager.settingsSetEnabled(%toEnable); } function PostFXManager::getEnableResultFromControl(%this, %control) { %toEnable = -1; %bTest = %control.getValue(); if(%bTest == 1) { %toEnable = true; } else { %toEnable = false; } return %toEnable; } function ppOptionsEnableSSAO::onAction(%this) { %toEnable = PostFXManager.getEnableResultFromControl(%this); PostFXManager.settingsEffectSetEnabled("SSAO", %toEnable); } function ppOptionsEnableHDR::onAction(%this) { %toEnable = PostFXManager.getEnableResultFromControl(%this); PostFXManager.settingsEffectSetEnabled("HDR", %toEnable); } function ppOptionsEnableLightRays::onAction(%this) { %toEnable = PostFXManager.getEnableResultFromControl(%this); PostFXManager.settingsEffectSetEnabled("LightRays", %toEnable); } function ppOptionsEnableDOF::onAction(%this) { %toEnable = PostFXManager.getEnableResultFromControl(%this); PostFXManager.settingsEffectSetEnabled("DOF", %toEnable); } function ppOptionsEnableSharpness::onAction(%this) { %toEnable = PostFXManager.getEnableResultFromControl(%this); PostFXManager.settingsEffectSetEnabled("Sharp", %toEnable); } function ppOptionsEnableNV::onAction(%this) { %toEnable = PostFXManager.getEnableResultFromControl(%this); PostFXManager.settingsEffectSetEnabled("NV", %toEnable); } function ppOptionsSavePreset::onClick(%this) { //Stores the current settings into a preset file for loading and use later on } function ppOptionsLoadPreset::onClick(%this) { //Loads and applies the settings from a postfxpreset file } //Other controls, Quality dropdown function ppOptionsSSAOQuality::onSelect( %this, %id, %text ) { if(%id > -1 && %id < 3) { $SSAOPostFx::quality = %id; } } //SSAO Slider controls //General Tab function ppOptionsSSAOOverallStrength::onMouseDragged(%this) { $SSAOPostFx::overallStrength = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOBlurDepth::onMouseDragged(%this) { $SSAOPostFx::blurDepthTol = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOBlurNormal::onMouseDragged(%this) { $SSAOPostFx::blurNormalTol = %this.value; %this.ToolTip = "Value : " @ %this.value; } //Near Tab function ppOptionsSSAONearRadius::onMouseDragged(%this) { $SSAOPostFx::sRadius = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAONearStrength::onMouseDragged(%this) { $SSAOPostFx::sStrength = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAONearDepthMin::onMouseDragged(%this) { $SSAOPostFx::sDepthMin = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAONearDepthMax::onMouseDragged(%this) { $SSAOPostFx::sDepthMax = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAONearToleranceNormal::onMouseDragged(%this) { $SSAOPostFx::sNormalTol = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAONearTolerancePower::onMouseDragged(%this) { $SSAOPostFx::sNormalPow = %this.value; %this.ToolTip = "Value : " @ %this.value; } //Far Tab function ppOptionsSSAOFarRadius::onMouseDragged(%this) { $SSAOPostFx::lRadius = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOFarStrength::onMouseDragged(%this) { $SSAOPostFx::lStrength = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOFarDepthMin::onMouseDragged(%this) { $SSAOPostFx::lDepthMin = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOFarDepthMax::onMouseDragged(%this) { $SSAOPostFx::lDepthMax = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOFarToleranceNormal::onMouseDragged(%this) { $SSAOPostFx::lNormalTol = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSSAOFarTolerancePower::onMouseDragged(%this) { $SSAOPostFx::lNormalPow = %this.value; %this.ToolTip = "Value : " @ %this.value; } //HDR Slider Controls //Brighness tab function ppOptionsHDRToneMappingAmount::onMouseDragged(%this) { $HDRPostFX::enableToneMapping = %this.value; %this.ToolTip = "value : " @ %this.value; } function ppOptionsHDRKeyValue::onMouseDragged(%this) { $HDRPostFX::keyValue = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRMinLuminance::onMouseDragged(%this) { $HDRPostFX::minLuminace = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRWhiteCutoff::onMouseDragged(%this) { $HDRPostFX::whiteCutoff = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRBrightnessAdaptRate::onMouseDragged(%this) { $HDRPostFX::adaptRate = %this.value; %this.ToolTip = "Value : " @ %this.value; } //Blur tab function ppOptionsHDRBloomBlurBrightPassThreshold::onMouseDragged(%this) { $HDRPostFX::brightPassThreshold = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRBloomBlurMultiplier::onMouseDragged(%this) { $HDRPostFX::gaussMultiplier = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRBloomBlurMean::onMouseDragged(%this) { $HDRPostFX::gaussMean = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRBloomBlurStdDev::onMouseDragged(%this) { $HDRPostFX::gaussStdDev = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsHDRBloom::onAction(%this) { $HDRPostFX::enableBloom = %this.getValue(); } function ppOptionsHDRToneMapping::onAction(%this) { //$HDRPostFX::enableToneMapping = %this.getValue(); } function ppOptionsHDREffectsBlueShift::onAction(%this) { $HDRPostFX::enableBlueShift = %this.getValue(); } //Controls for color range in blue Shift dialog function ppOptionsHDREffectsBlueShiftColorBlend::onAction(%this) { $HDRPostFX::blueShiftColor = %this.PickColor; %this.ToolTip = "Color Values : " @ %this.PickColor; } function ppOptionsHDREffectsBlueShiftColorBaseColor::onAction(%this) { //This one feeds the one above ppOptionsHDREffectsBlueShiftColorBlend.baseColor = %this.PickColor; %this.ToolTip = "Color Values : " @ %this.PickColor; } //Light rays Slider Controls function ppOptionsLightRaysBrightScalar::onMouseDragged(%this) { $LightRayPostFX::brightScalar = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsUpdateDOFSettings() { DOFPostEffect.setFocusParams( $DOFPostFx::BlurMin, $DOFPostFx::BlurMax, $DOFPostFx::FocusRangeMin, $DOFPostFx::FocusRangeMax, -($DOFPostFx::BlurCurveNear), $DOFPostFx::BlurCurveFar ); } //DOF General Tab //DOF Toggles function ppOptionsDOFEnableDOF::onAction(%this) { $PostFXManager::PostFX::EnableDOF = %this.getValue(); if(%this.getValue()) { DOFPostEffect.enable(); } else { DOFPostEffect.disable(); } } function ppOptionsDOFEnableAutoFocus::onAction(%this) { $DOFPostFx::EnableAutoFocus = %this.getValue(); DOFPostEffect.setAutoFocus( %this.getValue() ); } //DOF AutoFocus Slider controls function ppOptionsDOFFarBlurMinSlider::onMouseDragged(%this) { $DOFPostFx::BlurMin = %this.value; ppOptionsUpdateDOFSettings(); } function ppOptionsDOFFarBlurMaxSlider::onMouseDragged(%this) { $DOFPostFx::BlurMax = %this.value; ppOptionsUpdateDOFSettings(); } function ppOptionsDOFFocusRangeMinSlider::onMouseDragged(%this) { $DOFPostFx::FocusRangeMin = %this.value; ppOptionsUpdateDOFSettings(); } function ppOptionsDOFFocusRangeMaxSlider::onMouseDragged(%this) { $DOFPostFx::FocusRangeMax = %this.value; ppOptionsUpdateDOFSettings(); } function ppOptionsDOFBlurCurveNearSlider::onMouseDragged(%this) { $DOFPostFx::BlurCurveNear = %this.value; ppOptionsUpdateDOFSettings(); } function ppOptionsDOFBlurCurveFarSlider::onMouseDragged(%this) { $DOFPostFx::BlurCurveFar = %this.value; ppOptionsUpdateDOFSettings(); } function ppOptionsSharpenRange::onMouseDragged(%this) { $SharpPostFx::sharpRange = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSharpenWidth::onMouseDragged(%this) { $SharpPostFx::sharpWidth = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsSharpenStrength::onMouseDragged(%this) { $SharpPostFx::sharpPower = %this.value; %this.ToolTip = "Value : " @ %this.value; } //NightVision brightness function ppOptionsNVBright::onMouseDragged(%this) { $NVPostFx::brightThreshold = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsNVLowMul::onMouseDragged(%this) { $NVPostFx::lowMultiplier = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsNVHighMul::onMouseDragged(%this) { $NVPostFx::highMultiplier = %this.value; %this.ToolTip = "Value : " @ %this.value; } //NightVision distortion function ppOptionsNVDistMul::onMouseDragged(%this) { $NVPostFx::DistMul = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsNVDistFreq::onMouseDragged(%this) { $NVPostFx::DistFreq = %this.value; %this.ToolTip = "Value : " @ %this.value; } function ppOptionsNVDistRoll::onMouseDragged(%this) { $NVPostFx::DistRoll = %this.value; %this.ToolTip = "Value : " @ %this.value; } // function ppOptionsEnableHDRDebug::onAction(%this) { if ( %this.getValue() ) LuminanceVisPostFX.enable(); else LuminanceVisPostFX.disable(); }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Microsoft.DocAsCode.DataContracts.ManagedReference; public class VBYamlModelGenerator : SimpleYamlModelGenerator { #region Fields private static readonly Regex EndRegex = new Regex(@"\s+End\s*\w*\s*$", RegexOptions.Compiled); #endregion public VBYamlModelGenerator() : base(SyntaxLanguage.VB) { } #region Overrides public override void DefaultVisit(ISymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { item.DisplayNames[SyntaxLanguage.VB] = NameVisitorCreator.GetVB(NameOptions.WithGenericParameter | NameOptions.WithParameter).GetName(symbol); item.DisplayNamesWithType[SyntaxLanguage.VB] = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithGenericParameter | NameOptions.WithParameter).GetName(symbol); item.DisplayQualifiedNames[SyntaxLanguage.VB] = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithGenericParameter | NameOptions.WithParameter).GetName(symbol); } public override void GenerateNamedType(INamedTypeSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateNamedType(symbol, item, adapter); var modifiers = new List<string>(); var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.TypeKind == TypeKind.Class) { if (symbol.IsAbstract) { modifiers.Add("MustInherit"); } else if (symbol.IsSealed) { modifiers.Add("NotInheritable"); } } switch (symbol.TypeKind) { case TypeKind.Module: modifiers.Add("Module"); break; case TypeKind.Class: if (symbol.IsStatic) { modifiers.Add("Module"); } else { modifiers.Add("Class"); } break; case TypeKind.Delegate: modifiers.Add("Delegate"); break; case TypeKind.Enum: modifiers.Add("Enum"); break; case TypeKind.Interface: modifiers.Add("Interface"); break; case TypeKind.Struct: modifiers.Add("Structure"); break; default: break; } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateMethod(IMethodSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateMethod(symbol, item, adapter); var modifiers = new List<string>(); if (symbol.ContainingType.TypeKind != TypeKind.Interface) { var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsAbstract) { modifiers.Add("MustOverride"); } if (symbol.IsOverride) { modifiers.Add("Overrides"); } if (symbol.IsVirtual && symbol.IsSealed) { } else if (symbol.IsVirtual) { modifiers.Add("Overridable"); } else if (symbol.IsSealed) { modifiers.Add("NotOverridable"); } } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateField(IFieldSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateField(symbol, item, adapter); var modifiers = new List<string>(); var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.IsConst) { modifiers.Add("Const"); } else if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsReadOnly) { modifiers.Add("ReadOnly"); } if (symbol.IsVolatile) { // no modifier for volatile in vb } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateProperty(IPropertySymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateProperty(symbol, item, adapter); var modifiers = new List<string>(); var propertyVisiblity = GetVisiblity(symbol.DeclaredAccessibility); if (symbol.ContainingType.TypeKind != TypeKind.Interface) { if (propertyVisiblity != null) { modifiers.Add(propertyVisiblity); } if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsAbstract) { modifiers.Add("MustOverride"); } if (symbol.IsOverride) { modifiers.Add("Overrides"); } if (symbol.IsVirtual && symbol.IsSealed) { } else if (symbol.IsVirtual) { modifiers.Add("Overridable"); } else if (symbol.IsSealed) { modifiers.Add("NotOverridable"); } } bool hasGetMethod = symbol.GetMethod != null; bool hasSetMethod = symbol.SetMethod != null; var getMethodVisiblity = hasGetMethod ? GetVisiblity(symbol.GetMethod.DeclaredAccessibility) : null; var setMethodVisiblity = hasSetMethod ? GetVisiblity(symbol.SetMethod.DeclaredAccessibility) : null; if (hasGetMethod ^ hasSetMethod) { if (hasGetMethod) { modifiers.Add("ReadOnly"); } else { modifiers.Add("WriteOnly"); } } else if (propertyVisiblity != null && (getMethodVisiblity == null ^ setMethodVisiblity == null)) { if (setMethodVisiblity == null) { modifiers.Add("ReadOnly"); } if (getMethodVisiblity == null) { modifiers.Add("WriteOnly"); } } else if (getMethodVisiblity != propertyVisiblity || setMethodVisiblity != propertyVisiblity) { if (getMethodVisiblity != propertyVisiblity) { modifiers.Add($"{getMethodVisiblity} Get"); } else { modifiers.Add("Get"); } if (setMethodVisiblity != propertyVisiblity) { modifiers.Add($"{setMethodVisiblity} Set"); } else { modifiers.Add("Set"); } } item.Modifiers[SyntaxLanguage.VB] = modifiers; } public override void GenerateEvent(IEventSymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { base.GenerateEvent(symbol, item, adapter); var modifiers = new List<string>(); if (symbol.ContainingType.TypeKind != TypeKind.Interface) { var visiblity = GetVisiblity(symbol.DeclaredAccessibility); if (visiblity != null) { modifiers.Add(visiblity); } if (symbol.IsStatic) { modifiers.Add("Shared"); } if (symbol.IsAbstract) { modifiers.Add("MustOverride"); } if (symbol.IsOverride) { modifiers.Add("Overrides"); } if (symbol.IsVirtual && symbol.IsSealed) { } else if (symbol.IsVirtual) { modifiers.Add("Overridable"); } else if (symbol.IsSealed) { modifiers.Add("NotOverridable"); } } item.Modifiers[SyntaxLanguage.VB] = modifiers; } protected override string GetSyntaxContent(MemberType typeKind, ISymbol symbol, SymbolVisitorAdapter adapter) { switch (typeKind) { case MemberType.Class: return GetClassSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Enum: return GetEnumSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Interface: return GetInterfaceSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Struct: return GetStructSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Delegate: return GetDelegateSyntax((INamedTypeSymbol)symbol, adapter.FilterVisitor); case MemberType.Method: return GetMethodSyntax((IMethodSymbol)symbol, adapter.FilterVisitor); case MemberType.Operator: return GetOperatorSyntax((IMethodSymbol)symbol, adapter.FilterVisitor); case MemberType.Constructor: return GetConstructorSyntax((IMethodSymbol)symbol, adapter.FilterVisitor); case MemberType.Field: return GetFieldSyntax((IFieldSymbol)symbol, adapter.FilterVisitor); case MemberType.Event: return GetEventSyntax((IEventSymbol)symbol, adapter.FilterVisitor); case MemberType.Property: return GetPropertySyntax((IPropertySymbol)symbol, adapter.FilterVisitor); default: return null; } } protected override void GenerateReference(ISymbol symbol, ReferenceItem reference, SymbolVisitorAdapter adapter, bool asOverload) { symbol.Accept(new VBReferenceItemVisitor(reference, asOverload)); } #endregion #region Private Methods #region Syntax private string GetClassSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr; if (symbol.TypeKind == TypeKind.Module || symbol.IsStatic) { syntaxStr = SyntaxFactory.ModuleBlock( SyntaxFactory.ModuleStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), GetInheritsList(symbol), GetImplementsList(symbol), new SyntaxList<StatementSyntax>() ).NormalizeWhitespace().ToString(); } else { syntaxStr = SyntaxFactory.ClassBlock( SyntaxFactory.ClassStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.ClassKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), GetInheritsList(symbol), GetImplementsList(symbol), new SyntaxList<StatementSyntax>(), SyntaxFactory.EndClassStatement() ).NormalizeWhitespace().ToString(); } return RemoveEnd(syntaxStr); } private string GetEnumSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { var syntaxStr = SyntaxFactory.EnumBlock( SyntaxFactory.EnumStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.EnumKeyword), SyntaxFactory.Identifier(symbol.Name), GetEnumUnderlyingType(symbol) ) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetInterfaceSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { var syntaxStr = SyntaxFactory.InterfaceBlock( SyntaxFactory.InterfaceStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.InterfaceKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), GetInheritsList(symbol), new SyntaxList<ImplementsStatementSyntax>(), new SyntaxList<StatementSyntax>(), SyntaxFactory.EndInterfaceStatement() ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetStructSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr = SyntaxFactory.StructureBlock( SyntaxFactory.StructureStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.StructureKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol) ), new SyntaxList<InheritsStatementSyntax>(), GetImplementsList(symbol), new SyntaxList<StatementSyntax>(), SyntaxFactory.EndStructureStatement() ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetDelegateSyntax(INamedTypeSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr = SyntaxFactory.DelegateStatement( symbol.DelegateInvokeMethod.ReturnsVoid ? SyntaxKind.DelegateSubStatement : SyntaxKind.DelegateFunctionStatement, GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetTypeModifiers(symbol) ), symbol.DelegateInvokeMethod.ReturnsVoid ? SyntaxFactory.Token(SyntaxKind.SubKeyword) : SyntaxFactory.Token(SyntaxKind.FunctionKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol), GetParamerterList(symbol.DelegateInvokeMethod), GetReturnAsClause(symbol.DelegateInvokeMethod) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetMethodSyntax(IMethodSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr = SyntaxFactory.MethodStatement( symbol.ReturnsVoid ? SyntaxKind.SubStatement : SyntaxKind.FunctionStatement, GetAttributes(symbol, filterVisitor, isExtensionMethod: symbol.IsExtensionMethod), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), symbol.ReturnsVoid ? SyntaxFactory.Token(SyntaxKind.SubKeyword) : SyntaxFactory.Token(SyntaxKind.FunctionKeyword), SyntaxFactory.Identifier(symbol.Name), GetTypeParameters(symbol), GetParamerterList(symbol), GetReturnAsClause(symbol), null, GetImplementsClause(symbol, filterVisitor) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetOperatorSyntax(IMethodSymbol symbol, IFilterVisitor filterVisitor) { var operatorToken = GetOperatorToken(symbol); if (operatorToken == null) { return "VB cannot support this operator."; } return SyntaxFactory.OperatorStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), operatorToken.Value, GetParamerterList(symbol), GetReturnAsClause(symbol) ).NormalizeWhitespace().ToString(); } private string GetConstructorSyntax(IMethodSymbol symbol, IFilterVisitor filterVisitor) { var syntaxStr = SyntaxFactory.SubNewStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), GetParamerterList(symbol) ).NormalizeWhitespace().ToString(); return RemoveEnd(syntaxStr); } private string GetFieldSyntax(IFieldSymbol symbol, IFilterVisitor filterVisitor) { string syntaxStr; if (symbol.ContainingType.TypeKind == TypeKind.Enum) { syntaxStr = SyntaxFactory.EnumMemberDeclaration( GetAttributes(symbol, filterVisitor), SyntaxFactory.Identifier(symbol.Name), GetDefaultValue(symbol) ).NormalizeWhitespace().ToString(); } else { syntaxStr = SyntaxFactory.FieldDeclaration( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList(GetMemberModifiers(symbol)), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.ModifiedIdentifier(symbol.Name) ), SyntaxFactory.SimpleAsClause( GetTypeSyntax(symbol.Type) ), GetDefaultValue(symbol) ) ) ).NormalizeWhitespace().ToString(); } return RemoveEnd(syntaxStr); } private string GetEventSyntax(IEventSymbol symbol, IFilterVisitor filterVisitor) { return SyntaxFactory.EventStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), SyntaxFactory.Identifier(symbol.Name), null, SyntaxFactory.SimpleAsClause( GetTypeSyntax(symbol.Type) ), GetImplementsClause(symbol, filterVisitor) ).NormalizeWhitespace().ToString(); } private string GetPropertySyntax(IPropertySymbol symbol, IFilterVisitor filterVisitor) { return SyntaxFactory.PropertyStatement( GetAttributes(symbol, filterVisitor), SyntaxFactory.TokenList( GetMemberModifiers(symbol) ), SyntaxFactory.Identifier(symbol.MetadataName), GetParamerterList(symbol), SyntaxFactory.SimpleAsClause( GetTypeSyntax(symbol.Type) ), null, GetImplementsClause(symbol, filterVisitor) ).NormalizeWhitespace().ToString(); } #endregion private static SyntaxList<AttributeListSyntax> GetAttributes(ISymbol symbol, IFilterVisitor filterVisitor, bool inOneLine = false, bool isExtensionMethod = false) { var attrs = symbol.GetAttributes(); List<AttributeSyntax> attrList = null; if (attrs.Length > 0) { attrList = (from attr in attrs where !(attr.AttributeClass is IErrorTypeSymbol) where attr?.AttributeConstructor != null where filterVisitor.CanVisitAttribute(attr.AttributeConstructor) select GetAttributeSyntax(attr)).ToList(); } if (isExtensionMethod) { attrList = attrList ?? new List<AttributeSyntax>(); attrList.Add( SyntaxFactory.Attribute( SyntaxFactory.ParseName(nameof(System.Runtime.CompilerServices.ExtensionAttribute)))); } if (attrList?.Count > 0) { if (inOneLine) { return SyntaxFactory.SingletonList( SyntaxFactory.AttributeList( SyntaxFactory.SeparatedList(attrList))); } return SyntaxFactory.List( from attr in attrList select SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList(attr))); } return new SyntaxList<AttributeListSyntax>(); } private static AttributeSyntax GetAttributeSyntax(AttributeData attr) { var attrTypeName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(attr.AttributeClass); if (attrTypeName.EndsWith(nameof(Attribute))) { attrTypeName = attrTypeName.Remove(attrTypeName.Length - nameof(Attribute).Length); } if (attr.ConstructorArguments.Length == 0 && attr.NamedArguments.Length == 0) { return SyntaxFactory.Attribute(SyntaxFactory.ParseName(attrTypeName)); } return SyntaxFactory.Attribute( null, SyntaxFactory.ParseName(attrTypeName), SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList( (from item in attr.ConstructorArguments select GetLiteralExpression(item) into expr where expr != null select (ArgumentSyntax)SyntaxFactory.SimpleArgument(expr) ).Concat( from item in attr.NamedArguments let expr = GetLiteralExpression(item.Value) where expr != null select (ArgumentSyntax)SyntaxFactory.SimpleArgument( SyntaxFactory.NameColonEquals( SyntaxFactory.IdentifierName(item.Key) ), expr ) ) ) ) ); } private static IEnumerable<SyntaxToken> GetTypeModifiers(INamedTypeSymbol symbol) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } if (symbol.TypeKind == TypeKind.Class) { if (symbol.IsAbstract && symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword); } else { if (symbol.IsAbstract) { yield return SyntaxFactory.Token(SyntaxKind.MustInheritKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword); } } } } private IEnumerable<SyntaxToken> GetMemberModifiers(IMethodSymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsAbstract && symbol.ContainingType.TypeKind != TypeKind.Interface) { yield return SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword); } if (symbol.IsVirtual) { yield return SyntaxFactory.Token(SyntaxKind.OverridableKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword); } if (symbol.IsOverride) { yield return SyntaxFactory.Token(SyntaxKind.OverridesKeyword); } if (symbol.MethodKind == MethodKind.Conversion) { if (symbol.Name == "op_Implicit") { yield return SyntaxFactory.Token(SyntaxKind.WideningKeyword); } else if (symbol.Name == "op_Explicit") { yield return SyntaxFactory.Token(SyntaxKind.NarrowingKeyword); } } } private IEnumerable<SyntaxToken> GetMemberModifiers(IFieldSymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsConst) { yield return SyntaxFactory.Token(SyntaxKind.ConstKeyword); } else { if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsReadOnly) { yield return SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); } } } private IEnumerable<SyntaxToken> GetMemberModifiers(IEventSymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsAbstract && symbol.ContainingType.TypeKind != TypeKind.Interface) { yield return SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword); } if (symbol.IsVirtual) { yield return SyntaxFactory.Token(SyntaxKind.OverridableKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword); } if (symbol.IsOverride) { yield return SyntaxFactory.Token(SyntaxKind.OverridesKeyword); } } private IEnumerable<SyntaxToken> GetMemberModifiers(IPropertySymbol symbol) { if (symbol.ContainingType.TypeKind != TypeKind.Interface) { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrFriend: yield return SyntaxFactory.Token(SyntaxKind.ProtectedKeyword); break; case Accessibility.Public: yield return SyntaxFactory.Token(SyntaxKind.PublicKeyword); break; default: break; } } if (symbol.IsStatic) { yield return SyntaxFactory.Token(SyntaxKind.SharedKeyword); } if (symbol.IsAbstract && symbol.ContainingType.TypeKind != TypeKind.Interface) { yield return SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword); } if (symbol.IsVirtual) { yield return SyntaxFactory.Token(SyntaxKind.OverridableKeyword); } if (symbol.IsSealed) { yield return SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword); } if (symbol.IsOverride) { yield return SyntaxFactory.Token(SyntaxKind.OverridesKeyword); } if (symbol.IsReadOnly || symbol.SetMethod == null) { yield return SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); } else { switch (symbol.SetMethod.DeclaredAccessibility) { case Accessibility.Private: case Accessibility.ProtectedAndInternal: case Accessibility.Internal: yield return SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); break; default: break; } } if (symbol.IsWriteOnly || symbol.GetMethod == null) { yield return SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword); } else { switch (symbol.GetMethod.DeclaredAccessibility) { case Accessibility.Private: case Accessibility.ProtectedAndInternal: case Accessibility.Internal: yield return SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword); break; default: break; } } } private static TypeParameterListSyntax GetTypeParameters(INamedTypeSymbol symbol) { if (symbol.TypeArguments.Length == 0) { return null; } return SyntaxFactory.TypeParameterList( SyntaxFactory.SeparatedList( from ITypeParameterSymbol t in symbol.TypeArguments select SyntaxFactory.TypeParameter( GetVarianceToken(t), SyntaxFactory.Identifier(t.Name), GetTypeParameterConstraintClauseSyntax(t)))); } private static TypeParameterListSyntax GetTypeParameters(IMethodSymbol symbol) { if (symbol.TypeArguments.Length == 0) { return null; } return SyntaxFactory.TypeParameterList( SyntaxFactory.SeparatedList( from ITypeParameterSymbol t in symbol.TypeArguments select SyntaxFactory.TypeParameter( GetVarianceToken(t), SyntaxFactory.Identifier(t.Name), GetTypeParameterConstraintClauseSyntax(t)))); } private static SyntaxToken GetVarianceToken(ITypeParameterSymbol t) { if (t.Variance == VarianceKind.In) return SyntaxFactory.Token(SyntaxKind.InKeyword); if (t.Variance == VarianceKind.Out) return SyntaxFactory.Token(SyntaxKind.OutKeyword); return new SyntaxToken(); } private static TypeParameterConstraintClauseSyntax GetTypeParameterConstraintClauseSyntax(ITypeParameterSymbol symbol) { var contraints = GetConstraintSyntaxes(symbol).ToList(); if (contraints.Count == 0) { return null; } if (contraints.Count == 1) { return SyntaxFactory.TypeParameterSingleConstraintClause(contraints[0]); } return SyntaxFactory.TypeParameterMultipleConstraintClause(contraints.ToArray()); } private static IEnumerable<ConstraintSyntax> GetConstraintSyntaxes(ITypeParameterSymbol symbol) { if (symbol.HasReferenceTypeConstraint) { yield return SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword)); } if (symbol.HasValueTypeConstraint) { yield return SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword)); } if (symbol.ConstraintTypes.Length > 0) { for (int i = 0; i < symbol.ConstraintTypes.Length; i++) { yield return SyntaxFactory.TypeConstraint(GetTypeSyntax(symbol.ConstraintTypes[i])); } } if (symbol.HasConstructorConstraint) { yield return SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } private SyntaxList<InheritsStatementSyntax> GetInheritsList(INamedTypeSymbol symbol) { if (symbol.TypeKind == TypeKind.Class && symbol.BaseType != null && symbol.BaseType.GetDocumentationCommentId() != "T:System.Object") { return SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(GetTypeSyntax(symbol.BaseType))); } if (symbol.TypeKind == TypeKind.Interface && symbol.Interfaces.Length > 0) { return SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement( (from t in symbol.Interfaces select GetTypeSyntax(t)).ToArray())); } return new SyntaxList<InheritsStatementSyntax>(); } private SyntaxList<ImplementsStatementSyntax> GetImplementsList(INamedTypeSymbol symbol) { if (symbol.AllInterfaces.Any()) { return SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement( (from t in symbol.AllInterfaces select GetTypeSyntax(t)).ToArray())); } return new SyntaxList<ImplementsStatementSyntax>(); } private AsClauseSyntax GetEnumUnderlyingType(INamedTypeSymbol symbol) { if (symbol.EnumUnderlyingType.GetDocumentationCommentId() == "T:System.Int32") { return null; } return SyntaxFactory.SimpleAsClause(GetTypeSyntax(symbol.EnumUnderlyingType)); } private ParameterListSyntax GetParamerterList(IMethodSymbol symbol) { if (symbol.Parameters.Length == 0) { return null; } return SyntaxFactory.ParameterList( SyntaxFactory.SeparatedList( from p in symbol.Parameters select SyntaxFactory.Parameter( new SyntaxList<AttributeListSyntax>(), SyntaxFactory.TokenList(GetParameterModifiers(p)), SyntaxFactory.ModifiedIdentifier(p.Name), SyntaxFactory.SimpleAsClause(GetTypeSyntax(p.Type)), GetDefaultValue(p)))); } private ParameterListSyntax GetParamerterList(IPropertySymbol symbol) { if (symbol.Parameters.Length == 0) { return null; } return SyntaxFactory.ParameterList( SyntaxFactory.SeparatedList( from p in symbol.Parameters select SyntaxFactory.Parameter( new SyntaxList<AttributeListSyntax>(), SyntaxFactory.TokenList(GetParameterModifiers(p)), SyntaxFactory.ModifiedIdentifier(p.Name), SyntaxFactory.SimpleAsClause(GetTypeSyntax(p.Type)), GetDefaultValue(p)))); } private IEnumerable<SyntaxToken> GetParameterModifiers(IParameterSymbol symbol) { if (symbol.RefKind == RefKind.None) { } else { yield return SyntaxFactory.Token(SyntaxKind.ByRefKeyword); } if (symbol.IsParams) { yield return SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword); } } private ImplementsClauseSyntax GetImplementsClause(IMethodSymbol symbol, IFilterVisitor filterVisitor) { if (symbol.ExplicitInterfaceImplementations.Length == 0) { return null; } var list = (from eii in symbol.ExplicitInterfaceImplementations where filterVisitor.CanVisitApi(eii) select SyntaxFactory.QualifiedName(GetQualifiedNameSyntax(eii.ContainingType), (SimpleNameSyntax)SyntaxFactory.ParseName(eii.Name))).ToList(); if (list.Count == 0) { return null; } return SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(list.ToArray())); } private ImplementsClauseSyntax GetImplementsClause(IEventSymbol symbol, IFilterVisitor filterVisitor) { if (symbol.ExplicitInterfaceImplementations.Length == 0) { return null; } var list = (from eii in symbol.ExplicitInterfaceImplementations where filterVisitor.CanVisitApi(eii) select SyntaxFactory.QualifiedName(GetQualifiedNameSyntax(eii.ContainingType), (SimpleNameSyntax)SyntaxFactory.ParseName(eii.Name))).ToList(); if (list.Count == 0) { return null; } return SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(list.ToArray())); } private ImplementsClauseSyntax GetImplementsClause(IPropertySymbol symbol, IFilterVisitor filterVisitor) { if (symbol.ExplicitInterfaceImplementations.Length == 0) { return null; } var list = (from eii in symbol.ExplicitInterfaceImplementations where filterVisitor.CanVisitApi(eii) select SyntaxFactory.QualifiedName(GetQualifiedNameSyntax(eii.ContainingType), (SimpleNameSyntax)SyntaxFactory.ParseName(eii.Name))).ToList(); if (list.Count == 0) { return null; } return SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(list.ToArray())); } private EqualsValueSyntax GetDefaultValue(IParameterSymbol symbol) { if (symbol.HasExplicitDefaultValue) { return GetDefaultValueCore(symbol.ExplicitDefaultValue, symbol.Type); } return null; } private EqualsValueSyntax GetDefaultValue(IFieldSymbol symbol) { if (symbol.IsConst) { if (symbol.ContainingType.TypeKind == TypeKind.Enum) { return GetDefaultValueCore(symbol.ConstantValue, ((INamedTypeSymbol)symbol.Type).EnumUnderlyingType); } return GetDefaultValueCore(symbol.ConstantValue, symbol.Type); } return null; } //private EqualsValueSyntax GetDefaultValueCore(object value) //{ // if (value == null) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NothingLiteralExpression, // SyntaxFactory.Token(SyntaxKind.NothingKeyword))); // } // if (value is bool) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // (bool)value ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression, // SyntaxFactory.Token( // (bool)value ? SyntaxKind.TrueKeyword : SyntaxKind.FalseKeyword))); // } // if (value is long) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((long)value))); // } // if (value is ulong) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((ulong)value))); // } // if (value is int) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((int)value))); // } // if (value is uint) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((uint)value))); // } // if (value is short) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((short)value))); // } // if (value is ushort) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((ushort)value))); // } // if (value is byte) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((byte)value))); // } // if (value is sbyte) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((sbyte)value))); // } // if (value is double) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((double)value))); // } // if (value is float) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((float)value))); // } // if (value is decimal) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.NumericLiteralExpression, // SyntaxFactory.Literal((decimal)value))); // } // if (value is char) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.CharacterLiteralExpression, // SyntaxFactory.Literal((char)value))); // } // if (value is string) // { // return SyntaxFactory.EqualsValue( // SyntaxFactory.LiteralExpression( // SyntaxKind.StringLiteralExpression, // SyntaxFactory.Literal((string)value))); // } // Debug.Fail("Unknown default value!"); // return null; //} private static EqualsValueSyntax GetDefaultValueCore(object value, ITypeSymbol type) { var expr = GetLiteralExpression(value, type); if (expr != null) { return SyntaxFactory.EqualsValue(expr); } return null; } private static ExpressionSyntax GetLiteralExpression(TypedConstant constant) { if (constant.Type.TypeKind == TypeKind.Array) { if (constant.Values == null) { return GetLiteralExpression(null, constant.Type); } var items = (from value in constant.Values select GetLiteralExpression(value)).ToList(); if (items.TrueForAll(x => x != null)) { return SyntaxFactory.ArrayCreationExpression( SyntaxFactory.Token(SyntaxKind.NewKeyword), default(SyntaxList<AttributeListSyntax>), GetTypeSyntax( ((IArrayTypeSymbol)constant.Type).ElementType ), null, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier() ), SyntaxFactory.CollectionInitializer( SyntaxFactory.SeparatedList( from value in constant.Values select GetLiteralExpression(value) ) ) ); } return SyntaxFactory.ArrayCreationExpression( SyntaxFactory.Token(SyntaxKind.NewKeyword), default(SyntaxList<AttributeListSyntax>), GetTypeSyntax( ((IArrayTypeSymbol)constant.Type).ElementType ), null, new SyntaxList<ArrayRankSpecifierSyntax>(), SyntaxFactory.CollectionInitializer() ); } var expr = GetLiteralExpression(constant.Value, constant.Type); if (expr == null) { return null; } switch (constant.Type.SpecialType) { case SpecialType.System_SByte: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.SByteKeyword))); case SpecialType.System_Byte: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ByteKeyword))); case SpecialType.System_Int16: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ShortKeyword))); case SpecialType.System_UInt16: return SyntaxFactory.CTypeExpression( expr, SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.UShortKeyword))); default: return expr; } } private static ExpressionSyntax GetLiteralExpression(object value, ITypeSymbol type) { if (value == null) { return SyntaxFactory.LiteralExpression( SyntaxKind.NothingLiteralExpression, SyntaxFactory.Token(SyntaxKind.NothingKeyword)); } var result = GetLiteralExpressionCore(value, type); if (result != null) { return result; } if (type.TypeKind == TypeKind.Enum) { var namedType = (INamedTypeSymbol)type; var enumType = GetTypeSyntax(namedType); var isFlags = namedType.GetAttributes().Any(attr => attr.AttributeClass.GetDocumentationCommentId() == "T:System.FlagsAttribute"); var pairs = from member in namedType.GetMembers().OfType<IFieldSymbol>() where member.IsConst && member.HasConstantValue select new { member.Name, member.ConstantValue }; if (isFlags) { var exprs = (from pair in pairs where HasFlag(namedType.EnumUnderlyingType, value, pair.ConstantValue) select SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, enumType, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(pair.Name))).ToList(); if (exprs.Count > 0) { return exprs.Aggregate<ExpressionSyntax>((x, y) => SyntaxFactory.OrExpression(x, y)); } } else { var expr = (from pair in pairs where object.Equals(value, pair.ConstantValue) select SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, enumType, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(pair.Name))).FirstOrDefault(); if (expr != null) { return expr; } } return SyntaxFactory.CTypeExpression( GetLiteralExpressionCore( value, namedType.EnumUnderlyingType), enumType); } if (value is ITypeSymbol) { return SyntaxFactory.GetTypeExpression( GetTypeSyntax((ITypeSymbol)value)); } Debug.Fail("Unknown default value!"); return null; } private static bool HasFlag(ITypeSymbol type, object value, object constantValue) { switch (type.SpecialType) { case SpecialType.System_SByte: { var v = (sbyte)value; var cv = (sbyte)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Byte: { var v = (byte)value; var cv = (byte)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Int16: { var v = (short)value; var cv = (short)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_UInt16: { var v = (ushort)value; var cv = (ushort)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Int32: { var v = (int)value; var cv = (int)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_UInt32: { var v = (uint)value; var cv = (uint)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_Int64: { var v = (long)value; var cv = (long)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } case SpecialType.System_UInt64: { var v = (ulong)value; var cv = (ulong)constantValue; if (cv == 0) { return v == 0; } return (v & cv) == cv; } default: return false; } } private static ExpressionSyntax GetLiteralExpressionCore(object value, ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: if ((bool)value) { return SyntaxFactory.TrueLiteralExpression(SyntaxFactory.Token(SyntaxKind.TrueKeyword)); } else { return SyntaxFactory.FalseLiteralExpression(SyntaxFactory.Token(SyntaxKind.FalseKeyword)); } case SpecialType.System_Char: var ch = (char)value; var category = char.GetUnicodeCategory(ch); switch (category) { case System.Globalization.UnicodeCategory.Surrogate: return SyntaxFactory.LiteralExpression( SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal("\"\\u" + ((int)ch).ToString("X4") + "\"c", ch)); default: return SyntaxFactory.LiteralExpression( SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal((char)value)); } case SpecialType.System_SByte: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((sbyte)value)); case SpecialType.System_Byte: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((byte)value)); case SpecialType.System_Int16: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((short)value)); case SpecialType.System_UInt16: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((ushort)value)); case SpecialType.System_Int32: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((int)value)); case SpecialType.System_UInt32: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((uint)value)); case SpecialType.System_Int64: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((long)value)); case SpecialType.System_UInt64: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((ulong)value)); case SpecialType.System_Decimal: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((decimal)value)); case SpecialType.System_Single: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((float)value)); case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((double)value)); case SpecialType.System_String: return SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal((string)value)); default: return null; } } private SimpleAsClauseSyntax GetReturnAsClause(IMethodSymbol symbol) { if (symbol.ReturnsVoid) { return null; } return SyntaxFactory.SimpleAsClause(GetTypeSyntax(symbol.ReturnType)); } private static SyntaxToken? GetOperatorToken(IMethodSymbol symbol) { switch (symbol.Name) { // unary case "op_UnaryPlus": return SyntaxFactory.Token(SyntaxKind.PlusToken); case "op_UnaryNegation": return SyntaxFactory.Token(SyntaxKind.MinusToken); case "op_OnesComplement": return SyntaxFactory.Token(SyntaxKind.NotKeyword); case "op_True": return SyntaxFactory.Token(SyntaxKind.IsTrueKeyword); case "op_False": return SyntaxFactory.Token(SyntaxKind.IsFalseKeyword); // binary case "op_Addition": return SyntaxFactory.Token(SyntaxKind.PlusToken); case "op_Subtraction": return SyntaxFactory.Token(SyntaxKind.MinusToken); case "op_Multiply": return SyntaxFactory.Token(SyntaxKind.AsteriskToken); case "op_Division": return SyntaxFactory.Token(SyntaxKind.SlashToken); case "op_Modulus": return SyntaxFactory.Token(SyntaxKind.ModKeyword); case "op_BitwiseAnd": return SyntaxFactory.Token(SyntaxKind.AndKeyword); case "op_BitwiseOr": return SyntaxFactory.Token(SyntaxKind.OrKeyword); case "op_ExclusiveOr": return SyntaxFactory.Token(SyntaxKind.XorKeyword); case "op_RightShift": return SyntaxFactory.Token(SyntaxKind.GreaterThanGreaterThanToken); case "op_LeftShift": return SyntaxFactory.Token(SyntaxKind.LessThanLessThanToken); // comparision case "op_Equality": return SyntaxFactory.Token(SyntaxKind.EqualsToken); case "op_Inequality": return SyntaxFactory.Token(SyntaxKind.LessThanGreaterThanToken); case "op_GreaterThan": return SyntaxFactory.Token(SyntaxKind.GreaterThanToken); case "op_LessThan": return SyntaxFactory.Token(SyntaxKind.LessThanToken); case "op_GreaterThanOrEqual": return SyntaxFactory.Token(SyntaxKind.GreaterThanEqualsToken); case "op_LessThanOrEqual": return SyntaxFactory.Token(SyntaxKind.LessThanEqualsToken); // conversion case "op_Implicit": case "op_Explicit": return SyntaxFactory.Token(SyntaxKind.CTypeKeyword); // not supported: //case "op_LogicalNot": //case "op_Increment": //case "op_Decrement": //case "op_Assign": default: return null; } } private static TypeSyntax GetTypeSyntax(ITypeSymbol type) { var name = NameVisitorCreator.GetVB(NameOptions.UseAlias | NameOptions.WithGenericParameter).GetName(type); return SyntaxFactory.ParseTypeName(name); } private static SyntaxToken GetIdentifier(ITypeSymbol type) { var name = NameVisitorCreator.GetVB(NameOptions.UseAlias | NameOptions.WithGenericParameter).GetName(type); return SyntaxFactory.Identifier(name); } private static NameSyntax GetQualifiedNameSyntax(ITypeSymbol type) { var name = NameVisitorCreator.GetVB(NameOptions.UseAlias | NameOptions.WithGenericParameter).GetName(type); return SyntaxFactory.ParseName(name); } private static string RemoveEnd(string code) { return EndRegex.Replace(code, string.Empty); } private static string GetVisiblity(Accessibility accessibility) { switch (accessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrInternal: return "Protected"; case Accessibility.Public: return "Public"; default: return null; } } #endregion } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // 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 [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.Web; using System.Collections.Generic; #endregion /// <summary> /// Represents an error log capable of storing and retrieving errors /// generated in an ASP.NET Web application. /// </summary> public abstract class ErrorLog { private string _appName; private bool _appNameInitialized; private static readonly object _contextKey = new object(); /// <summary> /// Logs an error in log for the application. /// </summary> public abstract string Log(Error error); /// <summary> /// When overridden in a subclass, begins an asynchronous version /// of <see cref="Log"/>. /// </summary> public virtual IAsyncResult BeginLog(Error error, AsyncCallback asyncCallback, object asyncState) { return BeginSyncImpl(asyncCallback, asyncState, new LogHandler(Log), error); } /// <summary> /// When overridden in a subclass, ends an asynchronous version /// of <see cref="Log"/>. /// </summary> public virtual string EndLog(IAsyncResult asyncResult) { return (string) EndSyncImpl(asyncResult); } private delegate string LogHandler(Error error); /// <summary> /// Retrieves a single application error from log given its /// identifier, or null if it does not exist. /// </summary> public abstract ErrorLogEntry GetError(string id); /// <summary> /// When overridden in a subclass, begins an asynchronous version /// of <see cref="GetError"/>. /// </summary> public virtual IAsyncResult BeginGetError(string id, AsyncCallback asyncCallback, object asyncState) { return BeginSyncImpl(asyncCallback, asyncState, new GetErrorHandler(GetError), id); } /// <summary> /// When overridden in a subclass, ends an asynchronous version /// of <see cref="GetError"/>. /// </summary> public virtual ErrorLogEntry EndGetError(IAsyncResult asyncResult) { return (ErrorLogEntry) EndSyncImpl(asyncResult); } private delegate ErrorLogEntry GetErrorHandler(string id); /// <summary> /// Retrieves a page of application errors from the log in /// descending order of logged time. /// </summary> public abstract int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList); /// <summary> /// When overridden in a subclass, begins an asynchronous version /// of <see cref="GetErrors"/>. /// </summary> public virtual IAsyncResult BeginGetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList, AsyncCallback asyncCallback, object asyncState) { return BeginSyncImpl(asyncCallback, asyncState, new GetErrorsHandler(GetErrors), pageIndex, pageSize, errorEntryList); } /// <summary> /// When overridden in a subclass, ends an asynchronous version /// of <see cref="GetErrors"/>. /// </summary> public virtual int EndGetErrors(IAsyncResult asyncResult) { return (int) EndSyncImpl(asyncResult); } private delegate int GetErrorsHandler(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList); /// <summary> /// Get the name of this log. /// </summary> public virtual string Name { get { return GetType().Name; } } /// <summary> /// Gets the name of the application to which the log is scoped. /// </summary> public string ApplicationName { get { return _appName ?? string.Empty; } set { if (_appNameInitialized) throw new InvalidOperationException("The application name cannot be reset once initialized."); _appName = value; _appNameInitialized = (value ?? string.Empty).Length > 0; } } /// <summary> /// Gets the default error log implementation specified in the /// configuration file, or the in-memory log implemention if /// none is configured. /// </summary> public static ErrorLog GetDefault(HttpContext context) { return (ErrorLog) ServiceCenter.GetService(context, typeof(ErrorLog)); } internal static ErrorLog GetDefaultImpl(HttpContext context) { ErrorLog log; if (context != null) { log = (ErrorLog) context.Items[_contextKey]; if (log != null) return log; } // // Determine the default store type from the configuration and // create an instance of it. // // If no object got created (probably because the right // configuration settings are missing) then default to // the in-memory log implementation. // log = (ErrorLog) SimpleServiceProviderFactory.CreateFromConfigSection(Configuration.GroupSlash + "errorLog") ?? new MemoryErrorLog(); if (context != null) { // // Infer the application name from the context if it has not // been initialized so far. // if (log.ApplicationName.Length == 0) log.ApplicationName = InferApplicationName(context); // // Save into the context if context is there so retrieval is // quick next time. // context.Items[_contextKey] = log; } return log; } private static string InferApplicationName(HttpContext context) { Debug.Assert(context != null); // // Setup the application name (ASP.NET 2.0 or later). // string appName = null; if (context.Request != null) { // // ASP.NET 2.0 returns a different and more cryptic value // for HttpRuntime.AppDomainAppId comared to previous // versions. Also HttpRuntime.AppDomainAppId is not available // in partial trust environments. However, the APPL_MD_PATH // server variable yields the same value as // HttpRuntime.AppDomainAppId did previously so we try to // get to it over here for compatibility reasons (otherwise // folks upgrading to this version of ELMAH could find their // error log empty due to change in application name. // appName = context.Request.ServerVariables["APPL_MD_PATH"]; } if (string.IsNullOrEmpty(appName)) { // // Still no luck? Try HttpRuntime.AppDomainAppVirtualPath, // which is available even under partial trust. // appName = HttpRuntime.AppDomainAppVirtualPath; } return Mask.EmptyString(appName, "/"); } // // The following two methods are helpers that provide boilerplate // implementations for implementing asnychronous BeginXXXX and // EndXXXX methods over a default synchronous implementation. // private static IAsyncResult BeginSyncImpl(AsyncCallback asyncCallback, object asyncState, Delegate syncImpl, params object[] args) { Debug.Assert(syncImpl != null); SynchronousAsyncResult asyncResult; var syncMethodName = syncImpl.Method.Name; try { asyncResult = SynchronousAsyncResult.OnSuccess(syncMethodName, asyncState, syncImpl.DynamicInvoke(args)); } catch (Exception e) { asyncResult = SynchronousAsyncResult.OnFailure(syncMethodName, asyncState, e); } if (asyncCallback != null) asyncCallback(asyncResult); return asyncResult; } private static object EndSyncImpl(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); var syncResult = asyncResult as SynchronousAsyncResult; if (syncResult == null) throw new ArgumentException("IAsyncResult object did not come from the corresponding async method on this type.", "asyncResult"); // // IMPORTANT! The End method on SynchronousAsyncResult will // throw an exception if that's what Log did when // BeginLog called it. The unforunate side effect of this is // the stack trace information for the exception is lost and // reset to this point. There seems to be a basic failure in the // framework to accommodate for this case more generally. One // could handle this through a custom exception that wraps the // original exception, but this assumes that an invocation will // only throw an exception of that custom type. // return syncResult.End(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Text.Tests { public class EncoderConvert2Encoder : Encoder { private Encoder _encoder = null; public EncoderConvert2Encoder() { _encoder = Encoding.UTF8.GetEncoder(); } public override int GetByteCount(char[] chars, int index, int count, bool flush) { if (index >= count) throw new ArgumentException(); return _encoder.GetByteCount(chars, index, count, flush); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { return _encoder.GetBytes(chars, charIndex, charCount, bytes, byteIndex, flush); } } // Convert(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@) public class EncoderConvert2 { #region Private Fields private const int c_SIZE_OF_ARRAY = 256; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); #endregion #region Positive Test Cases // PosTest1: Call Convert to convert a arbitrary character array with ASCII encoder [Fact] public void PosTest1() { char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; Encoder encoder = Encoding.UTF8.GetEncoder(); for (int i = 0; i < chars.Length; ++i) { chars[i] = _generator.GetChar(-55); } int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed); // set flush to true and try again encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed); } // PosTest2: Call Convert to convert a arbitrary character array with Unicode encoder [Fact] public void PosTest2() { char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; Encoder encoder = Encoding.Unicode.GetEncoder(); for (int i = 0; i < chars.Length; ++i) { chars[i] = _generator.GetChar(-55); } int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed); // set flush to true and try again encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed); } // PosTest3: Call Convert to convert a ASCII character array with ASCII encoder [Fact] public void PosTest3() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, true, "003.1"); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, true, "003.2"); VerificationHelper(encoder, chars, 0, 0, bytes, 0, 0, true, 0, 0, true, "003.3"); } // PosTest4: Call Convert to convert a ASCII character array with user implemented encoder [Fact] public void PosTest4() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = new EncoderConvert2Encoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, true, "004.1"); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, true, "004.2"); } // PosTest5: Call Convert to convert partial of a ASCII character array with ASCII encoder [Fact] public void PosTest5() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, true, "005.1"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, true, "005.2"); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, true, "005.3"); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, true, "005.4"); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, true, "005.5"); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, true, "005.6"); // Verify maxBytes is large than character count VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, true, "005.7"); VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, true, "005.8"); } // PosTest6: Call Convert to convert a ASCII character array with Unicode encoder [Fact] public void PosTest6() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, true, "006.1"); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, true, "006.2"); } // PosTest7: Call Convert to convert partial of a ASCII character array with Unicode encoder [Fact] public void PosTest7() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, true, "007.1"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, true, "007.2"); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, true, "007.3"); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, true, "007.4"); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, true, "007.5"); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, true, "007.6"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, true, "007.3"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, true, "007.4"); } // PosTest8: Call Convert to convert a unicode character array with Unicode encoder [Fact] public void PosTest8() { char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, true, "008.1"); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, true, "008.2"); } // PosTest9: Call Convert to convert partial of a unicode character array with Unicode encoder [Fact] public void PosTest9() { char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, true, "009.1"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, true, "009.2"); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, true, "009.3"); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, true, "009.4"); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, true, "009.5"); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, true, "009.6"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, true, "009.3"); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, true, "009.4"); } #endregion #region Negative Test Cases // NegTest1: ArgumentNullException should be thrown when chars or bytes is a null reference [Fact] public void NegTest1() { Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper<ArgumentNullException>(encoder, null, 0, 0, new byte[1], 0, 0, true, typeof(ArgumentNullException), "101.1"); VerificationHelper<ArgumentNullException>(encoder, new char[1], 0, 0, null, 0, 0, true, typeof(ArgumentNullException), "101.2"); } // NegTest2: ArgumentOutOfRangeException should be thrown when charIndex, charCount, byteIndex, or byteCount is less than zero [Fact] public void NegTest2() { Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, -1, new byte[1], 0, 0, true, typeof(ArgumentOutOfRangeException), "102.1"); VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, 0, new byte[1], 0, -1, true, typeof(ArgumentOutOfRangeException), "102.2"); VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], -1, 0, new byte[1], 0, 0, true, typeof(ArgumentOutOfRangeException), "102.3"); VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, 0, new byte[1], -1, 0, true, typeof(ArgumentOutOfRangeException), "102.4"); } // NegTest3: ArgumentException should be thrown when The output buffer is too small to contain any of the converted input [Fact] public void NegTest3() { Encoder encoder = Encoding.Unicode.GetEncoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; for (int i = 0; i < chars.Length; ++i) { chars[i] = _generator.GetChar(-55); } byte[] bytes1 = new byte[1]; VerificationHelper<ArgumentException>(encoder, chars, 0, chars.Length, bytes1, 0, bytes1.Length, true, typeof(ArgumentException), "103.1"); } // NegTest4: ArgumentOutOfRangeException should be thrown when The length of chars - charIndex is less than charCount [Fact] public void NegTest4() { Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 1, 1, new byte[1], 0, 1, true, typeof(ArgumentOutOfRangeException), "104.1"); } // NegTest5: ArgumentOutOfRangeException should be thrown when The length of bytes - byteIndex is less than byteCount [Fact] public void NegTest5() { Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, 1, new byte[1], 1, 1, true, typeof(ArgumentOutOfRangeException), "105.1"); } #endregion private void VerificationHelper(Encoder encoder, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, int expectedCharsUsed, int expectedBytesUsed, bool expectedCompleted, string errorno) { int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, false, out charsUsed, out bytesUsed, out completed); Assert.Equal(expectedCharsUsed, charsUsed); Assert.Equal(expectedBytesUsed, bytesUsed); Assert.Equal(expectedCompleted, completed); } private void VerificationHelper<T>(Encoder encoder, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, Type desired, string errorno) where T : Exception { int charsUsed; int bytesUsed; bool completed; Assert.Throws<T>(() => { encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); }); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>CustomerLabel</c> resource.</summary> public sealed partial class CustomerLabelName : gax::IResourceName, sys::IEquatable<CustomerLabelName> { /// <summary>The possible contents of <see cref="CustomerLabelName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customerLabels/{label_id}</c>. /// </summary> CustomerLabel = 1, } private static gax::PathTemplate s_customerLabel = new gax::PathTemplate("customers/{customer_id}/customerLabels/{label_id}"); /// <summary>Creates a <see cref="CustomerLabelName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomerLabelName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerLabelName"/> with the pattern /// <c>customers/{customer_id}/customerLabels/{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerLabelName"/> constructed from the provided ids.</returns> public static CustomerLabelName FromCustomerLabel(string customerId, string labelId) => new CustomerLabelName(ResourceNameType.CustomerLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerLabelName"/> with pattern /// <c>customers/{customer_id}/customerLabels/{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerLabelName"/> with pattern /// <c>customers/{customer_id}/customerLabels/{label_id}</c>. /// </returns> public static string Format(string customerId, string labelId) => FormatCustomerLabel(customerId, labelId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerLabelName"/> with pattern /// <c>customers/{customer_id}/customerLabels/{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerLabelName"/> with pattern /// <c>customers/{customer_id}/customerLabels/{label_id}</c>. /// </returns> public static string FormatCustomerLabel(string customerId, string labelId) => s_customerLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerLabelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item> /// </list> /// </remarks> /// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerLabelName"/> if successful.</returns> public static CustomerLabelName Parse(string customerLabelName) => Parse(customerLabelName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerLabelName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomerLabelName"/> if successful.</returns> public static CustomerLabelName Parse(string customerLabelName, bool allowUnparsed) => TryParse(customerLabelName, allowUnparsed, out CustomerLabelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerLabelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item> /// </list> /// </remarks> /// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerLabelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerLabelName, out CustomerLabelName result) => TryParse(customerLabelName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerLabelName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerLabelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerLabelName, bool allowUnparsed, out CustomerLabelName result) { gax::GaxPreconditions.CheckNotNull(customerLabelName, nameof(customerLabelName)); gax::TemplatedResourceName resourceName; if (s_customerLabel.TryParseName(customerLabelName, out resourceName)) { result = FromCustomerLabel(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerLabelName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomerLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string labelId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; LabelId = labelId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerLabelName"/> class from the component parts of pattern /// <c>customers/{customer_id}/customerLabels/{label_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> public CustomerLabelName(string customerId, string labelId) : this(ResourceNameType.CustomerLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LabelId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerLabel: return s_customerLabel.Expand(CustomerId, LabelId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomerLabelName); /// <inheritdoc/> public bool Equals(CustomerLabelName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerLabelName a, CustomerLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerLabelName a, CustomerLabelName b) => !(a == b); } public partial class CustomerLabel { /// <summary> /// <see cref="CustomerLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerLabelName ResourceNameAsCustomerLabelName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerLabelName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CustomerName"/>-typed view over the <see cref="Customer"/> resource name property. /// </summary> internal CustomerName CustomerAsCustomerName { get => string.IsNullOrEmpty(Customer) ? null : CustomerName.Parse(Customer, allowUnparsed: true); set => Customer = value?.ToString() ?? ""; } /// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary> internal LabelName LabelAsLabelName { get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true); set => Label = value?.ToString() ?? ""; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Diagnostics { using System; using System.Globalization; using System.IO; using System.Net; using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; using System.Xml; sealed class MessageLogTraceRecord : TraceRecord { internal const string AddressingElementName = "Addressing"; internal const string BodyElementName = "Body"; internal const string HttpRequestMessagePropertyElementName = "HttpRequest"; internal const string HttpResponseMessagePropertyElementName = "HttpResponse"; internal const string NamespaceUri = "http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace"; internal const string NamespacePrefix = ""; internal const string MessageHeaderElementName = "Header"; internal const string MessageHeadersElementName = "MessageHeaders"; internal const string MessageLogTraceRecordElementName = "MessageLogTraceRecord"; internal const string MethodElementName = "Method"; internal const string QueryStringElementName = "QueryString"; internal const string StatusCodeElementName = "StatusCode"; internal const string StatusDescriptionElementName = "StatusDescription"; internal const string TraceTimeAttributeName = "Time"; internal const string TypeElementName = "Type"; internal const string WebHeadersElementName = "WebHeaders"; Message message; XmlReader reader; string messageString; DateTime timestamp; bool logMessageBody = true; MessageLoggingSource source; Type type; MessageLogTraceRecord(MessageLoggingSource source) { this.source = source; this.timestamp = DateTime.Now; } internal MessageLogTraceRecord(ArraySegment<byte> buffer, MessageLoggingSource source) : this(source) { this.type = null; this.messageString = System.Text.Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count); } internal MessageLogTraceRecord(string message, MessageLoggingSource source) : this(source) { this.type = null; this.messageString = message; } internal MessageLogTraceRecord(Stream stream, MessageLoggingSource source) : this(source) { this.type = null; System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); StreamReader streamReader = new StreamReader(stream); int chunkSize = 4096; char[] buffer = DiagnosticUtility.Utility.AllocateCharArray(chunkSize); int count = MessageLogger.MaxMessageSize; if (-1 == count) { count = 4096; //Can't buffer potentially unbounded stream, let's get 4K hoping it will help } while (count > 0) { int charsRead = streamReader.Read(buffer, 0, chunkSize); if (charsRead == 0) { break; } int charsToAppend = count < charsRead ? count : charsRead; stringBuilder.Append(buffer, 0, charsToAppend); count -= charsRead; } streamReader.Close(); this.messageString = stringBuilder.ToString(); } internal MessageLogTraceRecord(ref Message message, XmlReader reader, MessageLoggingSource source, bool logMessageBody) : this(source) { Fx.Assert(message != null, ""); MessageBuffer buffer = null; try { this.logMessageBody = logMessageBody; this.message = message; this.reader = reader; this.type = message.GetType(); } finally { if (buffer != null) { buffer.Close(); } } } public Message Message { get { return this.message; } } public MessageLoggingSource MessageLoggingSource { get { return this.source; } } internal override void WriteTo(XmlWriter writer) { writer.WriteStartElement(MessageLogTraceRecord.NamespacePrefix, MessageLogTraceRecord.MessageLogTraceRecordElementName, MessageLogTraceRecord.NamespaceUri); // <MessageLogTraceRecord> writer.WriteAttributeString(MessageLogTraceRecord.TraceTimeAttributeName, this.timestamp.ToString("o", CultureInfo.InvariantCulture)); writer.WriteAttributeString(DiagnosticStrings.SourceTag, this.source.ToString()); if (null != this.type) { Fx.Assert(this.message != null, ""); XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); dictionaryWriter.WriteAttributeString(MessageLogTraceRecord.TypeElementName, this.type.ToString()); #if DEBUG MessageProperties properties = this.message.Properties; dictionaryWriter.WriteStartElement("Properties"); foreach (string key in properties.Keys) { dictionaryWriter.WriteElementString(key, properties[key].ToString()); } dictionaryWriter.WriteEndElement(); // </Properties> #endif WriteAddressingProperties(dictionaryWriter); WriteHttpProperties(dictionaryWriter); if (null != this.reader) //TransportSend case: Message may miss some security data, so we use XmlReader created from serialized message { this.reader.MoveToContent(); } if (this.logMessageBody) { if (null != this.reader) { dictionaryWriter.WriteNode(this.reader, true); } else { bool hasAtLeastOneItemInsideSecurityHeaderEncrypted = false; if (this.message is SecurityVerifiedMessage) { SecurityVerifiedMessage verifiedMessage = this.message as SecurityVerifiedMessage; ReceiveSecurityHeader receivedHeader = verifiedMessage.ReceivedSecurityHeader; hasAtLeastOneItemInsideSecurityHeaderEncrypted = receivedHeader.HasAtLeastOneItemInsideSecurityHeaderEncrypted; } if (!hasAtLeastOneItemInsideSecurityHeaderEncrypted) { this.message.ToString(dictionaryWriter); } else { if (this.message.Version.Envelope != EnvelopeVersion.None) { dictionaryWriter.WriteStartElement(XD.MessageDictionary.Prefix.Value, XD.MessageDictionary.Envelope, this.message.Version.Envelope.DictionaryNamespace); WriteHeader(dictionaryWriter); this.message.WriteStartBody(writer); } this.message.BodyToString(dictionaryWriter); if (this.message.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); // </Body> dictionaryWriter.WriteEndElement(); // </Envelope> } } } } else if (this.message.Version.Envelope != EnvelopeVersion.None) //No headers for EnvelopeVersion.None { if (null != this.reader) { dictionaryWriter.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); this.reader.Read(); if (0 == String.CompareOrdinal(reader.LocalName, "Header")) { dictionaryWriter.WriteNode(this.reader, true); } dictionaryWriter.WriteEndElement(); } else { dictionaryWriter.WriteStartElement(XD.MessageDictionary.Prefix.Value, XD.MessageDictionary.Envelope, this.message.Version.Envelope.DictionaryNamespace); WriteHeader(dictionaryWriter); dictionaryWriter.WriteEndElement(); // </Envelope> } } if (null != this.reader) { this.reader.Close(); this.reader = null; } } else { writer.WriteCData(this.messageString); } writer.WriteEndElement(); // </MessageLogTraceRecord> } void WriteHeader(XmlDictionaryWriter dictionaryWriter) { dictionaryWriter.WriteStartElement(XD.MessageDictionary.Prefix.Value, XD.MessageDictionary.Header, this.message.Version.Envelope.DictionaryNamespace); MessageHeaders headers = this.message.Headers; Security.ReceiveSecurityHeader receivedHeader = null; if (this.message is SecurityVerifiedMessage) { SecurityVerifiedMessage verifiedMessage = this.message as SecurityVerifiedMessage; receivedHeader = verifiedMessage.ReceivedSecurityHeader; } for (int i = 0; i < headers.Count; ++i) { if (receivedHeader != null && receivedHeader.HasAtLeastOneItemInsideSecurityHeaderEncrypted && receivedHeader.HeaderIndex == i) { // // if this is the security header and we found at least one item // was encrypted inside the security header // receivedHeader.WriteStartHeader(dictionaryWriter, headers.MessageVersion); receivedHeader.WriteHeaderContents(dictionaryWriter, headers.MessageVersion); dictionaryWriter.WriteEndElement(); } else { headers.WriteHeader(i, dictionaryWriter); } } dictionaryWriter.WriteEndElement(); // </Headers> } void WriteAddressingProperties(XmlWriter dictionaryWriter) { Fx.Assert(this.message != null, ""); object property; if (this.message.Properties.TryGetValue(AddressingProperty.Name, out property)) { AddressingProperty addressingProperty = (AddressingProperty)property; dictionaryWriter.WriteStartElement(MessageLogTraceRecord.AddressingElementName); dictionaryWriter.WriteElementString(AddressingStrings.Action, addressingProperty.Action); if (null != addressingProperty.ReplyTo) { dictionaryWriter.WriteElementString(AddressingStrings.ReplyTo, addressingProperty.ReplyTo.ToString()); } if (null != addressingProperty.To) { dictionaryWriter.WriteElementString(AddressingStrings.To, addressingProperty.To.AbsoluteUri); } if (null != addressingProperty.MessageId) { dictionaryWriter.WriteElementString(AddressingStrings.MessageId, addressingProperty.MessageId.ToString()); } dictionaryWriter.WriteEndElement(); // Addressing message.Properties.Remove(AddressingProperty.Name); } } void WriteHttpProperties(XmlWriter dictionaryWriter) { Fx.Assert(this.message != null, ""); object property; if (this.message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out property)) { HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)property; dictionaryWriter.WriteStartElement(MessageLogTraceRecord.HttpResponseMessagePropertyElementName); dictionaryWriter.WriteElementString(MessageLogTraceRecord.StatusCodeElementName, responseProperty.StatusCode.ToString()); if (responseProperty.StatusDescription != null) { dictionaryWriter.WriteElementString(MessageLogTraceRecord.StatusDescriptionElementName, responseProperty.StatusDescription); } dictionaryWriter.WriteStartElement(MessageLogTraceRecord.WebHeadersElementName); WebHeaderCollection responseHeaders = responseProperty.Headers; for (int i = 0; i < responseHeaders.Count; i++) { string name = responseHeaders.Keys[i]; string value = responseHeaders[i]; dictionaryWriter.WriteElementString(name, value); } dictionaryWriter.WriteEndElement(); // dictionaryWriter.WriteEndElement(); // </HttpResponseMessageProperty> } if (this.message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; dictionaryWriter.WriteStartElement(MessageLogTraceRecord.HttpRequestMessagePropertyElementName); dictionaryWriter.WriteElementString(MessageLogTraceRecord.MethodElementName, requestProperty.Method); dictionaryWriter.WriteElementString(MessageLogTraceRecord.QueryStringElementName, requestProperty.QueryString); dictionaryWriter.WriteStartElement(MessageLogTraceRecord.WebHeadersElementName); WebHeaderCollection responseHeaders = requestProperty.Headers; for (int i = 0; i < responseHeaders.Count; i++) { string name = responseHeaders.Keys[i]; string value = responseHeaders[i]; dictionaryWriter.WriteElementString(name, value); } dictionaryWriter.WriteEndElement(); // dictionaryWriter.WriteEndElement(); // </HttpResponseMessageProperty> } } } }
using System; using LanguageExt; using System.Linq; using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using LanguageExt.TypeClasses; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class TaskT { // // Collections // public static async Task<Arr<B>> Traverse<A, B>(this Arr<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))).ConfigureAwait(false); return new Arr<B>(rb); } public static async Task<HashSet<B>> Traverse<A, B>(this HashSet<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))).ConfigureAwait(false); return new HashSet<B>(rb); } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<IEnumerable<B>> Traverse<A, B>(this IEnumerable<Task<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static async Task<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<Task<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { rb.Add(f(await a.ConfigureAwait(false))); } return rb; } public static Task<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<Task<A>> ma, int windowSize, Func<A, B> f) => ma.WindowMap(windowSize, f).Map(xs => (IEnumerable<B>)xs); public static Task<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<Task<A>> ma, Func<A, B> f) => ma.WindowMap(f).Map(xs => (IEnumerable<B>)xs); [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<IEnumerable<A>> Sequence<A>(this IEnumerable<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<Task<A>> ma) => TraverseSerial(ma, Prelude.identity); public static Task<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<Task<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static async Task<Lst<B>> Traverse<A, B>(this Lst<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))).ConfigureAwait(false); return new Lst<B>(rb); } public static async Task<Que<B>> Traverse<A, B>(this Que<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))).ConfigureAwait(false); return new Que<B>(rb); } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<Seq<B>> Traverse<A, B>(this Seq<Task<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static async Task<Seq<B>> TraverseSerial<A, B>(this Seq<Task<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { rb.Add(f(await a.ConfigureAwait(false))); } return Seq.FromArray<B>(rb.ToArray()); } public static Task<Seq<B>> TraverseParallel<A, B>(this Seq<Task<A>> ma, int windowSize, Func<A, B> f) => ma.WindowMap(windowSize, f).Map(toSeq); public static Task<Seq<B>> TraverseParallel<A, B>(this Seq<Task<A>> ma, Func<A, B> f) => ma.WindowMap(f).Map(toSeq); [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<Seq<A>> Sequence<A>(this Seq<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<Seq<A>> SequenceSerial<A>(this Seq<Task<A>> ma) => TraverseSerial(ma, Prelude.identity); public static Task<Seq<A>> SequenceParallel<A>(this Seq<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<Seq<A>> SequenceParallel<A>(this Seq<Task<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static async Task<Set<B>> Traverse<A, B>(this Set<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))).ConfigureAwait(false); return new Set<B>(rb); } public static async Task<Stck<B>> Traverse<A, B>(this Stck<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Reverse().Map(async a => f(await a))).ConfigureAwait(false); return new Stck<B>(rb); } // // Async types // public static async Task<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, Task<A>> ma, Func<A, B> f) { var da = await ma.Data.ConfigureAwait(false); if (da.State == EitherStatus.IsBottom) throw new BottomException(); if (da.State == EitherStatus.IsLeft) return EitherAsync<L, B>.Left(da.Left); var a = await da.Right.ConfigureAwait(false); return EitherAsync<L, B>.Right(f(a)); } public static async Task<OptionAsync<B>> Traverse<A, B>(this OptionAsync<Task<A>> ma, Func<A, B> f) { var (s, v) = await ma.Data.ConfigureAwait(false); if (!s) return OptionAsync<B>.None; var a = await v.ConfigureAwait(false); return OptionAsync<B>.Some(f(a)); } public static async Task<TryAsync<B>> Traverse<A, B>(this TryAsync<Task<A>> ma, Func<A, B> f) { var da = await ma.Try().ConfigureAwait(false); if (da.IsBottom) throw new BottomException(); if (da.IsFaulted) return TryAsyncFail<B>(da.Exception); var a = await da.Value.ConfigureAwait(false); return TryAsyncSucc(f(a)); } public static async Task<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<Task<A>> ma, Func<A, B> f) { var da = await ma.Try().ConfigureAwait(false); if (da.IsBottom) throw new BottomException(); if (da.IsNone) return TryOptionalAsync<B>(None); if (da.IsFaulted) return TryOptionAsyncFail<B>(da.Exception); var a = await da.Value.Value.ConfigureAwait(false); return TryOptionAsyncSucc(f(a)); } public static async Task<Task<B>> Traverse<A, B>(this Task<Task<A>> ma, Func<A, B> f) { var da = await ma.ConfigureAwait(false); var a = await da.ConfigureAwait(false); return TaskSucc(f(a)); } public static async Task<ValueTask<B>> Traverse<A, B>(this ValueTask<Task<A>> ma, Func<A, B> f) { var da = await ma.ConfigureAwait(false); var a = await da.ConfigureAwait(false); return ValueTaskSucc(f(a)); } public static async Task<Aff<B>> Traverse<A, B>(this Aff<Task<A>> ma, Func<A, B> f) { var da = await ma.Run().ConfigureAwait(false); if (da.IsBottom) throw new BottomException(); if (da.IsFail) return FailAff<B>(da.Error); var a = await da.Value.ConfigureAwait(false); return SuccessAff(f(a)); } // // Sync types // public static async Task<Either<L, B>> Traverse<L, A, B>(this Either<L, Task<A>> ma, Func<A, B> f) { if (ma.IsBottom) return Either<L, B>.Bottom; else if (ma.IsLeft) return Either<L, B>.Left(ma.LeftValue); return Either<L, B>.Right(f(await ma.RightValue.ConfigureAwait(false))); } public static async Task<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, Task<A>> ma, Func<A, B> f) { if (ma.IsBottom) return EitherUnsafe<L, B>.Bottom; else if (ma.IsLeft) return EitherUnsafe<L, B>.Left(ma.LeftValue); return EitherUnsafe<L, B>.Right(f(await ma.RightValue.ConfigureAwait(false))); } public static async Task<Identity<B>> Traverse<A, B>(this Identity<Task<A>> ma, Func<A, B> f) => new Identity<B>(f(await ma.Value.ConfigureAwait(false))); public static async Task<Fin<B>> Traverse<A, B>(this Fin<Task<A>> ma, Func<A, B> f) { if (ma.IsFail) return ma.Cast<B>(); return Fin<B>.Succ(f(await ma.Value.ConfigureAwait(false))); } public static async Task<Option<B>> Traverse<A, B>(this Option<Task<A>> ma, Func<A, B> f) { if (ma.IsNone) return Option<B>.None; return Option<B>.Some(f(await ma.Value.ConfigureAwait(false))); } public static async Task<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<Task<A>> ma, Func<A, B> f) { if (ma.IsNone) return OptionUnsafe<B>.None; return OptionUnsafe<B>.Some(f(await ma.Value.ConfigureAwait(false))); } public static async Task<Try<B>> Traverse<A, B>(this Try<Task<A>> ma, Func<A, B> f) { var mr = ma.Try(); if (mr.IsBottom) return Try<B>(BottomException.Default); else if (mr.IsFaulted) return Try<B>(mr.Exception); return Try<B>(f(await mr.Value.ConfigureAwait(false))); } public static async Task<TryOption<B>> Traverse<A, B>(this TryOption<Task<A>> ma, Func<A, B> f) { var mr = ma.Try(); if (mr.IsBottom) return TryOptionFail<B>(BottomException.Default); else if (mr.IsNone) return TryOption<B>(None); else if (mr.IsFaulted) return TryOption<B>(mr.Exception); return TryOption<B>(f(await mr.Value.Value.ConfigureAwait(false))); } public static async Task<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, Task<A>> ma, Func<A, B> f) { if (ma.IsFail) return Validation<Fail, B>.Fail(ma.FailValue); return Validation<Fail, B>.Success(f(await ma.SuccessValue.ConfigureAwait(false))); } public static async Task<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, Task<A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { if (ma.IsFail) return Validation<MonoidFail, Fail, B>.Fail(ma.FailValue); return Validation<MonoidFail, Fail, B>.Success(f(await ma.SuccessValue.ConfigureAwait(false))); } public static async Task<Eff<B>> Traverse<A, B>(this Eff<Task<A>> ma, Func<A, B> f) { var mr = ma.Run(); if (mr.IsBottom) return FailEff<B>(BottomException.Default); else if (mr.IsFail) return FailEff<B>(mr.Error); return SuccessEff<B>(f(await mr.Value.ConfigureAwait(false))); } } }
/* * Copyright 2011 Google 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.Diagnostics; using System.IO; using BitCoinSharp.IO; namespace BitCoinSharp { /// <summary> /// A transfer of coins from one address to another creates a transaction in which the outputs /// can be claimed by the recipient in the input of another transaction. You can imagine a /// transaction as being a module which is wired up to others, the inputs of one have to be wired /// to the outputs of another. The exceptions are coinbase transactions, which create new coins. /// </summary> [Serializable] public class TransactionInput : Message { public static readonly byte[] EmptyArray = new byte[0]; // Allows for altering transactions after they were broadcast. Tx replacement is currently disabled in the C++ // client so this is always the UINT_MAX. // TODO: Document this in more detail and build features that use it. private uint _sequence; // Data needed to connect to the output of the transaction we're gathering coins from. internal TransactionOutPoint Outpoint { get; private set; } // The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there // is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we // don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter. internal byte[] ScriptBytes { get; set; } // The Script object obtained from parsing scriptBytes. Only filled in on demand and if the transaction is not // coinbase. [NonSerialized] private Script _scriptSig; // A pointer to the transaction that owns this input. internal Transaction ParentTransaction { get; private set; } /// <summary> /// Used only in creation of the genesis block. /// </summary> internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] scriptBytes) : base(@params) { ScriptBytes = scriptBytes; Outpoint = new TransactionOutPoint(@params, -1, null); _sequence = uint.MaxValue; ParentTransaction = parentTransaction; } /// <summary> /// Creates an UNSIGNED input that links to the given output /// </summary> internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, TransactionOutput output) : base(@params) { var outputIndex = output.Index; Outpoint = new TransactionOutPoint(@params, outputIndex, output.ParentTransaction); ScriptBytes = EmptyArray; _sequence = uint.MaxValue; ParentTransaction = parentTransaction; } /// <summary> /// Deserializes an input message. This is usually part of a transaction message. /// </summary> /// <exception cref="ProtocolException"/> public TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] payload, int offset) : base(@params, payload, offset) { ParentTransaction = parentTransaction; } /// <exception cref="ProtocolException"/> protected override void Parse() { Outpoint = new TransactionOutPoint(Params, Bytes, Cursor); Cursor += Outpoint.MessageSize; var scriptLen = (int) ReadVarInt(); ScriptBytes = ReadBytes(scriptLen); _sequence = ReadUint32(); } /// <exception cref="IOException"/> public override void BitcoinSerializeToStream(Stream stream) { Outpoint.BitcoinSerializeToStream(stream); stream.Write(new VarInt((ulong) ScriptBytes.Length).Encode()); stream.Write(ScriptBytes); Utils.Uint32ToByteStreamLe(_sequence, stream); } /// <summary> /// Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true. /// </summary> public bool IsCoinBase { get { return Outpoint.Hash.Equals(Sha256Hash.ZeroHash); } } /// <summary> /// Returns the input script. /// </summary> /// <exception cref="ScriptException"/> public Script ScriptSig { get { // Transactions that generate new coins don't actually have a script. Instead this // parameter is overloaded to be something totally different. if (_scriptSig == null) { Debug.Assert(ScriptBytes != null); _scriptSig = new Script(Params, ScriptBytes, 0, ScriptBytes.Length); } return _scriptSig; } } /// <summary> /// Convenience method that returns the from address of this input by parsing the scriptSig. /// </summary> /// <exception cref="ScriptException">If the scriptSig could not be understood (eg, if this is a coinbase transaction).</exception> public Address FromAddress { get { Debug.Assert(!IsCoinBase); return ScriptSig.FromAddress; } } /// <summary> /// Returns a human readable debug string. /// </summary> public override string ToString() { if (IsCoinBase) { return "TxIn: COINBASE"; } return "TxIn from tx " + Outpoint + " (pubkey: " + Utils.BytesToHexString(ScriptSig.PubKey) + ") script:" + ScriptSig; } internal enum ConnectionResult { NoSuchTx, AlreadySpent, Success } // TODO: Clean all this up once TransactionOutPoint disappears. /// <summary> /// Locates the referenced output from the given pool of transactions. /// </summary> /// <returns>The TransactionOutput or null if the transactions map doesn't contain the referenced tx.</returns> internal TransactionOutput GetConnectedOutput(IDictionary<Sha256Hash, Transaction> transactions) { Transaction tx; if (!transactions.TryGetValue(Outpoint.Hash, out tx)) return null; var @out = tx.Outputs[Outpoint.Index]; return @out; } /// <summary> /// Connects this input to the relevant output of the referenced transaction if it's in the given map. /// Connecting means updating the internal pointers and spent flags. /// </summary> /// <param name="transactions">Map of txhash-&gt;transaction.</param> /// <param name="disconnect">Whether to abort if there's a pre-existing connection or not.</param> /// <returns>True if connection took place, false if the referenced transaction was not in the list.</returns> internal ConnectionResult Connect(IDictionary<Sha256Hash, Transaction> transactions, bool disconnect) { Transaction tx; if (!transactions.TryGetValue(Outpoint.Hash, out tx)) return ConnectionResult.NoSuchTx; var @out = tx.Outputs[Outpoint.Index]; if (!@out.IsAvailableForSpending) { if (disconnect) @out.MarkAsUnspent(); else return ConnectionResult.AlreadySpent; } Outpoint.FromTx = tx; @out.MarkAsSpent(this); return ConnectionResult.Success; } /// <summary> /// Release the connected output, making it spendable once again. /// </summary> /// <returns>True if the disconnection took place, false if it was not connected.</returns> internal bool Disconnect() { if (Outpoint.FromTx == null) return false; Outpoint.FromTx.Outputs[Outpoint.Index].MarkAsUnspent(); Outpoint.FromTx = null; return true; } } }
using System; using Microsoft.SPOT; /* * Copyright 2011-2014 Stefan Thoolen (http://www.netmftoolbox.com/) * * 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. */ namespace Toolbox.NETMF.NET { /// <summary> /// Simple HTTP Client /// </summary> public class HTTP_Client { /// <summary> /// HTTP Response container /// </summary> public class HTTP_Response { // Local header storage container private string[] _Headers = { }; // HTTP Response container private string _ResponseBody = ""; // Response code private int _ResponseCode = 0; /// <summary>Returns all response headers</summary> public string[] GetAllHeaders() { return this._Headers; } /// <summary>Returns the response body</summary> public string ResponseBody { get { return this._ResponseBody; } } /// <summary>Returns the response </summary> public int ResponseCode { get { return this._ResponseCode; } } /// <summary>Returns the webserver's response body</summary> /// <returns>The webserver's response body</returns> public override string ToString() { return this._ResponseBody; } /// <summary> /// Reads out a specific header /// </summary> /// <param name="Header">The name of the header</param> /// <returns>The value of the header</returns> public string ResponseHeader(string Header) { Header = Header.ToLower() + ":"; for (int Counter = 0; Counter < this._Headers.Length; ++Counter) if (this._Headers[Counter].Substring(0, Header.Length).ToLower() == Header) return this._Headers[Counter].Substring(Header.Length + 1); return ""; } /// <summary> /// Creates a new HTTP Response object based on some response data from the webserver /// </summary> /// <param name="ResponseData">The response data from the webserver</param> public HTTP_Response(string ResponseData) { // First, find the point that breaks between headers and content int BreakPoint = ResponseData.IndexOf("\r\n\r\n"); if (BreakPoint > -1) { // Lets set the response apart this._ResponseBody = ResponseData.Substring(BreakPoint + 4); } else { BreakPoint = ResponseData.IndexOf("\n\n"); if (BreakPoint > -1) this._ResponseBody = ResponseData.Substring(BreakPoint + 2); else BreakPoint = this._ResponseBody.Length; } // The headers remain this._Headers = ResponseData.Substring(0, BreakPoint).Split('\n'); // Trims all headers for (int Counter = 0; Counter < this._Headers.Length; ++Counter) this._Headers[Counter] = this._Headers[Counter].Trim(); // The first header also contains the ResponseCode if (this._Headers.Length > 0) { string[] Parts = this._Headers[0].Split(" ".ToCharArray()); if (Parts.Length > 1) this._ResponseCode = int.Parse(Parts[1]); } } } /// <summary>Reference to the socket</summary> private SimpleSocket _Socket; /// <summary>Contains all cookies</summary> private string[] _Cookies = new string[0]; /// <summary>When using HTTP Authentication, the username is stored here</summary> private string _Username = ""; /// <summary>When using HTTP Authentication, the password is stored here</summary> private string _Password = ""; /// <summary>Returns the hostname of the webserver</summary> public string Hostname { get { return this._Socket.Hostname; } } /// <summary>Returns the port the webserver should listen to</summary> public ushort Port { get { return this._Socket.Port; } } /// <summary>The referrer for the next HTTP request (will automaticly be filled when a page is requested)</summary> public string Referrer { get; set; } /// <summary>The user agent header we send with the HTTP request</summary> public string UserAgent { get; set; } /// <summary>The Accept-header we send with the HTTP request</summary> public string Accept { get; set; } /// <summary>The Accept Language-header we send with the HTTP request</summary> public string AcceptLanguage { get; set; } /// <summary> /// Initializes a web session /// </summary> /// <param name="Socket">The socket to use (default TCP port for HTTP is 80)</param> public HTTP_Client(SimpleSocket Socket) { this._Socket = Socket; this.Accept = "*/*"; this.AcceptLanguage = "en"; // What kind of device do we run on? string[] SocketProvider = Socket.ToString().Split(new char[] { '.' }); string[] Client = this.ToString().Split(new char[] { '.' }); // User Agent this.UserAgent = "NETMFToolbox/0.1 (textmode; " + Tools.HardwareProvider + "; " + SocketProvider[SocketProvider.Length - 1] + "; " + Client[Client.Length - 1] + ")"; // No referrer yet this.Referrer = ""; } /// <summary> /// When a Username is specified, HTTP Authentication will be used /// </summary> /// <param name="Username">The username</param> /// <param name="Password">The password</param> public void Authenticate(string Username, string Password) { this._Username = Username; this._Password = Password; } /// <summary> /// Saves cookie data to the memory /// </summary> /// <param name="Key">The cookie name</param> /// <param name="Value">The cookie value (Needs to be URL Encoded!)</param> public void SetCookie(string Key, string Value) { // Array that fits all current cookies plus one string[] NewCookie = new string[this._Cookies.Length + 1]; // Checks if the cookie already exists for (int Counter = 0; Counter < this._Cookies.Length; ++Counter) { if (this._Cookies[Counter].Substring(0, Key.Length + 1) == Key + "=") { // Replaces an existing cookie this._Cookies[Counter] = Key + "=" + Value; return; } NewCookie[Counter] = this._Cookies[Counter]; } // Appairently it's a new cookie, yum! NewCookie[NewCookie.Length - 1] = Key + "=" + Value; this._Cookies = NewCookie; } /// <summary> /// Executes a GET request and returns the HTTP response /// </summary> /// <param name="Url">Path to request</param> /// <param name="Arguments">Request arguments</param> /// <returns>HTTP response</returns> public HTTP_Response Get(string Url, string Arguments = "") { // Compiles the GET request string RequestData = "GET " + Url; if (Arguments != "") RequestData += "?" + Arguments; RequestData += " HTTP/1.1\r\n"; RequestData += "Accept: " + this.Accept + "\r\n"; RequestData += "Accept-Language: " + this.AcceptLanguage + "\r\n"; if (this.Referrer != "") RequestData += "Referer: " + this.Referrer + "\r\n"; // Funny thing, the Referer-typo: http://en.wikipedia.org/wiki/HTTP_referrer#Origin_of_the_term_referer RequestData += "User-Agent: " + this.UserAgent + "\r\n"; RequestData += "Host: " + this.Hostname + "\r\n"; for (int Counter = 0; Counter < this._Cookies.Length; ++Counter) RequestData += "Cookie: " + this._Cookies[Counter] + "\r\n"; if (this._Username != "") RequestData += "Authorization: Basic " + Tools.Base64Encode(this._Username + ":" + this._Password) + "\r\n"; RequestData += "Connection: Close\r\n"; RequestData += "\r\n"; // Sets the referrer for the next request this.Referrer = "http://" + this.Hostname + (this.Port == 80 ? "" : ":" + this.Port.ToString()) + Url + (Arguments == "" ? "" : "?" + Arguments); return this._DoRequest(RequestData); } /// <summary> /// Executes a POST request and returns the HTTP response /// </summary> /// <param name="Url">Path to request</param> /// <param name="Arguments">Request arguments</param> /// <returns>HTTP response</returns> public HTTP_Response Post(string Url, string Arguments = "") { // Compiles the POST request string RequestData = "POST " + Url + " HTTP/1.1\r\n"; RequestData += "Accept: " + this.Accept + "\r\n"; RequestData += "Accept-Language: " + this.AcceptLanguage + "\r\n"; if (this.Referrer != "") RequestData += "Referer: " + this.Referrer + "\r\n"; // Funny thing, the Referer-typo: http://en.wikipedia.org/wiki/HTTP_referrer#Origin_of_the_term_referer RequestData += "User-Agent: " + this.UserAgent + "\r\n"; RequestData += "Host: " + this.Hostname + "\r\n"; for (int Counter = 0; Counter < this._Cookies.Length; ++Counter) RequestData += "Cookie: " + this._Cookies[Counter] + "\r\n"; if (this._Username != "") RequestData += "Authorization: Basic " + Tools.Base64Encode(this._Username + ":" + this._Password) + "\r\n"; RequestData += "Content-Type: application/x-www-form-urlencoded\r\n"; RequestData += "Content-Length: " + Arguments.Length.ToString() + "\r\n"; RequestData += "Connection: Close\r\n"; RequestData += "\r\n"; RequestData += Arguments + "\r\n"; RequestData += "\r\n"; // Sets the referrer for the next request this.Referrer = "http://" + this.Hostname + (this.Port == 80 ? "" : ":" + this.Port.ToString()) + Url + (Arguments == "" ? "" : "?" + Arguments); return this._DoRequest(RequestData); } /// <summary> /// Actually executes a request /// </summary> /// <param name="RequestData">The Request Data</param> /// <returns>The HTTP Response</returns> private HTTP_Response _DoRequest(string RequestData) { // Opens the connection this._Socket.Connect(); // Sends out the request this._Socket.Send(RequestData); // Fetches the returned data string ResponseData = ""; while (this._Socket.IsConnected || this._Socket.BytesAvailable > 0) ResponseData += this._Socket.Receive(); // Closes the connection this._Socket.Close(); // Parses the response data HTTP_Response RetVal = new HTTP_Response(ResponseData); // Parses cookies and such this._ParseHeaders(RetVal.GetAllHeaders()); return RetVal; } /// <summary> /// Parses the headers from a response and processes all cookies /// </summary> /// <param name="HTTP_Headers">The response headers</param> private void _ParseHeaders(string[] HTTP_Headers) { // Lets read out all cookies for (int Counter = 0; Counter < HTTP_Headers.Length; ++Counter) { if (HTTP_Headers[Counter].ToLower().IndexOf("set-cookie:") == 0) { string CookieData = HTTP_Headers[Counter].Substring(11).Trim(); int ValuePos = CookieData.LastIndexOf(';'); if (ValuePos < 0) ValuePos = CookieData.Length; string Key = CookieData.Substring(0, CookieData.IndexOf('=')); string Value = CookieData.Substring(Key.Length + 1, ValuePos - Key.Length - 1); this.SetCookie(Key, Value); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Runtime.InteropServices; using System.Security; using Xunit; namespace System.Tests { public class SetEnvironmentVariable { private const int MAX_VAR_LENGTH_ALLOWED = 32767; private const string NullString = "\u0000"; private static bool IsSupportedTarget(EnvironmentVariableTarget target) { return target == EnvironmentVariableTarget.Process || RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } [Fact] public void NullVariableThrowsArgumentNull() { Assert.Throws<ArgumentNullException>(() => Environment.SetEnvironmentVariable(null, "test")); } [Fact] public void IncorrectVariableThrowsArgument() { Assert.Throws<ArgumentException>(() => Environment.SetEnvironmentVariable(string.Empty, "test")); Assert.Throws<ArgumentException>(() => Environment.SetEnvironmentVariable(NullString, "test")); Assert.Throws<ArgumentException>(() => Environment.SetEnvironmentVariable("Variable=Something", "test")); string varWithLenLongerThanAllowed = new string('c', MAX_VAR_LENGTH_ALLOWED + 1); Assert.Throws<ArgumentException>(() => Environment.SetEnvironmentVariable(varWithLenLongerThanAllowed, "test")); } private static void ExecuteAgainstTarget( EnvironmentVariableTarget target, Action action, Action cleanUp = null) { bool shouldCleanUp = cleanUp != null; try { action(); } catch (SecurityException) { shouldCleanUp = false; Assert.True(target == EnvironmentVariableTarget.Machine, "only machine target should have access issues"); Assert.True(PlatformDetection.IsWindows, "and it should be Windows"); Assert.False(PlatformDetection.IsWindowsAndElevated, "and we shouldn't be elevated"); } finally { if (shouldCleanUp) cleanUp(); } } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void Default(EnvironmentVariableTarget target) { const string varName = "Test_SetEnvironmentVariable_Default"; const string value = "true"; ExecuteAgainstTarget(target, () => { Environment.SetEnvironmentVariable(varName, value, target); Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target)); }, () => { // Clear the test variable Environment.SetEnvironmentVariable(varName, null, target); }); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void ModifyEnvironmentVariable(EnvironmentVariableTarget target) { const string varName = "Test_ModifyEnvironmentVariable"; const string value = "false"; ExecuteAgainstTarget(target, () => { // First set the value to something and then change it and ensure that it gets modified. Environment.SetEnvironmentVariable(varName, "true", target); Environment.SetEnvironmentVariable(varName, value, target); // Check whether the variable exists. Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target)); }, () => { // Clear the test variable Environment.SetEnvironmentVariable(varName, null); }); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void ModifyEnvironmentVariable_AndEnumerate(EnvironmentVariableTarget target) { const string varName = "Test_ModifyEnvironmentVariable_AndEnumerate"; const string value = "false"; ExecuteAgainstTarget(target, () => { // First set the value to something and then change it and ensure that it gets modified. Environment.SetEnvironmentVariable(varName, "true", target); // Enumerate to validate our first value to ensure we can still set after enumerating IDictionary variables = Environment.GetEnvironmentVariables(target); if (IsSupportedTarget(target)) { Assert.True(variables.Contains(varName), "has the key we entered"); Assert.Equal("true", variables[varName]); } Environment.SetEnvironmentVariable(varName, value, target); // Check whether the variable exists. Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target)); }, () => { // Clear the test variable Environment.SetEnvironmentVariable(varName, null); }); } [Theory] [InlineData(EnvironmentVariableTarget.Process)] [InlineData(EnvironmentVariableTarget.Machine)] [InlineData(EnvironmentVariableTarget.User)] public void DeleteEnvironmentVariable(EnvironmentVariableTarget target) { const string varName = "Test_DeleteEnvironmentVariable"; const string value = "false"; ExecuteAgainstTarget(target, () => { // First set the value to something and then ensure that it can be deleted. Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, string.Empty); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, null); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, NullString); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); }); } [Fact] public void DeleteEnvironmentVariableNonInitialNullInName() { const string varNamePrefix = "Begin_DeleteEnvironmentVariableNonInitialNullInName"; const string varNameSuffix = "End_DeleteEnvironmentVariableNonInitialNullInName"; const string varName = varNamePrefix + NullString + varNameSuffix; const string value = "false"; try { Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, null); Assert.Equal(Environment.GetEnvironmentVariable(varName), null); Assert.Equal(Environment.GetEnvironmentVariable(varNamePrefix), null); } finally { // Clear the test variable Environment.SetEnvironmentVariable(varName, null); } } [Fact] public void DeleteEnvironmentVariableInitialNullInValue() { const string value = NullString + "test"; const string varName = "DeleteEnvironmentVariableInitialNullInValue"; try { Environment.SetEnvironmentVariable(varName, value); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); } finally { Environment.SetEnvironmentVariable(varName, String.Empty); } } [Fact] public void NonInitialNullCharacterInVariableName() { const string varNamePrefix = "NonInitialNullCharacterInVariableName_Begin"; const string varNameSuffix = "NonInitialNullCharacterInVariableName_End"; const string varName = varNamePrefix + NullString + varNameSuffix; const string value = "true"; try { Environment.SetEnvironmentVariable(varName, value); Assert.Equal(value, Environment.GetEnvironmentVariable(varName)); Assert.Equal(value, Environment.GetEnvironmentVariable(varNamePrefix)); } finally { Environment.SetEnvironmentVariable(varName, String.Empty); Environment.SetEnvironmentVariable(varNamePrefix, String.Empty); } } [Fact] public void NonInitialNullCharacterInValue() { const string varName = "Test_TestNonInitialZeroCharacterInValue"; const string valuePrefix = "Begin"; const string valueSuffix = "End"; const string value = valuePrefix + NullString + valueSuffix; try { Environment.SetEnvironmentVariable(varName, value); Assert.Equal(valuePrefix, Environment.GetEnvironmentVariable(varName)); } finally { Environment.SetEnvironmentVariable(varName, String.Empty); } } [Fact] public void DeleteNonExistentEnvironmentVariable() { const string varName = "Test_TestDeletingNonExistingEnvironmentVariable"; if (Environment.GetEnvironmentVariable(varName) != null) { Environment.SetEnvironmentVariable(varName, null); } Environment.SetEnvironmentVariable("TestDeletingNonExistingEnvironmentVariable", String.Empty); } } }