context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* 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 RequestVoteDecoder { public const ushort BLOCK_LENGTH = 28; public const ushort TEMPLATE_ID = 51; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private RequestVoteDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public RequestVoteDecoder() { _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 RequestVoteDecoder 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 LogLeadershipTermIdId() { return 1; } public static int LogLeadershipTermIdSinceVersion() { return 0; } public static int LogLeadershipTermIdEncodingOffset() { return 0; } public static int LogLeadershipTermIdEncodingLength() { return 8; } public static string LogLeadershipTermIdMetaAttribute(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 LogLeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LogLeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LogLeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LogLeadershipTermId() { 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 CandidateTermIdId() { return 3; } public static int CandidateTermIdSinceVersion() { return 0; } public static int CandidateTermIdEncodingOffset() { return 16; } public static int CandidateTermIdEncodingLength() { return 8; } public static string CandidateTermIdMetaAttribute(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 CandidateTermIdNullValue() { return -9223372036854775808L; } public static long CandidateTermIdMinValue() { return -9223372036854775807L; } public static long CandidateTermIdMaxValue() { return 9223372036854775807L; } public long CandidateTermId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int CandidateMemberIdId() { return 4; } public static int CandidateMemberIdSinceVersion() { return 0; } public static int CandidateMemberIdEncodingOffset() { return 24; } public static int CandidateMemberIdEncodingLength() { return 4; } public static string CandidateMemberIdMetaAttribute(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 CandidateMemberIdNullValue() { return -2147483648; } public static int CandidateMemberIdMinValue() { return -2147483647; } public static int CandidateMemberIdMaxValue() { return 2147483647; } public int CandidateMemberId() { return _buffer.GetInt(_offset + 24, 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("[RequestVote](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='logLeadershipTermId', 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("LogLeadershipTermId="); builder.Append(LogLeadershipTermId()); 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='candidateTermId', 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='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, 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("CandidateTermId="); builder.Append(CandidateTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='candidateMemberId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, 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=24, 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("CandidateMemberId="); builder.Append(CandidateMemberId()); Limit(originalLimit); return builder; } } }
/*-----------------------------+-------------------------------\ | | | !!!NOTICE!!! | | | | These libraries are under heavy development so they are | | subject to make many changes as development continues. | | For this reason, the libraries may not be well commented. | | THANK YOU for supporting forge with all your feedback | | suggestions, bug reports and comments! | | | | - The Forge Team | | Bearded Man Studios, Inc. | | | | This source code, project files, and associated files are | | copyrighted by Bearded Man Studios, Inc. (2012-2017) and | | may not be redistributed without written permission. | | | \------------------------------+------------------------------*/ using BeardedManStudios.Forge.Networking.Frame; using BeardedManStudios.Threading; using System.Collections.Generic; using System.Linq; using System.Net; #if WINDOWS_UWP using Windows.Networking.Sockets; #else using System.Net.Sockets; #endif namespace BeardedManStudios.Forge.Networking { [System.Serializable] public class NetworkingPlayer { private const uint PLAYER_TIMEOUT_DISCONNECT = 90000; private const int DEFAULT_PING_INTERVAL = 5000; /// <summary> /// An event that is called whenever this player has disconnected /// </summary> public event NetWorker.BaseNetworkEvent disconnected; /// <summary> /// The socket to the Networking player /// </summary> public object SocketEndpoint { get; private set; } /// <summary> /// A reference to the raw tcp listener for this player (only used on server) /// </summary> #if WINDOWS_UWP public StreamSocketListener TcpListenerHandle { get; private set; } #else public TcpListener TcpListenerHandle { get; private set; } #endif /// <summary> /// A reference to the raw tcp client for this player /// </summary> #if WINDOWS_UWP public StreamSocket TcpClientHandle { get; private set; } #else public TcpClient TcpClientHandle { get; private set; } #endif /// <summary> /// A reference to the IPEndPoint for this player /// </summary> public IPEndPoint IPEndPointHandle { get; private set; } /// <summary> /// The NetworkID the NetworkingPlayer is /// </summary> public uint NetworkId { get; private set; } /// <summary> /// IP address of the NetworkingPlayer /// </summary> public string Ip { get; private set; } /// <summary> /// Port number of this NetworkingPlayer /// </summary> public ushort Port { get; private set; } /// <summary> /// Name of the NetworkingPlayer /// </summary> public string Name { get; set; } /// <summary> /// Determines if the player has been accepted for the connection by the server /// </summary> public bool Accepted { get; set; } /// <summary> /// Determines if the player has been sent an accept request but the server /// is still waiting on a confirmation of the acceptance /// </summary> public bool PendingAccpeted { get; set; } /// <summary> /// Determines if the player is currently connected /// </summary> public bool Connected { get; set; } /// <summary> /// Is set once a disconnection happens /// </summary> public bool Disconnected { get; private set; } /// <summary> /// This is the message group that this particular player is a part of /// </summary> public ushort MessageGroup { get; private set; } /// <summary> /// Last ping sent to the NetworkingPlayer /// </summary> public ulong LastPing { get; private set; } /// <summary> /// Whether this player is the one hosting /// </summary> public bool IsHost { get; private set; } /// <summary> /// Whether we are locked /// </summary> public object MutexLock = new object(); /// <summary> /// Keep a list of all of the composers that are reliable so that they are sent in order /// </summary> private List<UDPPacketComposer> reliableComposers = new List<UDPPacketComposer>(); /// <summary> /// Should be used for matching this networking player with another networking player reference /// on a different networker. /// </summary> public string InstanceGuid { get; set; } /// <summary> /// The amount of time in seconds to disconnect this player if no messages are sent /// </summary> public uint TimeoutMilliseconds { get; set; } private bool composerReady = false; private int currentPingWait = 0; public int PingInterval { get; set; } /// <summary> /// The amount of time it took for a ping to happen /// </summary> public int RoundTripLatency { get; set; } public NetWorker Networker { get; private set; } /// <summary> /// This is used for proximity based updates, this should update with /// the player location to properly be used with the NetWorker::ProximityDistance /// </summary> public Vector ProximityLocation { get; set; } private ulong currentReliableId = 0; public Dictionary<ulong, FrameStream> reliablePending = new Dictionary<ulong, FrameStream>(); public ulong UniqueReliableMessageIdCounter { get; private set; } private Queue<ulong> reliableComposersToRemove = new Queue<ulong>(); /// <summary> /// Constructor for the NetworkingPlayer /// </summary> /// <param name="networkId">NetworkId set for the NetworkingPlayer</param> /// <param name="ip">IP address of the NetworkingPlayer</param> /// <param name="socketEndpoint">The socket to the Networking player</param> /// <param name="name">Name of the NetworkingPlayer</param> public NetworkingPlayer(uint networkId, string ip, bool isHost, object socketEndpoint, NetWorker networker) { Networker = networker; NetworkId = networkId; Ip = ip.Split('+')[0]; IsHost = isHost; SocketEndpoint = socketEndpoint; LastPing = networker.Time.Timestep; TimeoutMilliseconds = PLAYER_TIMEOUT_DISCONNECT; PingInterval = DEFAULT_PING_INTERVAL; if (SocketEndpoint != null) { #if WINDOWS_UWP // Check to see if the supplied socket endpoint is TCP, if so // assign it to the TcpClientHandle for ease of access if (socketEndpoint is StreamSocket) { TcpClientHandle = (StreamSocket)socketEndpoint; IPEndPointHandle = (IPEndPoint)TcpClientHandle.Client.RemoteEndPoint; } else if (socketEndpoint is StreamSocketListener) { TcpListenerHandle = (StreamSocketListener)socketEndpoint; IPEndPointHandle = (IPEndPoint)TcpListenerHandle.LocalEndpoint; } else if (SocketEndpoint is IPEndPoint) IPEndPointHandle = (IPEndPoint)SocketEndpoint; #else // Check to see if the supplied socket endpoint is TCP, if so // assign it to the TcpClientHandle for ease of access if (socketEndpoint is TcpClient) { TcpClientHandle = (TcpClient)socketEndpoint; IPEndPointHandle = (IPEndPoint)TcpClientHandle.Client.RemoteEndPoint; } else if (socketEndpoint is TcpListener) { TcpListenerHandle = (TcpListener)socketEndpoint; IPEndPointHandle = (IPEndPoint)TcpListenerHandle.LocalEndpoint; } else if (SocketEndpoint is IPEndPoint) IPEndPointHandle = (IPEndPoint)SocketEndpoint; #endif Port = (ushort)IPEndPointHandle.Port; } } public void AssignPort(ushort port) { // Only allow to be assigned once if (Port != 0) return; Port = port; } /// <summary> /// Ping the NetworkingPlayer /// </summary> public void Ping() { LastPing = Networker.Time.Timestep; } /// <summary> /// Called by the server to check and see if this player has timed out /// </summary> /// <returns>True if the player has timed out</returns> public bool TimedOut() { return LastPing + TimeoutMilliseconds <= Networker.Time.Timestep; } /// <summary> /// Assigns the message group for this player /// </summary> /// <param name="messageGroup">The numerical identifier of the message group</param> public void SetMessageGroup(ushort messageGroup) { MessageGroup = messageGroup; } public void OnDisconnect() { Disconnected = true; Connected = false; StopComposers(); if (disconnected != null) disconnected(); } public void QueueComposer(UDPPacketComposer composer) { if (Disconnected) return; lock (reliableComposers) { reliableComposers.Add(composer); } // Start the reliable send thread on this composer NextComposerInQueue(); } /// <summary> /// Star the next composer available composer /// </summary> private void NextComposerInQueue() { // If there are not currently any queued composers then we can stop here if (reliableComposers.Count == 0) return; if (!composerReady && Networker.IsBound && !NetWorker.EndingSession) { composerReady = true; // Run this on a separate thread so that it doesn't interfere with the reading thread Task.Queue(() => { int waitTime = 10, composerCount = 0; while (Networker.IsBound && !Disconnected) { lock (reliableComposers) { composerCount = reliableComposers.Count; } if (composerCount == 0) { Task.Sleep(waitTime); currentPingWait += waitTime; if (!(Networker is IServer) && currentPingWait >= PingInterval) { currentPingWait = 0; Networker.Ping(); } continue; } do { // If there are too many packets to send, be sure to only send // a few to not clog the network. int counter = UDPPacketComposer.PACKET_SIZE; // Send all the packets that are pending lock (reliableComposers) { for (int i = 0; i < reliableComposers.Count; i++) reliableComposers[i].ResendPackets(Networker.Time.Timestep, ref counter); } Task.Sleep(10); // Check if we have some composers queued to remove lock (reliableComposersToRemove) { while (reliableComposersToRemove.Count > 0) { // Remove lock (reliableComposers) { ulong id = reliableComposersToRemove.Dequeue(); reliableComposers.Remove(reliableComposers.First(r => r.Frame.UniqueId == id)); } } } lock (reliableComposers) { composerCount = reliableComposers.Count; } } while (composerCount > 0 && Networker.IsBound && !NetWorker.EndingSession); currentPingWait = 0; } }); } } /// <summary> /// Cleans up the current composer and prepares to start up the next in the queue /// </summary> public void CleanupComposer(ulong uniqueId) { lock (reliableComposers) { reliableComposers.Remove(reliableComposers.First(r => r.Frame.UniqueId == uniqueId)); } } /// <summary> /// Add composer to the queue, so it will be removed by sending thread /// </summary> public void EnqueueComposerToRemove(ulong uniqueId) { lock (reliableComposersToRemove) { reliableComposersToRemove.Enqueue(uniqueId); } } /// <summary> /// Go through and stop all of the reliable composers for this player to prevent /// them from being sent /// </summary> public void StopComposers() { lock (reliableComposers) { reliableComposers.Clear(); } } public void WaitReliable(FrameStream frame) { if (!frame.IsReliable) return; if (frame.UniqueReliableId == currentReliableId) { Networker.FireRead(frame, this); currentReliableId++; FrameStream next = null; while (true) { if (!reliablePending.TryGetValue(currentReliableId, out next)) break; reliablePending.Remove(currentReliableId++); Networker.FireRead(next, this); } } else if (frame.UniqueReliableId > currentReliableId) reliablePending.Add(frame.UniqueReliableId, frame); } public ulong GetNextReliableId() { return UniqueReliableMessageIdCounter++; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedContextsClientTest { [xunit::FactAttribute] public void GetContextRequestObject() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.GetContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.GetContext(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetContextRequestObjectAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.GetContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.GetContextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.GetContextAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetContext() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.GetContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.GetContext(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetContextAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.GetContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.GetContextAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.GetContextAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetContextResourceNames() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.GetContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.GetContext(request.ContextName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetContextResourceNamesAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); GetContextRequest request = new GetContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.GetContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.GetContextAsync(request.ContextName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.GetContextAsync(request.ContextName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateContextRequestObject() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.CreateContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.CreateContext(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateContextRequestObjectAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.CreateContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.CreateContextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.CreateContextAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateContext() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.CreateContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.CreateContext(request.Parent, request.Context); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateContextAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.CreateContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.CreateContextAsync(request.Parent, request.Context, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.CreateContextAsync(request.Parent, request.Context, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateContextResourceNames() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.CreateContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.CreateContext(request.ParentAsSessionName, request.Context); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateContextResourceNamesAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), Context = new Context(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.CreateContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.CreateContextAsync(request.ParentAsSessionName, request.Context, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.CreateContextAsync(request.ParentAsSessionName, request.Context, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateContextRequestObject() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new wkt::FieldMask(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.UpdateContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.UpdateContext(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateContextRequestObjectAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new wkt::FieldMask(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.UpdateContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.UpdateContextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.UpdateContextAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateContext() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new wkt::FieldMask(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.UpdateContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context response = client.UpdateContext(request.Context, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateContextAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), UpdateMask = new wkt::FieldMask(), }; Context expectedResponse = new Context { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), LifespanCount = -2034952532, Parameters = new wkt::Struct(), }; mockGrpcClient.Setup(x => x.UpdateContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Context>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); Context responseCallSettings = await client.UpdateContextAsync(request.Context, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Context responseCancellationToken = await client.UpdateContextAsync(request.Context, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteContextRequestObject() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); client.DeleteContext(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteContextRequestObjectAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); await client.DeleteContextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteContextAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteContext() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); client.DeleteContext(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteContextAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); await client.DeleteContextAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteContextAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteContextResourceNames() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteContext(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); client.DeleteContext(request.ContextName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteContextResourceNamesAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteContextRequest request = new DeleteContextRequest { ContextName = ContextName.FromProjectSessionContext("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteContextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); await client.DeleteContextAsync(request.ContextName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteContextAsync(request.ContextName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAllContextsRequestObject() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAllContexts(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); client.DeleteAllContexts(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAllContextsRequestObjectAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAllContextsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); await client.DeleteAllContextsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAllContextsAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAllContexts() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAllContexts(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); client.DeleteAllContexts(request.Parent); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAllContextsAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAllContextsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); await client.DeleteAllContextsAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAllContextsAsync(request.Parent, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAllContextsResourceNames() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAllContexts(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); client.DeleteAllContexts(request.ParentAsSessionName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAllContextsResourceNamesAsync() { moq::Mock<Contexts.ContextsClient> mockGrpcClient = new moq::Mock<Contexts.ContextsClient>(moq::MockBehavior.Strict); DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAllContextsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContextsClient client = new ContextsClientImpl(mockGrpcClient.Object, null); await client.DeleteAllContextsAsync(request.ParentAsSessionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAllContextsAsync(request.ParentAsSessionName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// <copyright file="BoundNodes.Generated.cs" company="MIT License"> // Licensed under the MIT License. See LICENSE file in the project root for license information. // </copyright> /// <summary> /// This file is auto-generated by a build task. It shouldn't be edited by hand. /// </summary> namespace SmallBasic.Compiler.Binding { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SmallBasic.Compiler.Parsing; using SmallBasic.Compiler.Scanning; using SmallBasic.Utilities; public abstract class BaseBoundNodeVisitor { private protected void Visit(BaseBoundNode node) { switch (node) { case BoundSubModule subModule: this.VisitSubModule(subModule); break; case BoundStatementBlock statementBlock: this.VisitStatementBlock(statementBlock); break; case BoundIfPart ifPart: this.VisitIfPart(ifPart); break; case BoundElseIfPart elseIfPart: this.VisitElseIfPart(elseIfPart); break; case BoundElsePart elsePart: this.VisitElsePart(elsePart); break; case BoundIfStatement ifStatement: this.VisitIfStatement(ifStatement); break; case BoundWhileStatement whileStatement: this.VisitWhileStatement(whileStatement); break; case BoundForStatement forStatement: this.VisitForStatement(forStatement); break; case BoundLabelStatement labelStatement: this.VisitLabelStatement(labelStatement); break; case BoundGoToStatement goToStatement: this.VisitGoToStatement(goToStatement); break; case BoundSubModuleInvocationStatement subModuleInvocationStatement: this.VisitSubModuleInvocationStatement(subModuleInvocationStatement); break; case BoundLibraryMethodInvocationStatement libraryMethodInvocationStatement: this.VisitLibraryMethodInvocationStatement(libraryMethodInvocationStatement); break; case BoundVariableAssignmentStatement variableAssignmentStatement: this.VisitVariableAssignmentStatement(variableAssignmentStatement); break; case BoundPropertyAssignmentStatement propertyAssignmentStatement: this.VisitPropertyAssignmentStatement(propertyAssignmentStatement); break; case BoundEventAssignmentStatement eventAssignmentStatement: this.VisitEventAssignmentStatement(eventAssignmentStatement); break; case BoundArrayAssignmentStatement arrayAssignmentStatement: this.VisitArrayAssignmentStatement(arrayAssignmentStatement); break; case BoundInvalidExpressionStatement invalidExpressionStatement: this.VisitInvalidExpressionStatement(invalidExpressionStatement); break; case BoundUnaryExpression unaryExpression: this.VisitUnaryExpression(unaryExpression); break; case BoundBinaryExpression binaryExpression: this.VisitBinaryExpression(binaryExpression); break; case BoundArrayAccessExpression arrayAccessExpression: this.VisitArrayAccessExpression(arrayAccessExpression); break; case BoundLibraryTypeExpression libraryTypeExpression: this.VisitLibraryTypeExpression(libraryTypeExpression); break; case BoundLibraryMethodExpression libraryMethodExpression: this.VisitLibraryMethodExpression(libraryMethodExpression); break; case BoundLibraryPropertyExpression libraryPropertyExpression: this.VisitLibraryPropertyExpression(libraryPropertyExpression); break; case BoundLibraryEventExpression libraryEventExpression: this.VisitLibraryEventExpression(libraryEventExpression); break; case BoundLibraryMethodInvocationExpression libraryMethodInvocationExpression: this.VisitLibraryMethodInvocationExpression(libraryMethodInvocationExpression); break; case BoundSubModuleExpression subModuleExpression: this.VisitSubModuleExpression(subModuleExpression); break; case BoundSubModuleInvocationExpression subModuleInvocationExpression: this.VisitSubModuleInvocationExpression(subModuleInvocationExpression); break; case BoundVariableExpression variableExpression: this.VisitVariableExpression(variableExpression); break; case BoundStringLiteralExpression stringLiteralExpression: this.VisitStringLiteralExpression(stringLiteralExpression); break; case BoundNumberLiteralExpression numberLiteralExpression: this.VisitNumberLiteralExpression(numberLiteralExpression); break; case BoundParenthesisExpression parenthesisExpression: this.VisitParenthesisExpression(parenthesisExpression); break; case BoundInvalidExpression invalidExpression: this.VisitInvalidExpression(invalidExpression); break; default: throw ExceptionUtilities.UnexpectedValue(node); } } private protected virtual void VisitSubModule(BoundSubModule node) { this.DefaultVisit(node); } private protected virtual void VisitStatementBlock(BoundStatementBlock node) { this.DefaultVisit(node); } private protected virtual void VisitIfPart(BoundIfPart node) { this.DefaultVisit(node); } private protected virtual void VisitElseIfPart(BoundElseIfPart node) { this.DefaultVisit(node); } private protected virtual void VisitElsePart(BoundElsePart node) { this.DefaultVisit(node); } private protected virtual void VisitIfStatement(BoundIfStatement node) { this.DefaultVisit(node); } private protected virtual void VisitWhileStatement(BoundWhileStatement node) { this.DefaultVisit(node); } private protected virtual void VisitForStatement(BoundForStatement node) { this.DefaultVisit(node); } private protected virtual void VisitLabelStatement(BoundLabelStatement node) { this.DefaultVisit(node); } private protected virtual void VisitGoToStatement(BoundGoToStatement node) { this.DefaultVisit(node); } private protected virtual void VisitSubModuleInvocationStatement(BoundSubModuleInvocationStatement node) { this.DefaultVisit(node); } private protected virtual void VisitLibraryMethodInvocationStatement(BoundLibraryMethodInvocationStatement node) { this.DefaultVisit(node); } private protected virtual void VisitVariableAssignmentStatement(BoundVariableAssignmentStatement node) { this.DefaultVisit(node); } private protected virtual void VisitPropertyAssignmentStatement(BoundPropertyAssignmentStatement node) { this.DefaultVisit(node); } private protected virtual void VisitEventAssignmentStatement(BoundEventAssignmentStatement node) { this.DefaultVisit(node); } private protected virtual void VisitArrayAssignmentStatement(BoundArrayAssignmentStatement node) { this.DefaultVisit(node); } private protected virtual void VisitInvalidExpressionStatement(BoundInvalidExpressionStatement node) { this.DefaultVisit(node); } private protected virtual void VisitUnaryExpression(BoundUnaryExpression node) { this.DefaultVisit(node); } private protected virtual void VisitBinaryExpression(BoundBinaryExpression node) { this.DefaultVisit(node); } private protected virtual void VisitArrayAccessExpression(BoundArrayAccessExpression node) { this.DefaultVisit(node); } private protected virtual void VisitLibraryTypeExpression(BoundLibraryTypeExpression node) { this.DefaultVisit(node); } private protected virtual void VisitLibraryMethodExpression(BoundLibraryMethodExpression node) { this.DefaultVisit(node); } private protected virtual void VisitLibraryPropertyExpression(BoundLibraryPropertyExpression node) { this.DefaultVisit(node); } private protected virtual void VisitLibraryEventExpression(BoundLibraryEventExpression node) { this.DefaultVisit(node); } private protected virtual void VisitLibraryMethodInvocationExpression(BoundLibraryMethodInvocationExpression node) { this.DefaultVisit(node); } private protected virtual void VisitSubModuleExpression(BoundSubModuleExpression node) { this.DefaultVisit(node); } private protected virtual void VisitSubModuleInvocationExpression(BoundSubModuleInvocationExpression node) { this.DefaultVisit(node); } private protected virtual void VisitVariableExpression(BoundVariableExpression node) { this.DefaultVisit(node); } private protected virtual void VisitStringLiteralExpression(BoundStringLiteralExpression node) { this.DefaultVisit(node); } private protected virtual void VisitNumberLiteralExpression(BoundNumberLiteralExpression node) { this.DefaultVisit(node); } private protected virtual void VisitParenthesisExpression(BoundParenthesisExpression node) { this.DefaultVisit(node); } private protected virtual void VisitInvalidExpression(BoundInvalidExpression node) { this.DefaultVisit(node); } private void DefaultVisit(BaseBoundNode node) { foreach (var child in node.Children) { this.Visit(child); } } } internal sealed class BoundSubModule : BaseBoundNode { public BoundSubModule(SubModuleStatementSyntax syntax, string name, BoundStatementBlock body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Name = name; this.Body = body; } public SubModuleStatementSyntax Syntax { get; private set; } public string Name { get; private set; } public BoundStatementBlock Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Body; } } } internal abstract class BaseBoundStatement : BaseBoundNode { } internal sealed class BoundStatementBlock : BaseBoundStatement { public BoundStatementBlock(StatementBlockSyntax syntax, IReadOnlyList<BaseBoundStatement> body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Body = body; } public StatementBlockSyntax Syntax { get; private set; } public IReadOnlyList<BaseBoundStatement> Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { foreach (var child in this.Body) { yield return child; } } } } internal sealed class BoundIfPart : BaseBoundNode { public BoundIfPart(IfPartSyntax syntax, BaseBoundExpression condition, BoundStatementBlock body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!condition.IsDefault(), "'condition' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Condition = condition; this.Body = body; } public IfPartSyntax Syntax { get; private set; } public BaseBoundExpression Condition { get; private set; } public BoundStatementBlock Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Condition; yield return this.Body; } } } internal sealed class BoundElseIfPart : BaseBoundNode { public BoundElseIfPart(ElseIfPartSyntax syntax, BaseBoundExpression condition, BoundStatementBlock body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!condition.IsDefault(), "'condition' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Condition = condition; this.Body = body; } public ElseIfPartSyntax Syntax { get; private set; } public BaseBoundExpression Condition { get; private set; } public BoundStatementBlock Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Condition; yield return this.Body; } } } internal sealed class BoundElsePart : BaseBoundNode { public BoundElsePart(ElsePartSyntax syntax, BoundStatementBlock body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Body = body; } public ElsePartSyntax Syntax { get; private set; } public BoundStatementBlock Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Body; } } } internal sealed class BoundIfStatement : BaseBoundStatement { public BoundIfStatement(IfStatementSyntax syntax, BoundIfPart ifPart, IReadOnlyList<BoundElseIfPart> elseIfParts, BoundElsePart elsePartOpt) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!ifPart.IsDefault(), "'ifPart' must not be null."); Debug.Assert(!elseIfParts.IsDefault(), "'elseIfParts' must not be null."); this.Syntax = syntax; this.IfPart = ifPart; this.ElseIfParts = elseIfParts; this.ElsePartOpt = elsePartOpt; } public IfStatementSyntax Syntax { get; private set; } public BoundIfPart IfPart { get; private set; } public IReadOnlyList<BoundElseIfPart> ElseIfParts { get; private set; } public BoundElsePart ElsePartOpt { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.IfPart; foreach (var child in this.ElseIfParts) { yield return child; } if (!this.ElsePartOpt.IsDefault()) { yield return this.ElsePartOpt; } } } } internal sealed class BoundWhileStatement : BaseBoundStatement { public BoundWhileStatement(WhileStatementSyntax syntax, BaseBoundExpression condition, BoundStatementBlock body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!condition.IsDefault(), "'condition' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Condition = condition; this.Body = body; } public WhileStatementSyntax Syntax { get; private set; } public BaseBoundExpression Condition { get; private set; } public BoundStatementBlock Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Condition; yield return this.Body; } } } internal sealed class BoundForStatement : BaseBoundStatement { public BoundForStatement(ForStatementSyntax syntax, string identifier, BaseBoundExpression fromExpression, BaseBoundExpression toExpression, BaseBoundExpression stepExpressionOpt, BoundStatementBlock body) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!identifier.IsDefault(), "'identifier' must not be null."); Debug.Assert(!fromExpression.IsDefault(), "'fromExpression' must not be null."); Debug.Assert(!toExpression.IsDefault(), "'toExpression' must not be null."); Debug.Assert(!body.IsDefault(), "'body' must not be null."); this.Syntax = syntax; this.Identifier = identifier; this.FromExpression = fromExpression; this.ToExpression = toExpression; this.StepExpressionOpt = stepExpressionOpt; this.Body = body; } public ForStatementSyntax Syntax { get; private set; } public string Identifier { get; private set; } public BaseBoundExpression FromExpression { get; private set; } public BaseBoundExpression ToExpression { get; private set; } public BaseBoundExpression StepExpressionOpt { get; private set; } public BoundStatementBlock Body { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.FromExpression; yield return this.ToExpression; if (!this.StepExpressionOpt.IsDefault()) { yield return this.StepExpressionOpt; } yield return this.Body; } } } internal sealed class BoundLabelStatement : BaseBoundStatement { public BoundLabelStatement(LabelStatementSyntax syntax, string label) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!label.IsDefault(), "'label' must not be null."); this.Syntax = syntax; this.Label = label; } public LabelStatementSyntax Syntax { get; private set; } public string Label { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundGoToStatement : BaseBoundStatement { public BoundGoToStatement(GoToStatementSyntax syntax, string label) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!label.IsDefault(), "'label' must not be null."); this.Syntax = syntax; this.Label = label; } public GoToStatementSyntax Syntax { get; private set; } public string Label { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundSubModuleInvocationStatement : BaseBoundStatement { public BoundSubModuleInvocationStatement(ExpressionStatementSyntax syntax, BoundSubModuleInvocationExpression expression) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Expression = expression; } public ExpressionStatementSyntax Syntax { get; private set; } public BoundSubModuleInvocationExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Expression; } } } internal sealed class BoundLibraryMethodInvocationStatement : BaseBoundStatement { public BoundLibraryMethodInvocationStatement(ExpressionStatementSyntax syntax, BoundLibraryMethodInvocationExpression expression) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Expression = expression; } public ExpressionStatementSyntax Syntax { get; private set; } public BoundLibraryMethodInvocationExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Expression; } } } internal sealed class BoundVariableAssignmentStatement : BaseBoundStatement { public BoundVariableAssignmentStatement(ExpressionStatementSyntax syntax, BoundVariableExpression variable, BaseBoundExpression expression) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!variable.IsDefault(), "'variable' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Variable = variable; this.Expression = expression; } public ExpressionStatementSyntax Syntax { get; private set; } public BoundVariableExpression Variable { get; private set; } public BaseBoundExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Variable; yield return this.Expression; } } } internal sealed class BoundPropertyAssignmentStatement : BaseBoundStatement { public BoundPropertyAssignmentStatement(ExpressionStatementSyntax syntax, BoundLibraryPropertyExpression property, BaseBoundExpression expression) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!property.IsDefault(), "'property' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Property = property; this.Expression = expression; } public ExpressionStatementSyntax Syntax { get; private set; } public BoundLibraryPropertyExpression Property { get; private set; } public BaseBoundExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Property; yield return this.Expression; } } } internal sealed class BoundEventAssignmentStatement : BaseBoundStatement { public BoundEventAssignmentStatement(ExpressionStatementSyntax syntax, BoundLibraryEventExpression usedEvent, string subModule) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!usedEvent.IsDefault(), "'usedEvent' must not be null."); Debug.Assert(!subModule.IsDefault(), "'subModule' must not be null."); this.Syntax = syntax; this.UsedEvent = usedEvent; this.SubModule = subModule; } public ExpressionStatementSyntax Syntax { get; private set; } public BoundLibraryEventExpression UsedEvent { get; private set; } public string SubModule { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.UsedEvent; } } } internal sealed class BoundArrayAssignmentStatement : BaseBoundStatement { public BoundArrayAssignmentStatement(ExpressionStatementSyntax syntax, BoundArrayAccessExpression array, BaseBoundExpression expression) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!array.IsDefault(), "'array' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Array = array; this.Expression = expression; } public ExpressionStatementSyntax Syntax { get; private set; } public BoundArrayAccessExpression Array { get; private set; } public BaseBoundExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Array; yield return this.Expression; } } } internal sealed class BoundInvalidExpressionStatement : BaseBoundStatement { public BoundInvalidExpressionStatement(ExpressionStatementSyntax syntax, BaseBoundExpression expression) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Expression = expression; } public ExpressionStatementSyntax Syntax { get; private set; } public BaseBoundExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Expression; } } } internal abstract class BaseBoundExpression : BaseBoundNode { public BaseBoundExpression(bool hasValue, bool hasErrors) { Debug.Assert(!hasValue.IsDefault(), "'hasValue' must not be null."); Debug.Assert(!hasErrors.IsDefault(), "'hasErrors' must not be null."); this.HasValue = hasValue; this.HasErrors = hasErrors; } public bool HasValue { get; private set; } public bool HasErrors { get; private set; } } internal sealed class BoundUnaryExpression : BaseBoundExpression { public BoundUnaryExpression(UnaryOperatorExpressionSyntax syntax, bool hasValue, bool hasErrors, TokenKind kind, BaseBoundExpression expression) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!kind.IsDefault(), "'kind' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Kind = kind; this.Expression = expression; } public UnaryOperatorExpressionSyntax Syntax { get; private set; } public TokenKind Kind { get; private set; } public BaseBoundExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Expression; } } } internal sealed class BoundBinaryExpression : BaseBoundExpression { public BoundBinaryExpression(BinaryOperatorExpressionSyntax syntax, bool hasValue, bool hasErrors, TokenKind kind, BaseBoundExpression left, BaseBoundExpression right) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!kind.IsDefault(), "'kind' must not be null."); Debug.Assert(!left.IsDefault(), "'left' must not be null."); Debug.Assert(!right.IsDefault(), "'right' must not be null."); this.Syntax = syntax; this.Kind = kind; this.Left = left; this.Right = right; } public BinaryOperatorExpressionSyntax Syntax { get; private set; } public TokenKind Kind { get; private set; } public BaseBoundExpression Left { get; private set; } public BaseBoundExpression Right { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Left; yield return this.Right; } } } internal sealed class BoundArrayAccessExpression : BaseBoundExpression { public BoundArrayAccessExpression(ArrayAccessExpressionSyntax syntax, bool hasValue, bool hasErrors, string name, IReadOnlyList<BaseBoundExpression> indices) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); Debug.Assert(!indices.IsDefault(), "'indices' must not be null."); this.Syntax = syntax; this.Name = name; this.Indices = indices; } public ArrayAccessExpressionSyntax Syntax { get; private set; } public string Name { get; private set; } public IReadOnlyList<BaseBoundExpression> Indices { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { foreach (var child in this.Indices) { yield return child; } } } } internal sealed class BoundLibraryTypeExpression : BaseBoundExpression { public BoundLibraryTypeExpression(IdentifierExpressionSyntax syntax, bool hasValue, bool hasErrors, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Name = name; } public IdentifierExpressionSyntax Syntax { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundLibraryMethodExpression : BaseBoundExpression { public BoundLibraryMethodExpression(ObjectAccessExpressionSyntax syntax, bool hasValue, bool hasErrors, BoundLibraryTypeExpression library, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!library.IsDefault(), "'library' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Library = library; this.Name = name; } public ObjectAccessExpressionSyntax Syntax { get; private set; } public BoundLibraryTypeExpression Library { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Library; } } } internal sealed class BoundLibraryPropertyExpression : BaseBoundExpression { public BoundLibraryPropertyExpression(ObjectAccessExpressionSyntax syntax, bool hasValue, bool hasErrors, BoundLibraryTypeExpression library, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!library.IsDefault(), "'library' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Library = library; this.Name = name; } public ObjectAccessExpressionSyntax Syntax { get; private set; } public BoundLibraryTypeExpression Library { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Library; } } } internal sealed class BoundLibraryEventExpression : BaseBoundExpression { public BoundLibraryEventExpression(ObjectAccessExpressionSyntax syntax, bool hasValue, bool hasErrors, BoundLibraryTypeExpression library, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!library.IsDefault(), "'library' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Library = library; this.Name = name; } public ObjectAccessExpressionSyntax Syntax { get; private set; } public BoundLibraryTypeExpression Library { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Library; } } } internal sealed class BoundLibraryMethodInvocationExpression : BaseBoundExpression { public BoundLibraryMethodInvocationExpression(InvocationExpressionSyntax syntax, bool hasValue, bool hasErrors, BoundLibraryMethodExpression method, IReadOnlyList<BaseBoundExpression> arguments) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!method.IsDefault(), "'method' must not be null."); Debug.Assert(!arguments.IsDefault(), "'arguments' must not be null."); this.Syntax = syntax; this.Method = method; this.Arguments = arguments; } public InvocationExpressionSyntax Syntax { get; private set; } public BoundLibraryMethodExpression Method { get; private set; } public IReadOnlyList<BaseBoundExpression> Arguments { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Method; foreach (var child in this.Arguments) { yield return child; } } } } internal sealed class BoundSubModuleExpression : BaseBoundExpression { public BoundSubModuleExpression(IdentifierExpressionSyntax syntax, bool hasValue, bool hasErrors, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Name = name; } public IdentifierExpressionSyntax Syntax { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundSubModuleInvocationExpression : BaseBoundExpression { public BoundSubModuleInvocationExpression(InvocationExpressionSyntax syntax, bool hasValue, bool hasErrors, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Name = name; } public InvocationExpressionSyntax Syntax { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundVariableExpression : BaseBoundExpression { public BoundVariableExpression(IdentifierExpressionSyntax syntax, bool hasValue, bool hasErrors, string name) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!name.IsDefault(), "'name' must not be null."); this.Syntax = syntax; this.Name = name; } public IdentifierExpressionSyntax Syntax { get; private set; } public string Name { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundStringLiteralExpression : BaseBoundExpression { public BoundStringLiteralExpression(StringLiteralExpressionSyntax syntax, bool hasValue, bool hasErrors, string value) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!value.IsDefault(), "'value' must not be null."); this.Syntax = syntax; this.Value = value; } public StringLiteralExpressionSyntax Syntax { get; private set; } public string Value { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundNumberLiteralExpression : BaseBoundExpression { public BoundNumberLiteralExpression(NumberLiteralExpressionSyntax syntax, bool hasValue, bool hasErrors, decimal value) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!value.IsDefault(), "'value' must not be null."); this.Syntax = syntax; this.Value = value; } public NumberLiteralExpressionSyntax Syntax { get; private set; } public decimal Value { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } internal sealed class BoundParenthesisExpression : BaseBoundExpression { public BoundParenthesisExpression(ParenthesisExpressionSyntax syntax, bool hasValue, bool hasErrors, BaseBoundExpression expression) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); Debug.Assert(!expression.IsDefault(), "'expression' must not be null."); this.Syntax = syntax; this.Expression = expression; } public ParenthesisExpressionSyntax Syntax { get; private set; } public BaseBoundExpression Expression { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { yield return this.Expression; } } } internal sealed class BoundInvalidExpression : BaseBoundExpression { public BoundInvalidExpression(BaseExpressionSyntax syntax, bool hasValue, bool hasErrors) : base(hasValue, hasErrors) { Debug.Assert(!syntax.IsDefault(), "'syntax' must not be null."); this.Syntax = syntax; } public BaseExpressionSyntax Syntax { get; private set; } public override IEnumerable<BaseBoundNode> Children { get { return Enumerable.Empty<BaseBoundNode>(); } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class RecordingSubscriptionDescriptorDecoder { public const ushort BLOCK_LENGTH = 28; public const ushort TEMPLATE_ID = 23; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private RecordingSubscriptionDescriptorDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public RecordingSubscriptionDescriptorDecoder() { _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 RecordingSubscriptionDescriptorDecoder 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 ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(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 ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(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 CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int SubscriptionIdId() { return 3; } public static int SubscriptionIdSinceVersion() { return 0; } public static int SubscriptionIdEncodingOffset() { return 16; } public static int SubscriptionIdEncodingLength() { return 8; } public static string SubscriptionIdMetaAttribute(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 SubscriptionIdNullValue() { return -9223372036854775808L; } public static long SubscriptionIdMinValue() { return -9223372036854775807L; } public static long SubscriptionIdMaxValue() { return 9223372036854775807L; } public long SubscriptionId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int StreamIdId() { return 4; } public static int StreamIdSinceVersion() { return 0; } public static int StreamIdEncodingOffset() { return 24; } public static int StreamIdEncodingLength() { return 4; } public static string StreamIdMetaAttribute(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 StreamIdNullValue() { return -2147483648; } public static int StreamIdMinValue() { return -2147483647; } public static int StreamIdMaxValue() { return 2147483647; } public int StreamId() { return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian); } public static int StrippedChannelId() { return 5; } public static int StrippedChannelSinceVersion() { return 0; } public static string StrippedChannelCharacterEncoding() { return "US-ASCII"; } public static string StrippedChannelMetaAttribute(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 StrippedChannelHeaderLength() { return 4; } public int StrippedChannelLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetStrippedChannel(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetStrippedChannel(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string StrippedChannel() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[RecordingSubscriptionDescriptor](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='controlSessionId', 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("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', 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("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='subscriptionId', 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='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, 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("SubscriptionId="); builder.Append(SubscriptionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='streamId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, 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=24, 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("StreamId="); builder.Append(StreamId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='strippedChannel', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, 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'}} builder.Append("StrippedChannel="); builder.Append(StrippedChannel()); Limit(originalLimit); return builder; } } }
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using System.Collections.Generic; using SharpNav.Collections.Generic; using SharpNav.Geometry; #if MONOGAME using Vector3 = Microsoft.Xna.Framework.Vector3; #elif OPENTK using Vector3 = OpenTK.Vector3; #elif SHARPDX using Vector3 = SharpDX.Vector3; #endif namespace SharpNav.Crowds { public class ObstacleAvoidanceQuery { #region Fields private const int MaxPatternDivs = 32; private const int MaxPatternRings = 4; private ObstacleAvoidanceParams parameters; private float invHorizTime; private float vmax; private float invVmax; private int maxCircles; private ObstacleCircle[] circles; private int numCircles; private int maxSegments; private ObstacleSegment[] segments; private int numSegments; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ObstacleAvoidanceQuery" /> class. /// </summary> /// <param name="maxCircles">The maximum number of circles</param> /// <param name="maxSegments">The maximum number of segments</param> public ObstacleAvoidanceQuery(int maxCircles, int maxSegments) { this.maxCircles = maxCircles; this.numCircles = 0; this.circles = new ObstacleCircle[this.maxCircles]; this.maxSegments = maxSegments; this.numSegments = 0; this.segments = new ObstacleSegment[this.maxSegments]; } #endregion #region Methods /// <summary> /// Resets the ObstacleAvoidanceQuery's internal data /// </summary> public void Reset() { numCircles = 0; numSegments = 0; } /// <summary> /// Add a new circle to the array /// </summary> /// <param name="pos">The position</param> /// <param name="rad">The radius</param> /// <param name="vel">The velocity</param> /// <param name="dvel">The desired velocity</param> public void AddCircle(Vector3 pos, float rad, Vector3 vel, Vector3 dvel) { if (numCircles >= maxCircles) return; circles[numCircles].Position = pos; circles[numCircles].Radius = rad; circles[numCircles].Vel = vel; circles[numCircles].DesiredVel = dvel; numCircles++; } /// <summary> /// Add a segment to the array /// </summary> /// <param name="p">One endpoint</param> /// <param name="q">The other endpoint</param> public void AddSegment(Vector3 p, Vector3 q) { if (numSegments > maxSegments) return; segments[numSegments].P = p; segments[numSegments].Q = q; numSegments++; } /// <summary> /// Prepare the obstacles for further calculations /// </summary> /// <param name="position">Current position</param> /// <param name="desiredVel">Desired velocity</param> public void Prepare(Vector3 position, Vector3 desiredVel) { //prepare obstacles for (int i = 0; i < numCircles; i++) { //side Vector3 pa = position; Vector3 pb = circles[i].Position; Vector3 orig = new Vector3(0, 0, 0); circles[i].Dp = pb - pa; circles[i].Dp.Normalize(); Vector3 dv = circles[i].DesiredVel - desiredVel; float a = Triangle3.Area2D(orig, circles[i].Dp, dv); if (a < 0.01f) { circles[i].Np.X = -circles[i].Dp.Z; circles[i].Np.Z = circles[i].Dp.X; } else { circles[i].Np.X = circles[i].Dp.Z; circles[i].Np.Z = -circles[i].Dp.X; } } for (int i = 0; i < numSegments; i++) { //precalculate if the agent is close to the segment float r = 0.01f; float t; segments[i].Touch = Distance.PointToSegment2DSquared(ref position, ref segments[i].P, ref segments[i].Q, out t) < (r * r); } } public float ProcessSample(Vector3 vcand, float cs, Vector3 position, float radius, Vector3 vel, Vector3 desiredVel) { //find min time of impact and exit amongst all obstacles float tmin = parameters.HorizTime; float side = 0; int numSide = 0; for (int i = 0; i < numCircles; i++) { ObstacleCircle cir = circles[i]; //RVO Vector3 vab = vcand * 2; vab = vab - vel; vab = vab - cir.Vel; //side side += MathHelper.Clamp(Math.Min(Vector3Extensions.Dot2D(ref cir.Dp, ref vab) * 0.5f + 0.5f, Vector3Extensions.Dot2D(ref cir.Np, ref vab) * 2.0f), 0.0f, 1.0f); numSide++; float htmin = 0, htmax = 0; if (!SweepCircleCircle(position, radius, vab, cir.Position, cir.Radius, ref htmin, ref htmax)) continue; //handle overlapping obstacles if (htmin < 0.0f && htmax > 0.0f) { //avoid more when overlapped htmin = -htmin * 0.5f; } if (htmin >= 0.0f) { //the closest obstacle is sometime ahead of us, keep track of nearest obstacle if (htmin < tmin) tmin = htmin; } } for (int i = 0; i < numSegments; i++) { ObstacleSegment seg = segments[i]; float htmin; if (seg.Touch) { //special case when the agent is very close to the segment Vector3 sdir = seg.Q - seg.P; Vector3 snorm = new Vector3(0, 0, 0); snorm.X = -sdir.Z; snorm.Z = sdir.X; //if the velocity is pointing towards the segment, no collision if (Vector3Extensions.Dot2D(ref snorm, ref vcand) < 0.0f) continue; //else immediate collision htmin = 0.0f; } else { if (!Intersection.RaySegment(position, vcand, seg.P, seg.Q, out htmin)) continue; } //avoid less when facing walls htmin *= 2.0f; //the closest obstacle is somewhere ahead of us, keep track of the nearest obstacle if (htmin < tmin) tmin = htmin; } //normalize side bias if (numSide != 0) side /= numSide; float vpen = parameters.WeightDesVel * (Vector3Extensions.Distance2D(vcand, desiredVel) * invVmax); float vcpen = parameters.WeightCurVel * (Vector3Extensions.Distance2D(vcand, vel) * invVmax); float spen = parameters.WeightSide * side; float tpen = parameters.WeightToi * (1.0f / (0.1f + tmin * invHorizTime)); float penalty = vpen + vcpen + spen + tpen; return penalty; } public static bool SweepCircleCircle(Vector3 center0, float radius0, Vector3 v, Vector3 center1, float radius1, ref float tmin, ref float tmax) { const float EPS = 0.0001f; Vector3 s = center1 - center0; float r = radius0 + radius1; float c = Vector3Extensions.Dot2D(ref s, ref s) - r * r; float a = Vector3Extensions.Dot2D(ref v, ref v); if (a < EPS) return false; //not moving //overlap, calculate time to exit float b = Vector3Extensions.Dot2D(ref v, ref s); float d = b * b - a * c; if (d < 0.0f) return false; //no intersection a = 1.0f / a; float rd = (float)Math.Sqrt(d); tmin = (b - rd) * a; tmax = (b + rd) * a; return true; } public int SampleVelocityGrid(Vector3 pos, float rad, float vmax, Vector3 vel, Vector3 desiredVel, ref Vector3 nvel, ObstacleAvoidanceParams parameters) { Prepare(pos, desiredVel); this.parameters = parameters; this.invHorizTime = 1.0f / this.parameters.HorizTime; this.vmax = vmax; this.invVmax = 1.0f / vmax; nvel = new Vector3(0, 0, 0); float cvx = desiredVel.X * this.parameters.VelBias; float cvz = desiredVel.Z * this.parameters.VelBias; float cs = vmax * 2 * (1 - this.parameters.VelBias) / (float)(this.parameters.GridSize - 1); float half = (this.parameters.GridSize - 1) * cs * 0.5f; float minPenalty = float.MaxValue; int numSamples = 0; for (int y = 0; y < this.parameters.GridSize; y++) { for (int x = 0; x < this.parameters.GridSize; x++) { Vector3 vcand = new Vector3(0, 0, 0); vcand.X = cvx + x * cs - half; vcand.Y = 0; vcand.Z = cvz + y * cs - half; if (vcand.X * vcand.X + vcand.Z * vcand.Z > (vmax + cs / 2) * (vmax + cs / 2)) continue; float penalty = ProcessSample(vcand, cs, pos, rad, vel, desiredVel); numSamples++; if (penalty < minPenalty) { minPenalty = penalty; nvel = vcand; } } } return numSamples; } public int SampleVelocityAdaptive(Vector3 position, float radius, float vmax, Vector3 vel, Vector3 desiredVel, ref Vector3 nvel, ObstacleAvoidanceParams parameters) { Prepare(position, desiredVel); this.parameters = parameters; this.invHorizTime = 1.0f / parameters.HorizTime; this.vmax = vmax; this.invVmax = 1.0f / vmax; nvel = new Vector3(0, 0, 0); //build sampling pattern aligned to desired velocity float[] pattern = new float[(MaxPatternDivs * MaxPatternRings + 1) * 2]; int numPatterns = 0; int numDivs = parameters.AdaptiveDivs; int numRings = parameters.AdaptiveRings; int depth = parameters.AdaptiveDepth; int newNumDivs = MathHelper.Clamp(numDivs, 1, MaxPatternDivs); int newNumRings = MathHelper.Clamp(numRings, 1, MaxPatternRings); float da = (1.0f / newNumDivs) * (float)Math.PI * 2; float dang = (float)Math.Atan2(desiredVel.Z, desiredVel.X); //always add sample at zero pattern[numPatterns * 2 + 0] = 0; pattern[numPatterns * 2 + 1] = 0; numPatterns++; for (int j = 0; j < newNumRings; j++) { float r = (float)(newNumRings - j) / (float)newNumRings; float a = dang + (j & 1) * 0.5f * da; for (int i = 0; i < newNumDivs; i++) { pattern[numPatterns * 2 + 0] = (float)Math.Cos(a) * r; pattern[numPatterns * 2 + 1] = (float)Math.Sin(a) * r; numPatterns++; a += da; } } //start sampling float cr = vmax * (1.0f - parameters.VelBias); Vector3 res = new Vector3(desiredVel.X * parameters.VelBias, 0, desiredVel.Z * parameters.VelBias); int ns = 0; for (int k = 0; k < depth; k++) { float minPenalty = float.MaxValue; Vector3 bvel = new Vector3(0, 0, 0); for (int i = 0; i < numPatterns; i++) { Vector3 vcand = new Vector3(); vcand.X = res.X + pattern[i * 2 + 0] * cr; vcand.Y = 0; vcand.Z = res.Z + pattern[i * 2 + 1] * cr; if (vcand.X * vcand.X + vcand.Z * vcand.Z > (vmax + 0.001f) * (vmax + 0.001f)) continue; float penalty = ProcessSample(vcand, cr / 10, position, radius, vel, desiredVel); ns++; if (penalty < minPenalty) { minPenalty = penalty; bvel = vcand; } } res = bvel; cr *= 0.5f; } nvel = res; return ns; } #endregion private struct ObstacleCircle { /// <summary> /// The position of the obstacle /// </summary> public Vector3 Position; /// <summary> /// The velocity of the obstacle /// </summary> public Vector3 Vel; /// <summary> /// The desired velocity of the obstacle /// </summary> public Vector3 DesiredVel; /// <summary> /// The radius of the obstacle /// </summary> public float Radius; /// <summary> /// Used for side selection during sampling /// </summary> public Vector3 Dp, Np; } private struct ObstacleSegment { /// <summary> /// Endpoints of the obstacle segment /// </summary> public Vector3 P, Q; public bool Touch; } public struct ObstacleAvoidanceParams { public float VelBias; public float WeightDesVel; public float WeightCurVel; public float WeightSide; public float WeightToi; public float HorizTime; public int GridSize; public int AdaptiveDivs; public int AdaptiveRings; public int AdaptiveDepth; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/stats.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 Grpc.Testing { /// <summary>Holder for reflection information generated from src/proto/grpc/testing/stats.proto</summary> public static partial class StatsReflection { #region Descriptor /// <summary>File descriptor for src/proto/grpc/testing/stats.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static StatsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJzcmMvcHJvdG8vZ3JwYy90ZXN0aW5nL3N0YXRzLnByb3RvEgxncnBjLnRl", "c3RpbmcikQEKC1NlcnZlclN0YXRzEhQKDHRpbWVfZWxhcHNlZBgBIAEoARIR", "Cgl0aW1lX3VzZXIYAiABKAESEwoLdGltZV9zeXN0ZW0YAyABKAESFgoOdG90", "YWxfY3B1X3RpbWUYBCABKAQSFQoNaWRsZV9jcHVfdGltZRgFIAEoBBIVCg1j", "cV9wb2xsX2NvdW50GAYgASgEIjsKD0hpc3RvZ3JhbVBhcmFtcxISCgpyZXNv", "bHV0aW9uGAEgASgBEhQKDG1heF9wb3NzaWJsZRgCIAEoASJ3Cg1IaXN0b2dy", "YW1EYXRhEg4KBmJ1Y2tldBgBIAMoDRIQCghtaW5fc2VlbhgCIAEoARIQCght", "YXhfc2VlbhgDIAEoARILCgNzdW0YBCABKAESFgoOc3VtX29mX3NxdWFyZXMY", "BSABKAESDQoFY291bnQYBiABKAEiOAoSUmVxdWVzdFJlc3VsdENvdW50EhMK", "C3N0YXR1c19jb2RlGAEgASgFEg0KBWNvdW50GAIgASgDIs0BCgtDbGllbnRT", "dGF0cxIuCglsYXRlbmNpZXMYASABKAsyGy5ncnBjLnRlc3RpbmcuSGlzdG9n", "cmFtRGF0YRIUCgx0aW1lX2VsYXBzZWQYAiABKAESEQoJdGltZV91c2VyGAMg", "ASgBEhMKC3RpbWVfc3lzdGVtGAQgASgBEjkKD3JlcXVlc3RfcmVzdWx0cxgF", "IAMoCzIgLmdycGMudGVzdGluZy5SZXF1ZXN0UmVzdWx0Q291bnQSFQoNY3Ff", "cG9sbF9jb3VudBgGIAEoBGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.ServerStats), global::Grpc.Testing.ServerStats.Parser, new[]{ "TimeElapsed", "TimeUser", "TimeSystem", "TotalCpuTime", "IdleCpuTime", "CqPollCount" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.HistogramParams), global::Grpc.Testing.HistogramParams.Parser, new[]{ "Resolution", "MaxPossible" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.HistogramData), global::Grpc.Testing.HistogramData.Parser, new[]{ "Bucket", "MinSeen", "MaxSeen", "Sum", "SumOfSquares", "Count" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.RequestResultCount), global::Grpc.Testing.RequestResultCount.Parser, new[]{ "StatusCode", "Count" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grpc.Testing.ClientStats), global::Grpc.Testing.ClientStats.Parser, new[]{ "Latencies", "TimeElapsed", "TimeUser", "TimeSystem", "RequestResults", "CqPollCount" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ServerStats : pb::IMessage<ServerStats> { private static readonly pb::MessageParser<ServerStats> _parser = new pb::MessageParser<ServerStats>(() => new ServerStats()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ServerStats> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ServerStats() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ServerStats(ServerStats other) : this() { timeElapsed_ = other.timeElapsed_; timeUser_ = other.timeUser_; timeSystem_ = other.timeSystem_; totalCpuTime_ = other.totalCpuTime_; idleCpuTime_ = other.idleCpuTime_; cqPollCount_ = other.cqPollCount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ServerStats Clone() { return new ServerStats(this); } /// <summary>Field number for the "time_elapsed" field.</summary> public const int TimeElapsedFieldNumber = 1; private double timeElapsed_; /// <summary> /// wall clock time change in seconds since last reset /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double TimeElapsed { get { return timeElapsed_; } set { timeElapsed_ = value; } } /// <summary>Field number for the "time_user" field.</summary> public const int TimeUserFieldNumber = 2; private double timeUser_; /// <summary> /// change in user time (in seconds) used by the server since last reset /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double TimeUser { get { return timeUser_; } set { timeUser_ = value; } } /// <summary>Field number for the "time_system" field.</summary> public const int TimeSystemFieldNumber = 3; private double timeSystem_; /// <summary> /// change in server time (in seconds) used by the server process and all /// threads since last reset /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double TimeSystem { get { return timeSystem_; } set { timeSystem_ = value; } } /// <summary>Field number for the "total_cpu_time" field.</summary> public const int TotalCpuTimeFieldNumber = 4; private ulong totalCpuTime_; /// <summary> /// change in total cpu time of the server (data from proc/stat) /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong TotalCpuTime { get { return totalCpuTime_; } set { totalCpuTime_ = value; } } /// <summary>Field number for the "idle_cpu_time" field.</summary> public const int IdleCpuTimeFieldNumber = 5; private ulong idleCpuTime_; /// <summary> /// change in idle time of the server (data from proc/stat) /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong IdleCpuTime { get { return idleCpuTime_; } set { idleCpuTime_ = value; } } /// <summary>Field number for the "cq_poll_count" field.</summary> public const int CqPollCountFieldNumber = 6; private ulong cqPollCount_; /// <summary> /// Number of polls called inside completion queue /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong CqPollCount { get { return cqPollCount_; } set { cqPollCount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ServerStats); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ServerStats other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TimeElapsed != other.TimeElapsed) return false; if (TimeUser != other.TimeUser) return false; if (TimeSystem != other.TimeSystem) return false; if (TotalCpuTime != other.TotalCpuTime) return false; if (IdleCpuTime != other.IdleCpuTime) return false; if (CqPollCount != other.CqPollCount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (TimeElapsed != 0D) hash ^= TimeElapsed.GetHashCode(); if (TimeUser != 0D) hash ^= TimeUser.GetHashCode(); if (TimeSystem != 0D) hash ^= TimeSystem.GetHashCode(); if (TotalCpuTime != 0UL) hash ^= TotalCpuTime.GetHashCode(); if (IdleCpuTime != 0UL) hash ^= IdleCpuTime.GetHashCode(); if (CqPollCount != 0UL) hash ^= CqPollCount.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 (TimeElapsed != 0D) { output.WriteRawTag(9); output.WriteDouble(TimeElapsed); } if (TimeUser != 0D) { output.WriteRawTag(17); output.WriteDouble(TimeUser); } if (TimeSystem != 0D) { output.WriteRawTag(25); output.WriteDouble(TimeSystem); } if (TotalCpuTime != 0UL) { output.WriteRawTag(32); output.WriteUInt64(TotalCpuTime); } if (IdleCpuTime != 0UL) { output.WriteRawTag(40); output.WriteUInt64(IdleCpuTime); } if (CqPollCount != 0UL) { output.WriteRawTag(48); output.WriteUInt64(CqPollCount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (TimeElapsed != 0D) { size += 1 + 8; } if (TimeUser != 0D) { size += 1 + 8; } if (TimeSystem != 0D) { size += 1 + 8; } if (TotalCpuTime != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(TotalCpuTime); } if (IdleCpuTime != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(IdleCpuTime); } if (CqPollCount != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(CqPollCount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ServerStats other) { if (other == null) { return; } if (other.TimeElapsed != 0D) { TimeElapsed = other.TimeElapsed; } if (other.TimeUser != 0D) { TimeUser = other.TimeUser; } if (other.TimeSystem != 0D) { TimeSystem = other.TimeSystem; } if (other.TotalCpuTime != 0UL) { TotalCpuTime = other.TotalCpuTime; } if (other.IdleCpuTime != 0UL) { IdleCpuTime = other.IdleCpuTime; } if (other.CqPollCount != 0UL) { CqPollCount = other.CqPollCount; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 9: { TimeElapsed = input.ReadDouble(); break; } case 17: { TimeUser = input.ReadDouble(); break; } case 25: { TimeSystem = input.ReadDouble(); break; } case 32: { TotalCpuTime = input.ReadUInt64(); break; } case 40: { IdleCpuTime = input.ReadUInt64(); break; } case 48: { CqPollCount = input.ReadUInt64(); break; } } } } } /// <summary> /// Histogram params based on grpc/support/histogram.c /// </summary> public sealed partial class HistogramParams : pb::IMessage<HistogramParams> { private static readonly pb::MessageParser<HistogramParams> _parser = new pb::MessageParser<HistogramParams>(() => new HistogramParams()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HistogramParams> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HistogramParams() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HistogramParams(HistogramParams other) : this() { resolution_ = other.resolution_; maxPossible_ = other.maxPossible_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HistogramParams Clone() { return new HistogramParams(this); } /// <summary>Field number for the "resolution" field.</summary> public const int ResolutionFieldNumber = 1; private double resolution_; /// <summary> /// first bucket is [0, 1 + resolution) /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Resolution { get { return resolution_; } set { resolution_ = value; } } /// <summary>Field number for the "max_possible" field.</summary> public const int MaxPossibleFieldNumber = 2; private double maxPossible_; /// <summary> /// use enough buckets to allow this value /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double MaxPossible { get { return maxPossible_; } set { maxPossible_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HistogramParams); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HistogramParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Resolution != other.Resolution) return false; if (MaxPossible != other.MaxPossible) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Resolution != 0D) hash ^= Resolution.GetHashCode(); if (MaxPossible != 0D) hash ^= MaxPossible.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 (Resolution != 0D) { output.WriteRawTag(9); output.WriteDouble(Resolution); } if (MaxPossible != 0D) { output.WriteRawTag(17); output.WriteDouble(MaxPossible); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Resolution != 0D) { size += 1 + 8; } if (MaxPossible != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HistogramParams other) { if (other == null) { return; } if (other.Resolution != 0D) { Resolution = other.Resolution; } if (other.MaxPossible != 0D) { MaxPossible = other.MaxPossible; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 9: { Resolution = input.ReadDouble(); break; } case 17: { MaxPossible = input.ReadDouble(); break; } } } } } /// <summary> /// Histogram data based on grpc/support/histogram.c /// </summary> public sealed partial class HistogramData : pb::IMessage<HistogramData> { private static readonly pb::MessageParser<HistogramData> _parser = new pb::MessageParser<HistogramData>(() => new HistogramData()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HistogramData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HistogramData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HistogramData(HistogramData other) : this() { bucket_ = other.bucket_.Clone(); minSeen_ = other.minSeen_; maxSeen_ = other.maxSeen_; sum_ = other.sum_; sumOfSquares_ = other.sumOfSquares_; count_ = other.count_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HistogramData Clone() { return new HistogramData(this); } /// <summary>Field number for the "bucket" field.</summary> public const int BucketFieldNumber = 1; private static readonly pb::FieldCodec<uint> _repeated_bucket_codec = pb::FieldCodec.ForUInt32(10); private readonly pbc::RepeatedField<uint> bucket_ = new pbc::RepeatedField<uint>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<uint> Bucket { get { return bucket_; } } /// <summary>Field number for the "min_seen" field.</summary> public const int MinSeenFieldNumber = 2; private double minSeen_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double MinSeen { get { return minSeen_; } set { minSeen_ = value; } } /// <summary>Field number for the "max_seen" field.</summary> public const int MaxSeenFieldNumber = 3; private double maxSeen_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double MaxSeen { get { return maxSeen_; } set { maxSeen_ = value; } } /// <summary>Field number for the "sum" field.</summary> public const int SumFieldNumber = 4; private double sum_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Sum { get { return sum_; } set { sum_ = value; } } /// <summary>Field number for the "sum_of_squares" field.</summary> public const int SumOfSquaresFieldNumber = 5; private double sumOfSquares_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double SumOfSquares { get { return sumOfSquares_; } set { sumOfSquares_ = value; } } /// <summary>Field number for the "count" field.</summary> public const int CountFieldNumber = 6; private double count_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Count { get { return count_; } set { count_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HistogramData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HistogramData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!bucket_.Equals(other.bucket_)) return false; if (MinSeen != other.MinSeen) return false; if (MaxSeen != other.MaxSeen) return false; if (Sum != other.Sum) return false; if (SumOfSquares != other.SumOfSquares) return false; if (Count != other.Count) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= bucket_.GetHashCode(); if (MinSeen != 0D) hash ^= MinSeen.GetHashCode(); if (MaxSeen != 0D) hash ^= MaxSeen.GetHashCode(); if (Sum != 0D) hash ^= Sum.GetHashCode(); if (SumOfSquares != 0D) hash ^= SumOfSquares.GetHashCode(); if (Count != 0D) hash ^= Count.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) { bucket_.WriteTo(output, _repeated_bucket_codec); if (MinSeen != 0D) { output.WriteRawTag(17); output.WriteDouble(MinSeen); } if (MaxSeen != 0D) { output.WriteRawTag(25); output.WriteDouble(MaxSeen); } if (Sum != 0D) { output.WriteRawTag(33); output.WriteDouble(Sum); } if (SumOfSquares != 0D) { output.WriteRawTag(41); output.WriteDouble(SumOfSquares); } if (Count != 0D) { output.WriteRawTag(49); output.WriteDouble(Count); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += bucket_.CalculateSize(_repeated_bucket_codec); if (MinSeen != 0D) { size += 1 + 8; } if (MaxSeen != 0D) { size += 1 + 8; } if (Sum != 0D) { size += 1 + 8; } if (SumOfSquares != 0D) { size += 1 + 8; } if (Count != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HistogramData other) { if (other == null) { return; } bucket_.Add(other.bucket_); if (other.MinSeen != 0D) { MinSeen = other.MinSeen; } if (other.MaxSeen != 0D) { MaxSeen = other.MaxSeen; } if (other.Sum != 0D) { Sum = other.Sum; } if (other.SumOfSquares != 0D) { SumOfSquares = other.SumOfSquares; } if (other.Count != 0D) { Count = other.Count; } } [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: case 8: { bucket_.AddEntriesFrom(input, _repeated_bucket_codec); break; } case 17: { MinSeen = input.ReadDouble(); break; } case 25: { MaxSeen = input.ReadDouble(); break; } case 33: { Sum = input.ReadDouble(); break; } case 41: { SumOfSquares = input.ReadDouble(); break; } case 49: { Count = input.ReadDouble(); break; } } } } } public sealed partial class RequestResultCount : pb::IMessage<RequestResultCount> { private static readonly pb::MessageParser<RequestResultCount> _parser = new pb::MessageParser<RequestResultCount>(() => new RequestResultCount()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RequestResultCount> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestResultCount() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestResultCount(RequestResultCount other) : this() { statusCode_ = other.statusCode_; count_ = other.count_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestResultCount Clone() { return new RequestResultCount(this); } /// <summary>Field number for the "status_code" field.</summary> public const int StatusCodeFieldNumber = 1; private int statusCode_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int StatusCode { get { return statusCode_; } set { statusCode_ = value; } } /// <summary>Field number for the "count" field.</summary> public const int CountFieldNumber = 2; private long count_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Count { get { return count_; } set { count_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RequestResultCount); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RequestResultCount other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (StatusCode != other.StatusCode) return false; if (Count != other.Count) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (StatusCode != 0) hash ^= StatusCode.GetHashCode(); if (Count != 0L) hash ^= Count.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 (StatusCode != 0) { output.WriteRawTag(8); output.WriteInt32(StatusCode); } if (Count != 0L) { output.WriteRawTag(16); output.WriteInt64(Count); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (StatusCode != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(StatusCode); } if (Count != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RequestResultCount other) { if (other == null) { return; } if (other.StatusCode != 0) { StatusCode = other.StatusCode; } if (other.Count != 0L) { Count = other.Count; } } [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: { StatusCode = input.ReadInt32(); break; } case 16: { Count = input.ReadInt64(); break; } } } } } public sealed partial class ClientStats : pb::IMessage<ClientStats> { private static readonly pb::MessageParser<ClientStats> _parser = new pb::MessageParser<ClientStats>(() => new ClientStats()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ClientStats> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ClientStats() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ClientStats(ClientStats other) : this() { Latencies = other.latencies_ != null ? other.Latencies.Clone() : null; timeElapsed_ = other.timeElapsed_; timeUser_ = other.timeUser_; timeSystem_ = other.timeSystem_; requestResults_ = other.requestResults_.Clone(); cqPollCount_ = other.cqPollCount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ClientStats Clone() { return new ClientStats(this); } /// <summary>Field number for the "latencies" field.</summary> public const int LatenciesFieldNumber = 1; private global::Grpc.Testing.HistogramData latencies_; /// <summary> /// Latency histogram. Data points are in nanoseconds. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Grpc.Testing.HistogramData Latencies { get { return latencies_; } set { latencies_ = value; } } /// <summary>Field number for the "time_elapsed" field.</summary> public const int TimeElapsedFieldNumber = 2; private double timeElapsed_; /// <summary> /// See ServerStats for details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double TimeElapsed { get { return timeElapsed_; } set { timeElapsed_ = value; } } /// <summary>Field number for the "time_user" field.</summary> public const int TimeUserFieldNumber = 3; private double timeUser_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double TimeUser { get { return timeUser_; } set { timeUser_ = value; } } /// <summary>Field number for the "time_system" field.</summary> public const int TimeSystemFieldNumber = 4; private double timeSystem_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double TimeSystem { get { return timeSystem_; } set { timeSystem_ = value; } } /// <summary>Field number for the "request_results" field.</summary> public const int RequestResultsFieldNumber = 5; private static readonly pb::FieldCodec<global::Grpc.Testing.RequestResultCount> _repeated_requestResults_codec = pb::FieldCodec.ForMessage(42, global::Grpc.Testing.RequestResultCount.Parser); private readonly pbc::RepeatedField<global::Grpc.Testing.RequestResultCount> requestResults_ = new pbc::RepeatedField<global::Grpc.Testing.RequestResultCount>(); /// <summary> /// Number of failed requests (one row per status code seen) /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Grpc.Testing.RequestResultCount> RequestResults { get { return requestResults_; } } /// <summary>Field number for the "cq_poll_count" field.</summary> public const int CqPollCountFieldNumber = 6; private ulong cqPollCount_; /// <summary> /// Number of polls called inside completion queue /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong CqPollCount { get { return cqPollCount_; } set { cqPollCount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ClientStats); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ClientStats other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Latencies, other.Latencies)) return false; if (TimeElapsed != other.TimeElapsed) return false; if (TimeUser != other.TimeUser) return false; if (TimeSystem != other.TimeSystem) return false; if(!requestResults_.Equals(other.requestResults_)) return false; if (CqPollCount != other.CqPollCount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (latencies_ != null) hash ^= Latencies.GetHashCode(); if (TimeElapsed != 0D) hash ^= TimeElapsed.GetHashCode(); if (TimeUser != 0D) hash ^= TimeUser.GetHashCode(); if (TimeSystem != 0D) hash ^= TimeSystem.GetHashCode(); hash ^= requestResults_.GetHashCode(); if (CqPollCount != 0UL) hash ^= CqPollCount.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 (latencies_ != null) { output.WriteRawTag(10); output.WriteMessage(Latencies); } if (TimeElapsed != 0D) { output.WriteRawTag(17); output.WriteDouble(TimeElapsed); } if (TimeUser != 0D) { output.WriteRawTag(25); output.WriteDouble(TimeUser); } if (TimeSystem != 0D) { output.WriteRawTag(33); output.WriteDouble(TimeSystem); } requestResults_.WriteTo(output, _repeated_requestResults_codec); if (CqPollCount != 0UL) { output.WriteRawTag(48); output.WriteUInt64(CqPollCount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (latencies_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Latencies); } if (TimeElapsed != 0D) { size += 1 + 8; } if (TimeUser != 0D) { size += 1 + 8; } if (TimeSystem != 0D) { size += 1 + 8; } size += requestResults_.CalculateSize(_repeated_requestResults_codec); if (CqPollCount != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(CqPollCount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ClientStats other) { if (other == null) { return; } if (other.latencies_ != null) { if (latencies_ == null) { latencies_ = new global::Grpc.Testing.HistogramData(); } Latencies.MergeFrom(other.Latencies); } if (other.TimeElapsed != 0D) { TimeElapsed = other.TimeElapsed; } if (other.TimeUser != 0D) { TimeUser = other.TimeUser; } if (other.TimeSystem != 0D) { TimeSystem = other.TimeSystem; } requestResults_.Add(other.requestResults_); if (other.CqPollCount != 0UL) { CqPollCount = other.CqPollCount; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (latencies_ == null) { latencies_ = new global::Grpc.Testing.HistogramData(); } input.ReadMessage(latencies_); break; } case 17: { TimeElapsed = input.ReadDouble(); break; } case 25: { TimeUser = input.ReadDouble(); break; } case 33: { TimeSystem = input.ReadDouble(); break; } case 42: { requestResults_.AddEntriesFrom(input, _repeated_requestResults_codec); break; } case 48: { CqPollCount = input.ReadUInt64(); break; } } } } } #endregion } #endregion Designer generated code
namespace Humidifier.CodePipeline { using System.Collections.Generic; using PipelineTypes; public class Pipeline : Humidifier.Resource { public static class Attributes { public static string Version = "Version" ; } public override string AWSTypeName { get { return @"AWS::CodePipeline::Pipeline"; } } /// <summary> /// ArtifactStore /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstore /// Required: False /// UpdateType: Mutable /// Type: ArtifactStore /// </summary> public ArtifactStore ArtifactStore { get; set; } /// <summary> /// ArtifactStores /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstores /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: ArtifactStoreMap /// </summary> public List<ArtifactStoreMap> ArtifactStores { get; set; } /// <summary> /// DisableInboundStageTransitions /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-disableinboundstagetransitions /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: StageTransition /// </summary> public List<StageTransition> DisableInboundStageTransitions { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-name /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } /// <summary> /// RestartExecutionOnUpdate /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-restartexecutiononupdate /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic RestartExecutionOnUpdate { get; set; } /// <summary> /// RoleArn /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-rolearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RoleArn { get; set; } /// <summary> /// Stages /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-stages /// Required: True /// UpdateType: Mutable /// Type: List /// ItemType: StageDeclaration /// </summary> public List<StageDeclaration> Stages { get; set; } /// <summary> /// Tags /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-tags /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Tag /// </summary> public List<Tag> Tags { get; set; } } namespace PipelineTypes { public class InputArtifact { /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-inputartifacts.html#cfn-codepipeline-pipeline-stages-actions-inputartifacts-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } } public class BlockerDeclaration { /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html#cfn-codepipeline-pipeline-stages-blockers-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html#cfn-codepipeline-pipeline-stages-blockers-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } } public class ArtifactStoreMap { /// <summary> /// ArtifactStore /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstoremap.html#cfn-codepipeline-pipeline-artifactstoremap-artifactstore /// Required: True /// UpdateType: Mutable /// Type: ArtifactStore /// </summary> public ArtifactStore ArtifactStore { get; set; } /// <summary> /// Region /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstoremap.html#cfn-codepipeline-pipeline-artifactstoremap-region /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Region { get; set; } } public class OutputArtifact { /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-outputartifacts.html#cfn-codepipeline-pipeline-stages-actions-outputartifacts-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } } public class EncryptionKey { /// <summary> /// Id /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey-id /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Id { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } } public class ActionDeclaration { /// <summary> /// ActionTypeId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid /// Required: True /// UpdateType: Mutable /// Type: ActionTypeId /// </summary> public ActionTypeId ActionTypeId { get; set; } /// <summary> /// Configuration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-configuration /// Required: False /// UpdateType: Mutable /// PrimitiveType: Json /// </summary> public dynamic Configuration { get; set; } /// <summary> /// InputArtifacts /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-inputartifacts /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: InputArtifact /// </summary> public List<InputArtifact> InputArtifacts { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } /// <summary> /// Namespace /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-actiondeclaration-namespace /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Namespace { get; set; } /// <summary> /// OutputArtifacts /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-outputartifacts /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: OutputArtifact /// </summary> public List<OutputArtifact> OutputArtifacts { get; set; } /// <summary> /// Region /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-region /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Region { get; set; } /// <summary> /// RoleArn /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-rolearn /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RoleArn { get; set; } /// <summary> /// RunOrder /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-runorder /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic RunOrder { get; set; } } public class StageDeclaration { /// <summary> /// Actions /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-actions /// Required: True /// UpdateType: Mutable /// Type: List /// ItemType: ActionDeclaration /// </summary> public List<ActionDeclaration> Actions { get; set; } /// <summary> /// Blockers /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-blockers /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: BlockerDeclaration /// </summary> public List<BlockerDeclaration> Blockers { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } } public class StageTransition { /// <summary> /// Reason /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html#cfn-codepipeline-pipeline-disableinboundstagetransitions-reason /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Reason { get; set; } /// <summary> /// StageName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html#cfn-codepipeline-pipeline-disableinboundstagetransitions-stagename /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic StageName { get; set; } } public class ArtifactStore { /// <summary> /// EncryptionKey /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey /// Required: False /// UpdateType: Mutable /// Type: EncryptionKey /// </summary> public EncryptionKey EncryptionKey { get; set; } /// <summary> /// Location /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-location /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Location { get; set; } /// <summary> /// Type /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-type /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Type { get; set; } } public class ActionTypeId { /// <summary> /// Category /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-category /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Category { get; set; } /// <summary> /// Owner /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-owner /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Owner { get; set; } /// <summary> /// Provider /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-provider /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Provider { get; set; } /// <summary> /// Version /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-version /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Version { get; set; } } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Diagnostics; using SharpDX.Mathematics.Interop; namespace SharpDX.Direct3D10 { public partial class EffectVectorVariable { private const string VectorInvalidSize = "Invalid Vector size: Must be 16 bytes or 4 x 4 bytes"; /// <summary> /// Get a four-component vector that contains integer data. /// </summary> /// <returns>Returns a four-component vector that contains integer data </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetIntVector([Out] int* pData)</unmanaged> public RawInt4 GetIntVector() { RawInt4 temp; GetIntVector(out temp); return temp; } /// <summary> /// Get a four-component vector that contains floating-point data. /// </summary> /// <returns>Returns a four-component vector that contains floating-point data.</returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetFloatVector([Out] float* pData)</unmanaged> public RawVector4 GetFloatVector() { RawVector4 temp; GetFloatVector(out temp); return temp; } /// <summary> /// Get a four-component vector that contains boolean data. /// </summary> /// <returns>a four-component vector that contains boolean data. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetBoolVector([Out, Buffer] BOOL* pData)</unmanaged> public RawBool4 GetBoolVector() { RawBool4 temp; GetBoolVector(out temp); return temp; } /// <summary> /// Get a four-component vector. /// </summary> /// <typeparam name="T">Type of the four-component vector</typeparam> /// <returns>a four-component vector. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetFloatVector([Out, Buffer] BOOL* pData)</unmanaged> public unsafe T GetVector<T>() where T : struct { T temp; GetIntVector(out *(RawInt4*)Interop.CastOut(out temp)); return temp; } /// <summary> /// Set an array of four-component vectors that contain integer data. /// </summary> /// <param name="array">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetIntVectorArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(RawInt4[] array) { Set(array, 0, array.Length); } /// <summary> /// Set an array of four-component vectors that contain floating-point data. /// </summary> /// <param name="array">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(RawVector4[] array) { Set(array, 0, array.Length); } /// <summary> /// Set an array of four-component vectors that contain floating-point data. /// </summary> /// <typeparam name="T">Type of the four-component vector</typeparam> /// <param name="array">A reference to the start of the data to set.</param> /// <returns> /// Returns one of the following {{Direct3D 10 Return Codes}}. /// </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set<T>(T[] array) where T : struct { if (Utilities.SizeOf<T>() != 16) throw new ArgumentException(VectorInvalidSize, "array"); Set(Interop.CastArray<RawVector4, T>(array), 0, array.Length); } /// <summary> /// Set a x-component vector. /// </summary> /// <param name="value">A reference to the first component. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged> public void Set<T>(T value) where T : struct { Set(ref value); } /// <summary> /// Set a x-component vector. /// </summary> /// <param name="value">A reference to the first component. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged> public unsafe void Set<T>(ref T value) where T : struct { if (Utilities.SizeOf<T>() != 16) throw new ArgumentException(VectorInvalidSize, "value"); SetRawValue(new IntPtr(Interop.Fixed(ref value)), 0, Utilities.SizeOf<T>()); } /// <summary> /// Set a two-component vector that contains floating-point data. /// </summary> /// <param name="value">A reference to the first component. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged> public void Set(RawVector2 value) { unsafe { SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<RawVector2>()); } } /// <summary> /// Set a three-component vector that contains floating-point data. /// </summary> /// <param name="value">A reference to the first component. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged> public void Set(RawVector3 value) { unsafe { SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<RawVector3>()); } } /// <summary> /// Set a four-component color that contains floating-point data. /// </summary> /// <param name="value">A reference to the first component. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVector([In] float* pData)</unmanaged> public void Set(RawColor4 value) { unsafe { SetRawValue(new IntPtr(&value), 0, Utilities.SizeOf<RawColor4>()); } } /// <summary> /// Set an array of four-component color that contain floating-point data. /// </summary> /// <param name="array">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::SetFloatVectorArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(RawColor4[] array) { unsafe { fixed (void* pArray = &array[0]) SetRawValue((IntPtr)pArray, 0, array.Length * Utilities.SizeOf<RawColor4>()); } } /// <summary> /// Get an array of four-component vectors that contain integer data. /// </summary> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns an array of four-component vectors that contain integer data. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetIntVectorArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public RawInt4[] GetIntVectorArray(int count) { var temp = new RawInt4[count]; GetIntVectorArray(temp, 0, count); return temp; } /// <summary> /// Get an array of four-component vectors that contain floating-point data. /// </summary> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns an array of four-component vectors that contain floating-point data. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetFloatVectorArray([None] float* pData,[None] int Offset,[None] int Count)</unmanaged> public RawVector4[] GetFloatVectorArray(int count) { var temp = new RawVector4[count]; GetFloatVectorArray(temp, 0, count); return temp; } /// <summary> /// Get an array of four-component vectors that contain boolean data. /// </summary> /// <param name="count">The number of array elements to set. </param> /// <returns>an array of four-component vectors that contain boolean data. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetBoolVectorArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged> public RawBool4[] GetBoolVectorArray(int count) { var temp = new RawBool4[count]; GetBoolVectorArray(temp, 0, count); return temp; } /// <summary> /// Get an array of four-component vectors that contain boolean data. /// </summary> /// <param name="count">The number of array elements to set. </param> /// <returns>an array of four-component vectors that contain boolean data. </returns> /// <unmanaged>HRESULT ID3D10EffectVectorVariable::GetBoolVectorArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged> public T[] GetVectorArray<T>(int count) where T : struct { var temp = new T[count]; GetIntVectorArray(Interop.CastArray<RawInt4, T>(temp), 0, count); return temp; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Serialization.TypeSystem; using Orleans.TestingHost; using Tester; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; namespace UnitTests.ActivationsLifeCycleTests { public class ActivationCollectorTests : OrleansTestingBase, IAsyncLifetime { private static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromSeconds(10); private static readonly TimeSpan DEFAULT_IDLE_TIMEOUT = DEFAULT_COLLECTION_QUANTUM + TimeSpan.FromSeconds(1); private static readonly TimeSpan WAIT_TIME = DEFAULT_IDLE_TIMEOUT.Multiply(3.0); private TestCluster testCluster; private ILogger logger; private async Task Initialize(TimeSpan collectionAgeLimit, TimeSpan quantum) { var builder = new TestClusterBuilder(1); builder.Properties["CollectionQuantum"] = quantum.ToString(); builder.Properties["DefaultCollectionAgeLimit"] = collectionAgeLimit.ToString(); builder.AddSiloBuilderConfigurator<SiloConfigurator>(); testCluster = builder.Build(); await testCluster.DeployAsync(); this.logger = this.testCluster.Client.ServiceProvider.GetRequiredService<ILogger<ActivationCollectorTests>>(); } public class SiloConfigurator : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { var config = hostBuilder.GetConfiguration(); var collectionAgeLimit = TimeSpan.Parse(config["DefaultCollectionAgeLimit"]); var quantum = TimeSpan.Parse(config["CollectionQuantum"]); hostBuilder .ConfigureDefaults() .ConfigureServices(services => services.Where(s => s.ServiceType == typeof(IConfigurationValidator)).ToList().ForEach(s => services.Remove(s))); hostBuilder.Configure<GrainCollectionOptions>(options => { options.CollectionAge = collectionAgeLimit; options.CollectionQuantum = quantum; options.ClassSpecificCollectionAge = new Dictionary<string, TimeSpan> { [typeof(IdleActivationGcTestGrain2).FullName] = DEFAULT_IDLE_TIMEOUT, [typeof(BusyActivationGcTestGrain2).FullName] = DEFAULT_IDLE_TIMEOUT, [typeof(CollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain).FullName] = TimeSpan.FromSeconds(12), }; }); } } Task IAsyncLifetime.InitializeAsync() => Task.CompletedTask; private async Task Initialize(TimeSpan collectionAgeLimit) { await Initialize(collectionAgeLimit, DEFAULT_COLLECTION_QUANTUM); } public async Task DisposeAsync() { if (testCluster is null) return; try { await testCluster.StopAllSilosAsync(); } finally { await testCluster.DisposeAsync(); testCluster = null; } } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorForceCollection() { await Initialize(DEFAULT_IDLE_TIMEOUT); const int grainCount = 1000; var fullGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain1)); List<Task> tasks = new List<Task>(); logger.Info("ActivationCollectorForceCollection: activating {0} grains.", grainCount); for (var i = 0; i < grainCount; ++i) { IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid()); tasks.Add(g.Nop()); } await Task.WhenAll(tasks); await Task.Delay(TimeSpan.FromSeconds(5)); var grain = this.testCluster.GrainFactory.GetGrain<IManagementGrain>(0); await grain.ForceActivationCollection(TimeSpan.FromSeconds(4)); int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(0, activationsNotCollected); await grain.ForceActivationCollection(TimeSpan.FromSeconds(4)); } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorShouldCollectIdleActivations() { await Initialize(DEFAULT_IDLE_TIMEOUT); const int grainCount = 1000; var fullGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain1)); List<Task> tasks = new List<Task>(); logger.Info("IdleActivationCollectorShouldCollectIdleActivations: activating {0} grains.", grainCount); for (var i = 0; i < grainCount; ++i) { IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid()); tasks.Add(g.Nop()); } await Task.WhenAll(tasks); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(grainCount, activationsCreated); logger.Info("IdleActivationCollectorShouldCollectIdleActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(0, activationsNotCollected); } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorShouldNotCollectBusyActivations() { await Initialize(DEFAULT_IDLE_TIMEOUT); const int idleGrainCount = 500; const int busyGrainCount = 500; var idleGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain1)); var busyGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(BusyActivationGcTestGrain1)); List<Task> tasks0 = new List<Task>(); List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>(); logger.Info("ActivationCollectorShouldNotCollectBusyActivations: activating {0} busy grains.", busyGrainCount); for (var i = 0; i < busyGrainCount; ++i) { IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid()); busyGrains.Add(g); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); bool[] quit = new bool[]{ false }; Func<Task> busyWorker = async () => { logger.Info("ActivationCollectorShouldNotCollectBusyActivations: busyWorker started"); List<Task> tasks1 = new List<Task>(); while (!quit[0]) { foreach (var g in busyGrains) tasks1.Add(g.Nop()); await Task.WhenAll(tasks1); } }; Task.Run(busyWorker).Ignore(); logger.Info("ActivationCollectorShouldNotCollectBusyActivations: activating {0} idle grains.", idleGrainCount); tasks0.Clear(); for (var i = 0; i < idleGrainCount; ++i) { IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid()); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated); logger.Info("ActivationCollectorShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); // we should have only collected grains from the idle category (IdleActivationGcTestGrain1). int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName); int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(0, idleActivationsNotCollected); Assert.Equal(busyGrainCount, busyActivationsNotCollected); quit[0] = true; } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ManualCollectionShouldNotCollectBusyActivations() { await Initialize(DEFAULT_IDLE_TIMEOUT); TimeSpan shortIdleTimeout = TimeSpan.FromSeconds(1); const int idleGrainCount = 500; const int busyGrainCount = 500; var idleGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain1)); var busyGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(BusyActivationGcTestGrain1)); List<Task> tasks0 = new List<Task>(); List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>(); logger.Info("ManualCollectionShouldNotCollectBusyActivations: activating {0} busy grains.", busyGrainCount); for (var i = 0; i < busyGrainCount; ++i) { IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid()); busyGrains.Add(g); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); bool[] quit = new bool[]{ false }; Func<Task> busyWorker = async () => { logger.Info("ManualCollectionShouldNotCollectBusyActivations: busyWorker started"); List<Task> tasks1 = new List<Task>(); while (!quit[0]) { foreach (var g in busyGrains) tasks1.Add(g.Nop()); await Task.WhenAll(tasks1); } }; Task.Run(busyWorker).Ignore(); logger.Info("ManualCollectionShouldNotCollectBusyActivations: activating {0} idle grains.", idleGrainCount); tasks0.Clear(); for (var i = 0; i < idleGrainCount; ++i) { IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid()); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated); logger.Info("ManualCollectionShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", shortIdleTimeout.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(shortIdleTimeout); TimeSpan everything = TimeSpan.FromMinutes(10); logger.Info("ManualCollectionShouldNotCollectBusyActivations: triggering manual collection (timespan is {0} sec).", everything.TotalSeconds); IManagementGrain mgmtGrain = this.testCluster.GrainFactory.GetGrain<IManagementGrain>(0); await mgmtGrain.ForceActivationCollection(everything); logger.Info("ManualCollectionShouldNotCollectBusyActivations: waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); // we should have only collected grains from the idle category (IdleActivationGcTestGrain). int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName); int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(0, idleActivationsNotCollected); Assert.Equal(busyGrainCount, busyActivationsNotCollected); quit[0] = true; } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration() { //make sure default value won't cause activation collection during wait time var defaultCollectionAgeLimit = WAIT_TIME.Multiply(2); await Initialize(defaultCollectionAgeLimit); const int grainCount = 1000; var fullGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain2)); List<Task> tasks = new List<Task>(); logger.Info("ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration: activating {0} grains.", grainCount); for (var i = 0; i < grainCount; ++i) { IIdleActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain2>(Guid.NewGuid()); tasks.Add(g.Nop()); } await Task.WhenAll(tasks); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(grainCount, activationsCreated); logger.Info("ActivationCollectorShouldCollectIdleActivationsSpecifiedInPerTypeConfiguration: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(0, activationsNotCollected); } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration() { //make sure default value won't cause activation collection during wait time var defaultCollectionAgeLimit = WAIT_TIME.Multiply(2); await Initialize(defaultCollectionAgeLimit); const int idleGrainCount = 500; const int busyGrainCount = 500; var idleGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain2)); var busyGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(BusyActivationGcTestGrain2)); List<Task> tasks0 = new List<Task>(); List<IBusyActivationGcTestGrain2> busyGrains = new List<IBusyActivationGcTestGrain2>(); logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: activating {0} busy grains.", busyGrainCount); for (var i = 0; i < busyGrainCount; ++i) { IBusyActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain2>(Guid.NewGuid()); busyGrains.Add(g); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); bool[] quit = new bool[]{ false }; Func<Task> busyWorker = async () => { logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: busyWorker started"); List<Task> tasks1 = new List<Task>(); while (!quit[0]) { foreach (var g in busyGrains) tasks1.Add(g.Nop()); await Task.WhenAll(tasks1); } }; Task.Run(busyWorker).Ignore(); logger.Info("ActivationCollectorShouldNotCollectBusyActivationsSpecifiedInPerTypeConfiguration: activating {0} idle grains.", idleGrainCount); tasks0.Clear(); for (var i = 0; i < idleGrainCount; ++i) { IIdleActivationGcTestGrain2 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain2>(Guid.NewGuid()); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated); logger.Info("IdleActivationCollectorShouldNotCollectBusyActivations: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); // we should have only collected grains from the idle category (IdleActivationGcTestGrain2). int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName); int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(0, idleActivationsNotCollected); Assert.Equal(busyGrainCount, busyActivationsNotCollected); quit[0] = true; } [Fact(Skip = "Flaky test. Needs to be investigated."), TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorShouldNotCollectBusyStatelessWorkers() { await Initialize(DEFAULT_IDLE_TIMEOUT); // the purpose of this test is to determine whether idle stateless worker activations are properly identified by the activation collector. // in this test, we: // // 1. setup the test. // 2. activate a set of grains by sending a burst of messages to each one. the purpose of the burst is to ensure that multiple activations are used. // 3. verify that multiple activations for each grain have been created. // 4. periodically send a message to each grain, ensuring that only one activation remains busy. each time we check the activation id and compare it against the activation id returned by the previous grain call. initially, these may not be identical but as the other activations become idle and are collected, there will be only one activation servicing these calls. // 5. wait long enough for idle activations to be collected. // 6. verify that only one activation is still active per grain. // 7. ensure that test steps 2-6 are repeatable. const int grainCount = 1; var grainTypeName = RuntimeTypeNameFormatter.Format(typeof(StatelessWorkerActivationCollectorTestGrain1)); const int burstLength = 1000; List<Task> tasks0 = new List<Task>(); List<IStatelessWorkerActivationCollectorTestGrain1> grains = new List<IStatelessWorkerActivationCollectorTestGrain1>(); for (var i = 0; i < grainCount; ++i) { IStatelessWorkerActivationCollectorTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IStatelessWorkerActivationCollectorTestGrain1>(Guid.NewGuid()); grains.Add(g); } bool[] quit = new bool[] { false }; bool[] matched = new bool[grainCount]; string[] activationIds = new string[grainCount]; Func<int, Task> workFunc = async index => { // (part of) 4. periodically send a message to each grain... // take a grain and call Delay to keep it busy. IStatelessWorkerActivationCollectorTestGrain1 g = grains[index]; await g.Delay(DEFAULT_IDLE_TIMEOUT.Divide(2)); // identify the activation and record whether it matches the activation ID last reported. it probably won't match in the beginning but should always converge on a match as other activations get collected. string aid = await g.IdentifyActivation(); logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: identified {0}", aid); matched[index] = aid == activationIds[index]; activationIds[index] = aid; }; Func<Task> workerFunc = async () => { // (part of) 4. periodically send a message to each grain... logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: busyWorker started"); List<Task> tasks1 = new List<Task>(); while (!quit[0]) { for (int index = 0; index < grains.Count; ++index) { if (quit[0]) { break; } tasks1.Add(workFunc(index)); } await Task.WhenAll(tasks1); } }; // setup (1) ends here. for (int i = 0; i < 2; ++i) { // 2. activate a set of grains... this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: activating {0} stateless worker grains (run #{1}).", grainCount, i); foreach (var g in grains) { for (int j = 0; j < burstLength; ++j) { // having the activation delay will ensure that one activation cannot serve all requests that we send to it, making it so that additional activations will be created. tasks0.Add(g.Delay(TimeSpan.FromMilliseconds(10))); } } await Task.WhenAll(tasks0); // 3. verify that multiple activations for each grain have been created. int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, grainTypeName); Assert.True(activationsCreated > grainCount, string.Format("more than {0} activations should have been created; got {1} instead", grainCount, activationsCreated)); // 4. periodically send a message to each grain... this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: grains activated; sending heartbeat to {0} stateless worker grains.", grainCount); Task workerTask = Task.Run(workerFunc); // 5. wait long enough for idle activations to be collected. this.logger.Info("ActivationCollectorShouldNotCollectBusyStatelessWorkers: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); // 6. verify that only one activation is still active per grain. int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, grainTypeName); // signal that the worker task should stop and wait for it to finish. quit[0] = true; await workerTask; quit[0] = false; Assert.Equal(grainCount, busyActivationsNotCollected); // verify that we matched activation ids in the final iteration of step 4's loop. for (int index = 0; index < grains.Count; ++index) { Assert.True(matched[index], string.Format("activation ID of final subsequent heartbeats did not match for grain {0}", grains[index])); } } } [Fact, TestCategory("ActivationCollector"), TestCategory("Performance"), TestCategory("CorePerf")] public async Task ActivationCollectorShouldNotCauseMessageLoss() { await Initialize(DEFAULT_IDLE_TIMEOUT); const int idleGrainCount = 0; const int busyGrainCount = 500; var idleGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(IdleActivationGcTestGrain1)); var busyGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(BusyActivationGcTestGrain1)); const int burstCount = 100; List<Task> tasks0 = new List<Task>(); List<IBusyActivationGcTestGrain1> busyGrains = new List<IBusyActivationGcTestGrain1>(); logger.Info("ActivationCollectorShouldNotCauseMessageLoss: activating {0} busy grains.", busyGrainCount); for (var i = 0; i < busyGrainCount; ++i) { IBusyActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IBusyActivationGcTestGrain1>(Guid.NewGuid()); busyGrains.Add(g); tasks0.Add(g.Nop()); } await busyGrains[0].EnableBurstOnCollection(burstCount); logger.Info("ActivationCollectorShouldNotCauseMessageLoss: activating {0} idle grains.", idleGrainCount); tasks0.Clear(); for (var i = 0; i < idleGrainCount; ++i) { IIdleActivationGcTestGrain1 g = this.testCluster.GrainFactory.GetGrain<IIdleActivationGcTestGrain1>(Guid.NewGuid()); tasks0.Add(g.Nop()); } await Task.WhenAll(tasks0); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName) + await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(idleGrainCount + busyGrainCount, activationsCreated); logger.Info("ActivationCollectorShouldNotCauseMessageLoss: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); await Task.Delay(WAIT_TIME); // we should have only collected grains from the idle category (IdleActivationGcTestGrain1). int idleActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, idleGrainTypeName); int busyActivationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, busyGrainTypeName); Assert.Equal(0, idleActivationsNotCollected); Assert.Equal(busyGrainCount, busyActivationsNotCollected); } [Fact, TestCategory("ActivationCollector"), TestCategory("Functional")] public async Task ActivationCollectorShouldCollectByCollectionSpecificAgeLimitForTwelveSeconds() { var waitTime = TimeSpan.FromSeconds(30); var defaultCollectionAge = waitTime.Multiply(2); //make sure defaultCollectionAge value won't cause activation collection in wait time await Initialize(defaultCollectionAge); const int grainCount = 1000; // CollectionAgeLimit = 12 seconds var fullGrainTypeName = RuntimeTypeNameFormatter.Format(typeof(CollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain)); List<Task> tasks = new List<Task>(); logger.Info("ActivationCollectorShouldCollectByCollectionSpecificAgeLimit: activating {0} grains.", grainCount); for (var i = 0; i < grainCount; ++i) { ICollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain g = this.testCluster.GrainFactory.GetGrain<ICollectionSpecificAgeLimitForTenSecondsActivationGcTestGrain>(Guid.NewGuid()); tasks.Add(g.Nop()); } await Task.WhenAll(tasks); int activationsCreated = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(grainCount, activationsCreated); logger.Info("ActivationCollectorShouldCollectByCollectionSpecificAgeLimit: grains activated; waiting {0} sec (activation GC idle timeout is {1} sec).", WAIT_TIME.TotalSeconds, DEFAULT_IDLE_TIMEOUT.TotalSeconds); // Some time is required for GC to collect all of the Grains) await Task.Delay(waitTime); int activationsNotCollected = await TestUtils.GetActivationCount(this.testCluster.GrainFactory, fullGrainTypeName); Assert.Equal(0, activationsNotCollected); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Srclib.Nuget { ///<summary> ///Nuget cannot load a package only if both ///name and version are provided, while visual studio configuration files ///hold only dependency name. So this class holds a name->version map for top several ///hundred most popular nuget packages ///Generated based on https://www.nuget.org/stats/packageversions ///</summary> public class PackageVersions { private Dictionary<string, string> versions; public PackageVersions() { versions = new Dictionary<string, string>() { { "microsoft.web.infrastructure", "1.0.0" }, { "entityframework", "6.1.3" }, { "newtonsoft.json", "8.0.2" }, { "microsoft.aspnet.webapi.client", "5.2.3" }, { "microsoft.aspnet.webpages", "3.2.3" }, { "microsoft.aspnet.mvc", "5.2.3" }, { "microsoft.aspnet.razor", "3.2.3" }, { "owin", "1.0.0" }, { "microsoft.aspnet.webapi.core", "5.2.3" }, { "microsoft.aspnet.web.optimization", "1.1.3" }, { "microsoft.aspnet.webapi.webhost", "5.2.3" }, { "microsoft.owin", "3.0.1" }, { "microsoft.aspnet.webapi", "5.2.3" }, { "system.collections", "4.0.10" }, { "system.resources.resourcemanager", "4.0.0" }, { "system.runtime", "4.0.20" }, { "microsoft.owin.host.systemweb", "3.0.1" }, { "antlr", "3.4.1.9004" }, { "microsoft.owin.security", "3.0.1" }, { "system.threading", "4.0.10" }, { "system.reflection.primitives", "4.0.0" }, { "system.threading.tasks", "4.0.10" }, { "system.io", "4.0.10" }, { "system.private.uri", "4.0.0" }, { "webgrease", "1.5.2" }, { "system.reflection.extensions", "4.0.0" }, { "system.text.encoding", "4.0.10" }, { "system.io.filesystem.primitives", "4.0.0" }, { "system.reflection", "4.0.0" }, { "system.text.encoding.extensions", "4.0.10" }, { "system.globalization", "4.0.0" }, { "system.diagnostics.tracing", "4.0.20" }, { "system.diagnostics.debug", "4.0.0" }, { "system.runtime.extensions", "4.0.10" }, { "system.io.filesystem", "4.0.0" }, { "modernizr", "2.6.2" }, { "system.runtime.handles", "4.0.0" }, { "microsoft.bcl", "1.1.10" }, { "system.linq.expressions", "4.0.10" }, { "microsoft.owin.security.oauth", "3.0.1" }, { "system.runtime.interopservices", "4.0.20" }, { "system.threading.overlapped", "4.0.0" }, { "microsoft.net.http", "2.2.29" }, { "jquery", "1.10.2" }, { "system.reflection.typeextensions", "4.0.0" }, { "system.globalization.calendars", "4.0.0" }, { "microsoft.aspnet.identity.core", "2.2.1" }, { "microsoft.owin.security.cookies", "3.0.1" }, { "system.objectmodel", "4.0.10" }, { "microsoft.bcl.build", "1.0.21" }, { "system.reflection.emit.ilgeneration", "4.0.0" }, { "system.reflection.emit", "4.0.0" }, { "microsoft.jquery.unobtrusive.validation", "3.2.3" }, { "system.linq", "4.0.0" }, { "microsoft.win32.primitives", "4.0.0" }, { "system.reflection.emit.lightweight", "4.0.0" }, { "bootstrap", "3.0.0" }, { "system.collections.nongeneric", "4.0.0" }, { "microsoft.aspnet.identity.owin", "2.2.1" }, { "respond", "1.2.0" }, { "system.runtime.numerics", "4.0.0" }, { "moq", "4.2.1510.2205" }, { "jquery.validation", "1.11.1" }, { "microsoft.net.compilers", "1.0.0" }, { "xunit.abstractions", "2.0.0" }, { "system.collections.immutable", "1.1.37" }, { "system.diagnostics.tools", "4.0.0" }, { "system.text.regularexpressions", "4.0.10" }, { "commonservicelocator", "1.3.0" }, { "microsoft.bcl.async", "1.0.168" }, { "microsoft.aspnet.identity.entityframework", "2.2.1" }, { "nunit", "2.6.4" }, { "xunit.extensibility.execution", "2.1.0" }, { "system.security.principal", "4.0.0" }, { "xunit.core", "2.1.0" }, { "microsoft.aspnet.webapi.owin", "5.2.3" }, { "xunit.extensibility.core", "2.1.0" }, { "microsoft.codedom.providers.dotnetcompilerplatform", "1.0.0" }, { "microsoft.azure.keyvault.core", "1.0.0" }, { "microsoft.data.odata", "5.6.4" }, { "system.collections.concurrent", "4.0.10" }, { "microsoft.data.edm", "5.6.4" }, { "system.spatial", "5.6.4" }, { "system.componentmodel.primitives", "4.0.0" }, { "xunit.assert", "2.1.0" }, { "xunit", "2.1.0" }, { "system.componentmodel", "4.0.0" }, { "system.xml.readerwriter", "4.0.10" }, { "log4net", "2.0.5" }, { "system.security.claims", "4.0.0" }, { "microsoft.aspnet.cors", "5.2.3" }, { "microsoft.data.services.client", "5.6.4" }, { "system.net.primitives", "4.0.10" }, { "microsoft.owin.security.google", "3.0.1" }, { "microsoft.owin.security.facebook", "3.0.1" }, { "microsoft.applicationinsights", "1.2.3" }, { "system.net.http", "4.0.0" }, { "microsoft.owin.security.twitter", "3.0.1" }, { "microsoft.owin.security.microsoftaccount", "3.0.1" }, { "system.appcontext", "4.0.0" }, { "system.private.networking", "4.0.0" }, { "microsoft.applicationinsights.windowsserver.telemetrychannel", "1.2.3" }, { "microsoft.applicationinsights.dependencycollector", "1.2.3" }, { "microsoft.applicationinsights.perfcountercollector", "1.2.3" }, { "microsoft.applicationinsights.windowsserver", "1.2.3" }, { "microsoft.applicationinsights.web", "1.2.3" }, { "autofac", "3.5.2" }, { "system.componentmodel.eventbasedasync", "4.0.10" }, { "microsoft.aspnet.webapi.cors", "5.2.3" }, { "system.globalization.extensions", "4.0.0" }, { "system.threading.timer", "4.0.0" }, { "system.io.compression", "4.0.0" }, { "windowsazure.storage", "6.2.0" }, { "htmlagilitypack", "1.4.9" }, { "microsoft.windowsazure.configurationmanager", "3.1.0" }, { "nuget.commandline", "3.3.0" }, { "system.reflection.metadata", "1.1.0" }, { "microsoft.applicationinsights.agent.intercept", "1.2.0" }, { "system.data.common", "4.0.0" }, { "microsoft.aspnet.webapi.helppage", "5.2.3" }, { "sharpziplib", "0.86.0" }, { "restsharp", "105.2.3" }, { "system.identitymodel.tokens.jwt", "4.0.2.206221351" }, { "system.threading.threadpool", "4.0.10-beta-23409" }, { "microsoft.aspnet.signalr.core", "2.2.0" }, { "system.security.cryptography.primitives", "4.0.0-beta-23409" }, { "system.threading.thread", "4.0.0-beta-23409" }, { "system.xml.xmldocument", "4.0.0" }, { "unity", "4.0.1" }, { "system.threading.tasks.parallel", "4.0.0" }, { "system.diagnostics.tracesource", "4.0.0-beta-23409" }, { "system.collections.specialized", "4.0.0" }, { "system.io.compression.clrcompression-x64", "4.0.0" }, { "system.linq.queryable", "4.0.0" }, { "system.io.compression.clrcompression-x86", "4.0.0" }, { "microsoft.csharp", "4.0.0" }, { "jquery.ui.combined", "1.11.4" }, { "system.console", "4.0.0-beta-23409" }, { "xunit.runner.utility", "2.1.0" }, { "system.dynamic.runtime", "4.0.10" }, { "microsoft.applicationinsights.javascript", "0.15.0-build58334" }, { "microsoft.extensions.dependencyinjection.abstractions", "1.0.0-rc1-final" }, { "nlog", "4.2.3" }, { "microsoft.aspnet.signalr.js", "2.2.0" }, { "microsoft.extensions.logging.abstractions", "1.0.0-rc1-final" }, { "system.diagnostics.contracts", "4.0.0" }, { "microsoft.owin.cors", "3.0.1" }, { "system.io.unmanagedmemorystream", "4.0.0" }, { "microsoft.extensions.logging", "1.0.0-rc1-final" }, { "microsoft.framework.dependencyinjection.abstractions", "1.0.0-beta8" }, { "system.security.cryptography.algorithms", "4.0.0-beta-23409" }, { "ninject", "3.2.2" }, { "microsoft.aspnet.signalr.systemweb", "2.2.0" }, { "microsoft.framework.configuration", "1.0.0-beta8" }, { "system.componentmodel.annotations", "4.0.10" }, { "microsoft.framework.configuration.abstractions", "1.0.0-beta8" }, { "system.security.cryptography.encoding", "4.0.0-beta-23409" }, { "system.security.cryptography.x509certificates", "4.0.0-beta-23409" }, { "system.xml.xdocument", "4.0.10" }, { "microsoft.extensions.primitives", "1.0.0-rc1-final" }, { "microsoft.framework.logging.abstractions", "1.0.0-beta8" }, { "microsoft.extensions.configuration.abstractions", "1.0.0-rc1-final" }, { "webactivatorex", "2.0.6" }, { "microsoft.extensions.platformabstractions", "1.0.0-rc1-final" }, { "microsoft.framework.dependencyinjection", "1.0.0-beta8" }, { "microsoft.codeanalysis.analyzers", "1.0.0" }, { "microsoft.extensions.configuration", "1.0.0-rc1-final" }, { "nuget.build", "2.8.6" }, { "microsoft.framework.primitives", "1.0.0-beta8" }, { "microsoft.framework.logging", "1.0.0-beta8" }, { "microsoft.framework.optionsmodel", "1.0.0-beta8" }, { "xunit.runner.console", "2.1.0" }, { "microsoft.framework.configuration.binder", "1.0.0-beta8" }, { "microsoft.aspnet.signalr", "2.2.0" }, { "microsoft.framework.configuration.json", "1.0.0-beta8" }, { "system.linq.parallel", "4.0.0" }, { "microsoft.dnx.runtime.abstractions", "1.0.0-beta8" }, { "microsoft.framework.configuration.fileextensions", "1.0.0-beta8" }, { "system.io.filesystem.watcher", "4.0.0-beta-23409" }, { "microsoft.netcore.targets", "1.0.0" }, { "microsoft.framework.webencoders.core", "1.0.0-beta8" }, { "microsoft.aspnet.http.abstractions", "1.0.0-beta8" }, { "microsoft.aspnet.http.features", "1.0.0-beta8" }, { "microsoft.aspnet.fileproviders.abstractions", "1.0.0-beta8" }, { "microsoft.aspnet.hosting.abstractions", "1.0.0-beta8" }, { "system.componentmodel.typeconverter", "4.0.1-beta-23409" }, { "microsoft.net.http.headers", "1.0.0-beta8" }, { "microsoft.aspnet.http.extensions", "1.0.0-beta8" }, { "microsoft.dnx.compilation.abstractions", "1.0.0-beta8" }, { "system.diagnostics.tracing.telemetry", "4.0.0-beta-23409" }, { "microsoft.aspnet.webutilities", "1.0.0-beta8" }, { "microsoft.aspnet.fileproviders.physical", "1.0.0-beta8" }, { "system.net.websockets", "4.0.0-beta-23409" }, { "microsoft.extensions.dependencyinjection", "1.0.0-rc1-final" }, { "microsoft.framework.configuration.environmentvariables", "1.0.0-beta8" }, { "system.net.networkinformation", "4.0.0" }, { "microsoft.aspnet.http", "1.0.0-beta8" }, { "microsoft.framework.configuration.commandline", "1.0.0-beta8" }, { "microsoft.aspnet.hosting", "1.0.0-beta8" }, { "microsoft.aspnet.hosting.server.abstractions", "1.0.0-beta8" }, { "microsoft.framework.webencoders", "1.0.0-beta8" }, { "microsoft.netcore.platforms", "1.0.0" }, { "microsoft.aspnet.server.kestrel", "1.0.0-beta8" }, { "elmah.corelibrary", "1.2.2" }, { "system.numerics.vectors", "4.1.1-beta-23409" }, { "system.diagnostics.stacktrace", "4.0.1-beta-23409" }, { "runtime.unix.system.diagnostics.tracesource", "4.0.0-beta-23409" }, { "microsoft.owin.hosting", "3.0.1" }, { "microsoft.aspnet.staticfiles", "1.0.0-beta8" }, { "runtime.unix.system.security.cryptography.encoding", "4.0.0-beta-23409" }, { "runtime.unix.system.security.cryptography.x509certificates", "4.0.0-beta-23409" }, { "system.security.cryptography.openssl", "4.0.0-beta-23409" }, { "runtime.unix.system.console", "4.0.0-beta-23409" }, { "automapper", "4.1.1" }, { "runtime.unix.system.private.uri", "4.0.1-beta-23409" }, { "runtime.unix.system.threading", "4.0.11-beta-23409" }, { "microsoft.extensions.configuration.binder", "1.0.0-rc1-final" }, { "runtime.linux.system.runtime.extensions", "4.0.11-beta-23409" }, { "runtime.unix.system.diagnostics.debug", "4.0.11-beta-23409" }, { "runtime.linux.system.io.filesystem", "4.0.1-beta-23409" }, { "system.diagnostics.diagnosticsource", "4.0.0-beta-23516" }, { "runtime.linux.system.security.cryptography.algorithms", "4.0.0-beta-23409" }, { "runtime.unix.system.globalization.extensions", "4.0.1-beta-23409" }, { "runtime.unix.system.net.primitives", "4.0.11-beta-23409" }, { "runtime.linux.system.io.filesystem.watcher", "4.0.0-beta-23409" }, { "microsoft.extensions.optionsmodel", "1.0.0-rc1-final" }, { "xunit.runner.visualstudio", "2.1.0" }, { "microsoft.netcore.targets.universalwindowsplatform", "5.0.0" }, { "system.xml.xmlserializer", "4.0.10" }, { "microsoft.extensions.webencoders.core", "1.0.0-rc1-final" }, { "dapper", "1.42.0" }, { "system.runtime.interopservices.windowsruntime", "4.0.0" }, { "system.net.webheadercollection", "4.0.0" }, { "nunittestadapter", "2.0.0" }, { "rx-core", "2.2.5" }, { "dnx-coreclr-linux-x64", "1.0.0-beta8" }, { "system.reflection.dispatchproxy", "4.0.0" }, { "rx-interfaces", "2.2.5" }, { "microsoft.netcore.runtime.coreclr-x64", "1.0.0" }, { "system.text.encoding.codepages", "4.0.0" }, { "rx-linq", "2.2.5" }, { "microsoft.netcore.runtime.coreclr-x86", "1.0.0" }, { "microsoft.jquery.unobtrusive.ajax", "3.2.3" }, { "microsoft.extensions.configuration.json", "1.0.0-rc1-final" }, { "microsoft.extensions.caching.abstractions", "1.0.0-rc1-final" }, { "microsoft.extensions.caching.memory", "1.0.0-rc1-final" }, { "castle.core", "3.3.3" }, { "nuget.galleryuptime", "1.0.0" }, { "microsoft.extensions.configuration.fileextensions", "1.0.0-rc1-final" }, { "microsoft.visualbasic", "10.0.0" }, { "xunit.runner.reporters", "2.1.0" }, { "system.runtime.serialization.json", "4.0.0" }, { "microsoft.owin.security.jwt", "3.0.1" }, { "system.runtime.windowsruntime", "4.0.10" }, { "system.security.cryptography.cng", "4.0.0-beta-23516" }, { "microsoft.extensions.configuration.environmentvariables", "1.0.0-rc1-final" }, { "ix-async", "1.2.5" }, { "microsoft.extensions.configuration.commandline", "1.0.0-rc1-final" }, { "microsoft.extensions.webencoders", "1.0.0-rc1-final" }, { "microsoft.netcore.runtime.coreclr-arm", "1.0.0" }, { "autofac.webapi2", "3.4.0" }, { "microsoft.codeanalysis.csharp", "1.1.0-rc1-20151109-01" }, { "system.runtime.serialization.primitives", "4.0.10" }, { "system.threading.tasks.dataflow", "4.5.25" }, { "microsoft.codeanalysis.common", "1.1.0-rc1-20151109-01" }, { "bouncycastle", "1.7.0" }, { "rx-platformservices", "2.2.5" }, { "documentformat.openxml", "2.5.0" }, { "microsoft.owin.host.httplistener", "3.0.1" }, { "enterpriselibrary.transientfaulthandling", "6.0.1304" }, { "system.io.compression.zipfile", "4.0.0" }, { "microsoft.aspnet.html.abstractions", "1.0.0-rc1-final" }, { "microsoft.dnx.compilation.csharp.abstractions", "1.0.0-rc1-final" }, { "system.private.datacontractserialization", "4.0.0" }, { "microsoft.aspnet.cryptography.internal", "1.0.0-rc1-final" }, { "microsoft.aspnet.razor.runtime", "4.0.0-rc1-final" }, { "microsoft.aspnet.dataprotection", "1.0.0-rc1-final" }, { "microsoft.aspnet.dataprotection.abstractions", "1.0.0-rc1-final" }, { "microsoft.aspnet.diagnostics.abstractions", "1.0.0-rc1-final" }, { "microsoft.aspnet.authorization", "1.0.0-rc1-final" }, { "microsoft.aspnet.mvc.core", "6.0.0-rc1-final" }, { "microsoft.extensions.memorypool", "1.0.0-rc1-final" }, { "microsoft.aspnet.mvc.abstractions", "6.0.0-rc1-final" }, { "microsoft.aspnet.routing", "1.0.0-rc1-final" }, { "microsoft.aspnet.iisplatformhandler", "1.0.0-rc1-final" }, { "microsoft.aspnet.jsonpatch", "1.0.0-rc1-final" }, { "system.runtime.serialization.xml", "4.0.10" }, { "microsoft.extensions.localization.abstractions", "1.0.0-rc1-final" }, { "microsoft.extensions.localization", "1.0.0-rc1-final" }, { "microsoft.aspnet.antiforgery", "1.0.0-rc1-final" }, { "microsoft.aspnet.pageexecutioninstrumentation.interfaces", "1.0.0-rc1-final" }, { "microsoft.aspnet.mvc.razor.host", "6.0.0-rc1-final" }, { "microsoft.extensions.globalization.cultureinfocache", "1.0.0-rc1-final" }, { "microsoft.aspnet.localization", "1.0.0-rc1-final" }, { "sendgrid.smtpapi", "1.3.1" }, { "microsoft.aspnet.mvc.formatters.json", "6.0.0-rc1-final" }, { "microsoft.netcore.portable.compatibility", "1.0.0" }, { "microsoft.aspnet.mvc.viewfeatures", "6.0.0-rc1-final" }, { "microsoft.aspnet.mvc.dataannotations", "6.0.0-rc1-final" }, { "microsoft.aspnet.mvc.razor", "6.0.0-rc1-final" }, { "microsoft.aspnet.mvc.apiexplorer", "6.0.0-rc1-final" }, { "microsoft.aspnet.mvc.cors", "6.0.0-rc1-final" }, { "rx-main", "2.2.5" }, { "microsoft.aspnet.mvc.localization", "6.0.0-rc1-final" }, { "microsoft.aspnet.razor.runtime.precompilation", "4.0.0-rc1-final" }, { "microsoft.netcore.runtime", "1.0.0" }, { "microsoft.dnx.compilation.csharp.common", "1.0.0-rc1-final" } }; } /// <summary> /// get a version for a certain package name /// </summary> /// <param name="name">Package name.</param> /// <returns>returns a string with package version, if package name is present in a map, /// null otherwise</returns> public string GetVersion(string name) { if (versions.ContainsKey(name)) { return versions[name]; } else { return null; } } } }
/* Copyright (c) 2001 Lapo Luchini. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ /* This file is a port of jzlib v1.0.7, com.jcraft.jzlib.ZOutputStream.java */ using System; using System.Diagnostics; using System.IO; namespace Org.BouncyCastle.Utilities.Zlib { public class ZOutputStream : ZStream { private const int BufferSize = 512; //private ZStream _z = new ZStream(); private byte[] _bufffer = new byte[BufferSize]; private bool compress; private Stream _output; private bool _isDisposed; public virtual FlushType FlushMode { get; private set; } public ZOutputStream(Stream output) : base() { this.FlushMode = FlushType.Z_PARTIAL_FLUSH; this._output = output; this.inflateInit(); this.compress = false; } public ZOutputStream(Stream output, CompressionLevel level) : this(output, level, false) { } public ZOutputStream(Stream output, CompressionLevel level, bool nowrap) : base() { this.FlushMode = FlushType.Z_PARTIAL_FLUSH; this._output = output; this.deflateInit(level, nowrap); this.compress = true; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_isDisposed; } } public override void Flush() { this._output.Flush(); } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { if (count == 0) return; this.next_in = buffer; this.next_in_index = offset; this.avail_in = count; do { this.next_out = this._bufffer; this.next_out_index = 0; this.avail_out = this._bufffer.Length; ZLibStatus err = compress ? this.deflate(this.FlushMode) : this.inflate(this.FlushMode); if (err != ZLibStatus.Z_OK) throw new IOException((compress ? "de" : "in") + "flating: " + this.msg); this._output.Write(this._bufffer, 0, this._bufffer.Length - this.avail_out); } while (this.avail_in > 0 || this.avail_out == 0); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (this._isDisposed) return; try { do { this.next_out = this._bufffer; this.next_out_index = 0; this.avail_out = this._bufffer.Length; var err = compress? this.deflate(FlushType.Z_FINISH) : this.inflate(FlushType.Z_FINISH); if (err != ZLibStatus.Z_STREAM_END && err != ZLibStatus.Z_OK) throw new IOException((compress ? "de" : "in") + "flating: " + this.msg); int count = this._bufffer.Length - this.avail_out; if (count > 0) { this._output.Write(this._bufffer, 0, count); } } while (this.avail_in > 0 || this.avail_out == 0); this.Flush(); } finally { this._isDisposed = true; if (compress) this.deflateEnd(); else this.inflateEnd(); this._output.Close(); this._output = null; } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.Linq; using System.Collections.Generic; using System.Text; namespace System.Abstract { /// <summary> /// ServiceCache /// </summary> public static partial class ServiceCache { /// <summary> /// Provides <see cref="System.DateTime"/> instance to be used when no absolute expiration value to be set. /// </summary> public static readonly DateTime InfiniteAbsoluteExpiration = DateTime.MaxValue; /// <summary> /// Provides <see cref="System.TimeSpan"/> instance to be used when no sliding expiration value to be set. /// </summary> public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero; static ServiceCache() { var registrar = ServiceCacheRegistrar.Get(typeof(ServiceCache)); registrar.Register(Primitives.YesNo); registrar.Register(Primitives.Gender); registrar.Register(Primitives.Integer); } internal static string GetNamespace(IEnumerable<object> values) { if (values == null || !values.Any()) return null; var b = new StringBuilder(); foreach (var v in values) { if (v != null) b.Append(v.ToString()); b.Append("\\"); } return b.ToString(); } /// <summary> /// Touches the specified names. /// </summary> /// <param name="names">The names.</param> public static void Touch(params string[] names) { ServiceCacheManager.Current.Touch(null, names); } /// <summary> /// Touches the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> public static void Touch(object tag, params string[] names) { ServiceCacheManager.Current.Touch(tag, names); } #region Registrations /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="registration">The registration.</param> /// <returns></returns> public static object Get(IServiceCacheRegistration registration) { return ServiceCacheManager.Current.Get<object>(registration, null, null); } /// <summary> /// Gets the specified registration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <returns></returns> public static T Get<T>(IServiceCacheRegistration registration) { return ServiceCacheManager.Current.Get<T>(registration, null, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(IServiceCacheRegistration registration) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(registration, null, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(IServiceCacheRegistration registration) { return ServiceCacheManager.Current.Get<IQueryable<T>>(registration, null, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(IServiceCacheRegistration registration, object[] values) { return ServiceCacheManager.Current.Get<object>(registration, null, values); } /// <summary> /// Gets the specified registration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(IServiceCacheRegistration registration, object[] values) { return ServiceCacheManager.Current.Get<T>(registration, null, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(IServiceCacheRegistration registration, object[] values) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(registration, null, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(IServiceCacheRegistration registration, object[] values) { return ServiceCacheManager.Current.Get<IQueryable<T>>(registration, null, values); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static object Get(IServiceCacheRegistration registration, object tag) { return ServiceCacheManager.Current.Get<object>(registration, tag, null); } /// <summary> /// Gets the specified registration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static T Get<T>(IServiceCacheRegistration registration, object tag) { return ServiceCacheManager.Current.Get<T>(registration, tag, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(IServiceCacheRegistration registration, object tag) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(registration, tag, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(IServiceCacheRegistration registration, object tag) { return ServiceCacheManager.Current.Get<IQueryable<T>>(registration, tag, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(IServiceCacheRegistration registration, object tag, object[] values) { return ServiceCacheManager.Current.Get<object>(registration, tag, values); } /// <summary> /// Gets the specified registration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(IServiceCacheRegistration registration, object tag, object[] values) { return ServiceCacheManager.Current.Get<T>(registration, tag, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(IServiceCacheRegistration registration, object tag, object[] values) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(registration, tag, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(ServiceCacheRegistration registration, object tag, object[] values) { return ServiceCacheManager.Current.Get<IQueryable<T>>(registration, tag, values); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <returns></returns> public static object Get(Type anchorType, string registrationName) { return ServiceCacheManager.Current.Get<object>(anchorType, registrationName, null, null); } /// <summary> /// Gets the specified anchor type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static T Get<T>(Type anchorType, string registrationName) { return ServiceCacheManager.Current.Get<T>(anchorType, registrationName, null, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(Type anchorType, string registrationName) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(anchorType, registrationName, null, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(Type anchorType, string registrationName) { return ServiceCacheManager.Current.Get<IQueryable<T>>(anchorType, registrationName, null, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(Type anchorType, string registrationName, object[] values) { return ServiceCacheManager.Current.Get<object>(anchorType, registrationName, null, values); } /// <summary> /// Gets the specified anchor type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(Type anchorType, string registrationName, object[] values) { return ServiceCacheManager.Current.Get<T>(anchorType, registrationName, null, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(Type anchorType, string registrationName, object[] values) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(anchorType, registrationName, string.Empty, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(Type anchorType, string registrationName, object[] values) { return ServiceCacheManager.Current.Get<IQueryable<T>>(anchorType, registrationName, string.Empty, values); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static object Get(Type anchorType, string registrationName, object tag) { return ServiceCacheManager.Current.Get<object>(anchorType, registrationName, tag, null); } /// <summary> /// Gets the specified anchor type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static T Get<T>(Type anchorType, string registrationName, object tag) { return ServiceCacheManager.Current.Get<T>(anchorType, registrationName, tag, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(Type anchorType, string registrationName, object tag) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(anchorType, registrationName, tag, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(Type anchorType, string registrationName, object tag) { return ServiceCacheManager.Current.Get<IQueryable<T>>(anchorType, registrationName, tag, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(Type anchorType, string registrationName, object tag, object[] values) { return ServiceCacheManager.Current.Get<object>(anchorType, registrationName, tag, values); } /// <summary> /// Gets the specified anchor type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(Type anchorType, string registrationName, object tag, object[] values) { return ServiceCacheManager.Current.Get<T>(anchorType, registrationName, tag, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(Type anchorType, string registrationName, object tag, object[] values) { return ServiceCacheManager.Current.Get<IEnumerable<T>>(anchorType, registrationName, tag, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(Type anchorType, string registrationName, object tag, object[] values) { return ServiceCacheManager.Current.Get<IQueryable<T>>(anchorType, registrationName, tag, values); } #endregion } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// <summary> /// Borrower /// </summary> [DataContract] public partial class Borrower : IEquatable<Borrower> { /// <summary> /// Initializes a new instance of the <see cref="Borrower" /> class. /// </summary> [JsonConstructorAttribute] protected Borrower() { } /// <summary> /// Initializes a new instance of the <see cref="Borrower" /> class. /// </summary> /// <param name="Forename">Forename (required).</param> /// <param name="MiddleName">MiddleName.</param> /// <param name="Surname">Surname (required).</param> /// <param name="Token">Token (required).</param> /// <param name="Id">Id (required).</param> public Borrower(string Forename = null, string MiddleName = null, string Surname = null, string Token = null, string Id = null) { // to ensure "Forename" is required (not null) if (Forename == null) { throw new InvalidDataException("Forename is a required property for Borrower and cannot be null"); } else { this.Forename = Forename; } // to ensure "Surname" is required (not null) if (Surname == null) { throw new InvalidDataException("Surname is a required property for Borrower and cannot be null"); } else { this.Surname = Surname; } // to ensure "Token" is required (not null) if (Token == null) { throw new InvalidDataException("Token is a required property for Borrower and cannot be null"); } else { this.Token = Token; } // to ensure "Id" is required (not null) if (Id == null) { throw new InvalidDataException("Id is a required property for Borrower and cannot be null"); } else { this.Id = Id; } this.MiddleName = MiddleName; } /// <summary> /// Gets or Sets Forename /// </summary> [DataMember(Name="forename", EmitDefaultValue=false)] public string Forename { get; set; } /// <summary> /// Gets or Sets MiddleName /// </summary> [DataMember(Name="middle_name", EmitDefaultValue=false)] public string MiddleName { get; set; } /// <summary> /// Gets or Sets Surname /// </summary> [DataMember(Name="surname", EmitDefaultValue=false)] public string Surname { get; set; } /// <summary> /// Gets or Sets Token /// </summary> [DataMember(Name="token", EmitDefaultValue=false)] public string Token { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Borrower {\n"); sb.Append(" Forename: ").Append(Forename).Append("\n"); sb.Append(" MiddleName: ").Append(MiddleName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Token: ").Append(Token).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Borrower); } /// <summary> /// Returns true if Borrower instances are equal /// </summary> /// <param name="other">Instance of Borrower to be compared</param> /// <returns>Boolean</returns> public bool Equals(Borrower other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Forename == other.Forename || this.Forename != null && this.Forename.Equals(other.Forename) ) && ( this.MiddleName == other.MiddleName || this.MiddleName != null && this.MiddleName.Equals(other.MiddleName) ) && ( this.Surname == other.Surname || this.Surname != null && this.Surname.Equals(other.Surname) ) && ( this.Token == other.Token || this.Token != null && this.Token.Equals(other.Token) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Forename != null) hash = hash * 59 + this.Forename.GetHashCode(); if (this.MiddleName != null) hash = hash * 59 + this.MiddleName.GetHashCode(); if (this.Surname != null) hash = hash * 59 + this.Surname.GetHashCode(); if (this.Token != null) hash = hash * 59 + this.Token.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); return hash; } } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SchoolBusAPI.Models; namespace SchoolBusAPI.Models { /// <summary> /// The set of permissions defined in the application. Each permission is given a name and triggers some behavior defined in the application. For example, a permission might allow users to see data or to have access to functionality restricted to users without that permission. Permissions are created as needed to the application and are added to the permissions table by data migrations executed at the time the software that uses the permission is deployed. /// </summary> [MetaDataExtension (Description = "The set of permissions defined in the application. Each permission is given a name and triggers some behavior defined in the application. For example, a permission might allow users to see data or to have access to functionality restricted to users without that permission. Permissions are created as needed to the application and are added to the permissions table by data migrations executed at the time the software that uses the permission is deployed.")] public partial class Permission : AuditableEntity, IEquatable<Permission> { /// <summary> /// Default constructor, required by entity framework /// </summary> public Permission() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="Permission" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a Permission (required).</param> /// <param name="Code">The name of the permission referenced in the software of the application. (required).</param> /// <param name="Name">The &amp;#39;user friendly&amp;#39; name of the permission exposed to the user selecting the permissions to be included in a Role. (required).</param> /// <param name="Description">A description of the purpose of the permission and exposed to the user selecting the permissions to be included in a Role. (required).</param> public Permission(int Id, string Code, string Name, string Description) { this.Id = Id; this.Code = Code; this.Name = Name; this.Description = Description; } /// <summary> /// A system-generated unique identifier for a Permission /// </summary> /// <value>A system-generated unique identifier for a Permission</value> [MetaDataExtension (Description = "A system-generated unique identifier for a Permission")] public int Id { get; set; } /// <summary> /// The name of the permission referenced in the software of the application. /// </summary> /// <value>The name of the permission referenced in the software of the application.</value> [MetaDataExtension (Description = "The name of the permission referenced in the software of the application.")] [MaxLength(255)] public string Code { get; set; } /// <summary> /// The &#39;user friendly&#39; name of the permission exposed to the user selecting the permissions to be included in a Role. /// </summary> /// <value>The &#39;user friendly&#39; name of the permission exposed to the user selecting the permissions to be included in a Role.</value> [MetaDataExtension (Description = "The &#39;user friendly&#39; name of the permission exposed to the user selecting the permissions to be included in a Role.")] [MaxLength(255)] public string Name { get; set; } /// <summary> /// A description of the purpose of the permission and exposed to the user selecting the permissions to be included in a Role. /// </summary> /// <value>A description of the purpose of the permission and exposed to the user selecting the permissions to be included in a Role.</value> [MetaDataExtension (Description = "A description of the purpose of the permission and exposed to the user selecting the permissions to be included in a Role.")] [MaxLength(255)] public string Description { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Permission {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((Permission)obj); } /// <summary> /// Returns true if Permission instances are equal /// </summary> /// <param name="other">Instance of Permission to be compared</param> /// <returns>Boolean</returns> public bool Equals(Permission other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Code == other.Code || this.Code != null && this.Code.Equals(other.Code) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.Code != null) { hash = hash * 59 + this.Code.GetHashCode(); } if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.Description != null) { hash = hash * 59 + this.Description.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(Permission left, Permission right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(Permission left, Permission right) { return !Equals(left, right); } #endregion Operators } }
using System; using System.Data; using System.IO; using System.Web; using System.Web.UI; using Rainbow.Framework.Site.Data; using Rainbow.Framework.Web.UI.WebControls; using Path=Rainbow.Framework.Settings.Path; namespace Rainbow.Framework.Helpers { /// <summary> /// ModuleInstall incapsulates all the logic for install, /// uninstall modules on portal /// </summary> [History("jminond", "2006/02/22", "corrected case where install group is null exception")] public class ModuleInstall { /// <summary> /// Installs the group. /// </summary> /// <param name="groupFileName">Name of the group file.</param> /// <param name="install">if set to <c>true</c> [install].</param> public static void InstallGroup(string groupFileName, bool install) { DataTable modules = GetInstallGroup(groupFileName); // In case Modules are null if (modules != null && (modules.Rows.Count > 0)) { foreach (DataRow r in modules.Rows) { string friendlyName = r["FriendlyName"].ToString(); string desktopSource = r["DesktopSource"].ToString(); string mobileSource = r["MobileSource"].ToString(); Install(friendlyName, desktopSource, mobileSource, install); } } else { Exception ex = new Exception("Tried to install 0 modules in groupFileName:" + groupFileName); ErrorHandler.Publish(LogLevel.Warn, ex); } } /// <summary> /// Gets the install group. /// </summary> /// <param name="groupFileName">Name of the group file.</param> /// <returns></returns> private static DataTable GetInstallGroup(string groupFileName) { //Load the XML as dataset using (DataSet ds = new DataSet()) { string installer = groupFileName; try { ds.ReadXml(installer); } catch (Exception ex) { ErrorHandler.Publish(LogLevel.Error, "Exception installing module: " + installer, ex); return null; } return ds.Tables[0]; } } /// <summary> /// Uninstalls the group. /// </summary> /// <param name="groupFileName">Name of the group file.</param> public static void UninstallGroup(string groupFileName) { DataTable modules = GetInstallGroup(groupFileName); foreach (DataRow r in modules.Rows) { // string friendlyName = r["FriendlyName"].ToString(); string desktopSource = r["DesktopSource"].ToString(); string mobileSource = r["MobileSource"].ToString(); Uninstall(desktopSource, mobileSource); } } /// <summary> /// Installs the specified friendly name. /// </summary> /// <param name="friendlyName">Name of the friendly.</param> /// <param name="desktopSource">The desktop source.</param> /// <param name="mobileSource">The mobile source.</param> public static void Install(string friendlyName, string desktopSource, string mobileSource) { Install(friendlyName, desktopSource, mobileSource, true); } /// <summary> /// Installs module /// </summary> /// <param name="friendlyName">Name of the friendly.</param> /// <param name="desktopSource">The desktop source.</param> /// <param name="mobileSource">The mobile source.</param> /// <param name="install">if set to <c>true</c> [install].</param> public static void Install(string friendlyName, string desktopSource, string mobileSource, bool install) { ErrorHandler.Publish(LogLevel.Info, "Installing DesktopModule '" + friendlyName + "' from '" + desktopSource + "'"); if (mobileSource != null && mobileSource.Length > 0) ErrorHandler.Publish(LogLevel.Info, "Installing MobileModule '" + friendlyName + "' from '" + mobileSource + "'"); string controlFullPath = Path.ApplicationRoot + "/" + desktopSource; // Instantiate the module Page page = new Page(); //http://sourceforge.net/tracker/index.php?func=detail&aid=738670&group_id=66837&atid=515929 //Rainbow.Framework.Web.UI.Page page = new Rainbow.Framework.Web.UI.Page(); Control myControl = page.LoadControl(controlFullPath); if (!(myControl is PortalModuleControl)) throw new Exception("Module '" + myControl.GetType().FullName + "' is not a PortalModule Control"); PortalModuleControl portalModule = (PortalModuleControl) myControl; // Check mobile module if (mobileSource != null && mobileSource.Length != 0 && mobileSource.ToLower().EndsWith(".ascx")) { //TODO: Check mobile module //TODO: MobilePortalModuleControl mobileModule = (MobilePortalModuleControl) page.LoadControl(Rainbow.Framework.Settings.Path.ApplicationRoot + "/" + mobileSource); if (!File.Exists(HttpContext.Current.Server.MapPath(Path.ApplicationRoot + "/" + mobileSource))) throw new FileNotFoundException("Mobile Control not found"); } // Get Module ID Guid defID = portalModule.GuidID; //Get Assembly name string assemblyName = portalModule.GetType().BaseType.Assembly.CodeBase; assemblyName = assemblyName.Substring(assemblyName.LastIndexOf('/') + 1); //Get name only // Get Module Class name string className = portalModule.GetType().BaseType.FullName; // Now we add the definition to module list ModulesDB modules = new ModulesDB(); if (install) { //Install as new module //Call Install try { ErrorHandler.Publish(LogLevel.Debug, "Installing '" + friendlyName + "' as new module."); portalModule.Install(null); } catch (Exception ex) { //Error occurred portalModule.Rollback(null); //Rethrow exception throw new Exception("Exception occurred installing '" + portalModule.GuidID.ToString() + "'!", ex); } try { // Add a new module definition to the database modules.AddGeneralModuleDefinitions(defID, friendlyName, desktopSource, mobileSource, assemblyName, className, portalModule.AdminModule, portalModule.Searchable); } catch (Exception ex) { //Rethrow exception throw new Exception( "AddGeneralModuleDefinitions Exception '" + portalModule.GuidID.ToString() + "'!", ex); } // All is fine: we can call Commit portalModule.Commit(null); } else { // Update the general module definition try { ErrorHandler.Publish(LogLevel.Debug, "Updating '" + friendlyName + "' as new module."); modules.UpdateGeneralModuleDefinitions(defID, friendlyName, desktopSource, mobileSource, assemblyName, className, portalModule.AdminModule, portalModule.Searchable); } catch (Exception ex) { //Rethrow exception throw new Exception( "UpdateGeneralModuleDefinitions Exception '" + portalModule.GuidID.ToString() + "'!", ex); } } // Update the module definition - install for portal 0 modules.UpdateModuleDefinitions(defID, 0, true); } /// <summary> /// Uninstalls the specified desktop source. /// </summary> /// <param name="desktopSource">The desktop source.</param> /// <param name="mobileSource">The mobile source.</param> public static void Uninstall(string desktopSource, string mobileSource) { Page page = new Page(); // Istantiate the module PortalModuleControl portalModule = (PortalModuleControl) page.LoadControl(Path.ApplicationRoot + "/" + desktopSource); //Call Uninstall try { portalModule.Uninstall(null); } catch (Exception ex) { //Rethrow exception throw new Exception("Exception during uninstall!", ex); } // Delete definition new ModulesDB().DeleteModuleDefinition(portalModule.GuidID); } } }
using System; namespace WinApiWrappers { [Flags] public enum WindowMessages { Activate = 0x6, Activateapp = 0x1c, Afxfirst = 0x360, Afxlast = 0x37f, App = 0x8000, Askcbformatname = 0x30c, Canceljournal = 0x4b, Cancelmode = 0x1f, Capturechanged = 0x215, Changecbchain = 0x30d, Char = 0x102, Chartoitem = 0x2f, Childactivate = 0x22, Clear = 0x303, Close = 0x10, Command = 0x111, Compacting = 0x41, Compareitem = 0x39, Contextmenu = 0x7b, Copy = 0x301, Copydata = 0x4a, Create = 0x1, Ctlcolorbtn = 0x135, Ctlcolordlg = 0x136, Ctlcoloredit = 0x133, Ctlcolorlistbox = 0x134, Ctlcolormsgbox = 0x132, Ctlcolorscrollbar = 0x137, Ctlcolorstatic = 0x138, Cut = 0x300, Deadchar = 0x103, Deleteitem = 0x2d, Destroy = 0x2, Destroyclipboard = 0x307, Devicechange = 0x219, Devmodechange = 0x1b, Displaychange = 0x7e, Drawclipboard = 0x308, Drawitem = 0x2b, Dropfiles = 0x233, Enable = 0xa, Endsession = 0x16, Enteridle = 0x121, Entermenuloop = 0x211, Entersizemove = 0x231, Erasebkgnd = 0x14, Exitmenuloop = 0x212, Exitsizemove = 0x232, Fontchange = 0x1d, Getdlgcode = 0x87, Getfont = 0x31, Gethotkey = 0x33, Geticon = 0x7f, Getminmaxinfo = 0x24, Getobject = 0x3d, Getsysmenu = 0x313, Gettext = 0xd, Gettextlength = 0xe, Handheldfirst = 0x358, Handheldlast = 0x35f, Help = 0x53, Hotkey = 0x312, Hscroll = 0x114, Hscrollclipboard = 0x30e, Iconerasebkgnd = 0x27, Ime_Char = 0x286, Ime_Composition = 0x10f, Ime_Compositionfull = 0x284, Ime_Control = 0x283, Ime_Endcomposition = 0x10e, Ime_Keydown = 0x290, Ime_Keylast = 0x10f, Ime_Keyup = 0x291, Ime_Notify = 0x282, Ime_Request = 0x288, Ime_Select = 0x285, Ime_Setcontext = 0x281, Ime_Startcomposition = 0x10d, Initdialog = 0x110, Initmenu = 0x116, Initmenupopup = 0x117, Input = 0xff, Inputlangchange = 0x51, Inputlangchangerequest = 0x50, Keydown = 0x100, Keyfirst = 0x100, Keylast = 0x108, Keyup = 0x101, Killfocus = 0x8, Lbuttondblclk = 0x203, Lbuttondown = 0x201, Lbuttonup = 0x202, Mbuttondblclk = 0x209, Mbuttondown = 0x207, Mbuttonup = 0x208, Mdiactivate = 0x222, Mdicascade = 0x227, Mdicreate = 0x220, Mdidestroy = 0x221, Mdigetactive = 0x229, Mdiiconarrange = 0x228, Mdimaximize = 0x225, Mdinext = 0x224, Mdirefreshmenu = 0x234, Mdirestore = 0x223, Mdisetmenu = 0x230, Mditile = 0x226, Measureitem = 0x2c, Menuchar = 0x120, Menucommand = 0x126, Menudrag = 0x123, Menugetobject = 0x124, Menurbuttonup = 0x122, Menuselect = 0x11f, Mouseactivate = 0x21, Mousefirst = 0x200, Mousehover = 0x2a1, Mouselast = 0x20a, Mouseleave = 0x2a3, Mousemove = 0x200, Mousewheel = 0x20a, Mousehwheel = 0x20e, Move = 0x3, Moving = 0x216, Ncactivate = 0x86, Nccalcsize = 0x83, Nccreate = 0x81, Ncdestroy = 0x82, Nchittest = 0x84, NclButtonDblClk = 0xa3, Nclbuttondown = 0xa1, Nclbuttonup = 0xa2, Ncmbuttondblclk = 0xa9, Ncmbuttondown = 0xa7, Ncmbuttonup = 0xa8, Ncmousehover = 0x2a0, Ncmouseleave = 0x2a2, Ncmousemove = 0xa0, Ncpaint = 0x85, Ncrbuttondblclk = 0xa6, Ncrbuttondown = 0xa4, Ncrbuttonup = 0xa5, Nextdlgctl = 0x28, Nextmenu = 0x213, Notify = 0x4e, Notifyformat = 0x55, Null = 0x0, Paint = 0xf, Paintclipboard = 0x309, Painticon = 0x26, Palettechanged = 0x311, Paletteischanging = 0x310, Parentnotify = 0x210, Paste = 0x302, Penwinfirst = 0x380, Penwinlast = 0x38f, Power = 0x48, Print = 0x317, Printclient = 0x318, Querydragicon = 0x37, Queryendsession = 0x11, Querynewpalette = 0x30f, Queryopen = 0x13, Queryuistate = 0x129, Queuesync = 0x23, Quit = 0x12, Rbuttondblclk = 0x206, Rbuttondown = 0x204, Rbuttonup = 0x205, Renderallformats = 0x306, Renderformat = 0x305, Setcursor = 0x20, Setfocus = 0x7, Setfont = 0x30, Sethotkey = 0x32, Seticon = 0x80, Setredraw = 0xb, Settext = 0xc, Settingchange = 0x1a, Showwindow = 0x18, Size = 0x5, Sizeclipboard = 0x30b, Sizing = 0x214, Spoolerstatus = 0x2a, Stylechanged = 0x7d, Stylechanging = 0x7c, Syncpaint = 0x88, Syschar = 0x106, Syscolorchange = 0x15, SysCommand = 0x112, Sysdeadchar = 0x107, Syskeydown = 0x104, Syskeyup = 0x105, Systimer = 0x118, Tcard = 0x52, Timechange = 0x1e, Themechanged = 794, Timer = 0x113, Undo = 0x304, Uninitmenupopup = 0x125, User = 0x400, Userchanged = 0x54, Vkeytoitem = 0x2e, Vscroll = 0x115, Vscrollclipboard = 0x30a, Windowposchanged = 0x47, Windowposchanging = 0x46, Wininichange = 0x1a, Xbuttondblclk = 0x20d, Xbuttondown = 0x20b, Xbuttonup = 0x20c } }
// 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.Threading.Tasks.Tests { public class ValueTaskTests { [Fact] public void DefaultValueTask_ValueType_DefaultValue() { Assert.True(default(ValueTask<int>).IsCompleted); Assert.True(default(ValueTask<int>).IsCompletedSuccessfully); Assert.False(default(ValueTask<int>).IsFaulted); Assert.False(default(ValueTask<int>).IsCanceled); Assert.Equal(0, default(ValueTask<int>).Result); Assert.True(default(ValueTask<string>).IsCompleted); Assert.True(default(ValueTask<string>).IsCompletedSuccessfully); Assert.False(default(ValueTask<string>).IsFaulted); Assert.False(default(ValueTask<string>).IsCanceled); Assert.Equal(null, default(ValueTask<string>).Result); } [Fact] public void CreateFromValue_IsRanToCompletion() { ValueTask<int> t = new ValueTask<int>(42); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Equal(42, t.Result); } [Fact] public void CreateFromCompletedTask_IsRanToCompletion() { ValueTask<int> t = new ValueTask<int>(Task.FromResult(42)); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); Assert.Equal(42, t.Result); } [Fact] public void CreateFromNotCompletedTask_IsNotRanToCompletion() { var tcs = new TaskCompletionSource<int>(); ValueTask<int> t = new ValueTask<int>(tcs.Task); Assert.False(t.IsCompleted); Assert.False(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); tcs.SetResult(42); Assert.Equal(42, t.Result); Assert.True(t.IsCompleted); Assert.True(t.IsCompletedSuccessfully); Assert.False(t.IsFaulted); Assert.False(t.IsCanceled); } [Fact] public void CreateFromNullTask_Throws() { Assert.Throws<ArgumentNullException>(() => new ValueTask<int>((Task<int>)null)); Assert.Throws<ArgumentNullException>(() => new ValueTask<string>((Task<string>)null)); } [Fact] public void CreateFromTask_AsTaskIdempotent() { Task<int> source = Task.FromResult(42); ValueTask<int> t = new ValueTask<int>(source); Assert.Same(source, t.AsTask()); Assert.Same(t.AsTask(), t.AsTask()); } [Fact] public void CreateFromValue_AsTaskNotIdempotent() { ValueTask<int> t = new ValueTask<int>(42); Assert.NotSame(Task.FromResult(42), t.AsTask()); Assert.NotSame(t.AsTask(), t.AsTask()); } [Fact] public async Task CreateFromValue_Await() { ValueTask<int> t = new ValueTask<int>(42); Assert.Equal(42, await t); Assert.Equal(42, await t.ConfigureAwait(false)); Assert.Equal(42, await t.ConfigureAwait(true)); } [Fact] public async Task CreateFromTask_Await_Normal() { Task<int> source = Task.Delay(1).ContinueWith(_ => 42); ValueTask<int> t = new ValueTask<int>(source); Assert.Equal(42, await t); } [Fact] public async Task CreateFromTask_Await_ConfigureAwaitFalse() { Task<int> source = Task.Delay(1).ContinueWith(_ => 42); ValueTask<int> t = new ValueTask<int>(source); Assert.Equal(42, await t.ConfigureAwait(false)); } [Fact] public async Task CreateFromTask_Await_ConfigureAwaitTrue() { Task<int> source = Task.Delay(1).ContinueWith(_ => 42); ValueTask<int> t = new ValueTask<int>(source); Assert.Equal(42, await t.ConfigureAwait(true)); } [Fact] public async Task Awaiter_OnCompleted() { // Since ValueTask implements both OnCompleted and UnsafeOnCompleted, // OnCompleted typically won't be used by await, so we add an explicit test // for it here. ValueTask<int> t = new ValueTask<int>(42); var tcs = new TaskCompletionSource<bool>(); t.GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Theory] [InlineData(true)] [InlineData(false)] public async Task ConfiguredAwaiter_OnCompleted(bool continueOnCapturedContext) { // Since ValueTask implements both OnCompleted and UnsafeOnCompleted, // OnCompleted typically won't be used by await, so we add an explicit test // for it here. ValueTask<int> t = new ValueTask<int>(42); var tcs = new TaskCompletionSource<bool>(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => tcs.SetResult(true)); await tcs.Task; } [Fact] public async Task Awaiter_ContinuesOnCapturedContext() { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = new ValueTask<int>(42); var mres = new ManualResetEventSlim(); t.GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(1, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ConfiguredAwaiter_ContinuesOnCapturedContext(bool continueOnCapturedContext) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = new ValueTask<int>(42); var mres = new ManualResetEventSlim(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); } [Fact] public void GetHashCode_ContainsResult() { ValueTask<int> t = new ValueTask<int>(42); Assert.Equal(t.Result.GetHashCode(), t.GetHashCode()); } [Fact] public void GetHashCode_ContainsTask() { ValueTask<string> t = new ValueTask<string>(Task.FromResult("42")); Assert.Equal(t.AsTask().GetHashCode(), t.GetHashCode()); } [Fact] public void GetHashCode_ContainsNull() { ValueTask<string> t = new ValueTask<string>((string)null); Assert.Equal(0, t.GetHashCode()); } [Fact] public void OperatorEquals() { Assert.True(new ValueTask<int>(42) == new ValueTask<int>(42)); Assert.False(new ValueTask<int>(42) == new ValueTask<int>(43)); Assert.True(new ValueTask<string>("42") == new ValueTask<string>("42")); Assert.True(new ValueTask<string>((string)null) == new ValueTask<string>((string)null)); Assert.False(new ValueTask<string>("42") == new ValueTask<string>((string)null)); Assert.False(new ValueTask<string>((string)null) == new ValueTask<string>("42")); Assert.False(new ValueTask<int>(42) == new ValueTask<int>(Task.FromResult(42))); Assert.False(new ValueTask<int>(Task.FromResult(42)) == new ValueTask<int>(42)); } [Fact] public void OperatorNotEquals() { Assert.False(new ValueTask<int>(42) != new ValueTask<int>(42)); Assert.True(new ValueTask<int>(42) != new ValueTask<int>(43)); Assert.False(new ValueTask<string>("42") != new ValueTask<string>("42")); Assert.False(new ValueTask<string>((string)null) != new ValueTask<string>((string)null)); Assert.True(new ValueTask<string>("42") != new ValueTask<string>((string)null)); Assert.True(new ValueTask<string>((string)null) != new ValueTask<string>("42")); Assert.True(new ValueTask<int>(42) != new ValueTask<int>(Task.FromResult(42))); Assert.True(new ValueTask<int>(Task.FromResult(42)) != new ValueTask<int>(42)); } [Fact] public void Equals_ValueTask() { Assert.True(new ValueTask<int>(42).Equals(new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals(new ValueTask<int>(43))); Assert.True(new ValueTask<string>("42").Equals(new ValueTask<string>("42"))); Assert.True(new ValueTask<string>((string)null).Equals(new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>("42").Equals(new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>((string)null).Equals(new ValueTask<string>("42"))); Assert.False(new ValueTask<int>(42).Equals(new ValueTask<int>(Task.FromResult(42)))); Assert.False(new ValueTask<int>(Task.FromResult(42)).Equals(new ValueTask<int>(42))); } [Fact] public void Equals_Object() { Assert.True(new ValueTask<int>(42).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals((object)new ValueTask<int>(43))); Assert.True(new ValueTask<string>("42").Equals((object)new ValueTask<string>("42"))); Assert.True(new ValueTask<string>((string)null).Equals((object)new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>("42").Equals((object)new ValueTask<string>((string)null))); Assert.False(new ValueTask<string>((string)null).Equals((object)new ValueTask<string>("42"))); Assert.False(new ValueTask<int>(42).Equals((object)new ValueTask<int>(Task.FromResult(42)))); Assert.False(new ValueTask<int>(Task.FromResult(42)).Equals((object)new ValueTask<int>(42))); Assert.False(new ValueTask<int>(42).Equals((object)null)); Assert.False(new ValueTask<int>(42).Equals(new object())); Assert.False(new ValueTask<int>(42).Equals((object)42)); } [Fact] public void ToString_Success() { Assert.Equal("Hello", new ValueTask<string>("Hello").ToString()); Assert.Equal("Hello", new ValueTask<string>(Task.FromResult("Hello")).ToString()); Assert.Equal("42", new ValueTask<int>(42).ToString()); Assert.Equal("42", new ValueTask<int>(Task.FromResult(42)).ToString()); Assert.Same(string.Empty, new ValueTask<string>(string.Empty).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromResult(string.Empty)).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromException<string>(new InvalidOperationException())).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromException<string>(new OperationCanceledException())).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromCanceled<string>(new CancellationToken(true))).ToString()); Assert.Equal("0", default(ValueTask<int>).ToString()); Assert.Same(string.Empty, default(ValueTask<string>).ToString()); Assert.Same(string.Empty, new ValueTask<string>((string)null).ToString()); Assert.Same(string.Empty, new ValueTask<string>(Task.FromResult<string>(null)).ToString()); Assert.Same(string.Empty, new ValueTask<DateTime>(new TaskCompletionSource<DateTime>().Task).ToString()); } private sealed class TrackingSynchronizationContext : SynchronizationContext { internal int Posts { get; set; } public override void Post(SendOrPostCallback d, object state) { Posts++; base.Post(d, state); } } } }
// 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 { using System; using System.Globalization; using System.Text; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.Contracts; // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout public struct Guid : IFormattable, IComparable , IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid(byte[] b) { if (b==null) throw new ArgumentNullException(nameof(b)); if (b.Length != 16) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), nameof(b)); Contract.EndContractBlock(); _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d==null) throw new ArgumentNullException(nameof(d)); // Check that array is not too big if(d.Length != 8) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), nameof(d)); Contract.EndContractBlock(); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid parsedGuid; internal GuidParseThrowStyle throwStyle; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal object m_failureMessageFormatArgument; internal string m_failureArgumentName; internal Exception m_innerException; internal void Init(GuidParseThrowStyle canThrow) { parsedGuid = Guid.Empty; throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { m_failure = ParseFailureKind.NativeException; m_innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; m_failureArgumentName = failureArgumentName; m_innerException = innerException; if (throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.NativeException: return m_innerException; default: Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized")); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(String g) { if (g==null) { throw new ArgumentNullException(nameof(g)); } Contract.EndContractBlock(); this = Guid.Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(String input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Contract.EndContractBlock(); GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(String input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } public static Guid ParseExact(String input, String format) { if (input == null) throw new ArgumentNullException(nameof(input)); if (format == null) throw new ArgumentNullException(nameof(format)); if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(String input, String format, out Guid result) { if (format == null || format.Length != 1) { result = Guid.Empty; return false; } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { // invalid guid format specification result = Guid.Empty; return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result) { if (g == null) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } String guidString = g.Trim(); //Remove Whitespace if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } // Check for dashes bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0); if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch(IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Check for '0x' if(!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; // Check for '{' if(guidString.Length <= numStart+numLen+1 || guidString[numStart+numLen+1] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Prepare for loop numLen++; byte[] bytes = new byte[8]; for(int i = 0; i < 8; i++) { // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if(i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber"); return false; } } // Read in the number int signedNumber; if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) { return false; } uint number = (uint)signedNumber; // check for overflow if(number > 255) { result.SetFailure(ParseFailureKind.Format, "Overflow_Byte"); return false; } bytes[i] = (byte)number; } result.parsedGuid._d = bytes[0]; result.parsedGuid._e = bytes[1]; result.parsedGuid._f = bytes[2]; result.parsedGuid._g = bytes[3]; result.parsedGuid._h = bytes[4]; result.parsedGuid._i = bytes[5]; result.parsedGuid._j = bytes[6]; result.parsedGuid._k = bytes[7]; // Check for last '}' if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace"); return false; } // Check if we have extra characters at the end if( numStart+numLen+1 != guidString.Length -1) { result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd"); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; if(guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } for(int i= 0; i< guidString.Length; i++) { char ch = guidString[i]; if(ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture); if(upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos!=12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0]=='{') { if (guidString.Length!=38 || guidString[37]!='}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if (guidString[0]=='(') { if (guidString.Length!=38 || guidString[37]!=')') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if(guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } if (guidString[8+startPos] != '-' || guidString[13+startPos] != '-' || guidString[18+startPos] != '-' || guidString[23+startPos] != '-') { result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes"); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos=currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines; private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { return StringToShort(str, null, requiredLength, flags, out result, ref parseResult); } private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult); } } private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { return StringToInt(str, null, requiredLength, flags, out result, ref parseResult); } private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult); } } private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = (parsePos == null) ? 0 : (*parsePos); try { result = ParseNumbers.StringToInt(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } return true; } private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) { return StringToLong(str, null, flags, out result, ref parseResult); } private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToLong(str, ppos, flags, out result, ref parseResult); } } private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static String EatAllWhitespace(String str) { int newLength = 0; char[] chArr = new char[str.Length]; char curChar; // Now get each char from str and if it is not whitespace add it to chArr for(int i = 0; i < str.Length; i++) { curChar = str[i]; if(!Char.IsWhiteSpace(curChar)) { chArr[newLength++] = curChar; } } // Return a new string based on chArr return new String(chArr, 0, newLength); } private static bool IsHexPrefix(String str, int i) { if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x')) return true; else return false; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } // Returns the guid in "registry" format. public override String ToString() { return ToString("D",null); } public unsafe override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. fixed (int* ptr = &this._a) return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3]; } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(Object o) { Guid g; // Check that o is a Guid first if(o == null || !(o is Guid)) return false; else g = (Guid) o; // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } public bool Equals(Guid g) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } private int GetResult(uint me, uint them) { if (me<them) { return -1; } return 1; } public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"), nameof(value)); } Guid g = (Guid)value; if (g._a!=this._a) { return GetResult((uint)this._a, (uint)g._a); } if (g._b!=this._b) { return GetResult((uint)this._b, (uint)g._b); } if (g._c!=this._c) { return GetResult((uint)this._c, (uint)g._c); } if (g._d!=this._d) { return GetResult((uint)this._d, (uint)g._d); } if (g._e!=this._e) { return GetResult((uint)this._e, (uint)g._e); } if (g._f!=this._f) { return GetResult((uint)this._f, (uint)g._f); } if (g._g!=this._g) { return GetResult((uint)this._g, (uint)g._g); } if (g._h!=this._h) { return GetResult((uint)this._h, (uint)g._h); } if (g._i!=this._i) { return GetResult((uint)this._i, (uint)g._i); } if (g._j!=this._j) { return GetResult((uint)this._j, (uint)g._j); } if (g._k!=this._k) { return GetResult((uint)this._k, (uint)g._k); } return 0; } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=(Guid a, Guid b) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. public static Guid NewGuid() { // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some // uniqueness guarantees. It should also never return a known GUID, but it's unclear // how extensively it checks for known values. Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid guid; Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1)); return guid; } public String ToString(String format) { return ToString(format, null); } private static char HexToChar(int a) { a = a & 0xf; return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30); } unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b) { return HexsToChars(guidChars, offset, a, b, false); } unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(a>>4); guidChars[offset++] = HexToChar(a); if (hex) { guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(b>>4); guidChars[offset++] = HexToChar(b); return offset; } // IFormattable interface // We currently ignore provider public String ToString(String format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; string guidString; int offset = 0; bool dash = true; bool hex = false; if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { guidString = string.FastAllocateString(36); } else if (formatCh == 'N' || formatCh == 'n') { guidString = string.FastAllocateString(32); dash = false; } else if (formatCh == 'B' || formatCh == 'b') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[37] = '}'; } } } else if (formatCh == 'P' || formatCh == 'p') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '('; guidChars[37] = ')'; } } } else if (formatCh == 'X' || formatCh == 'x') { guidString = string.FastAllocateString(68); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[67] = '}'; } } dash = false; hex = true; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } unsafe { fixed (char* guidChars = guidString) { if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); guidChars[offset++] = ','; guidChars[offset++] = '{'; offset = HexsToChars(guidChars, offset, _d, _e, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _f, _g, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _h, _i, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _j, _k, true); guidChars[offset++] = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _d, _e); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _f, _g); offset = HexsToChars(guidChars, offset, _h, _i); offset = HexsToChars(guidChars, offset, _j, _k); } } } return guidString; } } }
// 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.IO; using System.Linq; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { public static class CmsRecipientCollectionTests { [Fact] public static void Nullary() { CmsRecipientCollection c = new CmsRecipientCollection(); AssertEquals(c, Array.Empty<CmsRecipient>()); } [Fact] public static void Oneary() { CmsRecipient a0 = s_cr0; CmsRecipientCollection c = new CmsRecipientCollection(a0); AssertEquals(c, new CmsRecipient[] { a0 }); } [Fact] public static void Twoary() { CmsRecipient a0 = s_cr0; CmsRecipientCollection c = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, new X509Certificate2Collection(a0.Certificate)); Assert.Equal(1, c.Count); CmsRecipient actual = c[0]; Assert.Equal(a0.RecipientIdentifierType, actual.RecipientIdentifierType); Assert.Equal(a0.Certificate, actual.Certificate); } [Fact] public static void Twoary_Ski() { CmsRecipient a0 = s_cr0; CmsRecipientCollection c = new CmsRecipientCollection(SubjectIdentifierType.SubjectKeyIdentifier, new X509Certificate2Collection(a0.Certificate)); Assert.Equal(1, c.Count); CmsRecipient actual = c[0]; Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, actual.RecipientIdentifierType); Assert.Equal(a0.Certificate, actual.Certificate); } [Fact] public static void Twoary_Negative() { object ignore; Assert.Throws<NullReferenceException>(() => ignore = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void Add() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); int index; index = c.Add(a0); Assert.Equal(0, index); index = c.Add(a1); Assert.Equal(1, index); index = c.Add(a2); Assert.Equal(2, index); AssertEquals(c, new CmsRecipient[] { a0, a1, a2 }); } [Fact] public static void Remove() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); int index; index = c.Add(a0); Assert.Equal(0, index); index = c.Add(a1); Assert.Equal(1, index); index = c.Add(a2); Assert.Equal(2, index); c.Remove(a1); AssertEquals(c, new CmsRecipient[] { a0, a2 }); } [Fact] public static void AddNegative() { CmsRecipientCollection c = new CmsRecipientCollection(); Assert.Throws<ArgumentNullException>(() => c.Add(null)); } [Fact] public static void RemoveNegative() { CmsRecipientCollection c = new CmsRecipientCollection(); Assert.Throws<ArgumentNullException>(() => c.Remove(null)); } [Fact] public static void RemoveNonExistent() { CmsRecipientCollection c = new CmsRecipientCollection(); CmsRecipient a0 = s_cr0; c.Remove(a0); // You can "remove" items that aren't in the collection - this is defined as a NOP. } [Fact] public static void IndexOutOfBounds() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); c.Add(a0); c.Add(a1); c.Add(a2); object ignore = null; Assert.Throws<ArgumentOutOfRangeException>(() => ignore = c[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ignore = c[3]); } [Fact] public static void CopyExceptions() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); c.Add(a0); c.Add(a1); c.Add(a2); CmsRecipient[] a = new CmsRecipient[3]; Assert.Throws<ArgumentNullException>(() => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, 3)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(a, 1)); ICollection ic = c; Assert.Throws<ArgumentNullException>(() => ic.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(a, 3)); AssertExtensions.Throws<ArgumentException>(null, () => ic.CopyTo(a, 1)); AssertExtensions.Throws<ArgumentException>(null, () => ic.CopyTo(new CmsRecipient[2, 2], 1)); Assert.Throws<InvalidCastException>(() => ic.CopyTo(new int[10], 1)); if (PlatformDetection.IsNonZeroLowerBoundArraySupported) { // Array has non-zero lower bound Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => ic.CopyTo(array, 0)); } } private static void AssertEquals(CmsRecipientCollection c, IList<CmsRecipient> expected) { Assert.Equal(expected.Count, c.Count); for (int i = 0; i < c.Count; i++) { Assert.Equal(expected[i], c[i]); } int index = 0; foreach (CmsRecipient a in c) { Assert.Equal(expected[index++], a); } Assert.Equal(c.Count, index); ValidateEnumerator(c.GetEnumerator(), expected); ValidateEnumerator(((ICollection)c).GetEnumerator(), expected); { CmsRecipient[] dumped = new CmsRecipient[c.Count + 3]; c.CopyTo(dumped, 2); Assert.Equal(null, dumped[0]); Assert.Equal(null, dumped[1]); Assert.Equal(null, dumped[dumped.Length - 1]); Assert.Equal<CmsRecipient>(expected, dumped.Skip(2).Take(c.Count)); } { CmsRecipient[] dumped = new CmsRecipient[c.Count + 3]; ((ICollection)c).CopyTo(dumped, 2); Assert.Equal(null, dumped[0]); Assert.Equal(null, dumped[1]); Assert.Equal(null, dumped[dumped.Length - 1]); Assert.Equal<CmsRecipient>(expected, dumped.Skip(2).Take(c.Count)); } } private static void ValidateEnumerator(IEnumerator enumerator, IList<CmsRecipient> expected) { foreach (CmsRecipient e in expected) { Assert.True(enumerator.MoveNext()); CmsRecipient actual = (CmsRecipient)(enumerator.Current); Assert.Equal(e, actual); } Assert.False(enumerator.MoveNext()); } private static readonly CmsRecipient s_cr0 = new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()); private static readonly CmsRecipient s_cr1 = new CmsRecipient(Certificates.RSAKeyTransfer2.GetCertificate()); private static readonly CmsRecipient s_cr2 = new CmsRecipient(Certificates.RSAKeyTransfer3.GetCertificate()); } }
/* * 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 log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class UserAccountServicesConnector : IUserAccountService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public UserAccountServicesConnector() { } public UserAccountServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public UserAccountServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig assetConfig = source.Configs["UserAccountService"]; if (assetConfig == null) { m_log.Error("[ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini"); throw new Exception("User account connector init error"); } string serviceURI = assetConfig.GetString("UserAccountServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ACCOUNT CONNECTOR]: No Server URI named in section UserAccountService"); throw new Exception("User account connector init error"); } m_ServerURI = serviceURI; } public virtual UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccount"; sendData["ScopeID"] = scopeID; sendData["FirstName"] = firstName.ToString(); sendData["LastName"] = lastName.ToString(); return SendAndGetReply(sendData); } public virtual UserAccount GetUserAccount(UUID scopeID, string email) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccount"; sendData["ScopeID"] = scopeID; sendData["Email"] = email; return SendAndGetReply(sendData); } public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID) { m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccount {0}", userID); Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccount"; sendData["ScopeID"] = scopeID; sendData["UserID"] = userID.ToString(); return SendAndGetReply(sendData); } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccounts"; sendData["ScopeID"] = scopeID.ToString(); sendData["query"] = query; string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/accounts", reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting accounts server: {0}", e.Message); } List<UserAccount> accounts = new List<UserAccount>(); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && replyData.ContainsKey("result").ToString() == "null") { return accounts; } Dictionary<string, object>.ValueCollection accountList = replyData.Values; //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object acc in accountList) { if (acc is Dictionary<string, object>) { UserAccount pinfo = new UserAccount((Dictionary<string, object>)acc); accounts.Add(pinfo); } else m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}", acc.GetType()); } } else m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response"); return accounts; } public virtual bool StoreUserAccount(UserAccount data) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "setaccount"; Dictionary<string, object> structData = data.ToKeyValuePairs(); foreach (KeyValuePair<string,object> kvp in structData) sendData[kvp.Key] = kvp.Value.ToString(); return SendAndGetBoolReply(sendData); } private UserAccount SendAndGetReply(Dictionary<string, object> sendData) { string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/accounts", reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccount received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user account server: {0}", e.Message); } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); UserAccount account = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) { account = new UserAccount((Dictionary<string, object>)replyData["result"]); } } return account; } private bool SendAndGetBoolReply(Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/accounts", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount reply data does not contain result field"); } else m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount received empty reply"); } catch (Exception e) { m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Exception when contacting user account server: {0}", e.Message); } return false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.CompilerServices; using System.IO; using System.Collections; using System.Globalization; using System.Text; using System.Threading; using Xunit; public class FileInfo_set_Attributes { public static String s_strActiveBugNums = ""; public static String s_strDtTmVer = "2000/05/09 11:28"; public static String s_strClassMethod = "File.Directory()"; public static String s_strTFName = "set_Attributes.cs"; public static String s_strTFPath = Directory.GetCurrentDirectory(); [Fact] public static void runTest() { String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// String filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName()); FileInfo fil2; /* ReadOnly = 0x1, Hidden = 0x2, System = 0x4, Directory = 0x10, Archive = 0x20, Encrypted = 0x40, Normal = 0x80, Temporary = 0x100, SparseFile = 0x200, ReparsePoint = 0x400, Compressed = 0x800, Offline = 0x1000, NotContentIndexed = 0x2000 */ if (File.Exists(filName)) { fil2 = new FileInfo(filName); fil2.Attributes = new FileAttributes(); File.Delete(filName); } // [] File does not exist //-------------------------------------------------------- strLoc = "loc_2yg8c"; fil2 = new FileInfo("FileDoesNotExist"); iCountTestcases++; try { fil2.Attributes = new FileAttributes(); iCountErrors++; printerr("Error_27t8b! Expected exception not thrown"); } catch (FileNotFoundException) { } catch (Exception exc) { iCountErrors++; printerr("Error_21409! Incorrect exception thrown, exc==" + exc.ToString()); } //----------------------------------------------------------------- File.Create(filName).Dispose(); /* // [] Invalid enum value //----------------------------------------------------------------- strLoc = "Loc_298g8"; fil2 = new FileInfo(filName); iCountTestcases++; try { fil2.Attributes = (FileAttributes)0x4000; iCountErrors++; printerr( "Error_28g8b! Expected exception not thrown"); } catch (ArgumentException aexc) { } catch (Exception exc) { iCountErrors++; printerr( "Error_t94u9! Incorrect exception thrown, exc=="+exc.ToString()); } //----------------------------------------------------------------- */ try { // [] valid data //----------------------------------------------------------------- strLoc = "Loc_48yx9"; fil2 = new FileInfo(filName); fil2.Attributes = FileAttributes.Hidden; iCountTestcases++; #if TEST_WINRT // WinRT doesn't support hidden if ((fil2.Attributes & FileAttributes.Hidden)!=0) { #else if ((fil2.Attributes & FileAttributes.Hidden) == 0 && Interop.IsWindows) // setting Hidden not supported on Unix { #endif iCountErrors++; printerr("ERror_2g985! Hidden not set"); } fil2.Attributes = FileAttributes.System | FileAttributes.Normal; fil2.Refresh(); iCountTestcases++; #if TEST_WINRT // WinRT doesn't support system if((fil2.Attributes & FileAttributes.System) == FileAttributes.System) { #else if ((fil2.Attributes & FileAttributes.System) != FileAttributes.System && Interop.IsWindows) // setting System not supported on Unix { #endif iCountErrors++; printerr("Error_298g7! System not set"); } fil2.Attributes = FileAttributes.Temporary; fil2.Refresh(); iCountTestcases++; if ((fil2.Attributes & FileAttributes.Temporary) == 0 && Interop.IsWindows) // setting Temporary not supported on Unix { iCountErrors++; printerr("Error_87tg8! Temporary not set"); } //----------------------------------------------------------------- // [] //----------------------------------------------------------------- strLoc = "Loc_29gy7"; fil2 = new FileInfo(filName); fil2.Attributes = FileAttributes.ReadOnly; fil2.Refresh(); fil2.Attributes = fil2.Attributes | FileAttributes.Encrypted | FileAttributes.Archive; fil2.Refresh(); iCountTestcases++; if ((fil2.Attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly) { iCountErrors++; printerr("Error_g58y8! ReadOnly attribute not set"); } iCountTestcases++; if ((fil2.Attributes & FileAttributes.Archive) != FileAttributes.Archive && Interop.IsWindows) // setting Archive not supported on Unix { iCountErrors++; printerr("Error_2g78b! Archive attribute not set"); } fil2.Attributes = new FileAttributes(); //----------------------------------------------------------------- } catch (Exception exc) { iCountErrors++; printerr("Error_284y8! Unexpected exception thrown, bug 29808, exc==" + exc.ToString()); } if (File.Exists(filName)) { fil2 = new FileInfo(filName); fil2.Attributes = new FileAttributes(); File.Delete(filName); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics if (iCountErrors != 0) { Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString()); } Assert.Equal(0, iCountErrors); } public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err); } }
//--------------------------------------- // Sphere.cs (c) 2007 by Charles Petzold //--------------------------------------- using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; namespace Petzold.Media3D { public class Sphere : ModelVisualBase { // Objects reused by calls to Triangulate. AxisAngleRotation3D rotate; RotateTransform3D xform; // Public constructor to initialize those fields, etc public Sphere() { rotate = new AxisAngleRotation3D(); xform = new RotateTransform3D(rotate); PropertyChanged(this, new DependencyPropertyChangedEventArgs()); } // Dependency properties public static readonly DependencyProperty SlicesProperty = DependencyProperty.Register("Slices", typeof(int), typeof(Sphere), new PropertyMetadata(36, PropertyChanged), ValidatePositive); public static readonly DependencyProperty StacksProperty = DependencyProperty.Register("Stacks", typeof(int), typeof(Sphere), new PropertyMetadata(18, PropertyChanged), ValidatePositive); public static readonly DependencyProperty CenterProperty = DependencyProperty.Register("Center", typeof(Point3D), typeof(Sphere), new PropertyMetadata(new Point3D(0, 0, 0), PropertyChanged)); public static readonly DependencyProperty LongitudeFromProperty = DependencyProperty.Register("LongitudeFrom", typeof(Double), typeof(Sphere), new PropertyMetadata(-180.0, PropertyChanged), ValidateLongitude); public static readonly DependencyProperty LongitudeToProperty = DependencyProperty.Register("LongitudeTo", typeof(Double), typeof(Sphere), new PropertyMetadata(180.0, PropertyChanged), ValidateLongitude); public static readonly DependencyProperty LatitudeFromProperty = DependencyProperty.Register("LatitudeFrom", typeof(Double), typeof(Sphere), new PropertyMetadata(90.0, PropertyChanged), ValidateLatitude); public static readonly DependencyProperty LatitudeToProperty = DependencyProperty.Register("LatitudeTo", typeof(Double), typeof(Sphere), new PropertyMetadata(-90.0, PropertyChanged), ValidateLatitude); public static readonly DependencyProperty RadiusProperty = DependencyProperty.Register("Radius", typeof(double), typeof(Sphere), new PropertyMetadata(1.0, PropertyChanged), ValidateNonNegative); // CLR properties public int Slices { get { return (int)GetValue(SlicesProperty); } set { SetValue(SlicesProperty, value); } } public int Stacks { get { return (int)GetValue(StacksProperty); } set { SetValue(StacksProperty, value); } } public Point3D Center { get { return (Point3D)GetValue(CenterProperty); } set { SetValue(CenterProperty, value); } } public Double LongitudeFrom { get { return (Double)GetValue(LongitudeFromProperty); } set { SetValue(LongitudeFromProperty, value); } } public Double LongitudeTo { get { return (Double)GetValue(LongitudeToProperty); } set { SetValue(LongitudeFromProperty, value); } } public Double LatitudeFrom { get { return (Double)GetValue(LatitudeFromProperty); } set { SetValue(LatitudeFromProperty, value); } } public Double LatitudeTo { get { return (Double)GetValue(LatitudeToProperty); } set { SetValue(LatitudeToProperty, value); } } public double Radius { get { return (double)GetValue(RadiusProperty); } set { SetValue(RadiusProperty, value); } } // Private validate methods static bool ValidatePositive(object value) { return (int)value > 0; } static bool ValidateNonNegative(object value) { return (double)value >= 0; } static bool ValidateLongitude(object value) { Double d = (double)value; return d >= -180 && d <= 180; } static bool ValidateLatitude(object value) { Double d = (double)value; return d >= -90 && d <= 90; } protected override void Triangulate(DependencyPropertyChangedEventArgs args, Point3DCollection vertices, Vector3DCollection normals, Int32Collection indices, PointCollection textures) { vertices.Clear(); normals.Clear(); indices.Clear(); textures.Clear(); // Copy properties to local variables to improve speed int slices = Slices; int stacks = Stacks; double radius = Radius; Point3D ctr = Center; double lat1 = Math.Max(LatitudeFrom, LatitudeTo); // default is 90 double lat2 = Math.Min(LatitudeFrom, LatitudeTo); // default is -90 double lng1 = LongitudeFrom; // default is -180 double lng2 = LongitudeTo; // default is 180 for (int lat = 0; lat <= stacks; lat++) { double degrees = lat1 - lat * (lat1 - lat2) / stacks; double angle = Math.PI * degrees / 180; double y = radius * Math.Sin(angle); double scale = Math.Cos(angle); for (int lng = 0; lng <= slices; lng++) { double diff = lng2 - lng1; if (diff < 0) diff += 360; degrees = lng1 + lng * diff / slices; angle = Math.PI * degrees / 180; double x = radius * scale * Math.Sin(angle); double z = radius * scale * Math.Cos(angle); Vector3D vect = new Vector3D(x, y, z); vertices.Add(ctr + vect); normals.Add(vect); textures.Add(new Point((double)lng / slices, (double)lat / stacks)); } } for (int lat = 0; lat < stacks; lat++) { int start = lat * (slices + 1); int next = start + slices + 1; for (int lng = 0; lng < slices; lng++) { indices.Add(start + lng); indices.Add(next + lng); indices.Add(next + lng + 1); indices.Add(start + lng); indices.Add(next + lng + 1); indices.Add(start + lng + 1); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Appearance { /// <summary> /// A module that just holds commands for inspecting avatar appearance. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AppearanceInfoModule")] public class AppearanceInfoModule : ISharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_scenes = new List<Scene>(); // private IAvatarFactoryModule m_avatarFactory; public string Name { get { return "Appearance Information Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Remove(scene); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Add(scene); scene.AddCommand( "Users", this, "show appearance", "show appearance [<first-name> <last-name>]", "Synonym for 'appearance show'", HandleShowAppearanceCommand); scene.AddCommand( "Users", this, "appearance show", "appearance show [<first-name> <last-name>]", "Show appearance information for avatars.", "This command checks whether the simulator has all the baked textures required to display an avatar to other viewers. " + "\nIf not, then appearance is 'corrupt' and other avatars will continue to see it as a cloud." + "\nOptionally, you can view just a particular avatar's appearance information." + "\nIn this case, the texture UUID for each bake type is also shown and whether the simulator can find the referenced texture.", HandleShowAppearanceCommand); scene.AddCommand( "Users", this, "appearance send", "appearance send [<first-name> <last-name>]", "Send appearance data for each avatar in the simulator to other viewers.", "Optionally, you can specify that only a particular avatar's appearance data is sent.", HandleSendAppearanceCommand); scene.AddCommand( "Users", this, "appearance rebake", "appearance rebake <first-name> <last-name>", "Send a request to the user's viewer for it to rebake and reupload its appearance textures.", "This is currently done for all baked texture references previously received, whether the simulator can find the asset or not." + "\nThis will only work for texture ids that the viewer has already uploaded." + "\nIf the viewer has not yet sent the server any texture ids then nothing will happen" + "\nsince requests can only be made for ids that the client has already sent us", HandleRebakeAppearanceCommand); scene.AddCommand( "Users", this, "appearance find", "appearance find <uuid-or-start-of-uuid>", "Find out which avatar uses the given asset as a baked texture, if any.", "You can specify just the beginning of the uuid, e.g. 2008a8d. A longer UUID must be in dashed format.", HandleFindAppearanceCommand); scene.AddCommand( "Users", this, "wearables show", "wearables show [<first-name> <last-name>]", "Show information about wearables for avatars.", "If no avatar name is given then a general summary for all avatars in the scene is shown.\n" + "If an avatar name is given then specific information about current wearables is shown.", HandleShowWearablesCommand); scene.AddCommand( "Users", this, "wearables check", "wearables check <first-name> <last-name>", "Check that the wearables of a given avatar in the scene are valid.", "This currently checks that the wearable assets themselves and any assets referenced by them exist.", HandleCheckWearablesCommand); } private void HandleSendAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: appearance send [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } lock (m_scenes) { foreach (Scene scene in m_scenes) { if (targetNameSupplied) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) { MainConsole.Instance.OutputFormat( "Sending appearance information for {0} to all other avatars in {1}", sp.Name, scene.RegionInfo.RegionName); scene.AvatarFactory.SendAppearance(sp.UUID); } } else { scene.ForEachRootScenePresence( sp => { MainConsole.Instance.OutputFormat( "Sending appearance information for {0} to all other avatars in {1}", sp.Name, scene.RegionInfo.RegionName); scene.AvatarFactory.SendAppearance(sp.UUID); } ); } } } } private void HandleShowAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: appearance show [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } lock (m_scenes) { foreach (Scene scene in m_scenes) { if (targetNameSupplied) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) scene.AvatarFactory.WriteBakedTexturesReport(sp, MainConsole.Instance.OutputFormat); } else { scene.ForEachRootScenePresence( sp => { bool bakedTextureValid = scene.AvatarFactory.ValidateBakedTextureCache(sp); MainConsole.Instance.OutputFormat( "{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete"); } ); } } } } private void HandleRebakeAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 4) { MainConsole.Instance.OutputFormat("Usage: appearance rebake <first-name> <last-name>"); return; } string firstname = cmd[2]; string lastname = cmd[3]; lock (m_scenes) { foreach (Scene scene in m_scenes) { ScenePresence sp = scene.GetScenePresence(firstname, lastname); if (sp != null && !sp.IsChildAgent) { int rebakesRequested = scene.AvatarFactory.RequestRebake(sp, false); if (rebakesRequested > 0) MainConsole.Instance.OutputFormat( "Requesting rebake of {0} uploaded textures for {1} in {2}", rebakesRequested, sp.Name, scene.RegionInfo.RegionName); else MainConsole.Instance.OutputFormat( "No texture IDs available for rebake request for {0} in {1}", sp.Name, scene.RegionInfo.RegionName); } } } } private void HandleFindAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 3) { MainConsole.Instance.OutputFormat("Usage: appearance find <uuid-or-start-of-uuid>"); return; } string rawUuid = cmd[2]; HashSet<ScenePresence> matchedAvatars = new HashSet<ScenePresence>(); lock (m_scenes) { foreach (Scene scene in m_scenes) { scene.ForEachRootScenePresence( sp => { Dictionary<BakeType, Primitive.TextureEntryFace> bakedFaces = scene.AvatarFactory.GetBakedTextureFaces(sp.UUID); foreach (Primitive.TextureEntryFace face in bakedFaces.Values) { if (face != null && face.TextureID.ToString().StartsWith(rawUuid)) matchedAvatars.Add(sp); } }); } } if (matchedAvatars.Count == 0) { MainConsole.Instance.OutputFormat("{0} did not match any baked avatar textures in use", rawUuid); } else { MainConsole.Instance.OutputFormat( "{0} matched {1}", rawUuid, string.Join(", ", matchedAvatars.ToList().ConvertAll<string>(sp => sp.Name).ToArray())); } } protected void HandleShowWearablesCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: wearables show [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } StringBuilder sb = new StringBuilder(); if (targetNameSupplied) { lock (m_scenes) { foreach (Scene scene in m_scenes) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) AppendWearablesDetailReport(sp, sb); } } } else { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Name", ConsoleDisplayUtil.UserNameSize); cdt.AddColumn("Wearables", 2); lock (m_scenes) { foreach (Scene scene in m_scenes) { scene.ForEachRootScenePresence( sp => { int count = 0; for (int i = (int)WearableType.Shape; i < (int)WearableType.Physics; i++) count += sp.Appearance.Wearables[i].Count; cdt.AddRow(sp.Name, count); } ); } } sb.Append(cdt.ToString()); } MainConsole.Instance.Output(sb.ToString()); } private void HandleCheckWearablesCommand(string module, string[] cmd) { if (cmd.Length != 4) { MainConsole.Instance.OutputFormat("Usage: wearables check <first-name> <last-name>"); return; } string firstname = cmd[2]; string lastname = cmd[3]; StringBuilder sb = new StringBuilder(); UuidGatherer uuidGatherer = new UuidGatherer(m_scenes[0].AssetService); lock (m_scenes) { foreach (Scene scene in m_scenes) { ScenePresence sp = scene.GetScenePresence(firstname, lastname); if (sp != null && !sp.IsChildAgent) { sb.AppendFormat("Wearables checks for {0}\n\n", sp.Name); AvatarWearable[] wearables = sp.Appearance.Wearables; if(wearables.Count() == 0) { MainConsole.Instance.OutputFormat("avatar has no wearables"); return; } for (int i = 0; i < wearables.Count(); i++) { AvatarWearable aw = wearables[i]; sb.Append(Enum.GetName(typeof(WearableType), i)); sb.Append("\n"); if (aw.Count > 0) { for (int j = 0; j < aw.Count; j++) { WearableItem wi = aw[j]; ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.Indent = 2; cdl.AddRow("Item UUID", wi.ItemID); cdl.AddRow("Assets", ""); sb.Append(cdl.ToString()); uuidGatherer.AddForInspection(wi.AssetID); uuidGatherer.GatherAll(); string[] assetStrings = Array.ConvertAll<UUID, string>(uuidGatherer.GatheredUuids.Keys.ToArray(), u => u.ToString()); bool[] existChecks = scene.AssetService.AssetsExist(assetStrings); ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.Indent = 4; cdt.AddColumn("Type", 10); cdt.AddColumn("UUID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Found", 5); for (int k = 0; k < existChecks.Length; k++) cdt.AddRow( (AssetType)uuidGatherer.GatheredUuids[new UUID(assetStrings[k])], assetStrings[k], existChecks[k] ? "yes" : "no"); sb.Append(cdt.ToString()); sb.Append("\n"); } } else sb.Append(" Empty\n"); } } } } MainConsole.Instance.Output(sb.ToString()); } private void AppendWearablesDetailReport(ScenePresence sp, StringBuilder sb) { sb.AppendFormat("\nWearables for {0}\n", sp.Name); ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Type", 10); cdt.AddColumn("Item UUID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Asset UUID", ConsoleDisplayUtil.UuidSize); for (int i = (int)WearableType.Shape; i < (int)WearableType.Physics; i++) { AvatarWearable aw = sp.Appearance.Wearables[i]; for (int j = 0; j < aw.Count; j++) { WearableItem wi = aw[j]; cdt.AddRow(Enum.GetName(typeof(WearableType), i), wi.ItemID, wi.AssetID); } } sb.Append(cdt.ToString()); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; namespace BlueOnion { /// <summary> /// Summary description for EventsForm. /// </summary> public class EventsForm : Form { private bool suspendUpdates; private Event[] events; private ListBox eventsListBox; private Button okButton; private Button cancelButton; private Button newEventButton; private Button deleteEventButton; private RadioButton movableRadioButton; private RadioButton specialRadioButton; private TextBox descriptionTextBox; private Label weekdayLabel; private Label monthLlabel; private ComboBox weekdayComboBox; private ComboBox monthComboBox; private Label weekLabel; private ComboBox weekComboBox; private GroupBox movableGroupBox; private NumericUpDown specialDaysUpDown; private Label specialDaysLabel; private GroupBox specialGoupBox; private ComboBox recurringComboBox; private DateTimePicker recurringDateTimePicker; private GroupBox recurringGroupBox; private RadioButton recurringRadioButton; private GroupBox descriptionGroupBox; private ComboBox specialComboBox; private PictureBox pictureBoxHighlightColor; private CheckBox checkBoxHighlightDayForeColor; /// <summary> /// Required designer variable. /// </summary> private readonly Container components = null; // --------------------------------------------------------------------- public EventsForm(EventsCollection events, Color colorHighlightDate) { InitializeComponent(); weekdayComboBox.Items.AddRange (DateTimeFormatInfo.CurrentInfo.DayNames); monthComboBox.Items.AddRange(Event.AbbreviatedMonthNames); recurringComboBox.DataSource = RecurringEventNameValue.List(); recurringComboBox.DisplayMember = "Name"; recurringComboBox.ValueMember = "Value"; weekComboBox.Items.AddRange(Event.WeekNumbers()); specialComboBox.DataSource = SpecialEventNameValue.List(); specialComboBox.DisplayMember = "Name"; specialComboBox.ValueMember = "Value"; if (events != null) { eventsListBox.Items.AddRange(events.GetEvents()); if (eventsListBox.Items.Count != 0) { eventsListBox.SelectedIndex = 0; } } pictureBoxHighlightColor.BackColor = colorHighlightDate; } // --------------------------------------------------------------------- protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> // --------------------------------------------------------------------- private void InitializeComponent() { this.eventsListBox = new System.Windows.Forms.ListBox(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.newEventButton = new System.Windows.Forms.Button(); this.deleteEventButton = new System.Windows.Forms.Button(); this.movableRadioButton = new System.Windows.Forms.RadioButton(); this.specialRadioButton = new System.Windows.Forms.RadioButton(); this.descriptionTextBox = new System.Windows.Forms.TextBox(); this.weekdayLabel = new System.Windows.Forms.Label(); this.monthLlabel = new System.Windows.Forms.Label(); this.weekdayComboBox = new System.Windows.Forms.ComboBox(); this.monthComboBox = new System.Windows.Forms.ComboBox(); this.weekLabel = new System.Windows.Forms.Label(); this.weekComboBox = new System.Windows.Forms.ComboBox(); this.movableGroupBox = new System.Windows.Forms.GroupBox(); this.specialComboBox = new System.Windows.Forms.ComboBox(); this.specialDaysUpDown = new System.Windows.Forms.NumericUpDown(); this.specialDaysLabel = new System.Windows.Forms.Label(); this.specialGoupBox = new System.Windows.Forms.GroupBox(); this.recurringComboBox = new System.Windows.Forms.ComboBox(); this.recurringDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.recurringGroupBox = new System.Windows.Forms.GroupBox(); this.recurringRadioButton = new System.Windows.Forms.RadioButton(); this.descriptionGroupBox = new System.Windows.Forms.GroupBox(); this.pictureBoxHighlightColor = new System.Windows.Forms.PictureBox(); this.checkBoxHighlightDayForeColor = new System.Windows.Forms.CheckBox(); this.movableGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize) (this.specialDaysUpDown)).BeginInit(); this.specialGoupBox.SuspendLayout(); this.recurringGroupBox.SuspendLayout(); this.descriptionGroupBox.SuspendLayout(); this.SuspendLayout(); // // eventsListBox // this.eventsListBox.HorizontalScrollbar = true; this.eventsListBox.Location = new System.Drawing.Point(24, 8); this.eventsListBox.Name = "eventsListBox"; this.eventsListBox.Size = new System.Drawing.Size(296, 95); this.eventsListBox.TabIndex = 0; this.eventsListBox.SelectedIndexChanged += new System.EventHandler(this.eventsListBox_SelectedIndexChanged); // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.okButton.Location = new System.Drawing.Point(80, 448); this.okButton.Name = "okButton"; this.okButton.TabIndex = 11; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.cancelButton.Location = new System.Drawing.Point(176, 448); this.cancelButton.Name = "cancelButton"; this.cancelButton.TabIndex = 12; this.cancelButton.Text = "Cancel"; // // newEventButton // this.newEventButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.newEventButton.Location = new System.Drawing.Point(45, 112); this.newEventButton.Name = "newEventButton"; this.newEventButton.Size = new System.Drawing.Size(112, 24); this.newEventButton.TabIndex = 1; this.newEventButton.Text = "New Event"; this.newEventButton.Click += new System.EventHandler(this.newEventButton_Click); // // deleteEventButton // this.deleteEventButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.deleteEventButton.Location = new System.Drawing.Point(173, 112); this.deleteEventButton.Name = "deleteEventButton"; this.deleteEventButton.Size = new System.Drawing.Size(112, 24); this.deleteEventButton.TabIndex = 2; this.deleteEventButton.Text = "Delete Event"; this.deleteEventButton.Click += new System.EventHandler(this.deleteEventButton_Click); // // movableRadioButton // this.movableRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.movableRadioButton.Location = new System.Drawing.Point(8, 296); this.movableRadioButton.Name = "movableRadioButton"; this.movableRadioButton.Size = new System.Drawing.Size(16, 16); this.movableRadioButton.TabIndex = 7; this.movableRadioButton.CheckedChanged += new System.EventHandler(this.eventTypeRadioButton_CheckedChanged); // // specialRadioButton // this.specialRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.specialRadioButton.Location = new System.Drawing.Point(8, 384); this.specialRadioButton.Name = "specialRadioButton"; this.specialRadioButton.Size = new System.Drawing.Size(16, 16); this.specialRadioButton.TabIndex = 9; this.specialRadioButton.CheckedChanged += new System.EventHandler(this.eventTypeRadioButton_CheckedChanged); // // descriptionTextBox // this.descriptionTextBox.Location = new System.Drawing.Point(32, 168); this.descriptionTextBox.MaxLength = 50; this.descriptionTextBox.Name = "descriptionTextBox"; this.descriptionTextBox.Size = new System.Drawing.Size(280, 20); this.descriptionTextBox.TabIndex = 4; this.descriptionTextBox.Text = "event description"; this.descriptionTextBox.TextChanged += new System.EventHandler(this.descriptionTextBox_TextChanged); // // weekdayLabel // this.weekdayLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.weekdayLabel.Location = new System.Drawing.Point(104, 24); this.weekdayLabel.Name = "weekdayLabel"; this.weekdayLabel.Size = new System.Drawing.Size(72, 16); this.weekdayLabel.TabIndex = 2; this.weekdayLabel.Text = "Weekday"; // // monthLlabel // this.monthLlabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.monthLlabel.Location = new System.Drawing.Point(208, 24); this.monthLlabel.Name = "monthLlabel"; this.monthLlabel.Size = new System.Drawing.Size(72, 16); this.monthLlabel.TabIndex = 4; this.monthLlabel.Text = "Month"; // // weekdayComboBox // this.weekdayComboBox.AllowDrop = true; this.weekdayComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.weekdayComboBox.ItemHeight = 13; this.weekdayComboBox.Location = new System.Drawing.Point(104, 48); this.weekdayComboBox.MaxDropDownItems = 12; this.weekdayComboBox.Name = "weekdayComboBox"; this.weekdayComboBox.Size = new System.Drawing.Size(80, 21); this.weekdayComboBox.TabIndex = 3; this.weekdayComboBox.SelectedIndexChanged += new System.EventHandler(this.weekdayComboBox_SelectedIndexChanged); // // monthComboBox // this.monthComboBox.AllowDrop = true; this.monthComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.monthComboBox.ItemHeight = 13; this.monthComboBox.Location = new System.Drawing.Point(208, 48); this.monthComboBox.MaxDropDownItems = 12; this.monthComboBox.Name = "monthComboBox"; this.monthComboBox.Size = new System.Drawing.Size(80, 21); this.monthComboBox.TabIndex = 5; this.monthComboBox.SelectedIndexChanged += new System.EventHandler(this.monthComboBox_SelectedIndexChanged); // // weekLabel // this.weekLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.weekLabel.Location = new System.Drawing.Point(8, 24); this.weekLabel.Name = "weekLabel"; this.weekLabel.Size = new System.Drawing.Size(72, 16); this.weekLabel.TabIndex = 0; this.weekLabel.Text = "Week"; // // weekComboBox // this.weekComboBox.AllowDrop = true; this.weekComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.weekComboBox.ItemHeight = 13; this.weekComboBox.Location = new System.Drawing.Point(8, 48); this.weekComboBox.MaxDropDownItems = 12; this.weekComboBox.Name = "weekComboBox"; this.weekComboBox.Size = new System.Drawing.Size(80, 21); this.weekComboBox.TabIndex = 1; this.weekComboBox.SelectedIndexChanged += new System.EventHandler(this.weekComboBox_SelectedIndexChanged); // // movableGroupBox // this.movableGroupBox.Controls.Add(this.weekdayLabel); this.movableGroupBox.Controls.Add(this.monthLlabel); this.movableGroupBox.Controls.Add(this.weekdayComboBox); this.movableGroupBox.Controls.Add(this.monthComboBox); this.movableGroupBox.Controls.Add(this.weekLabel); this.movableGroupBox.Controls.Add(this.weekComboBox); this.movableGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.movableGroupBox.Location = new System.Drawing.Point(24, 296); this.movableGroupBox.Name = "movableGroupBox"; this.movableGroupBox.Size = new System.Drawing.Size(296, 80); this.movableGroupBox.TabIndex = 8; this.movableGroupBox.TabStop = false; this.movableGroupBox.Text = "Movable"; // // specialComboBox // this.specialComboBox.ItemHeight = 13; this.specialComboBox.Location = new System.Drawing.Point(8, 24); this.specialComboBox.Name = "specialComboBox"; this.specialComboBox.Size = new System.Drawing.Size(144, 21); this.specialComboBox.TabIndex = 0; this.specialComboBox.SelectedIndexChanged += new System.EventHandler(this.specialComboBox_SelectedIndexChanged); // // specialDaysUpDown // this.specialDaysUpDown.Location = new System.Drawing.Point(224, 24); this.specialDaysUpDown.Maximum = new System.Decimal(new int[] { 365, 0, 0, 0 }); this.specialDaysUpDown.Minimum = new System.Decimal(new int[] { 365, 0, 0, -2147483648 }); this.specialDaysUpDown.Name = "specialDaysUpDown"; this.specialDaysUpDown.Size = new System.Drawing.Size(48, 20); this.specialDaysUpDown.TabIndex = 2; this.specialDaysUpDown.ValueChanged += new System.EventHandler(this.specialDaysUpDown_ValueChanged); // // specialDaysLabel // this.specialDaysLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.specialDaysLabel.Location = new System.Drawing.Point(168, 26); this.specialDaysLabel.Name = "specialDaysLabel"; this.specialDaysLabel.Size = new System.Drawing.Size(48, 16); this.specialDaysLabel.TabIndex = 1; this.specialDaysLabel.Text = "+/- days"; // // specialGoupBox // this.specialGoupBox.Controls.Add(this.specialComboBox); this.specialGoupBox.Controls.Add(this.specialDaysUpDown); this.specialGoupBox.Controls.Add(this.specialDaysLabel); this.specialGoupBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.specialGoupBox.Location = new System.Drawing.Point(24, 384); this.specialGoupBox.Name = "specialGoupBox"; this.specialGoupBox.Size = new System.Drawing.Size(296, 56); this.specialGoupBox.TabIndex = 10; this.specialGoupBox.TabStop = false; this.specialGoupBox.Text = "Special"; // // recurringComboBox // this.recurringComboBox.ItemHeight = 13; this.recurringComboBox.Location = new System.Drawing.Point(120, 24); this.recurringComboBox.Name = "recurringComboBox"; this.recurringComboBox.Size = new System.Drawing.Size(120, 21); this.recurringComboBox.TabIndex = 1; this.recurringComboBox.SelectedIndexChanged += new System.EventHandler(this.recurringComboBox_SelectedIndexChanged); // // recurringDateTimePicker // this.recurringDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Short; this.recurringDateTimePicker.Location = new System.Drawing.Point(8, 24); this.recurringDateTimePicker.Name = "recurringDateTimePicker"; this.recurringDateTimePicker.Size = new System.Drawing.Size(96, 20); this.recurringDateTimePicker.TabIndex = 0; this.recurringDateTimePicker.Value = new System.DateTime(2005, 3, 11, 19, 52, 15, 920); this.recurringDateTimePicker.ValueChanged += new System.EventHandler(this.recurringDateTimePicker_ValueChanged); // // recurringGroupBox // this.recurringGroupBox.Controls.Add(this.recurringComboBox); this.recurringGroupBox.Controls.Add(this.recurringDateTimePicker); this.recurringGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.recurringGroupBox.Location = new System.Drawing.Point(24, 232); this.recurringGroupBox.Name = "recurringGroupBox"; this.recurringGroupBox.Size = new System.Drawing.Size(296, 56); this.recurringGroupBox.TabIndex = 6; this.recurringGroupBox.TabStop = false; this.recurringGroupBox.Text = "Recurring"; // // recurringRadioButton // this.recurringRadioButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.recurringRadioButton.Location = new System.Drawing.Point(8, 232); this.recurringRadioButton.Name = "recurringRadioButton"; this.recurringRadioButton.Size = new System.Drawing.Size(16, 16); this.recurringRadioButton.TabIndex = 5; this.recurringRadioButton.CheckedChanged += new System.EventHandler(this.eventTypeRadioButton_CheckedChanged); // // descriptionGroupBox // this.descriptionGroupBox.Controls.Add(this.pictureBoxHighlightColor); this.descriptionGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System; this.descriptionGroupBox.ForeColor = System.Drawing.SystemColors.ControlText; this.descriptionGroupBox.Location = new System.Drawing.Point(24, 144); this.descriptionGroupBox.Name = "descriptionGroupBox"; this.descriptionGroupBox.Size = new System.Drawing.Size(296, 80); this.descriptionGroupBox.TabIndex = 3; this.descriptionGroupBox.TabStop = false; this.descriptionGroupBox.Text = "Description"; // // pictureBoxHighlightColor // this.pictureBoxHighlightColor.BackColor = System.Drawing.SystemColors.Control; this.pictureBoxHighlightColor.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pictureBoxHighlightColor.Location = new System.Drawing.Point(264, 56); this.pictureBoxHighlightColor.Name = "pictureBoxHighlightColor"; this.pictureBoxHighlightColor.Size = new System.Drawing.Size(24, 16); this.pictureBoxHighlightColor.TabIndex = 14; this.pictureBoxHighlightColor.TabStop = false; // // checkBoxHighlightDayForeColor // this.checkBoxHighlightDayForeColor.Location = new System.Drawing.Point(32, 200); this.checkBoxHighlightDayForeColor.Name = "checkBoxHighlightColor"; this.checkBoxHighlightDayForeColor.Size = new System.Drawing.Size(152, 16); this.checkBoxHighlightDayForeColor.TabIndex = 13; this.checkBoxHighlightDayForeColor.Text = "Use highlight color"; this.checkBoxHighlightDayForeColor.CheckedChanged += new System.EventHandler(this.checkBoxHighlightDayForeColor_CheckedChanged); // // EventsForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(330, 480); this.ControlBox = false; this.Controls.Add(this.checkBoxHighlightDayForeColor); this.Controls.Add(this.deleteEventButton); this.Controls.Add(this.specialRadioButton); this.Controls.Add(this.movableRadioButton); this.Controls.Add(this.recurringRadioButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.recurringGroupBox); this.Controls.Add(this.movableGroupBox); this.Controls.Add(this.specialGoupBox); this.Controls.Add(this.eventsListBox); this.Controls.Add(this.newEventButton); this.Controls.Add(this.descriptionTextBox); this.Controls.Add(this.descriptionGroupBox); this.ForeColor = System.Drawing.SystemColors.ControlText; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "EventsForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Events"; this.Load += new System.EventHandler(this.EventsForm_Load); this.movableGroupBox.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize) (this.specialDaysUpDown)).EndInit(); this.specialGoupBox.ResumeLayout(false); this.recurringGroupBox.ResumeLayout(false); this.descriptionGroupBox.ResumeLayout(false); this.ResumeLayout(false); } #endregion // --------------------------------------------------------------------- private void eventsListBox_SelectedIndexChanged(object sender, EventArgs e) { var ev = eventsListBox.SelectedItem as Event; if (ev == null) { return; } suspendUpdates = true; // Recurring section descriptionTextBox.Text = ev.Description; // The DateTimePicker control's minimum date time is not the same as DateTime.MinValue var eventDate = ev.Date(); if (eventDate < recurringDateTimePicker.MinDate) { eventDate = recurringDateTimePicker.MinDate; } recurringDateTimePicker.Value = eventDate; recurringComboBox.SelectedIndex = Convert.ToInt32(ev.Recurring, CultureInfo.InvariantCulture); // Movable section weekComboBox.SelectedIndex = (ev.Week >= 1 && ev.Week <= Event.WeekNumbers().Length) ? ev.Week - 1 : 0; weekdayComboBox.SelectedIndex = Convert.ToInt32(ev.Weekday, CultureInfo.CurrentCulture); monthComboBox.SelectedIndex = (ev.EventType == EventType.Movable && ev.Recurring == RecurringEvent.Monthly) ? 0 : ev.Month; // Special section specialComboBox.SelectedValue = ev.Special; specialDaysUpDown.Value = ev.Days; // Activate dialog section based on event type switch (ev.EventType) { case EventType.Recurring: recurringRadioButton.Checked = true; break; case EventType.Movable: movableRadioButton.Checked = true; break; case EventType.Special: specialRadioButton.Checked = true; break; } // Highlight color check box checkBoxHighlightDayForeColor.Checked = ev.HighlightColor; suspendUpdates = false; } // --------------------------------------------------------------------- private void eventTypeRadioButton_CheckedChanged(object sender, EventArgs e) { var recurring = recurringRadioButton.Checked; var movable = movableRadioButton.Checked; var special = specialRadioButton.Checked; recurringGroupBox.Enabled = recurring; recurringDateTimePicker.Enabled = recurring; recurringComboBox.Enabled = recurring; movableGroupBox.Enabled = movable; weekComboBox.Enabled = movable; weekdayComboBox.Enabled = movable; monthComboBox.Enabled = movable; specialGoupBox.Enabled = special; specialComboBox.Enabled = special; specialDaysLabel.Enabled = special; specialDaysUpDown.Enabled = special; var ev = eventsListBox.SelectedItem as Event; if (ev != null) { if (recurring) { ev.EventType = EventType.Recurring; } if (movable) { ev.EventType = EventType.Movable; } if (special) { ev.EventType = EventType.Special; } suspendUpdates = true; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; suspendUpdates = false; } } // --------------------------------------------------------------------- private void newEventButton_Click(object sender, EventArgs e) { var ev = new Event(); ev.Description = "New Event"; eventsListBox.Items.Add(ev); eventsListBox.SelectedIndex = eventsListBox.Items.Count - 1; descriptionTextBox.Focus(); descriptionTextBox.SelectAll(); } // --------------------------------------------------------------------- private void deleteEventButton_Click(object sender, EventArgs e) { var selectedIndex = eventsListBox.SelectedIndex; eventsListBox.Items.RemoveAt(selectedIndex); if (eventsListBox.Items.Count > 0) { eventsListBox.SelectedIndex = Math.Max(0, selectedIndex - 1); } else { newEventButton_Click(sender, e); } } // --------------------------------------------------------------------- private void okButton_Click(object sender, EventArgs e) { events = new Event[eventsListBox.Items.Count]; for (var i = 0; i < eventsListBox.Items.Count; ++i) { events.SetValue(eventsListBox.Items[i], i); } } // --------------------------------------------------------------------- public Event[] GetEvents() { return events; } // --------------------------------------------------------------------- private void descriptionTextBox_TextChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.Description = descriptionTextBox.Text; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void recurringDateTimePicker_ValueChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { var date = recurringDateTimePicker.Value; ev.Day = date.Day; ev.Month = date.Month; ev.Year = date.Year; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void recurringComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.Recurring = (RecurringEvent) recurringComboBox.SelectedValue; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void weekComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.Week = weekComboBox.SelectedIndex + 1; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void weekdayComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.Weekday = (DayOfWeek) weekdayComboBox.SelectedIndex; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void monthComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { if (monthComboBox.SelectedIndex == 0) { ev.Month = 1; ev.Recurring = RecurringEvent.Monthly; } else { ev.Month = monthComboBox.SelectedIndex; ev.Recurring = RecurringEvent.Annually; } eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void specialComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.Special = (SpecialEvent) specialComboBox.SelectedValue; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void specialDaysUpDown_ValueChanged(object sender, EventArgs e) { if (suspendUpdates) { return; } var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.Days = Convert.ToInt32(specialDaysUpDown.Value); eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } // --------------------------------------------------------------------- private void EventsForm_Load(object sender, EventArgs e) { Location = Calendar.PositionAdjacent(this); } // --------------------------------------------------------------------- private void checkBoxHighlightDayForeColor_CheckedChanged(object sender, EventArgs e) { var ev = eventsListBox.SelectedItem as Event; if (ev != null) { ev.HighlightColor = checkBoxHighlightDayForeColor.Checked; eventsListBox.Items[eventsListBox.SelectedIndex] = ev; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Threading.Tasks.Tests { public class YieldAwaitableTests { // awaiting Task.Yield [Fact] public static void RunAsyncYieldAwaiterTests() { // Test direct usage works even though it's not encouraged { for (int i = 0; i < 2; i++) { SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = i == 0 ? new YieldAwaitable.YieldAwaiter() : new YieldAwaitable().GetAwaiter(); var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, "RunAsyncYieldAwaiterTests > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } } { // Yield when there's a current sync context SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format("RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, " > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } { // Yield when there's a current TaskScheduler Task.Factory.StartNew(() => { try { var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler."); mres.Set(); }); mres.Wait(); ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); } }, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait(); } { // Yield when there's a current TaskScheduler and SynchronizationContext.Current is the base SynchronizationContext Task.Factory.StartNew(() => { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); try { var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler."); mres.Set(); }); mres.Wait(); ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); } SynchronizationContext.SetSynchronizationContext(null); }, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait(); } { // OnCompleted grabs the current context, not Task.Yield nor GetAwaiter SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var ya = Task.Yield().GetAwaiter(); SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, " > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } } // awaiting Task.Yield [Fact] public static void RunAsyncYieldAwaiterTests_Negative() { // Yield when there's a current sync context SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = Task.Yield().GetAwaiter(); Assert.Throws<ArgumentNullException>(() => { ya.OnCompleted(null); }); } #region Helper Methods / Classes private class ValidateCorrectContextSynchronizationContext : SynchronizationContext { [ThreadStatic] internal static bool IsPostedInContext; internal int PostCount; internal int SendCount; public override void Post(SendOrPostCallback d, object state) { Interlocked.Increment(ref PostCount); Task.Run(() => { IsPostedInContext = true; d(state); IsPostedInContext = false; }); } public override void Send(SendOrPostCallback d, object state) { Interlocked.Increment(ref SendCount); d(state); } } /// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary> private class QUWITaskScheduler : TaskScheduler { private int _queueTaskCount; private int _tryExecuteTaskInlineCount; public int QueueTaskCount { get { return _queueTaskCount; } } public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } } protected override IEnumerable<Task> GetScheduledTasks() { return null; } protected override void QueueTask(Task task) { Interlocked.Increment(ref _queueTaskCount); Task.Run(() => TryExecuteTask(task)); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Interlocked.Increment(ref _tryExecuteTaskInlineCount); return TryExecuteTask(task); } } #endregion } }
//--------------------------------------------------------------------- // This file is part of the Microsoft .NET Framework SDK Code Samples. // // Copyright (C) Microsoft Corporation. All rights reserved. // //This source code is intended only as a supplement to Microsoft //Development Tools and/or on-line documentation. See these other //materials for detailed information regarding Microsoft code samples. // //THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY //KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE //IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //PARTICULAR PURPOSE. //--------------------------------------------------------------------- // This file has been updated by csells@sellsbrothers.com and is // redistributed w/o permission from Microsoft, Corp (although // I'm working on it) //--------------------------------------------------------------------- // NOTE: This provider uses Assembly metadata such as ProductName, etc. // to determine a workable registry path in which to store settings. // Note that these are NOT secure metadata elements, however they are // reasonably safe from collision but not at all safe from malicious tampering. // A robust implementation of the provider would include a better pathing algorithm. // NOTE: this provider is built to be a drop-in replacement for the // LocalFileSettingsProvider (LFSP), so when it doubt, it attempts to // do what the LFSP would do, except: // -this provider doesn't support roaming settings // -this provider ignores the values in the SettingsContext, // which means that settings groups won't work properly. //--------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Diagnostics; using System.Text; using System.Windows.Forms; using Microsoft.Win32; namespace WmcSoft.Configuration { class RegistrySettingsProvider : SettingsProvider, IApplicationSettingsProvider { /// <summary>Gets or sets the name of the currently running application.</summary> /// <returns>A string that contains the application's display name.</returns> public override string ApplicationName { get { return applicationName; } set { applicationName = value; } } string applicationName; RegistrySettingsProvider() { applicationName = Application.ProductName; } public override void Initialize(string name, NameValueCollection values) { if (string.IsNullOrEmpty(name)) { name = "RegistrySettingsProvider"; } base.Initialize(name, values); } // SetPropertyValue is invoked when ApplicationSettingsBase.Save is called // ASB makes sure to pass each provider only the values marked for that provider, // whether on a per setting or setting class-wide basis public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection values) { // Iterate through the settings to be stored string version = GetCurrentVersionNumber(); foreach (SettingsPropertyValue propval in values) { // If property hasn't been set, no need to save it if (!propval.IsDirty || (propval.SerializedValue == null)) { continue; } // Application-scoped settings can't change // NOTE: the settings machinery may cause or allow an app-scoped setting // to become dirty, in which case, like the LFSP, we ignore it instead // of throwning an exception if (IsApplicationScoped(propval.Property)) { continue; } using (RegistryKey key = CreateRegKey(propval.Property, version)) { key.SetValue(propval.Name, propval.SerializedValue); } } } public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties) { // Create new collection of values SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); string version = GetCurrentVersionNumber(); // Iterate through the settings to be retrieved foreach (SettingsProperty prop in properties) { SettingsPropertyValue value = GetPropertyValue(prop, version); Debug.Assert(value != null); values.Add(value); } return values; } SettingsPropertyValue GetPropertyValue(SettingsProperty prop, string version) { SettingsPropertyValue value = new SettingsPropertyValue(prop); // Only User-scoped settings can be found in the Registry. // By leaving the Application-scoped setting's value at null, // we get the "default" value if (IsUserScoped(prop)) { using (RegistryKey key = CreateRegKey(prop, version)) { value.SerializedValue = key.GetValue(prop.Name); } } value.IsDirty = false; return value; } // Looks in the "attribute bag" for a given property to determine if it is app-scoped bool IsApplicationScoped(SettingsProperty prop) { return HasSettingScope(prop, typeof(ApplicationScopedSettingAttribute)); } // Looks in the "attribute bag" for a given property to determine if it is user-scoped bool IsUserScoped(SettingsProperty prop) { return HasSettingScope(prop, typeof(UserScopedSettingAttribute)); } // Checks for app or user-scoped based on the attributeType argument // Also checks for sanity, i.e. a setting not marked as both or neither scope // (just like the LFSP) bool HasSettingScope(SettingsProperty prop, Type attributeType) { // TODO: add support for roaming Debug.Assert((attributeType == typeof(ApplicationScopedSettingAttribute)) || (attributeType == typeof(UserScopedSettingAttribute))); bool isAppScoped = prop.Attributes[typeof(ApplicationScopedSettingAttribute)] != null; bool isUserScoped = prop.Attributes[typeof(UserScopedSettingAttribute)] != null; // Check constraints if (isUserScoped && isAppScoped) { throw new ArgumentException("Can't mark a setting as User and Application-scoped: " + prop.Name + ".", "prop"); } else if (!isUserScoped && !isAppScoped) { throw new ArgumentException("Must mark a setting as User or Application-scoped: " + prop.Name + ".", "prop"); } // Return scope check result if (attributeType == typeof(ApplicationScopedSettingAttribute)) { return isAppScoped; } else if (attributeType == typeof(UserScopedSettingAttribute)) { return isUserScoped; } else { Debug.Assert(false); return false; } } // Creates a sub-key under HKCU\Software\CompanyName\ProductName\version RegistryKey CreateRegKey(SettingsProperty prop, string version) { Debug.Assert(!IsApplicationScoped(prop), "Can't get Registry key for a read-only Application scoped setting: " + prop.Name); return Registry.CurrentUser.CreateSubKey(GetSubKeyPath(version)); } // Adds a specific version to the version-independent key path string GetSubKeyPath(string version) { Debug.Assert(!string.IsNullOrEmpty(version)); return GetVersionIndependentSubKeyPath() + "\\" + version; } // Builds a key path based on the CompanyName and ProductName attributes in // the AssemblyInfo file (editable directly or within the Project Properties UI) string GetVersionIndependentSubKeyPath() { return "Software\\" + Application.CompanyName + "\\" + Application.ProductName; } string GetPreviousVersionNumber() { Version current = new Version(GetCurrentVersionNumber()); Version previous = null; // Enum setting versions using (RegistryKey key = Registry.CurrentUser.OpenSubKey(GetVersionIndependentSubKeyPath(), false)) { foreach (string keyName in key.GetSubKeyNames()) { try { Version version = new Version(keyName); if (version >= current) { continue; } if (previous == null || version > previous) { previous = version; } } catch { // If the version can't be created, don't cry about it... continue; } } } // Return the string of the previous version return (previous != null ? previous.ToString() : null); } string GetCurrentVersionNumber() { // The compiler will make sure this is a sane value return Application.ProductVersion; } #region IApplicationSettingsProvider Members // Will be called when MySettingsClass.GetPreviousVersion(propName) is called // This method's job is to retrieve a setting value from the previous version // of the settings w/o updating the setting at the storage location public SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty prop) { // If there's no previous setting version, return an empty property // NOTE: the LFSP returns an empty property for all app-scoped settings, so so do we string previousVersion = GetPreviousVersionNumber(); if (IsApplicationScoped(prop) || string.IsNullOrEmpty(previousVersion)) { // NOTE: can't just return null, as the settings engine turns that into // a default property -- have to return a SettingsPropertyValue object // with the PropertyValue set to null to really build an empty property SettingsPropertyValue propval = new SettingsPropertyValue(prop); propval.PropertyValue = null; return propval; } // Get the property value from the previous version // NOTE: if it's null, the settings machinery will assume the current default value // ideally, we'd want to use the previous version's default value, but a) that's // likely to be the current default value and b) if it's not, that data is lost return GetPropertyValue(prop, previousVersion); } // Will be called when MySettingsClass.Reset() is called // This method's job is to update the location where the settings are stored // with the default settings values. GetPropertyValues, overriden from the // SettingsProvider base, will be called to retrieve the new values from the // storage location public void Reset(SettingsContext context) { // Delete the user's current settings so that default values are used try { Registry.CurrentUser.DeleteSubKeyTree(GetSubKeyPath(GetCurrentVersionNumber())); } catch (ArgumentException) { // If the key's not there, this is the exception we'll get // TODO: figure out a way to detect that w/o consuming // an overly generic exception... } } // Will be called when MySettingsClass.Upgrade() is called // This method's job is to update the location where the settings are stored // with the previous version's values. GetPropertyValues, overriden from the // SettingsProvider base, will be called to retrieve the new values from the // storage location public void Upgrade(SettingsContext context, SettingsPropertyCollection properties) { // If there's no previous version, do nothing (just like the LFSP) string previousVersion = GetPreviousVersionNumber(); if (string.IsNullOrEmpty(previousVersion)) { return; } // Delete the current setting values Reset(context); // Copy the old settings to the new version string currentVersion = GetCurrentVersionNumber(); using (RegistryKey keyPrevious = Registry.CurrentUser.OpenSubKey(GetSubKeyPath(previousVersion), false)) using (RegistryKey keyCurrent = Registry.CurrentUser.CreateSubKey(GetSubKeyPath(currentVersion), RegistryKeyPermissionCheck.ReadWriteSubTree)) { foreach (string valueName in keyPrevious.GetValueNames()) { object serializedValue = keyPrevious.GetValue(valueName); if (serializedValue != null) { keyCurrent.SetValue(valueName, serializedValue); } } } } #endregion } }
// ---------------------------------------------------------------------------------- // // 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; using System.Collections.Generic; using System.IO; using System.Management.Automation; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Used to initiate a failover operation. /// </summary> [Cmdlet( VerbsLifecycle.Start, "AzureRmRecoveryServicesAsrPlannedFailoverJob", DefaultParameterSetName = ASRParameterSets.ByRPIObject, SupportsShouldProcess = true)] [Alias( "Start-ASRPFO", "Start-ASRPlannedFailoverJob")] [OutputType(typeof(ASRJob))] public class StartAzureRmRecoveryServicesAsrPlannedFailoverJob : SiteRecoveryCmdletBase { /// <summary> /// Gets or sets Recovery Plan object. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRRecoveryPlan RecoveryPlan { get; set; } /// <summary> /// Gets or sets Replication Protected Item. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRReplicationProtectedItem ReplicationProtectedItem { get; set; } /// <summary> /// Gets or sets Failover direction for the protected Item. /// </summary> [Parameter(Mandatory = true)] [ValidateSet( Constants.PrimaryToRecovery, Constants.RecoveryToPrimary)] public string Direction { get; set; } /// <summary> /// Gets or sets the Optimize value. /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false)] [ValidateSet( Constants.ForDownTime, Constants.ForSynchronization)] public string Optimize { get; set; } /// <summary> /// Gets or sets the recovery vm creation value. /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false)] [ValidateSet( Constants.Yes, Constants.No)] public string CreateVmIfNotFound { get; set; } /// <summary> /// Gets or sets hyper-V recovery services provider to create vm on. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = false, ValueFromPipeline = false)] public ASRRecoveryServicesProvider ServicesProvider { get; set; } /// <summary> /// Gets or sets Data encryption certificate file path for failover of Protected Item. /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false)] [ValidateNotNullOrEmpty] public string DataEncryptionPrimaryCertFile { get; set; } /// <summary> /// Gets or sets Data encryption certificate file path for failover of Protected Item. /// </summary> [Parameter( Mandatory = false, ValueFromPipeline = false)] [ValidateNotNullOrEmpty] public string DataEncryptionSecondaryCertFile { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( "Protected item or Recovery plan", "Start planned failover")) { if (!string.IsNullOrEmpty(this.DataEncryptionPrimaryCertFile)) { var certBytesPrimary = File.ReadAllBytes(this.DataEncryptionPrimaryCertFile); this.primaryKekCertpfx = Convert.ToBase64String(certBytesPrimary); } if (!string.IsNullOrEmpty(this.DataEncryptionSecondaryCertFile)) { var certBytesSecondary = File.ReadAllBytes(this.DataEncryptionSecondaryCertFile); this.secondaryKekCertpfx = Convert.ToBase64String(certBytesSecondary); } switch (this.ParameterSetName) { case ASRParameterSets.ByRPIObject: this.protectionContainerName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers); this.fabricName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationFabrics); this.StartRPIPlannedFailover(); break; case ASRParameterSets.ByRPObject: this.StartRpPlannedFailover(); break; } } } /// <summary> /// Starts RPI Planned failover. /// </summary> private void StartRPIPlannedFailover() { var plannedFailoverInputProperties = new PlannedFailoverInputProperties { FailoverDirection = this.Direction, ProviderSpecificDetails = new ProviderSpecificFailoverInput() }; var input = new PlannedFailoverInput { Properties = plannedFailoverInputProperties }; if (0 == string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { if (this.Direction == Constants.PrimaryToRecovery) { var failoverInput = new HyperVReplicaAzureFailoverProviderInput { PrimaryKekCertificatePfx = this.primaryKekCertpfx, SecondaryKekCertificatePfx = this.secondaryKekCertpfx, VaultLocation = "dummy" }; input.Properties.ProviderSpecificDetails = failoverInput; } else { var failbackInput = new HyperVReplicaAzureFailbackProviderInput { DataSyncOption = this.Optimize == Constants.ForDownTime ? Constants.ForDownTime : Constants.ForSynchronization, RecoveryVmCreationOption = string.Compare( this.CreateVmIfNotFound, Constants.Yes, StringComparison.OrdinalIgnoreCase) == 0 ? Constants.CreateVmIfNotFound : Constants.NoAction }; if ((string.Compare( this.CreateVmIfNotFound, Constants.Yes, StringComparison.OrdinalIgnoreCase) == 0) && this.RecoveryServicesClient.GetAzureSiteRecoveryFabric(this.fabricName) .Properties.CustomDetails is HyperVSiteDetails) { if ((this.ServicesProvider == null) || (string.Compare( this.ServicesProvider.FabricType, Constants.HyperVSite) != 0)) { throw new InvalidOperationException( Resources.ImproperServerObjectPassedForHyperVFailback); } failbackInput.ProviderIdForAlternateRecovery = this.ServicesProvider.ID; } input.Properties.ProviderSpecificDetails = failbackInput; } } else if (string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.InMage, StringComparison.OrdinalIgnoreCase) == 0) { throw new InvalidOperationException( string.Format( Resources.UnsupportedReplicationProviderForPlannedFailover, this.ReplicationProtectedItem.ReplicationProvider)); } var response = this.RecoveryServicesClient.StartAzureSiteRecoveryPlannedFailover( this.fabricName, this.protectionContainerName, this.ReplicationProtectedItem.Name, input); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } /// <summary> /// Starts RP Planned failover. /// </summary> private void StartRpPlannedFailover() { // Refresh RP Object var rp = this.RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan( this.RecoveryPlan.Name); var recoveryPlanPlannedFailoverInputProperties = new RecoveryPlanPlannedFailoverInputProperties { FailoverDirection = this.Direction == PossibleOperationsDirections.PrimaryToRecovery.ToString() ? PossibleOperationsDirections.PrimaryToRecovery : PossibleOperationsDirections.RecoveryToPrimary, ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() }; foreach (var replicationProvider in rp.Properties.ReplicationProviders) { if (0 == string.Compare( replicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { if (this.Direction == Constants.PrimaryToRecovery) { var recoveryPlanHyperVReplicaAzureFailoverInput = new RecoveryPlanHyperVReplicaAzureFailoverInput { PrimaryKekCertificatePfx = this.primaryKekCertpfx, SecondaryKekCertificatePfx = this.secondaryKekCertpfx, VaultLocation = "dummy" }; recoveryPlanPlannedFailoverInputProperties.ProviderSpecificDetails.Add( recoveryPlanHyperVReplicaAzureFailoverInput); } else { var recoveryPlanHyperVReplicaAzureFailbackInput = new RecoveryPlanHyperVReplicaAzureFailbackInput { DataSyncOption = this.Optimize == Constants.ForDownTime ? DataSyncStatus.ForDownTime : DataSyncStatus.ForSynchronization, RecoveryVmCreationOption = string.Compare( this.CreateVmIfNotFound, Constants.Yes, StringComparison .OrdinalIgnoreCase) == 0 ? AlternateLocationRecoveryOption .CreateVmIfNotFound : AlternateLocationRecoveryOption.NoAction }; recoveryPlanPlannedFailoverInputProperties.ProviderSpecificDetails.Add( recoveryPlanHyperVReplicaAzureFailbackInput); } } else if (string.Compare( replicationProvider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare( replicationProvider, Constants.InMage, StringComparison.OrdinalIgnoreCase) == 0) { throw new InvalidOperationException( string.Format( Resources.UnsupportedReplicationProviderForPlannedFailover, replicationProvider)); } } var recoveryPlanPlannedFailoverInput = new RecoveryPlanPlannedFailoverInput { Properties = recoveryPlanPlannedFailoverInputProperties }; var response = this.RecoveryServicesClient.StartAzureSiteRecoveryPlannedFailover( this.RecoveryPlan.Name, recoveryPlanPlannedFailoverInput); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } #region local parameters /// <summary> /// Gets or sets Name of the PE. /// </summary> private string protectionEntityName; /// <summary> /// Gets or sets Name of the Protection Container. /// </summary> private string protectionContainerName; /// <summary> /// Gets or sets Name of the Fabric. /// </summary> public string fabricName; /// <summary> /// Primary Kek Cert pfx file. /// </summary> private string primaryKekCertpfx; /// <summary> /// Secondary Kek Cert pfx file. /// </summary> private string secondaryKekCertpfx; #endregion local parameters } }
// <copyright file="PlayGamesUserProfile.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. 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. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames { using System; using System.Collections; using GooglePlayGames.OurUtils; using UnityEngine; #if UNITY_2017_1_OR_NEWER using UnityEngine.Networking; #endif using UnityEngine.SocialPlatforms; /// <summary> /// Represents a Google Play Games user profile. In the current implementation, /// this is only used as a base class of <see cref="PlayGamesLocalUser" /> /// and should not be used directly. /// </summary> public class PlayGamesUserProfile : IUserProfile { private string mDisplayName; private string mPlayerId; private string mAvatarUrl; private volatile bool mImageLoading = false; private Texture2D mImage; internal PlayGamesUserProfile(string displayName, string playerId, string avatarUrl) { mDisplayName = displayName; mPlayerId = playerId; mAvatarUrl = avatarUrl; mImageLoading = false; } protected void ResetIdentity(string displayName, string playerId, string avatarUrl) { mDisplayName = displayName; mPlayerId = playerId; if (mAvatarUrl != avatarUrl) { mImage = null; mAvatarUrl = avatarUrl; } mImageLoading = false; } #region IUserProfile implementation public string userName { get { return mDisplayName; } } public string id { get { return mPlayerId; } } public bool isFriend { get { return true; } } public UserState state { get { return UserState.Online; } } public Texture2D image { get { if (!mImageLoading && mImage == null && !string.IsNullOrEmpty(AvatarURL)) { Debug.Log("Starting to load image: " + AvatarURL); mImageLoading = true; PlayGamesHelperObject.RunCoroutine(LoadImage()); } return mImage; } } #endregion public string AvatarURL { get { return mAvatarUrl; } } /// <summary> /// Loads the local user's image from the url. Loading urls /// is asynchronous so the return from this call is fast, /// the image is returned once it is loaded. null is returned /// up to that point. /// </summary> internal IEnumerator LoadImage() { // the url can be null if the user does not have an // avatar configured. if (!string.IsNullOrEmpty(AvatarURL)) { #if UNITY_2017_1_OR_NEWER UnityWebRequest www = UnityWebRequestTexture.GetTexture(AvatarURL); www.SendWebRequest(); #else WWW www = new WWW(AvatarURL); #endif while (!www.isDone) { yield return null; } if (www.error == null) { #if UNITY_2017_1_OR_NEWER this.mImage = DownloadHandlerTexture.GetContent(www); #else this.mImage = www.texture; #endif } else { mImage = Texture2D.blackTexture; Debug.Log("Error downloading image: " + www.error); } mImageLoading = false; } else { Debug.Log("No URL found."); mImage = Texture2D.blackTexture; mImageLoading = false; } } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } PlayGamesUserProfile other = obj as PlayGamesUserProfile; if (other == null) { return false; } return StringComparer.Ordinal.Equals(mPlayerId, other.mPlayerId); } public override int GetHashCode() { return typeof(PlayGamesUserProfile).GetHashCode() ^ mPlayerId.GetHashCode(); } public override string ToString() { return string.Format("[Player: '{0}' (id {1})]", mDisplayName, mPlayerId); } } } #endif
// 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.Collections.Immutable; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase, IClassFixture<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected readonly Mock<ICompletionSession> MockCompletionSession; protected TWorkspaceFixture WorkspaceFixture; protected AbstractCompletionProviderTests(TWorkspaceFixture workspaceFixture) { MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict); this.WorkspaceFixture = workspaceFixture; } public override void Dispose() { this.WorkspaceFixture.CloseTextView(); base.Dispose(); } protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position) { var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } internal CompletionServiceWithProviders GetCompletionService(Workspace workspace) { return CreateCompletionService(workspace, ImmutableArray.Create(CreateCompletionProvider())); } internal abstract CompletionServiceWithProviders CreateCompletionService( Workspace workspace, ImmutableArray<CompletionProvider> exclusiveProviders); protected abstract string ItemPartiallyWritten(string expectedItemOrNull); protected abstract TestWorkspace CreateWorkspace(string fileContents); protected abstract Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority); internal static CompletionHelper GetCompletionHelper(Document document) { return CompletionHelper.GetHelper(document); } internal Task<CompletionList> GetCompletionListAsync( CompletionService service, Document document, int position, CompletionTrigger triggerInfo, OptionSet options = null) { return service.GetCompletionsAsync(document, position, triggerInfo, options: options); } protected async Task CheckResultsAsync( Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority) { var code = (await document.GetTextAsync()).ToString(); var trigger = CompletionTrigger.Invoke; if (usePreviousCharAsTrigger) { trigger = CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)); } var completionService = GetCompletionService(document.Project.Solution.Workspace); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); var items = completionList == null ? ImmutableArray<CompletionItem>.Empty : completionList.Items; if (checkForAbsence) { if (items == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(items); } else { AssertEx.None( items, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(items); } else { AssertEx.Any(items, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true) && (glyph.HasValue ? c.Tags.SequenceEqual(GlyphTags.GetTags((Glyph)glyph.Value)) : true) && (matchPriority.HasValue ? (int)c.Rules.MatchPriority == matchPriority.Value : true )); } } } private Task VerifyAsync( string markup, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority) { MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int position); return VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } protected async Task VerifyCustomCommitProviderAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null) { MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out var code, out int position); if (sourceCodeKind.HasValue) { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar); } else { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar); await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar); } } protected async Task VerifyProviderCommitAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind? sourceCodeKind = null) { MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out var code, out int position); expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings(); if (sourceCodeKind.HasValue) { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, sourceCodeKind.Value); } else { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Regular); await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Script); } } protected virtual bool CompareItems(string actualItem, string expectedItem) { return actualItem.Equals(expectedItem); } protected async Task VerifyItemExistsAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, int? glyph = null, int? matchPriority = null) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority); } else { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority); await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority); } } protected async Task VerifyItemIsAbsentAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } else { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } } protected async Task VerifyAnyItemExistsAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null); } else { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null); await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null); } } protected async Task VerifyNoItemsExistAsync(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } else { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } } internal abstract CompletionProvider CreateCompletionProvider(); /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="code">The source code (not markup).</param> /// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param> /// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param> /// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param> /// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param> protected virtual async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority) { Glyph? expectedGlyph = null; if (glyph.HasValue) { expectedGlyph = (Glyph)glyph.Value; } var document1 = WorkspaceFixture.UpdateDocument(code, sourceCodeKind); await CheckResultsAsync(document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = WorkspaceFixture.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false); await CheckResultsAsync(document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual async Task VerifyCustomCommitProviderWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null) { var document1 = WorkspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind); await VerifyCustomCommitProviderCheckResultsAsync(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = WorkspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyCustomCommitProviderCheckResultsAsync(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private async Task VerifyCustomCommitProviderCheckResultsAsync(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar) { var workspace = WorkspaceFixture.GetWorkspace(); SetWorkspaceOptions(workspace); var textBuffer = workspace.Documents.Single().TextBuffer; var service = GetCompletionService(workspace); var items = (await GetCompletionListAsync(service, document, position, CompletionTrigger.Invoke)).Items; var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); var customCommitCompletionProvider = service.ExclusiveProviders?[0] as ICustomCommitCompletionProvider; if (customCommitCompletionProvider != null) { var completionRules = GetCompletionHelper(document); var textView = (WorkspaceFixture.GetWorkspace()).Documents.Single().GetTextView(); VerifyCustomCommitWorker(service, customCommitCompletionProvider, firstItem, completionRules, textView, textBuffer, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } else { await VerifyCustomCommitWorkerAsync(service, document, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } } protected virtual void SetWorkspaceOptions(TestWorkspace workspace) { } internal async Task VerifyCustomCommitWorkerAsync( CompletionServiceWithProviders service, Document document, CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString())) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } var commit = await service.GetChangeAsync(document, completionItem, commitChar, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = (WorkspaceFixture.GetWorkspace()).Documents.Single().TextBuffer; var textView = (WorkspaceFixture.GetWorkspace()).Documents.Single().GetTextView(); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = commit.NewPosition != null ? commit.NewPosition.Value : textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } internal virtual void VerifyCustomCommitWorker( CompletionService service, ICustomCommitCompletionProvider customCommitCompletionProvider, CompletionItem completionItem, CompletionHelper completionRules, ITextView textView, ITextBuffer textBuffer, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString())) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind sourceCodeKind) { var document1 = WorkspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind); await VerifyProviderCommitCheckResultsAsync(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = WorkspaceFixture.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyProviderCommitCheckResultsAsync(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); } } private async Task VerifyProviderCommitCheckResultsAsync( Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitCharOpt, string textTypedSoFar) { var workspace = WorkspaceFixture.GetWorkspace(); var textBuffer = workspace.Documents.Single().TextBuffer; var textSnapshot = textBuffer.CurrentSnapshot.AsText(); var service = GetCompletionService(workspace); var items = (await GetCompletionListAsync(service, document, position, CompletionTrigger.Invoke)).Items; var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); var completionRules = GetCompletionHelper(document); var commitChar = commitCharOpt ?? '\t'; var text = await document.GetTextAsync(); if (commitChar == '\t' || Controller.IsCommitCharacter(service.GetRules(), firstItem, commitChar, textTypedSoFar + commitChar)) { var textChange = (await service.GetChangeAsync(document, firstItem, commitChar, CancellationToken.None)).TextChange; // Adjust TextChange to include commit character, so long as it isn't TAB. if (commitChar != '\t') { textChange = new TextChange(textChange.Span, textChange.NewText.TrimEnd(commitChar) + commitChar); } text = text.WithChanges(textChange); } else { // nothing was committed, but we should insert the commit character. var textChange = new TextChange(new TextSpan(firstItem.Span.End, 0), commitChar.ToString()); text = text.WithChanges(textChange); } Assert.Equal(expectedCodeAfterCommit, text.ToString()); } protected async Task VerifyItemInEditorBrowsableContextsAsync( string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { await VerifyItemWithMetadataReferenceAsync(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); await VerifyItemWithProjectReferenceAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // If the source and referenced languages are different, then they cannot be in the same project if (sourceLanguage == referencedLanguage) { await VerifyItemInSameProjectAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers); } } private Task VerifyItemWithMetadataReferenceAsync(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}, global"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataAlias)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected Task VerifyItemWithProjectReferenceAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private Task VerifyItemInSameProjectAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private async Task VerifyItemWithReferenceWorkerAsync( string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspace.Create(xmlString)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); testWorkspace.Options = testWorkspace.Options.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers); var triggerInfo = CompletionTrigger.Invoke; var completionService = GetCompletionService(testWorkspace); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); if (expectedSymbols >= 1) { AssertEx.Any(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); var item = completionList.Items.First(c => CompareItems(c.DisplayText, expectedItem)); var description = await completionService.GetDescriptionAsync(document, item); if (expectedSymbols == 1) { Assert.DoesNotContain("+", description.Text, StringComparison.Ordinal); } else { Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.Text, StringComparison.Ordinal); } } else { if (completionList != null) { AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); } } } } protected Task VerifyItemWithMscorlib45Async(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); return VerifyItemWithMscorlib45WorkerAsync(xmlString, expectedItem, expectedDescription); } private async Task VerifyItemWithMscorlib45WorkerAsync( string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspace.Create(xmlString)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var completionService = GetCompletionService(testWorkspace); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem); Assert.Equal(expectedDescription, (await completionService.GetDescriptionAsync(document, item)).Text); } } private const char NonBreakingSpace = (char)0x00A0; private string GetExpectedOverloadSubstring(int expectedSymbols) { if (expectedSymbols <= 1) { throw new ArgumentOutOfRangeException(nameof(expectedSymbols)); } return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + FeaturesResources.overload; } protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspace.Create(xmlString)) { var position = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().TextBuffer.AsTextContainer(); var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer); var document = solution.GetDocument(currentContextDocumentId); var triggerInfo = CompletionTrigger.Invoke; var completionService = GetCompletionService(testWorkspace); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.Single(c => c.DisplayText == expectedItem); Assert.NotNull(item); if (expectedDescription != null) { var actualDescription = (await completionService.GetDescriptionAsync(document, item)).Text; Assert.Equal(expectedDescription, actualDescription); } } } protected Task VerifyAtPositionAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { code = code.Substring(0, position) + insertText + code.Substring(position); position += insertText.Length; return BaseVerifyWorkerAsync(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtPositionAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtPositionAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected async Task VerifyAtEndOfFileAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { // only do this if the placeholder was at the end of the text. if (code.Length != position) { return; } code = code.Substring(startIndex: 0, length: position) + insertText; position += insertText.Length; await BaseVerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtPosition_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtPositionAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtEndOfFileAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected void VerifyTextualTriggerCharacter( string markup, bool shouldTriggerWithTriggerOnLettersEnabled, bool shouldTriggerWithTriggerOnLettersDisabled) { VerifyTextualTriggerCharacterWorker(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersEnabled, triggerOnLetter: true); VerifyTextualTriggerCharacterWorker(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersDisabled, triggerOnLetter: false); } private void VerifyTextualTriggerCharacterWorker( string markup, bool expectedTriggerCharacter, bool triggerOnLetter) { using (var workspace = CreateWorkspace(markup)) { var document = workspace.Documents.Single(); var position = document.CursorPosition.Value; var text = document.TextBuffer.CurrentSnapshot.AsText(); var options = workspace.Options.WithChangedOption( CompletionOptions.TriggerOnTypingLetters, document.Project.Language, triggerOnLetter); var trigger = CompletionTrigger.CreateInsertionTrigger(text[position]); var service = GetCompletionService(workspace); var isTextualTriggerCharacterResult = service.ShouldTriggerCompletion(text, position + 1, trigger, options: options); if (expectedTriggerCharacter) { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to be textual trigger character"; Assert.True(isTextualTriggerCharacterResult, assertText); } else { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to NOT be textual trigger character"; Assert.False(isTextualTriggerCharacterResult, assertText); } } } protected async Task VerifyCommonCommitCharactersAsync(string initialMarkup, string textTypedSoFar) { var commitCharacters = new[] { ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\' }; await VerifyCommitCharactersAsync(initialMarkup, textTypedSoFar, commitCharacters); } protected async Task VerifyCommitCharactersAsync(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null) { Assert.NotNull(validChars); invalidChars = invalidChars ?? new[] { 'x' }; using (var workspace = CreateWorkspace(initialMarkup)) { var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; var service = GetCompletionService(workspace); var completionList = await GetCompletionListAsync(service, document, position, CompletionTrigger.Invoke); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); foreach (var ch in validChars) { Assert.True(Controller.IsCommitCharacter( service.GetRules(), item, ch, textTypedSoFar + ch), $"Expected '{ch}' to be a commit character"); } foreach (var ch in invalidChars) { Assert.False(Controller.IsCommitCharacter( service.GetRules(), item, ch, textTypedSoFar + ch), $"Expected '{ch}' NOT to be a commit character"); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Timers; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Statistics; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; private string m_timedScript = "disabled"; private Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = m_config.Source.Configs["Startup"]; IConfig networkConfig = m_config.Source.Configs["Network"]; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_logFileAppender != null) { if (m_logFileAppender is log4net.Appender.FileAppender) { log4net.Appender.FileAppender appender = (log4net.Appender.FileAppender)m_logFileAppender; string fileName = startupConfig.GetString("LogFile", String.Empty); if (fileName != String.Empty) { appender.File = fileName; appender.ActivateOptions(); } m_log.InfoFormat("[LOGGING]: Logging started to file {0}", appender.File); } } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); m_log.InfoFormat("[OPENSIM MAIN]: Running in {0} mode", (ConfigurationSettings.Standalone ? "sandbox" : "grid")); //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI m_console = new CommandConsole("Region"); else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(m_config.Source); break; default: m_console = new LocalConsole("Region"); break; } } MainConsole.Instance = m_console; RegisterConsoleCommands(); base.StartupSpecific(); if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = 1200*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); m_log.InfoFormat("[NETWORK]: Using {0} as SYSTEMIP", Util.GetLocalHost().ToString()); // For now, start at the 'root' level by default if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", m_sceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { m_console.Commands.AddCommand("region", false, "clear assets", "clear assets", "Clear the asset cache", HandleClearAssets); m_console.Commands.AddCommand("region", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("region", false, "debug packet", "debug packet <level>", "Turn on packet debugging", Debug); m_console.Commands.AddCommand("region", false, "debug scene", "debug scene <cripting> <collisions> <physics>", "Turn on scene debugging", Debug); m_console.Commands.AddCommand("region", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("region", false, "save xml", "save xml", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("region", false, "save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("region", false, "load xml", "load xml [-newIDs [<x> <y> <z>]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("region", false, "load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("region", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("region", false, "load oar", "load oar [--merge] <oar name>", "Load a region's data from OAR archive", LoadOar); m_console.Commands.AddCommand("region", false, "save oar", "save oar <oar name>", "Save a region's data to an OAR archive", "More information on forthcoming options here soon", SaveOar); m_console.Commands.AddCommand("region", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("region", false, "kick user", "kick user <first> <last> [message]", "Kick a user off the simulator", KickUserCommand); m_console.Commands.AddCommand("region", false, "show assets", "show assets", "Show asset data", HandleShow); m_console.Commands.AddCommand("region", false, "show users", "show users [full]", "Show user data", HandleShow); m_console.Commands.AddCommand("region", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("region", false, "show users full", "show users full", String.Empty, HandleShow); m_console.Commands.AddCommand("region", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("region", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("region", false, "show queues", "show queues", "Show queue data", HandleShow); m_console.Commands.AddCommand("region", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("region", false, "backup", "backup", "Persist objects to the database now", RunCommand); m_console.Commands.AddCommand("region", false, "create region", "create region", "Create a new region", HandleCreateRegion); m_console.Commands.AddCommand("region", false, "restart", "restart", "Restart all sims in this instance", RunCommand); m_console.Commands.AddCommand("region", false, "config set", "config set <section> <field> <value>", "Set a config option", HandleConfig); m_console.Commands.AddCommand("region", false, "config get", "config get <section> <field>", "Read a config option", HandleConfig); m_console.Commands.AddCommand("region", false, "config save", "config save", "Save current configuration", HandleConfig); m_console.Commands.AddCommand("region", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("region", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("region", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); m_console.Commands.AddCommand("region", false, "modules list", "modules list", "List modules", HandleModules); m_console.Commands.AddCommand("region", false, "modules load", "modules load <name>", "Load a module", HandleModules); m_console.Commands.AddCommand("region", false, "modules unload", "modules unload <name>", "Unload a module", HandleModules); m_console.Commands.AddCommand("region", false, "Add-InventoryHost", "Add-InventoryHost <host>", String.Empty, RunCommand); m_console.Commands.AddCommand("region", false, "kill uuid", "kill uuid <UUID>", "Kill an object by UUID", KillUUID); if (ConfigurationSettings.Standalone) { m_console.Commands.AddCommand("region", false, "create user", "create user [<first> [<last> [<pass> [<x> <y> [<email>]]]]]", "Create a new user", HandleCreateUser); m_console.Commands.AddCommand("region", false, "reset user password", "reset user password [<first> [<last> [<password>]]]", "Reset a user password", HandleResetUserPassword); } m_console.Commands.AddCommand("hypergrid", false, "link-mapping", "link-mapping [<x> <y>] <cr>", "Set local coordinate to map HG regions to", RunCommand); m_console.Commands.AddCommand("hypergrid", false, "link-region", "link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>] <cr>", "Link a hypergrid region", RunCommand); m_console.Commands.AddCommand("hypergrid", false, "unlink-region", "unlink-region <local name> or <HostName>:<HttpPort> <cr>", "Unlink a hypergrid region", RunCommand); } public override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(System.Threading.Thread thread, int lastTick) { int now = Environment.TickCount & Int32.MaxValue; m_log.ErrorFormat("[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago", thread.Name, thread.ThreadState, now - lastTick); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { if (cmdparams.Length < 4) return; string alert = null; if (cmdparams.Length > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = m_sceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = m_sceneManager.GetRegionInfo(presence.RegionHandle); if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) && presence.Lastname.ToLower().Contains(cmdparams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16}{1,-16}{2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n"); // ...and close on our side presence.Scene.IncomingCloseAgent(presence.UUID); } } MainConsole.Instance.Output(""); } /// <summary> /// Run an optional startup list of commands /// </summary> /// <param name="fileName"></param> private void RunCommandScript(string fileName) { if (File.Exists(fileName)) { m_log.Info("[COMMANDFILE]: Running " + fileName); using (StreamReader readFile = File.OpenText(fileName)) { string currentCommand; while ((currentCommand = readFile.ReadLine()) != null) { if (currentCommand != String.Empty) { m_log.Info("[COMMANDFILE]: Running '" + currentCommand + "'"); m_console.RunCommand(currentCommand); } } } } } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { StreamReader readFile = File.OpenText(fileName); string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } private void HandleClearAssets(string module, string[] args) { MainConsole.Instance.Output("Not implemented."); } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); m_sceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { m_sceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region XML file</param> private void HandleCreateRegion(string module, string[] cmd) { if (cmd.Length < 4) { MainConsole.Instance.Output("Usage: create region <region name> <region_file.ini>"); return; } if (cmd[3].EndsWith(".xml")) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); string regionFile = String.Format("{0}/{1}", regionsDir, cmd[3]); // Allow absolute and relative specifiers if (cmd[3].StartsWith("/") || cmd[3].StartsWith("\\") || cmd[3].StartsWith("..")) regionFile = cmd[3]; IScene scene; CreateRegion(new RegionInfo(cmd[2], regionFile, false, ConfigSource.Source), true, out scene); } else if (cmd[3].EndsWith(".ini")) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); string regionFile = String.Format("{0}/{1}", regionsDir, cmd[3]); // Allow absolute and relative specifiers if (cmd[3].StartsWith("/") || cmd[3].StartsWith("\\") || cmd[3].StartsWith("..")) regionFile = cmd[3]; IScene scene; CreateRegion(new RegionInfo(cmd[2], regionFile, false, ConfigSource.Source, cmd[2]), true, out scene); } else { MainConsole.Instance.Output("Usage: create region <region name> <region_file.ini>"); return; } } /// <summary> /// Change and load configuration file data. /// </summary> /// <param name="module"></param> /// <param name="cmd"></param> private void HandleConfig(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] cmdparams = args.ToArray(); string n = "CONFIG"; if (cmdparams.Length > 0) { switch (cmdparams[0].ToLower()) { case "set": if (cmdparams.Length < 4) { MainConsole.Instance.Output(String.Format("SYNTAX: {0} SET SECTION KEY VALUE",n)); MainConsole.Instance.Output(String.Format("EXAMPLE: {0} SET ScriptEngine.DotNetEngine NumberOfScriptThreads 5",n)); } else { IConfig c; IConfigSource source = new IniConfigSource(); c = source.AddConfig(cmdparams[1]); if (c != null) { string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3); c.Set(cmdparams[2], _value); m_config.Source.Merge(source); MainConsole.Instance.Output(String.Format("{0} {0} {1} {2} {3}",n,cmdparams[1],cmdparams[2],_value)); } } break; case "get": if (cmdparams.Length < 3) { MainConsole.Instance.Output(String.Format("SYNTAX: {0} GET SECTION KEY",n)); MainConsole.Instance.Output(String.Format("EXAMPLE: {0} GET ScriptEngine.DotNetEngine NumberOfScriptThreads",n)); } else { IConfig c = m_config.Source.Configs[cmdparams[1]]; if (c == null) { MainConsole.Instance.Output(String.Format("Section \"{0}\" does not exist.",cmdparams[1])); break; } else { MainConsole.Instance.Output(String.Format("{0} GET {1} {2} : {3}",n,cmdparams[1],cmdparams[2], c.GetString(cmdparams[2]))); } } break; case "save": if (cmdparams.Length < 2) { MainConsole.Instance.Output("SYNTAX: " + n + " SAVE FILE"); return; } if (Application.iniFilePath == cmdparams[1]) { MainConsole.Instance.Output("FILE can not be " + Application.iniFilePath); return; } MainConsole.Instance.Output("Saving configuration file: " + cmdparams[1]); m_config.Save(cmdparams[1]); break; } } } /// <summary> /// Load, Unload, and list Region modules in use /// </summary> /// <param name="module"></param> /// <param name="cmd"></param> private void HandleModules(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] cmdparams = args.ToArray(); if (cmdparams.Length > 0) { switch (cmdparams[0].ToLower()) { case "list": foreach (IRegionModule irm in m_moduleLoader.GetLoadedSharedModules) { MainConsole.Instance.Output(String.Format("Shared region module: {0}", irm.Name)); } break; case "unload": if (cmdparams.Length > 1) { foreach (IRegionModule rm in new ArrayList(m_moduleLoader.GetLoadedSharedModules)) { if (rm.Name.ToLower() == cmdparams[1].ToLower()) { MainConsole.Instance.Output(String.Format("Unloading module: {0}", rm.Name)); m_moduleLoader.UnloadModule(rm); } } } break; case "load": if (cmdparams.Length > 1) { foreach (Scene s in new ArrayList(m_sceneManager.Scenes)) { MainConsole.Instance.Output(String.Format("Loading module: {0}", cmdparams[1])); m_moduleLoader.LoadRegionModules(cmdparams[1], s); } } break; } } } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "command-script": if (cmdparams.Length > 0) { RunCommandScript(cmdparams[0]); } break; case "backup": m_sceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (m_sceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("no region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (m_sceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": m_sceneManager.RestartCurrentScene(); break; case "Add-InventoryHost": if (cmdparams.Length > 0) { MainConsole.Instance.Output("Not implemented."); } break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!m_sceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } string regionName = (m_sceneManager.CurrentScene == null ? "root" : m_sceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); m_console.DefaultPrompt = String.Format("Region ({0}) ", regionName); m_console.ConsoleScene = m_sceneManager.CurrentScene; } /// <summary> /// Execute switch for some of the create commands /// </summary> /// <param name="args"></param> private void HandleCreateUser(string module, string[] cmd) { if (ConfigurationSettings.Standalone) { CreateUser(cmd); } else { MainConsole.Instance.Output("Create user is not available in grid mode, use the user server."); } } /// <summary> /// Execute switch for some of the reset commands /// </summary> /// <param name="args"></param> protected void HandleResetUserPassword(string module, string[] cmd) { if (ConfigurationSettings.Standalone) { ResetUserPassword(cmd); } else { MainConsole.Instance.Output("Reset user password is not available in grid mode, use the user-server."); } } /// <summary> /// Turn on some debugging values for OpenSim. /// </summary> /// <param name="args"></param> protected void Debug(string module, string[] args) { if (args.Length == 1) return; switch (args[1]) { case "packet": if (args.Length > 2) { int newDebug; if (int.TryParse(args[2], out newDebug)) { m_sceneManager.SetDebugPacketLevelOnCurrentScene(newDebug); } else { MainConsole.Instance.Output("packet debug should be 0..255"); } MainConsole.Instance.Output(String.Format("New packet debug: {0}", newDebug)); } break; case "scene": if (args.Length == 5) { if (m_sceneManager.CurrentScene == null) { MainConsole.Instance.Output("Please use 'change region <regioname>' first"); } else { bool scriptingOn = !Convert.ToBoolean(args[2]); bool collisionsOn = !Convert.ToBoolean(args[3]); bool physicsOn = !Convert.ToBoolean(args[4]); m_sceneManager.CurrentScene.SetSceneCoreDebug(scriptingOn, collisionsOn, physicsOn); MainConsole.Instance.Output( String.Format( "Set debug scene scripting = {0}, collisions = {1}, physics = {2}", !scriptingOn, !collisionsOn, !physicsOn)); } } else { MainConsole.Instance.Output("debug scene <scripting> <collisions> <physics> (where inside <> is true/false)"); } break; default: MainConsole.Instance.Output("Unknown debug"); break; } } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "assets": MainConsole.Instance.Output("Not implemented."); break; case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = m_sceneManager.GetCurrentScenePresences(); } else { agents = m_sceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16}{1,-16}{2,-37}{3,-11}{4,-16}{5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position")); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = m_sceneManager.GetRegionInfo(presence.RegionHandle); string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16}{1,-16}{2,-37}{3,-11}{4,-16}{5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString())); } MainConsole.Instance.Output(String.Empty); break; case "connections": System.Text.StringBuilder connections = new System.Text.StringBuilder("Connections:\n"); m_sceneManager.ForEachScene( delegate(Scene scene) { scene.ForEachClient( delegate(IClientAPI client) { connections.AppendFormat("{0}: {1} ({2}) from {3} on circuit {4}\n", scene.RegionInfo.RegionName, client.Name, client.AgentId, client.RemoteEndPoint, client.CircuitCode); }, false ); } ); MainConsole.Instance.Output(connections.ToString()); break; case "modules": MainConsole.Instance.Output("The currently loaded shared modules are:"); foreach (IRegionModule module in m_moduleLoader.GetLoadedSharedModules) { MainConsole.Instance.Output("Shared Module: " + module.Name); } MainConsole.Instance.Output(""); break; case "regions": m_sceneManager.ForEachScene( delegate(Scene scene) { MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.InternalEndPoint.Port)); }); break; case "queues": MainConsole.Instance.Output(GetQueuesReport()); break; case "ratings": m_sceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } /// <summary> /// print UDP Queue data for each client /// </summary> /// <returns></returns> private string GetQueuesReport() { string report = String.Empty; m_sceneManager.ForEachScene(delegate(Scene scene) { scene.ForEachClient(delegate(IClientAPI client) { if (client is IStatsCollector) { report = report + client.FirstName + " " + client.LastName; IStatsCollector stats = (IStatsCollector) client; report = report + string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}\n", "Send", "In", "Out", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"); report = report + stats.Report() + "\n"; } }); }); return report; } /// <summary> /// Create a new user /// </summary> /// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param> protected void CreateUser(string[] cmdparams) { string firstName; string lastName; string password; string email; uint regX = 1000; uint regY = 1000; IConfig standalone; if ((standalone = m_config.Source.Configs["StandAlone"]) != null) { regX = (uint)standalone.GetInt("default_location_x", (int)regX); regY = (uint)standalone.GetInt("default_location_y", (int)regY); } if (cmdparams.Length < 3) firstName = MainConsole.Instance.CmdPrompt("First name", "Default"); else firstName = cmdparams[2]; if (cmdparams.Length < 4) lastName = MainConsole.Instance.CmdPrompt("Last name", "User"); else lastName = cmdparams[3]; if (cmdparams.Length < 5) password = MainConsole.Instance.PasswdPrompt("Password"); else password = cmdparams[4]; if (cmdparams.Length < 6) regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString())); else regX = Convert.ToUInt32(cmdparams[5]); if (cmdparams.Length < 7) regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString())); else regY = Convert.ToUInt32(cmdparams[6]); if (cmdparams.Length < 8) email = MainConsole.Instance.CmdPrompt("Email", ""); else email = cmdparams[7]; if (null == m_commsManager.UserProfileCacheService.GetUserDetails(firstName, lastName)) { m_commsManager.UserAdminService.AddUser(firstName, lastName, password, email, regX, regY); } else { MainConsole.Instance.Output(string.Format("A user with the name {0} {1} already exists!", firstName, lastName)); } } /// <summary> /// Reset a user password. /// </summary> /// <param name="cmdparams"></param> private void ResetUserPassword(string[] cmdparams) { string firstName; string lastName; string newPassword; if (cmdparams.Length < 4) firstName = MainConsole.Instance.CmdPrompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.CmdPrompt("Last name"); else lastName = cmdparams[4]; if (cmdparams.Length < 6) newPassword = MainConsole.Instance.PasswdPrompt("New password"); else newPassword = cmdparams[5]; m_commsManager.UserAdminService.ResetUserPassword(firstName, lastName, newPassword); } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 5) { m_sceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { m_sceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 0) { m_sceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { m_sceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } m_sceneManager.LoadCurrentSceneFromXml(cmdparams[0], generateNewIDS, loadOffset); } else { try { m_sceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { m_sceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { m_sceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { m_sceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { m_sceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { m_sceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { m_sceneManager.SaveCurrentSceneToArchive(cmdparams); } private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } /// <summary> /// Kill an object given its UUID. /// </summary> /// <param name="cmdparams"></param> protected void KillUUID(string module, string[] cmdparams) { if (cmdparams.Length > 2) { UUID id = UUID.Zero; SceneObjectGroup grp = null; Scene sc = null; if (!UUID.TryParse(cmdparams[2], out id)) { MainConsole.Instance.Output("[KillUUID]: Error bad UUID format!"); return; } m_sceneManager.ForEachScene( delegate(Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(id); if (part == null) return; grp = part.ParentGroup; sc = scene; }); if (grp == null) { MainConsole.Instance.Output(String.Format("[KillUUID]: Given UUID {0} not found!", id)); } else { MainConsole.Instance.Output(String.Format("[KillUUID]: Found UUID {0} in scene {1}", id, sc.RegionInfo.RegionName)); try { sc.DeleteSceneObject(grp, false); } catch (Exception e) { m_log.ErrorFormat("[KillUUID]: Error while removing objects from scene: " + e); } } } else { MainConsole.Instance.Output("[KillUUID]: Usage: kill uuid <UUID>"); } } #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. /*============================================================ ** ** Purpose: Some single-precision floating-point math operations ** ===========================================================*/ namespace System { //This class contains only static members and doesn't require serialization. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class MathF { private static float singleRoundLimit = 1e8f; private const int maxRoundingDigits = 6; // This table is required for the Round function which can specify the number of digits to round to private static float[] roundPower10Single = new float[] { 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f }; public const float PI = 3.14159265f; public const float E = 2.71828183f; public static float Abs(float x) => Math.Abs(x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Acos(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Asin(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Atan(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Atan2(float y, float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Ceiling(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Cos(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Cosh(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Exp(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Floor(float x); public static float IEEERemainder(float x, float y) { if (float.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (float.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } var regularMod = x % y; if (float.IsNaN(regularMod)) { return float.NaN; } if ((regularMod == 0) && float.IsNegative(x)) { return float.NegativeZero; } var alternativeResult = (regularMod - (Abs(y) * Sign(x))); if (Abs(alternativeResult) == Abs(regularMod)) { var divisionResult = x / y; var roundedResult = Round(divisionResult); if (Abs(roundedResult) > Abs(divisionResult)) { return alternativeResult; } else { return regularMod; } } if (Abs(alternativeResult) < Abs(regularMod)) { return alternativeResult; } else { return regularMod; } } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Log(float x); public static float Log(float x, float y) { if (float.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (float.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } if (y == 1) { return float.NaN; } if ((x != 1) && ((y == 0) || float.IsPositiveInfinity(y))) { return float.NaN; } return Log(x) / Log(y); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Log10(float x); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Max(float x, float y) => Math.Max(x, y); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Min(float x, float y) => Math.Min(x, y); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Pow(float x, float y); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Round(float x); public static float Round(float x, int digits) { if ((digits < 0) || (digits > maxRoundingDigits)) { throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); } Contract.EndContractBlock(); return InternalRound(x, digits, MidpointRounding.ToEven); } public static float Round(float x, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) { throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); } if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode)); } Contract.EndContractBlock(); return InternalRound(x, digits, mode); } public static float Round(float x, MidpointRounding mode) { if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode)); } Contract.EndContractBlock(); return InternalRound(x, 0, mode); } public static int Sign(float x) => Math.Sign(x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Sin(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Sinh(float x); [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Sqrt(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Tan(float x); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern float Tanh(float x); public static float Truncate(float x) => InternalTruncate(x); [System.Security.SecuritySafeCritical] // auto-generated private static unsafe float InternalRound(float x, int digits, MidpointRounding mode) { if (Abs(x) < singleRoundLimit) { var power10 = roundPower10Single[digits]; x *= power10; if (mode == MidpointRounding.AwayFromZero) { var fraction = SplitFractionSingle(&x); if (Abs(fraction) >= 0.5f) { x += Sign(fraction); } } else { x = Round(x); } x /= power10; } return x; } [System.Security.SecuritySafeCritical] // auto-generated private unsafe static float InternalTruncate(float x) { SplitFractionSingle(&x); return x; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern float SplitFractionSingle(float* x); } }
// 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.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder; using Xunit; namespace System.Linq.Expressions.Tests { public class DynamicExpressionTests { public static IEnumerable<object[]> SizesAndSuffixes => Enumerable.Range(0, 6).Select(i => new object[] { i, i > 0 & i < 5 ? i.ToString() : "N" }); private static Type[] Types = { typeof(int), typeof(object), typeof(DateTime), typeof(DynamicExpressionTests) }; public static IEnumerable<object[]> SizesAndTypes => Enumerable.Range(1, 6).SelectMany(i => Types, (i, t) => new object[] { i, t }); [Theory, MemberData(nameof(SizesAndSuffixes))] public void AritySpecialisedUsedWhenPossible(int size, string nameSuffix) { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Type delType = Expression.GetFuncType( Enumerable.Repeat(typeof(object), size + 1).Prepend(typeof(CallSite)).ToArray()); DynamicExpression exp = DynamicExpression.MakeDynamic( delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null))); Assert.Equal("DynamicExpression" + nameSuffix, exp.GetType().Name); exp = Expression.MakeDynamic( delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null))); Assert.Equal("DynamicExpression" + nameSuffix, exp.GetType().Name); if (size != 0) { exp = Expression.Dynamic( binder, typeof(object), Enumerable.Range(0, size).Select(_ => Expression.Constant(null))); Assert.Equal("DynamicExpression" + nameSuffix, exp.GetType().Name); } } [Theory, MemberData(nameof(SizesAndSuffixes))] public void TypedAritySpecialisedUsedWhenPossible(int size, string nameSuffix) { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Type delType = Expression.GetFuncType( Enumerable.Repeat(typeof(object), size).Append(typeof(string)).Prepend(typeof(CallSite)).ToArray()); DynamicExpression exp = DynamicExpression.MakeDynamic( delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null))); Assert.Equal("TypedDynamicExpression" + nameSuffix, exp.GetType().Name); exp = Expression.MakeDynamic( delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null))); Assert.Equal("TypedDynamicExpression" + nameSuffix, exp.GetType().Name); if (size != 0) { exp = Expression.Dynamic( binder, typeof(string), Enumerable.Range(0, size).Select(_ => Expression.Constant(null))); Assert.Equal("TypedDynamicExpression" + nameSuffix, exp.GetType().Name); } } [Theory, MemberData(nameof(SizesAndTypes))] public void TypeProperty(int size, Type type) { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); DynamicExpression exp = Expression.Dynamic( binder, type, Enumerable.Range(0, size).Select(_ => Expression.Constant(0))); Assert.Equal(type, exp.Type); Assert.Equal(ExpressionType.Dynamic, exp.NodeType); } [Theory, MemberData(nameof(SizesAndTypes))] public void Reduce(int size, Type type) { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); DynamicExpression exp = Expression.Dynamic( binder, type, Enumerable.Range(0, size).Select(_ => Expression.Constant(0))); Assert.True(exp.CanReduce); InvocationExpression reduced = (InvocationExpression)exp.ReduceAndCheck(); Assert.Equal(exp.Arguments, reduced.Arguments.Skip(1)); } [Theory, MemberData(nameof(SizesAndTypes))] public void GetArguments(int size, Type type) { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); ConstantExpression[] arguments = Enumerable.Range(0, size).Select(_ => Expression.Constant(0)).ToArray(); DynamicExpression exp = Expression.Dynamic(binder, type, arguments); Assert.Equal(arguments, exp.Arguments); } [Theory, MemberData(nameof(SizesAndTypes))] public void ArgumentProvider(int size, Type type) { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); ConstantExpression[] arguments = Enumerable.Range(0, size).Select(_ => Expression.Constant(0)).ToArray(); IArgumentProvider ap = Expression.Dynamic(binder, type, arguments); Assert.Equal(size, ap.ArgumentCount); for (int i = 0; i != size; ++i) { Assert.Same(arguments[i], ap.GetArgument(i)); } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => ap.GetArgument(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => ap.GetArgument(size)); } [Fact] public void UpdateToSameReturnsSame0() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object>), binder); Assert.Same(exp, exp.Update(null)); Assert.Same(exp, exp.Update(Array.Empty<Expression>())); Assert.Same(exp, exp.Update(Enumerable.Repeat<Expression>(null, 0))); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSame1() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); Expression arg = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object, object>), binder, arg); Assert.Same(exp, exp.Update(new[] {arg})); Assert.Same(exp, exp.Update(Enumerable.Repeat(arg, 1))); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSame2() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object>), binder, arg0, arg1); Assert.Same(exp, exp.Update(new[] {arg0, arg1})); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSame3() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object>), binder, arg0, arg1, arg2); Assert.Same(exp, exp.Update(new[] {arg0, arg1, arg2})); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSame4() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); Expression arg3 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3); Assert.Same(exp, exp.Update(new[] {arg0, arg1, arg2, arg3})); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSame5() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); Expression arg3 = Expression.Constant(null); Expression arg4 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3, arg4); Assert.Same(exp, exp.Update(new[] {arg0, arg1, arg2, arg3, arg4})); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSameTyped0() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, string>), binder); Assert.Same(exp, exp.Update(null)); Assert.Same(exp, exp.Update(Array.Empty<Expression>())); Assert.Same(exp, exp.Update(Enumerable.Repeat<Expression>(null, 0))); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSameTyped1() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object, string>), binder, arg); Assert.Same(exp, exp.Update(new[] { arg })); Assert.Same(exp, exp.Update(Enumerable.Repeat(arg, 1))); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSameTyped2() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, string>), binder, arg0, arg1); Assert.Same(exp, exp.Update(new[] { arg0, arg1 })); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSameTyped3() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, string>), binder, arg0, arg1, arg2); Assert.Same(exp, exp.Update(new[] { arg0, arg1, arg2 })); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSameTyped4() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); Expression arg3 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object, string>), binder, arg0, arg1, arg2, arg3); Assert.Same(exp, exp.Update(new[] { arg0, arg1, arg2, arg3 })); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToSameReturnsSameTyped5() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); Expression arg3 = Expression.Constant(null); Expression arg4 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object, object, string>), binder, arg0, arg1, arg2, arg3, arg4); Assert.Same(exp, exp.Update(new[] { arg0, arg1, arg2, arg3, arg4 })); Assert.Same(exp, exp.Update(exp.Arguments)); } [Fact] public void UpdateToDifferentReturnsDifferent0() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object>), binder); // Wrong number of arguments continues to attempt to create new expression, which fails. AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new [] {Expression.Constant(null)})); } [Fact] public void UpdateToDifferentReturnsDifferent1() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object, object>), binder, arg); Assert.NotSame(exp, exp.Update(new[] { Expression.Constant(null) })); // Wrong number of arguments continues to attempt to create new expression, which fails. AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null)); AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new[] { arg, arg })); } [Fact] public void UpdateToDifferentReturnsDifferent2() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object>), binder, arg0, arg1); Assert.NotSame(exp, exp.Update(new[] { arg0, arg0 })); Assert.NotSame(exp, exp.Update(new[] { arg1, arg0 })); // Wrong number of arguments continues to attempt to create new expression, which fails. AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null)); AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0])); } [Fact] public void UpdateToDifferentReturnsDifferent3() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object>), binder, arg0, arg1, arg2); Assert.NotSame(exp, exp.Update(new[] { arg1, arg1, arg2 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg0, arg2 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg0 })); // Wrong number of arguments continues to attempt to create new expression, which fails. AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null)); AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0])); } [Fact] public void UpdateToDifferentReturnsDifferent4() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); Expression arg3 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3); Assert.NotSame(exp, exp.Update(new[] { arg1, arg1, arg2, arg3 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg0, arg2, arg3 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg0, arg3 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg2, arg0 })); // Wrong number of arguments continues to attempt to create new expression, which fails. AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null)); AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0])); } [Fact] public void UpdateToDifferentReturnsDifferent5() { CallSiteBinder binder = Binder.GetMember( CSharpBinderFlags.None, "Member", GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); Expression arg0 = Expression.Constant(null); Expression arg1 = Expression.Constant(null); Expression arg2 = Expression.Constant(null); Expression arg3 = Expression.Constant(null); Expression arg4 = Expression.Constant(null); DynamicExpression exp = Expression.MakeDynamic( typeof(Func<CallSite, object, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3, arg4); Assert.NotSame(exp, exp.Update(new[] { arg1, arg1, arg2, arg3, arg4 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg0, arg2, arg3, arg4 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg0, arg3, arg4 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg2, arg0, arg4 })); Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg2, arg3, arg0 })); // Wrong number of arguments continues to attempt to create new expression, which fails. AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null)); AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0])); } } }
using System; using System.Data; using System.Globalization; using System.IO; using System.Windows.Forms; using System.Xml; using System.Collections.Generic; using Epi.Collections; using Epi.Data; using Epi.Data.Services; namespace Epi { /// <summary> /// Class Project /// </summary> public class Project : INamedObject, IDisposable // Project { #region Public Events /// <summary> /// Event Handler for TableCopyStatusEvent /// </summary> public event TableCopyStatusEventHandler TableCopyStatusEvent; /// <summary> /// Raise the TableCopyStatus Event /// </summary> /// <param name="tableName">Table name</param> /// <param name="recordCount">Record Count</param> public void RaiseEventTableCopyStatus(string tableName, int recordCount) { if (this.TableCopyStatusEvent != null) { this.TableCopyStatusEvent(this, new TableCopyStatusEventArgs(tableName, recordCount)); } } #endregion Public Events #region Private class members /// <summary> /// Collection of project views. /// </summary> public ViewCollection views = null; /// <summary> /// List of project pages. /// </summary> /// public List<Page> pages = null; private Guid id; private XmlDocument xmlDoc = null; private const int currentSchemaVersion = 102; private XmlElement currentViewElement; private string collectedDataConnectionString; bool _useMetaDataSet = false; #endregion Private class members #region Protected Class Members /// <summary> /// Project metadata accessor. /// </summary> protected IMetadataProvider metadata = null; /// <summary> /// Project collected data accessor. /// </summary> protected CollectedDataProvider collectedData = null; #endregion Protected Class Members #region Constructors /// <summary> /// Default Constructors /// </summary> public Project() { //isNew = true; PreConstruct(); // Add root element and attributes XmlElement root = xmlDoc.CreateElement("Project"); xmlDoc.AppendChild(root); // Add attributes of the root node XmlAttribute attr = xmlDoc.CreateAttribute("id"); root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("name"); root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("location"); root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("description"); root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("schemaVersion"); attr.Value = currentSchemaVersion.ToString(); root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("epiVersion"); root.Attributes.Append(attr = xmlDoc.CreateAttribute("epiVersion")); attr = xmlDoc.CreateAttribute("createDate"); attr.Value = DateTime.Now.ToString(CultureInfo.InvariantCulture.DateTimeFormat); root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("useMetadataDbForCollectedData"); attr.Value = string.Empty; root.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("useBackgroundOnAllPages"); attr.Value = Epi.Defaults.UseBackgroundOnAllPages.ToString(); root.Attributes.Append(attr); // Add Collected data node XmlElement xCollectedData = xmlDoc.CreateElement("CollectedData"); root.AppendChild(xCollectedData); XmlElement xDb = xmlDoc.CreateElement("Database"); xCollectedData.AppendChild(xDb); xDb.Attributes.Append(xmlDoc.CreateAttribute("connectionString")); xDb.Attributes.Append(xmlDoc.CreateAttribute("dataDriver")); // Add Metadata node. XmlElement xMetadata = xmlDoc.CreateElement("Metadata"); root.AppendChild(xMetadata); attr = xmlDoc.CreateAttribute("source"); attr.Value = ((int)MetadataSource.Unknown).ToString(); xMetadata.Attributes.Append(attr); // Add Enter and MakeView Interpreter node. XmlElement xEnter_MakeViewInterpreter = xmlDoc.CreateElement("EnterMakeviewInterpreter"); root.AppendChild(xEnter_MakeViewInterpreter); attr = xmlDoc.CreateAttribute("source"); attr.Value = "Epi.Core.EnterInterpreter"; xEnter_MakeViewInterpreter.Attributes.Append(attr); } public Project(string filePath) { Construct(filePath); } public Project(string filePath, bool useMetaDataTable) { _useMetaDataSet = useMetaDataTable; Construct(filePath); } private void PreConstruct() { xmlDoc = new XmlDocument(); metaDbInfo = new DbDriverInfo(); collectedDataDbInfo = new DbDriverInfo(); collectedData = new CollectedDataProvider(this); } private void Construct(string filePath) { PreConstruct(); try { xmlDoc.Load(filePath); ValidateXmlDoc(); FileInfo fileInfo = new FileInfo(filePath); if (string.IsNullOrEmpty(Location)) { Location = fileInfo.DirectoryName; Save(); } else { if (string.Compare(fileInfo.DirectoryName, Location, true) != 0) { Location = fileInfo.DirectoryName; Save(); } } string[] Driver = this.CollectedDataDriver.Split(','); if (Driver[1].Trim().ToLower() == Configuration.WebDriver.ToLower()) { this.collectedData.IsWebMode = true; switch (Driver[0].Trim()) { case "Epi.Data.MySQL.MySQLDBFactory": this.CollectedDataDriver = Configuration.MySQLDriver; break; case "Epi.Data.Office.AccessDBFactory": this.CollectedDataDriver = Configuration.AccessDriver; break; case "Epi.Cloud.SqlServer.SqlDBFactory": default: this.CollectedDataDriver = Configuration.SqlDriver; break; } } this.collectedDataDbInfo.DBCnnStringBuilder.ConnectionString = this.CollectedDataConnectionString; collectedData.Initialize(this.collectedDataDbInfo, this.CollectedDataDriver, false); if (MetadataSource == MetadataSource.Xml) { metadata = new MetadataXmlProvider(this); } else { if (_useMetaDataSet) { metadata = new MetadataDataSet(this); } else { metadata = new MetadataDbProvider(this); if (MetadataSource == MetadataSource.SameDb) { metadata.AttachDbDriver(CollectedData.GetDbDriver()); } else { this.metaDbInfo.DBCnnStringBuilder.ConnectionString = this.MetadataConnectionString; metadata.Initialize(this.metaDbInfo, this.MetadataDriver, false); } } } } finally { } } #endregion Constructors #region Public Properties public bool UseMetaDataSet { set { _useMetaDataSet = value; } } /// <summary> /// Gets/sets the path name of project file. /// </summary> public string Location { get { return xmlDoc.DocumentElement.Attributes["location"].Value; } set { xmlDoc.DocumentElement.Attributes["location"].Value = value; } } public string EnterMakeviewIntepreter { get { return xmlDoc.DocumentElement["EnterMakeviewInterpreter"].Attributes["source"].Value; } set { xmlDoc.DocumentElement["EnterMakeviewInterpreter"].Attributes["source"].Value = value; } } /// <summary> /// Gets project display name. /// </summary> public string DisplayName { get { return Name; } } /// <summary> /// Project name. /// </summary> public string Name { get { return xmlDoc.DocumentElement.Attributes["name"].Value; } set { xmlDoc.DocumentElement.Attributes["name"].Value = value; } } /// <summary> /// The width of the panel that contains the controls. /// </summary> public string PageWidth { get { return xmlDoc.DocumentElement.Attributes["pageWidth"].Value; } set { xmlDoc.DocumentElement.Attributes["pageWidth"].Value = value; } } /// <summary> /// The height of the panel that contains the controls. /// </summary> public string PageHeight { get { return xmlDoc.DocumentElement.Attributes["pageHeight"].Value; } set { xmlDoc.DocumentElement.Attributes["pageHeight"].Value = value; } } /// <summary> /// Returns the file name of the project. /// </summary> public string FileName { get { if (!string.IsNullOrEmpty(Name)) { return Name.Replace(FileExtension, string.Empty) + FileExtension; } else { return string.Empty; } } } /// <summary> /// Returns the full name of the data source. /// </summary> public string FilePath { get { if (string.IsNullOrEmpty(Location) || string.IsNullOrEmpty(FileName)) { return string.Empty; } else { return Path.Combine(Location, FileName); } } } /// <summary> /// Returns the full name of the data source. /// </summary> public string FullName { get { return FilePath; } } /// <summary> /// Returns use metadata for collected data flag. /// </summary> public virtual bool UseMetadataDbForCollectedData { get { return bool.Parse(xmlDoc.DocumentElement.Attributes["useMetadataDbForCollectedData"].Value); } set { xmlDoc.DocumentElement.Attributes["useMetadataDbForCollectedData"].Value = value.ToString(); } } /// <summary> /// Determines if the project is empty. /// </summary> public bool IsEmpty { get { return (string.IsNullOrEmpty(FullName)); } } /// <summary> /// Project metadata. /// </summary> public IMetadataProvider Metadata { get { return metadata; } } /// <summary> /// Project collected data. /// </summary> public CollectedDataProvider CollectedData { get { return collectedData; } } /// <summary> /// Project metadata. /// </summary> public IMetadataProvider CodeData { get { return Metadata; } } /// <summary> /// Determines if this data source is actually an Epi (2000 or 7)collected data. /// </summary> public virtual bool IsEpiCollectedData { get { return false; } } /// <summary> /// Returns a globally unique identifier for the project. /// </summary> public System.Guid Id { get { if (id.Equals(Guid.Empty)) { if (string.IsNullOrEmpty(FilePath)) { //return Guid.Empty; id = Guid.NewGuid(); } else { id = Util.GetFileGuid(FilePath); } } return id; } set { xmlDoc.DocumentElement.Attributes["id"].Value = value.ToString(); } } /// <summary> /// Views of the project. /// </summary> public ViewCollection Views { get { if (views == null) { LoadViews(); } return views; } } /// <summary> /// Returns the original Epi Info version of the project. /// </summary> public string EpiVersion { get { return xmlDoc.DocumentElement.Attributes["epiVersion"].Value; } } /// <summary> /// Returns date the project was created. /// </summary> public DateTime CreateDate { get { return DateTime.Parse(xmlDoc.DocumentElement.Attributes["createDate"].Value, CultureInfo.InvariantCulture.DateTimeFormat); } } /// <summary> /// Project description. /// </summary> public string Description { get { return xmlDoc.DocumentElement.Attributes["description"].Value; } set { xmlDoc.DocumentElement.Attributes["description"].Value = value; } } private XmlNode GetMetadataDbNode() { return xmlDoc.DocumentElement.SelectSingleNode("/Project/Metadata/Database"); } private XmlNode GetCollectedDataDbNode() { return xmlDoc.DocumentElement.SelectSingleNode("/Project/CollectedData/Database"); } /// <summary> /// Connection string for the Metadata database. /// </summary> public string MetadataConnectionString { get { return GetMetadataDbNode().Attributes["connectionString"].Value; } set { GetMetadataDbNode().Attributes["connectionString"].Value = value; } } /// <summary> /// Driver name for the Metadata database. /// </summary> public string MetadataDriver { get { return GetMetadataDbNode().Attributes["dataDriver"].Value; } set { GetMetadataDbNode().Attributes["dataDriver"].Value = value.ToString(); } } private DbDriverInfo metaDbInfo; /// <summary> /// Information for the Metadata database. /// </summary> public DbDriverInfo MetaDbInfo { get { return metaDbInfo; } set { metaDbInfo = value; } } private DbDriverInfo collectedDataDbInfo; /// <summary> /// Information for the Collected database. /// </summary> public DbDriverInfo CollectedDataDbInfo { get { return collectedDataDbInfo; } set { collectedDataDbInfo = value; } } /// <summary> /// Gets/sets the metadata source. Possible values are Database and Xml. /// </summary> public Epi.MetadataSource MetadataSource { get { XmlNode metadataNode = GetMetadataNode(); XmlAttribute sourceAttribute = metadataNode.Attributes.GetNamedItem("source") as XmlAttribute; if (sourceAttribute == null) { return MetadataSource.Unknown; } else { return (MetadataSource)int.Parse(sourceAttribute.Value); } } set { XmlNode metadataNode = GetMetadataNode(); metadataNode.Attributes["source"].Value = ((int)value).ToString(); switch (value) { case MetadataSource.Xml: metadata = new MetadataXmlProvider(this); break; case MetadataSource.SameDb: metadata = new MetadataDbProvider(this); break; case MetadataSource.DifferentDb: metadata = new MetadataDbProvider(this); XmlElement xDb = xmlDoc.CreateElement("Database"); GetMetadataNode().AppendChild(xDb); xDb.Attributes.Append(xmlDoc.CreateAttribute("connectionString")); xDb.Attributes.Append(xmlDoc.CreateAttribute("dataDriver")); break; default: break; } } } /// <summary> /// Connection string for the Collected database. /// </summary> public string CollectedDataConnectionString { get { if (string.IsNullOrEmpty(collectedDataConnectionString)) { collectedDataConnectionString = Configuration.Decrypt(GetCollectedDataDbNode().Attributes["connectionString"].Value); } if (this.CollectedDataDriver == "Epi.Data.Office.AccessDBFactory, Epi.Data.Office") return this.SetOleDbDatabaseFilePath(collectedDataConnectionString); else return collectedDataConnectionString; } set { GetCollectedDataDbNode().Attributes["connectionString"].Value = Configuration.Encrypt(value); collectedDataConnectionString = value; } } /// <summary> /// Data Driver for the Collected database. /// </summary> public string CollectedDataDriver { get { return GetCollectedDataDbNode().Attributes["dataDriver"].Value; } set { GetCollectedDataDbNode().Attributes["dataDriver"].Value = value.ToString(); } } #endregion Public Properties #region Static Methods /// <summary> /// Checks the name of a project to make sure the syntax is valid. /// </summary> /// <param name="projectName">The name of the project to validate</param> /// <param name="validationStatus">The message that is passed back to the calling method regarding the status of the validation attempt</param> /// <returns>Whether or not the name passed validation; true for a valid name, false for an invalid name</returns> public static bool IsValidProjectName(string projectName, ref string validationStatus) { // assume valid by default bool valid = true; if (string.IsNullOrEmpty(projectName.Trim())) { // if the project name is empty, or just a series of spaces, invalidate it validationStatus = SharedStrings.MISSING_PROJECT_NAME; valid = false; } else if (AppData.Instance.IsReservedWord(projectName)) { // if the project name is a reserved word, invalidate it validationStatus = SharedStrings.INVALID_PROJECT_NAME_RESERVED_WORD; valid = false; } else if (projectName.Length > 64) { validationStatus = SharedStrings.INVALID_PROJECT_NAME_TOO_LONG; valid = false; } else { // if the project name is not empty or in the list of reserved words... System.Text.RegularExpressions.Match numMatch = System.Text.RegularExpressions.Regex.Match(projectName.Substring(0, 1), "[0-9]"); if (numMatch.Success) { // if the project name has numbers for the first character, invalidate it validationStatus = SharedStrings.PROJECT_NAME_BEGIN_NUMERIC; valid = false; } // if the project name doesn't have a number as the first character... else { // iterate over all of the characters in the project name for (int i = 0; i < projectName.Length; i++) { string viewChar = projectName.Substring(i, 1); System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(viewChar, "[A-Za-z0-9_]"); // if the project name does not consist of only letters and numbers... if (!m.Success) { // we found an invalid character; invalidate the project name validationStatus = SharedStrings.INVALID_PROJECT_NAME; valid = false; break; // stop the for loop here, no point in continuing } } } } return valid; } #endregion // Static Methods #region Public Methods /// <summary> /// Returns the Project Id /// </summary> /// <returns>The GUID representation of the project Id</returns> public Guid GetProjectId() { return this.Id; } /// <summary> /// Disposes the object. /// </summary> public virtual void Dispose() { if (metadata != null) { //metadata.Dispose(); metadata = null; } if (collectedData != null) { //collectedData.Dispose(); collectedData = null; } if (views != null) { //views.Dispose(); views = null; } } /// <summary> /// Saves the XML document for the project using the specified <see cref="System.Xml.XmlWriter"/>. /// </summary> public virtual void Save() { try { xmlDoc.Save(FilePath); } catch (UnauthorizedAccessException ex) { throw ex; } catch (XmlException xmlEx) { throw xmlEx; } } /// <summary> /// Returns the Xml document for the project. /// </summary> /// <returns>Xml Document object.</returns> public XmlDocument GetXmlDocument() { return xmlDoc; } /// <summary> /// Returns all views in the current project as a DataTable /// </summary> /// <returns>Contents of view's data table.</returns> public virtual DataTable GetViewsAsDataTable() { return (Metadata.GetViewsAsDataTable()); } /// <summary> /// Returns list of tables that are <see cref="Epi.View"/>s. /// </summary> /// <returns>Listof view names</returns> public virtual List<string> GetViewNames() { DataTable dt = Metadata.GetViewsAsDataTable(); List<String> list = new List<String>(); foreach (DataRow row in dt.Rows) { list.Add(row[ColumnNames.NAME].ToString()); } return list; } /// <summary> /// /// </summary> /// <returns></returns> public virtual List<string> GetParentViewNames() { DataTable dt = Metadata.GetViewsAsDataTable(); List<String> list = new List<String>(); //If SQL permissions denied, returns dt with no rows--checked here. den4 11/23/2010 if (dt == null || dt.Rows.Count == 0) { return list; } DataRow[] rows = dt.Select(ColumnNames.IS_RELATED_VIEW + "=false"); foreach (DataRow row in rows) { list.Add(row[ColumnNames.NAME].ToString()); } return list; } /// <summary> /// Is View (by name) flag. /// </summary> /// <remarks> /// returns true if the named object is (or has) a view /// </remarks> /// <param name="name">Name of view to check.</param> /// <returns>True/False</returns> public bool IsView(string name) { // dcs0 If it's not in MetaViews - it's not a view - period! //if (name.ToLower().StartsWith("view")) //{ // return true; //} //else //{ //List<string> list = GetViewNames(); // dcs0 was case sensitive foreach (string s in GetViewNames()) { if (string.Compare(s, name, true) == 0) { return true; } //return (list.Contains(name)); } return false; // return GetViewNames().Contains(name); } /// <summary> /// Returns a view by it's name /// </summary> /// <param name="viewName"></param> /// <returns>Project <see cref="Epi.View"/></returns> public View GetViewByName(string viewName) { //foreach (View view in GetViews()) foreach (View view in Views) { if (string.Compare(view.Name, viewName, true) == 0) { return view; } } throw new System.ApplicationException(string.Format(SharedStrings.ERROR_LOADING_VIEW, viewName)); } /// <summary> /// Returns table column names. /// </summary> /// <param name="tableName">Name of table.</param> /// <returns>Listof table column names.</returns> public List<string> GetTableColumnNames(string tableName) { return CollectedData.GetTableColumnNames(tableName); } /// <summary> /// Returns Primary key names. /// </summary> /// <param name="tableName">Name of table.</param> /// <returns>List of primary key names.</returns> public List<string> GetPrimaryKeyNames(string tableName) { DataTable dt = CollectedData.GetPrimaryKeysAsDataTable(tableName); List<string> list = new List<string>(); foreach (DataRow row in dt.Rows) { list.Add(row[ColumnNames.COLUMN_NAME].ToString()); } return list; } /// <summary> /// Returns contents of all nonview (collected data) tables. /// </summary> /// <returns>Contents of nonview tables.</returns> public virtual DataTable GetNonViewTablesAsDataTable() { return CollectedData.GetNonViewTablesAsDataTable(); } /// <summary> /// Returns names of all nonview (collected data) tables. /// </summary> /// <returns>List of nonview table names.</returns> public List<string> GetNonViewTableNames() { DataTable dt = Metadata.GetNonViewTablesAsDataTable(); List<string> list = new List<string>(); foreach (DataRow row in dt.Rows) { list.Add(row[ColumnNames.NAME].ToString()); } return list; } /// <summary> /// Gets <see cref="Epi.View"/> by view Id. /// </summary> /// <param name="viewId">Id of <see cref="Epi.View"/> to get.</param> /// <returns>Project <see cref="Epi.View"/></returns> public View GetViewById(int viewId) { return (Views.GetViewById(viewId)); } /// <summary> /// Saves project information /// </summary> public virtual Project CreateProject(string projectName, string projectDescription, string projectLocation, string collectedDataDriver, DbDriverInfo collectedDataDBInfo) { Project newProject = new Project(); newProject.Name = projectName; newProject.Location = Path.Combine(projectLocation, projectName); if (collectedDataDBInfo.DBCnnStringBuilder.ContainsKey("Provider") && (collectedDataDBInfo.DBCnnStringBuilder["Provider"].ToString() == "Microsoft.Jet.OLEDB.4.0")) { collectedDataDBInfo.DBCnnStringBuilder["Data Source"] = newProject.FilePath.Substring(0, newProject.FilePath.Length - 4) + ".mdb"; } if (!Directory.Exists(newProject.Location)) { Directory.CreateDirectory(newProject.Location); } newProject.Id = newProject.GetProjectId(); if (File.Exists(newProject.FilePath)) { DialogResult dr = MessageBox.Show(string.Format(SharedStrings.PROJECT_ALREADY_EXISTS, newProject.FilePath), SharedStrings.PROJECT_ALREADY_EXISTS_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); switch (dr) { case DialogResult.Yes: break; case DialogResult.No: return null; } } newProject.Description = projectDescription; // Collected data ... newProject.CollectedDataDbInfo = collectedDataDBInfo; newProject.CollectedDataConnectionString = collectedDataDBInfo.DBCnnStringBuilder.ToString(); newProject.CollectedDataDriver = collectedDataDriver; newProject.CollectedData.Initialize(collectedDataDBInfo, collectedDataDriver, true); // Check that there isn't an Epi 7 project already here. if (newProject.CollectedDataDriver != "Epi.Data.Office.AccessDBFactory, Epi.Data.Office") { List<string> tableNames = new List<string>(); tableNames.Add("metaBackgrounds"); tableNames.Add("metaDataTypes"); tableNames.Add("metaDbInfo"); tableNames.Add("metaFields"); tableNames.Add("metaFieldTypes"); tableNames.Add("metaGridColumns"); tableNames.Add("metaImages"); tableNames.Add("metaLayerRenderTypes"); tableNames.Add("metaLayers"); tableNames.Add("metaMapLayers"); tableNames.Add("metaMapPoints"); tableNames.Add("metaMaps"); tableNames.Add("metaPages"); tableNames.Add("metaPatterns"); tableNames.Add("metaPrograms"); tableNames.Add("metaViews"); bool projectExists = false; foreach (string s in tableNames) { if (newProject.CollectedData.TableExists(s)) { projectExists = true; break; } } if (projectExists) { DialogResult result = MessageBox.Show(SharedStrings.WARNING_PROJECT_MAY_ALREADY_EXIST, SharedStrings.WARNING_PROJECT_MAY_ALREADY_EXIST_SHORT, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (result == DialogResult.Cancel) { Logger.Log(DateTime.Now + ": " + "Project creation aborted by user [" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString() + "] after being prompted to overwrite existing Epi Info 7 project metadata."); return null; } else { Logger.Log(DateTime.Now + ": " + "Project creation proceeded by user [" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString() + "] after being prompted to overwrite existing Epi Info 7 project metadata."); } } } Logger.Log(DateTime.Now + ": " + string.Format("Project [{0}] created in {1} by user [{2}].", newProject.Name, newProject.Location, System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString())); // Metadata .. newProject.MetadataSource = MetadataSource.SameDb; MetadataDbProvider typedMetadata = newProject.Metadata as MetadataDbProvider; typedMetadata.AttachDbDriver(newProject.CollectedData.GetDbDriver()); typedMetadata.CreateMetadataTables(); try { newProject.Save(); return newProject; } catch (UnauthorizedAccessException ex) { MessageBox.Show(ex.Message); return newProject; } } /// <summary> /// Default Constructor /// </summary> /// <param name="viewName"></param> /// <returns>New project <see cref="Epi.View"/></returns> public View CreateView(string viewName) { return CreateView(viewName, false); } /// <summary> /// Constructor /// </summary> /// <param name="viewName">New <see cref="Epi.View"/> name.</param> /// <param name="isChildView">Is Related (child) view flag.</param> /// <returns>New project <see cref="Epi.View"/></returns> public View CreateView(string viewName, bool isChildView) { View newView = new View(this); newView.Name = viewName; newView.SetTableName(newView.Name); newView.IsRelatedView = isChildView; if (!Views.Contains(newView)) { Views.Add(newView); } Metadata.InsertView(newView); currentViewElement = newView.ViewElement; LoadViews(); return newView; } /// <summary> /// Returns a list of programs saved in the project. /// </summary> /// <returns>DataTable containing a list of programs</returns> public virtual DataTable GetPgms() { return (Metadata.GetPgms()); } /// <summary> /// Returns a list of program names. /// </summary> /// <returns>List of program names.</returns> public List<string> GetPgmNames() { DataTable dt = Metadata.GetPgms(); List<string> list = new List<String>(); foreach (DataRow row in dt.Rows) { list.Add(row[ColumnNames.NAME].ToString()); } return list; } /// <summary> /// Inserts a program into the database /// </summary> /// <param name="name">Name of the program</param> /// <param name="content">Content of the program</param> /// <param name="comment">Comment for the program</param> /// <param name="author">Author of the program</param> public virtual void InsertPgm(string name, string content, string comment, string author) { Metadata.InsertPgm(name, content, comment, author); } /// <summary> /// Inserts a program into the database /// </summary> /// <param name="pgmRow">A DataRow with all of the parameters</param> public virtual void InsertPgm(DataRow pgmRow) { // dcs TODO temporary; overload MetaData method Metadata.InsertPgm(pgmRow[ColumnNames.PGM_NAME].ToString(), pgmRow[ColumnNames.PGM_CONTENT].ToString(), pgmRow[ColumnNames.PGM_COMMENT].ToString(), pgmRow[ColumnNames.PGM_AUTHOR].ToString()); } /// <summary> /// Deletes a program from the database /// </summary> /// <param name="programName">Name of the program to be deleted</param> /// <param name="programId">Id of the program to be deleted</param> public virtual void DeletePgm(string programName, int programId) { Metadata.DeletePgm(programId); } /// <summary> /// Updates a program saved in the database /// </summary> /// <param name="programId">Id of the program</param> /// <param name="name">Name of the program</param> /// <param name="content">Content of the program</param> /// <param name="comment">Comment for the program</param> /// <param name="author">Author of the program</param> public virtual void UpdatePgm(int programId, string name, string content, string comment, string author) { Metadata.UpdatePgm(programId, name, content, comment, author); } /// <summary> /// Returns a list of data table names. /// </summary> /// <remarks>Make same call as Project.GetDataTableNames().</remarks> /// <returns>List of data table names.</returns> public virtual List<string> GetDataTableList() { return (Metadata.GetDataTableList()); } /// <summary> /// Returns a list of data table names. /// </summary> /// <remarks>Makes same call as Project.GetDataTableList().</remarks> /// <returns>List of data table names.</returns> public List<string> GetDataTableNames() { return Metadata.GetDataTableList(); } /// <summary> /// Create a new code table. /// </summary> /// <param name="tableName">Name of new code table.</param> /// <param name="columnNames">List of new columns to create in new code table.</param> public virtual void CreateCodeTable(string tableName, string[] columnNames) { CodeData.CreateCodeTable(tableName, columnNames); } /// <summary> /// Create a new code table. /// </summary> /// <param name="tableName">Name of new code table.</param> /// <param name="columnName">Name of column to create in new code table.</param> public virtual void CreateCodeTable(string tableName, string columnName) { CodeData.CreateCodeTable(tableName, columnName); } /// <summary> /// Save code table data. /// </summary> /// <param name="dataTable"><see cref="System.Data.DataTable"/> containing code table data.</param> /// <param name="tableName">Name of code table.</param> /// <param name="columnName">Name of code table column.</param> public virtual void SaveCodeTableData(DataTable dataTable, string tableName, string columnName) { CodeData.SaveCodeTableData(dataTable, tableName, columnName); } /// <summary> /// Save code table data /// </summary> /// <param name="dataTable"><see cref="System.Data.DataTable"/> containing code table data.</param> /// <param name="tablename">Name of code table.</param> /// <param name="columnNames">List of code table column names.</param> public virtual void SaveCodeTableData(DataTable dataTable, string tablename, string[] columnNames) { CodeData.SaveCodeTableData(dataTable, tablename, columnNames); } /// <summary> /// Insert code table data /// </summary> /// <param name="dataTable"><see cref="System.Data.DataTable"/> containing code table data.</param> /// <param name="tablename">Name of code table.</param> /// <param name="columnNames">List of code table column names.</param> public virtual void InsertCodeTableData(DataTable dataTable, string tablename, string[] columnNames) { CodeData.InsertCodeTableData(dataTable, tablename, columnNames); } /// <summary> /// Obsolete calls to return code table data by code table name. /// </summary> /// <param name="codeTableName">Code table name</param> /// <returns>Code table data.</returns> [Obsolete("Use of DataTable in this context is no different than the use of a multidimensional System.Object array (not recommended).", false)] public virtual DataTable GetCodeTableData(string codeTableName) { return CodeData.GetCodeTableData(codeTableName); } /// <summary> /// Returns table data /// </summary> /// <param name="tableName">Name of data table.</param> /// <returns>Contents of data table.</returns> public virtual DataTable GetTableData(string tableName) { if (tableName.StartsWith("code", StringComparison.InvariantCultureIgnoreCase)) // it is a code table { return CodeData.GetCodeTableData(tableName); } else // It is a data table { return CollectedData.GetTableData(tableName); } } /// <summary> /// Returns table data /// </summary> /// <param name="tableName">Name of data table.</param> /// <param name="columnNames">List of column names in data table.</param> /// <returns>Contents of data table.</returns> public virtual DataTable GetTableData(string tableName, string columnNames) { if (tableName.StartsWith("code", StringComparison.InvariantCultureIgnoreCase)) // it is a code table { return CodeData.GetCodeTableData(tableName, columnNames); } else // It is a data table { return CollectedData.GetTableData(tableName, columnNames); } } /// <summary> /// Returns table data /// </summary> /// <param name="tableName">Name of data table.</param> /// <param name="columnNames">Name of column in data table.</param> /// <param name="sortCriteria"></param> /// <returns>Contents of data table.</returns> public virtual DataTable GetTableData(string tableName, string columnNames, string sortCriteria) { if (tableName.StartsWith("code", StringComparison.InvariantCultureIgnoreCase)) // it is a code table { return CodeData.GetCodeTableData(tableName, columnNames, sortCriteria); } else // It is a data table { return CollectedData.GetTableData(tableName, columnNames, sortCriteria); } } /// <summary> /// Creates a link to a table from this project /// </summary> /// <param name="linkName">Name of link to make.</param> /// <param name="tableName">Name of table to link.</param> /// <param name="connectionString">Remote table connection information.</param> public virtual void CreateLinkTable(string linkName, string tableName, string connectionString) { // ??? Add the link to the project's XML file } /// <summary> /// Deletes link table from the project. /// </summary> /// <param name="linkName">Name of link to delete.</param> public void DeleteLinkTable(string linkName) { // ??? Delete the link from the XML file } /// <summary> /// Compares this project against the other and determines if they are same. /// </summary> /// <param name="other">Epi.Project to compare.</param> /// <returns>True/False</returns> public virtual bool Equals(Project other) { return (this.Id == other.Id); } /// <summary> /// Retrieves a list of all code tables. /// </summary> /// <returns>List of all code tables</returns> public DataSets.TableSchema.TablesDataTable GetCodeTableList() { return CodeData.GetCodeTableList(); } /// <summary> /// Returns a list of CodeTableNames /// </summary> /// <returns>List of code table names.</returns> public List<String> GetCodeTableNames() { DataTable dt = CodeData.GetCodeTableList(); List<string> list = new List<string>(); foreach (DataRow row in dt.Rows) { if (dt.Columns.Contains(ColumnNames.TABLE_NAME)) { list.Add(row[ColumnNames.TABLE_NAME].ToString()); } else { list.Add(row[ColumnNames.NAME].ToString()); } } return list; } /// <summary> /// Load Views /// </summary> public virtual void LoadViews() { if (MetadataSource == MetadataSource.Unknown) { throw new GeneralException(SharedStrings.ERROR_LOADING_METADATA_UNKNOWN_SOURCE); } if (MetadataSource != MetadataSource.Xml) { views = Metadata.GetViews(); } else { XmlNode viewsNode = GetViewsNode(); views = Metadata.GetViews(currentViewElement, viewsNode); } } #region OBSOLETE // public void CopyCodeTablesTo(Project destination) // { // List<String> codeTableList = GetCodeTableNames(); //// DataTable codeTableList = GetCodeTableList(); //// foreach (DataRow codeTableRow in codeTableList.Rows) // foreach (string codeTableName in codeTableList) // { //// string codeTableName = codeTableRow["TABLE_NAME"].ToString(); // // Raise event indicating the copy has begun. // if (TableCopyBeginEvent != null) // { // TableCopyBeginEvent(this, new MessageEventArgs(codeTableName)); // } // DataTable columns = CodeData.GetCodeTableColumnSchema(codeTableName); // string[] columnNames = new string[columns.Rows.Count]; // for (int x = 0; x < columns.Rows.Count; x++) // { // columnNames[x] = columns.Rows[x]["COLUMN_NAME"].ToString(); // } // destination.CreateCodeTable(codeTableName, columnNames); // DataTable CodeTable = CodeData.GetCodeTableData(codeTableName); // int rowIndex = 0; // foreach (DataRow CodeRow in CodeTable.Rows) // { // rowIndex++; // string[] columnData = new string[columnNames.Length]; // for (int x = 0; x < columnNames.Length; x++) // { // columnData[x] = CodeRow[columnNames[x]].ToString(); // } // destination.Metadata.CreateCodeTableRecord(codeTableName, columnNames, columnData); // RaiseEventTableCopyStatus(codeTableName, rowIndex); // // RaiseEventImportStatus(codeTableName + " (" + rowIndex + " reocrds copied)"); // } // if (this.TableCopyEndEvent != null) // { // TableCopyEndEvent(this, new MessageEventArgs(codeTableName)); // } // } // } ///// <summary> ///// Creates project's relevant databases ///// </summary> //public void Initialize() //{ // //this is a hack to ensure that relative file paths are read // //correctly // string oldCurrentDirectory = Directory.GetCurrentDirectory(); // string tempCurrentDirectory = this.Location; // Directory.SetCurrentDirectory(tempCurrentDirectory); // //if (!this.metadataSource.Equals(MetadataSource.Xml)) // //{ // if (metadata is MetadataDbProvider) // { // if (!string.IsNullOrEmpty(this.MetadataDriver)) // { // ((MetadataDbProvider)metadata).Initialize(this.MetaDbInfo, this.MetadataDriver, true); // } // } // //} // //else // //{ // //} // if (!UseMetadataDbForCollectedData) // { // collectedData.Initialize(this.collectedDataDbInfo, this.CollectedDataDriver, true); // } // else // { // collectedData.Initialize(this.metaDbInfo, this.MetadataDriver, false); // } // Directory.SetCurrentDirectory(oldCurrentDirectory); //} // public void SetMetadataDbInfo(string ConnectionString, string driver); #endregion OBSOLETE #endregion Public Methods #region Protected properties /// <summary> /// Project file extension. /// </summary> protected virtual string FileExtension { get { return Epi.FileExtensions.EPI_PROJ; } } #endregion Protected properties #region Protected Methods #endregion Protected Methods #region Private properties private bool IsNew { get { return (id.Equals(Guid.Empty)); } } #endregion Private properties #region Private Methods #region Deprecated //private void FillXmlDoc() //{ // XmlNode root = xmlDoc.DocumentElement; // if (IsNew) // This is a newly created project. // { // ApplicationIdentity appId = new ApplicationIdentity(typeof(Configuration).Assembly); // // id = Guid.NewGuid(); // id = Util.GetFileGuid(FilePath); // EpiVersion = appId.Version; // createDate = System.DateTime.Now; // // If Metadata Db is used for Collected data, remove the collected data Db node. // if (UseMetadataDbForCollectedData) // { // XmlNode collectedDataNode = root.SelectSingleNode("/Project/CollectedData"); // if (collectedDataNode != null) // { // root.RemoveChild(collectedDataNode); // } // } // } // root.Attributes["id"].Value = Id.ToString(); // root.Attributes["name"].Value = Name; // root.Attributes["location"].Value = Location; // root.Attributes["useMetadataDbForCollectedData"].Value = useMetadataDbForCollectedData.ToString(); // //root.Attributes["databaseFormat"].Value = ((short)DbFormatType).ToString(); // root.Attributes["description"].Value = Description ; // root.Attributes["epiVersion"].Value = EpiVersion ; // root.Attributes["createDate"].Value = CreateDate.ToString(CultureInfo.InvariantCulture.DateTimeFormat); // XmlNode metadataDbNode = root.SelectSingleNode("/Project/Metadata/Database"); // Metadata.Db.FillXmlDoc(metadataDbNode); // if (UseMetadataDbForCollectedData == false) // { // XmlNode collectedDataDbNode = root.SelectSingleNode("/Project/CollectedData/Database"); // CollectedData.FillXmlDoc(collectedDataDbNode); // } //} //private void LoadFromXml(XmlNode rootNode) //{ // //id = new Guid(rootNode.Attributes["id"].Value); // Name = rootNode.Attributes["name"].Value; // Location = rootNode.Attributes["location"].Value; // epiVersion = rootNode.Attributes["epiVersion"].Value; // string createDateString = rootNode.Attributes["createDate"].Value; // createDate = DateTime.Parse(createDateString, CultureInfo.InvariantCulture.DateTimeFormat); // //DbFormatType = (DbFormatType)(short.Parse(rootNode.Attributes["databaseFormat"].Value)); // UseMetadataDbForCollectedData = bool.Parse(rootNode.Attributes["useMetadataDbForCollectedData"].Value); // Description = rootNode.Attributes["description"].Value; // XmlNode dbNode = rootNode.SelectSingleNode("/Project/Metadata/Database"); // string dataDriver = dbNode.Attributes["dataDriver"].Value; // string connString = dbNode.Attributes["connectionString"].Value; // ConnectionStringInfo connInfo = new ConnectionStringInfo(connString); // string fileName = connInfo.DataSource; // // Metadata.Db = DbProvider.GetFileDatabase(fileName); // Metadata.Db = DbProvider.GetDatabaseInstance(dataDriver); // Metadata.Db.ConnectionString = connString; // if (this.UseMetadataDbForCollectedData == false) // { // dbNode = rootNode.SelectSingleNode("/Project/CollectedData/Database"); // dataDriver = dbNode.Attributes["dataDriver"].Value; // connString = dbNode.Attributes["connectionString"].Value; // // connInfo = new ConnectionStringInfo(connString); // // fileName = connInfo.DataSource; // CollectedData = DbProvider.GetDatabaseInstance(dataDriver); // CollectedData.ConnectionString = connString; // } //} #endregion /// <summary> /// Get the metadata node /// </summary> /// <returns>Xml node</returns> public XmlNode GetMetadataNode() { XmlNode metadataNode = xmlDoc.DocumentElement.SelectSingleNode("/Project/Metadata"); return metadataNode; } private XmlNode GetViewsNode() { // return xmlDoc.DocumentElement.SelectSingleNode("/Project/Views"); return xmlDoc.DocumentElement.SelectSingleNode("/Project/Metadata/Views"); } private XmlNode GetFieldsNode() { return xmlDoc.DocumentElement.SelectSingleNode("/Project/Metadata/Views/View/Fields"); } /// <summary> /// Validates the XML doc read. Looks for schema differences and rejects if the schema is out of date. /// </summary> private void ValidateXmlDoc() { // Check schema version. If the schema is old, can't read the project. if (xmlDoc.DocumentElement.HasAttribute("schemaVersion")) { int schemaVersion = int.Parse(xmlDoc.DocumentElement.Attributes["schemaVersion"].Value.ToString()); if (schemaVersion < currentSchemaVersion) { throw new GeneralException(SharedStrings.PROJECT_SCHEMA_OUT_OF_DATE); } } else { throw new GeneralException(SharedStrings.PROJECT_SCHEMA_OUT_OF_DATE); } } /// <summary> /// Gets the Pages Node of the Project file /// </summary> /// <returns></returns> private XmlNode GetPagesNode() { return xmlDoc.DocumentElement.SelectSingleNode("/Project/Views/View/Pages"); } private String SetOleDbDatabaseFilePath(string pConnectionString) { System.Data.OleDb.OleDbConnectionStringBuilder connectionBuilder = new System.Data.OleDb.OleDbConnectionStringBuilder(pConnectionString); connectionBuilder.DataSource = this.FilePath.Replace(".prj", ".mdb"); return connectionBuilder.ToString(); } #endregion Private Methods } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace Microsoft.Management.UI.Internal { /// <summary> /// Defines a method which will be called when /// a condition is met. /// </summary> /// <typeparam name="T">The type of the item.</typeparam> /// <param name="item">The parameter to pass to the method.</param> [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] internal delegate void RetryActionCallback<T>(T item); /// <summary> /// Provides common WPF methods for use in the library. /// </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] internal static class WpfHelp { #region RetryActionAfterLoaded private static Dictionary<FrameworkElement, RetryActionAfterLoadedDataQueue> retryActionData = new Dictionary<FrameworkElement, RetryActionAfterLoadedDataQueue>(); /// <summary> /// Calls a method when the Loaded event is fired on a FrameworkElement. /// </summary> /// <typeparam name="T">The type of the parameter to pass to the callback method.</typeparam> /// <param name="element">The element whose Loaded state we are interested in.</param> /// <param name="callback">The method we will call if element.IsLoaded is false.</param> /// <param name="parameter">The parameter to pass to the callback method.</param> /// <returns> /// Returns true if the element is not loaded and the callback will be called /// when the element is loaded, false otherwise. /// </returns> public static bool RetryActionAfterLoaded<T>(FrameworkElement element, RetryActionCallback<T> callback, T parameter) { if (element.IsLoaded) { return false; } RetryActionAfterLoadedDataQueue data; if (!retryActionData.TryGetValue(element, out data)) { data = new RetryActionAfterLoadedDataQueue(); retryActionData.Add(element, data); } data.Enqueue(callback, parameter); element.Loaded += Element_Loaded; element.ApplyTemplate(); return true; } private static void Element_Loaded(object sender, RoutedEventArgs e) { FrameworkElement element = (FrameworkElement)sender; element.Loaded -= Element_Loaded; RetryActionAfterLoadedDataQueue data; if (!retryActionData.TryGetValue(element, out data) || data.IsEmpty) { throw new InvalidOperationException("Event loaded callback data expected."); } Delegate callback; object parameter; data.Dequeue(out callback, out parameter); if (data.IsEmpty) { retryActionData.Remove(element); } callback.DynamicInvoke(parameter); } private class RetryActionAfterLoadedDataQueue { private Queue<Delegate> callbacks = new Queue<Delegate>(); private Queue<object> parameters = new Queue<object>(); /// <summary> /// Adds a callback with its associated parameter to the collection. /// </summary> /// <param name="callback">The callback to invoke.</param> /// <param name="parameter">The parameter to pass to the callback.</param> public void Enqueue(Delegate callback, object parameter) { this.callbacks.Enqueue(callback); this.parameters.Enqueue(parameter); } /// <summary> /// Removes a callback with its associated parameter from the head of /// the collection. /// </summary> /// <param name="callback">The callback to invoke.</param> /// <param name="parameter">The parameter to pass to the callback.</param> public void Dequeue(out Delegate callback, out object parameter) { callback = null; parameter = null; if (this.callbacks.Count < 1) { throw new InvalidOperationException("Trying to remove when there is no data"); } callback = this.callbacks.Dequeue(); parameter = this.parameters.Dequeue(); } /// <summary> /// Gets whether there is any callback data available. /// </summary> public bool IsEmpty { get { return this.callbacks.Count == 0; } } } #endregion RetryActionAfterLoaded #region RemoveFromParent/AddChild /// <summary> /// Removes the specified element from its parent. /// </summary> /// <param name="element">The element to remove.</param> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> /// <exception cref="NotSupportedException">The specified value does not have a parent that supports removal.</exception> public static void RemoveFromParent(FrameworkElement element) { if (element == null) { throw new ArgumentNullException("element"); } // If the element has already been detached, do nothing \\ if (element.Parent == null) { return; } ContentControl parentContentControl = element.Parent as ContentControl; if (parentContentControl != null) { parentContentControl.Content = null; return; } var parentDecorator = element.Parent as Decorator; if (parentDecorator != null) { parentDecorator.Child = null; return; } ItemsControl parentItemsControl = element.Parent as ItemsControl; if (parentItemsControl != null) { parentItemsControl.Items.Remove(element); return; } Panel parentPanel = element.Parent as Panel; if (parentPanel != null) { parentPanel.Children.Remove(element); return; } var parentAdorner = element.Parent as UIElementAdorner; if (parentAdorner != null) { parentAdorner.Child = null; return; } throw new NotSupportedException("The specified value does not have a parent that supports removal."); } /// <summary> /// Removes the specified element from its parent. /// </summary> /// <param name="parent">The parent element.</param> /// <param name="element">The element to add.</param> /// <exception cref="NotSupportedException">The specified value does not have a parent that supports removal.</exception> public static void AddChild(FrameworkElement parent, FrameworkElement element) { if (element == null) { throw new ArgumentNullException("element"); } if (parent == null) { throw new ArgumentNullException("element"); } ContentControl parentContentControl = parent as ContentControl; if (parentContentControl != null) { parentContentControl.Content = element; return; } var parentDecorator = parent as Decorator; if (parentDecorator != null) { parentDecorator.Child = element; return; } ItemsControl parentItemsControl = parent as ItemsControl; if (parentItemsControl != null) { parentItemsControl.Items.Add(element); return; } Panel parentPanel = parent as Panel; if (parentPanel != null) { parentPanel.Children.Add(element); return; } throw new NotSupportedException("The specified parent doesn't support children."); } #endregion RemoveFromParent/AddChild #region VisualChild /// <summary> /// Returns the first visual child that matches the type T. /// Performs a breadth-first search. /// </summary> /// <typeparam name="T">The type of the child to find.</typeparam> /// <param name="obj">The object with a visual tree.</param> /// <returns>Returns an object of type T if found, otherwise null.</returns> public static T GetVisualChild<T>(DependencyObject obj) where T : DependencyObject { if (obj == null) { return null; } var elementQueue = new Queue<DependencyObject>(); elementQueue.Enqueue(obj); while (elementQueue.Count > 0) { var element = elementQueue.Dequeue(); T item = element as T; if (item != null) { return item; } for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i); elementQueue.Enqueue(child); } } return null; } /// <summary> /// Finds all children of type within the specified object's visual tree. /// </summary> /// <typeparam name="T">The type of the child to find.</typeparam> /// <param name="obj">The object with a visual tree.</param> /// <returns>All children of the specified object matching the specified type.</returns> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public static List<T> FindVisualChildren<T>(DependencyObject obj) where T : DependencyObject { Debug.Assert(obj != null, "obj is null"); if (obj == null) { throw new ArgumentNullException("obj"); } List<T> childrenOfType = new List<T>(); // Recursively loop through children looking for children of type within their trees \\ for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject childObj = VisualTreeHelper.GetChild(obj, i); T child = childObj as T; if (child != null) { childrenOfType.Add(child); } else { // Recurse \\ childrenOfType.AddRange(FindVisualChildren<T>(childObj)); } } return childrenOfType; } #endregion VisualChild /// <summary> /// Searches ancestors for data of the specified type. /// </summary> /// <typeparam name="T">The type of the data to find.</typeparam> /// <param name="obj">The visual whose ancestors are searched.</param> /// <returns>The data of the specified type; or if not found, <c>null</c>.</returns> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public static T FindVisualAncestorData<T>(this DependencyObject obj) where T : class { if (obj == null) { throw new ArgumentNullException("obj"); } FrameworkElement parent = obj.FindVisualAncestor<FrameworkElement>(); if (parent != null) { T data = parent.DataContext as T; if (data != null) { return data; } else { return parent.FindVisualAncestorData<T>(); } } return null; } /// <summary> /// Walks up the visual tree looking for an ancestor of a given type. /// </summary> /// <typeparam name="T">The type to look for.</typeparam> /// <param name="object">The object to start from.</param> /// <returns>The parent of the right type, or null.</returns> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public static T FindVisualAncestor<T>(this DependencyObject @object) where T : class { if (@object == null) { throw new ArgumentNullException("object"); } DependencyObject parent = VisualTreeHelper.GetParent(@object); if (parent != null) { T parentObj = parent as T; if (parentObj != null) { return parentObj; } return parent.FindVisualAncestor<T>(); } return null; } /// <summary> /// Executes the <see cref="RoutedCommand"/> on the current command target if it is allowed. /// </summary> /// <param name="command">The routed command.</param> /// <param name="parameter">A user defined data type.</param> /// <param name="target">The command target.</param> /// <returns><c>true</c> if the command could execute; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public static bool TryExecute(this RoutedCommand command, object parameter, IInputElement target) { if (command == null) { throw new ArgumentNullException("command"); } if (command.CanExecute(parameter, target)) { command.Execute(parameter, target); return true; } return false; } #region TemplateChild /// <summary> /// Gets the named child of an item from a templated control. /// </summary> /// <typeparam name="T">The type of the child.</typeparam> /// <param name="templateParent">The parent of the control.</param> /// <param name="childName">The name of the child.</param> /// <returns>The reference to the child, or null if the template part wasn't found.</returns> public static T GetOptionalTemplateChild<T>(Control templateParent, string childName) where T : FrameworkElement { if (templateParent == null) { throw new ArgumentNullException("templateParent"); } if (string.IsNullOrEmpty(childName)) { throw new ArgumentNullException("childName"); } object templatePart = templateParent.Template.FindName(childName, templateParent); T item = templatePart as T; if (item == null && templatePart != null) { HandleWrongTemplatePartType<T>(childName); } return item; } /// <summary> /// Gets the named child of an item from a templated control. /// </summary> /// <typeparam name="T">The type of the child.</typeparam> /// <param name="templateParent">The parent of the control.</param> /// <param name="childName">The name of the child.</param> /// <returns>The reference to the child.</returns> public static T GetTemplateChild<T>(Control templateParent, string childName) where T : FrameworkElement { T item = GetOptionalTemplateChild<T>(templateParent, childName); if (item == null) { HandleMissingTemplatePart<T>(childName); } return item; } /// <summary> /// Throws an exception with information about the template part with the wrong type. /// </summary> /// <typeparam name="T">The type of the expected template part.</typeparam> /// <param name="name">The name of the expected template part.</param> private static void HandleWrongTemplatePartType<T>(string name) { throw new ApplicationException(string.Format( CultureInfo.CurrentCulture, "A template part with the name of '{0}' is not of type {1}.", name, typeof(T).Name)); } /// <summary> /// Throws an exception with information about the missing template part. /// </summary> /// <typeparam name="T">The type of the expected template part.</typeparam> /// <param name="name">The name of the expected template part.</param> public static void HandleMissingTemplatePart<T>(string name) { throw new ApplicationException(string.Format( CultureInfo.CurrentCulture, "A template part with the name of '{0}' and type of {1} was not found.", name, typeof(T).Name)); } #endregion TemplateChild #region SetComponentResourceStyle /// <summary> /// Sets Style for control given a component resource key. /// </summary> /// <typeparam name="T">Type in which Component Resource Style is Defined.</typeparam> /// <param name="element">Element whose style need to be set.</param> /// <param name="keyName">Component Resource Key for Style.</param> public static void SetComponentResourceStyle<T>(FrameworkElement element, string keyName) where T : FrameworkElement { ComponentResourceKey styleKey = new ComponentResourceKey(typeof(T), keyName); element.Style = (Style)element.FindResource(styleKey); } #endregion SetComponentResourceStyle #region CreateRoutedPropertyChangedEventArgs /// <summary> /// Helper function to create a RoutedPropertyChangedEventArgs from a DependencyPropertyChangedEventArgs. /// </summary> /// <typeparam name="T">The type for the RoutedPropertyChangedEventArgs.</typeparam> /// <param name="propertyEventArgs">The DependencyPropertyChangedEventArgs data source.</param> /// <returns>The created event args, configured from the parameter.</returns> public static RoutedPropertyChangedEventArgs<T> CreateRoutedPropertyChangedEventArgs<T>(DependencyPropertyChangedEventArgs propertyEventArgs) { RoutedPropertyChangedEventArgs<T> eventArgs = new RoutedPropertyChangedEventArgs<T>( (T)propertyEventArgs.OldValue, (T)propertyEventArgs.NewValue); return eventArgs; } /// <summary> /// Helper function to create a RoutedPropertyChangedEventArgs from a DependencyPropertyChangedEventArgs. /// </summary> /// <typeparam name="T">The type for the RoutedPropertyChangedEventArgs.</typeparam> /// <param name="propertyEventArgs">The DependencyPropertyChangedEventArgs data source.</param> /// <param name="routedEvent">The routed event the property change is associated with.</param> /// <returns>The created event args, configured from the parameter.</returns> public static RoutedPropertyChangedEventArgs<T> CreateRoutedPropertyChangedEventArgs<T>(DependencyPropertyChangedEventArgs propertyEventArgs, RoutedEvent routedEvent) { RoutedPropertyChangedEventArgs<T> eventArgs = new RoutedPropertyChangedEventArgs<T>( (T)propertyEventArgs.OldValue, (T)propertyEventArgs.NewValue, routedEvent); return eventArgs; } #endregion CreateRoutedPropertyChangedEventArgs #region ChangeIndex /// <summary> /// Moves the item in the specified collection to the specified index. /// </summary> /// <param name="items">The collection to move the item in.</param> /// <param name="item">The item to move.</param> /// <param name="newIndex">The new index of the item.</param> /// <exception cref="ArgumentException">The specified item is not in the specified collection.</exception> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> /// <exception cref="ArgumentOutOfRangeException">The specified index is not valid for the specified collection.</exception> public static void ChangeIndex(ItemCollection items, object item, int newIndex) { if (items == null) { throw new ArgumentNullException("items"); } if (!items.Contains(item)) { throw new ArgumentException("The specified item is not in the specified collection.", "item"); } if (newIndex < 0 || newIndex > items.Count) { throw new ArgumentOutOfRangeException("newIndex", "The specified index is not valid for the specified collection."); } int oldIndex = items.IndexOf(item); // If the tile isn't moving, don't do anything \\ if (newIndex == oldIndex) { return; } items.Remove(item); // If adding to the end, add instead of inserting \\ if (newIndex > items.Count) { items.Add(item); } else { items.Insert(newIndex, item); } } #endregion ChangeIndex } }
using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace l2pvp { public class CharInfo { private readonly object AbnormalEffectsLock; private readonly object AllyCrestIDLock; private readonly object AllyIDLock; private readonly object AttackSpeedMultLock; private readonly object BackLock; private readonly object ChestLock; private readonly object ClanCrestIDLargeLock; private readonly object ClanCrestIDLock; private readonly object ClanIDLock; private readonly object ClassLock; private readonly object CollisionHeightLock; private readonly object CollisionRadiusLock; private readonly object CubicCountLock; private readonly object CubicsLock; private readonly object Cur_CPLock; private readonly object Cur_HPLock; private readonly object Cur_MPLock; private readonly object CurCPLock; private readonly object DemonSwordLock; private readonly object Dest_XLock; private readonly object Dest_YLock; private readonly object Dest_ZLock; private readonly object DollFaceLock; private readonly object EnchantAmountLock; private readonly object FaceLock; private readonly object FeetLock; private readonly object FindPartyLock; private readonly object FishXLock; private readonly object FishYLock; private readonly object FishZLock; private readonly object flRunSpeedLock; private readonly object flWalkSpeedLock; private readonly object FlyRunSpeedLock; private readonly object FlyWalkSpeedLock; private readonly object GlovesLock; private readonly object HairColorLock; private readonly object HairLock; private readonly object HairSytleLock; private readonly object HeadingLock; private readonly object HeadLock; private readonly object HeroGlowLock; private readonly object HeroIconLock; private readonly object IDLock; private readonly object InvisibleLock; private readonly object isAlikeDeadLock; private readonly object isFishingLock; private readonly object isInCombatLock; private readonly object isRunningLock; private readonly object isSittingLock; private readonly object Karma2Lock; private readonly object KarmaLock; private readonly object lastMoveTimeLock; private readonly object LegsLock; private readonly object LevelLock; private readonly object LHandLock; private readonly object LRHandLock; private readonly object MatkSpeedLock; private readonly object Max_CPLock; private readonly object Max_HPLock; private readonly object Max_MPLock; private readonly object MaxCPLock; private readonly object MountTypeLock; private readonly object MoveSpeedMultLock; private readonly object MoveTargetLock; private readonly object MoveTargetTypeLock; private readonly object MovingLock; private readonly object my_buffsLock; private readonly object NameColorLock; private readonly object NameLock; private readonly object PatkSpeedLock; private readonly object PledgeClassLock; private readonly object PrivateStoreTypeLock; private readonly object PvPFlag2Lock; private readonly object PvPFlagLock; private readonly object RaceLock; private readonly object RecAmountLock; private readonly object RecLeftLock; private readonly object RHandLock; private readonly object RunSpeedLock; private readonly object SexLock; private readonly object SiegeFlagsLock; private readonly object SwimRunSpeedLock; private readonly object SwimWalkSpeedLock; private readonly object TargetIDLock; private readonly object TargetTypeLock; private readonly object TeamCircleLock; private readonly object TitleColorLock; private readonly object TitleLock; private readonly object UnderwearLock; private readonly object UNKNOWN1Lock; private readonly object UNKNOWN2Lock; private readonly object UNKNOWN3Lock; private readonly object WalkSpeedLock; private readonly object WarStateLock; private readonly object XLock; private readonly object YLock; private readonly object ZLock; private uint _AbnormalEffects; private uint _AllyCrestID; private uint _AllyID; private double _AttackSpeedMult; private uint _Back; private uint _Chest; private uint _ClanCrestID; private uint _ClanCrestIDLarge; private uint _ClanID; private uint _Class; private double _CollisionHeight; private double _CollisionRadius; private ushort _CubicCount; private ArrayList _Cubics; private uint _Cur_CP; private uint _Cur_HP; private uint _Cur_MP; private uint _DemonSword; private int _Dest_X; private int _Dest_Y; private int _Dest_Z; private uint _DollFace; private byte _EnchantAmount; private uint _Face; private uint _Feet; private byte _FindParty; private int _FishX; private int _FishY; private int _FishZ; private uint _flRunSpeed; private uint _flWalkSpeed; private uint _FlyRunSpeed; private uint _FlyWalkSpeed; private uint _Gloves; private uint _Hair; private uint _HairColor; private uint _HairSytle; private uint _Head; private int _Heading; private byte _HeroGlow; private byte _HeroIcon; private uint _ID; private byte _Invisible; private byte _isAlikeDead; private byte _isFishing; private byte _isInCombat; private byte _isRunning; private byte _isSitting; private uint _Karma; private uint _Karma2; private DateTime _lastMoveTime; private uint _Legs; private uint _Level; private uint _LHand; private uint _LRHand; private uint _MatkSpeed; private uint _Max_CP; private uint _Max_HP; private uint _Max_MP; private byte _MountType; private double _MoveSpeedMult; private uint _MoveTarget; private int _MoveTargetType; private bool _Moving; private string _Name; private uint _NameColor; private uint _PatkSpeed; private uint _PledgeClass; private byte _PrivateStoreType; private uint _PvPFlag; private uint _PvPFlag2; private uint _Race; private ushort _RecAmount; private byte _RecLeft; private uint _RHand; private uint _RunSpeed; private uint _Sex; private uint _SiegeFlags; private uint _SwimRunSpeed; private uint _SwimWalkSpeed; private uint _TargetID; private int _TargetType; private byte _TeamCircle; private string _Title; private uint _TitleColor; private uint _Underwear; private uint _UNKNOWN1; private uint _UNKNOWN2; private uint _UNKNOWN3; private uint _WalkSpeed; private uint _WarState; private int _X; private int _Y; private int _Z; public int relation = 0; public uint AbnormalEffects { get { uint ui; lock (AbnormalEffectsLock) { ui = _AbnormalEffects; } return ui; } set { lock (AbnormalEffectsLock) { _AbnormalEffects = value; } } } public uint AllyCrestID { get { uint ui; lock (AllyCrestIDLock) { ui = _AllyCrestID; } return ui; } set { lock (AllyCrestIDLock) { _AllyCrestID = value; } } } public uint AllyID { get { uint ui; lock (AllyIDLock) { ui = _AllyID; } return ui; } set { lock (AllyIDLock) { _AllyID = value; } } } public double AttackSpeedMult { get { double d; lock (AttackSpeedMultLock) { d = _AttackSpeedMult; } return d; } set { lock (AttackSpeedMultLock) { _AttackSpeedMult = value; } } } public uint Back { get { uint ui; lock (BackLock) { ui = _Back; } return ui; } set { lock (BackLock) { _Back = value; } } } public uint Chest { get { uint ui; lock (ChestLock) { ui = _Chest; } return ui; } set { lock (ChestLock) { _Chest = value; } } } public uint ClanCrestID { get { uint ui; lock (ClanCrestIDLock) { ui = _ClanCrestID; } return ui; } set { lock (ClanCrestIDLock) { _ClanCrestID = value; } } } public uint ClanCrestIDLarge { get { uint ui; lock (ClanCrestIDLargeLock) { ui = _ClanCrestIDLarge; } return ui; } set { lock (ClanCrestIDLargeLock) { _ClanCrestIDLarge = value; } } } public uint ClanID { get { uint ui; lock (ClanIDLock) { ui = _ClanID; } return ui; } set { lock (ClanIDLock) { _ClanID = value; } } } public uint Class { get { uint ui; lock (ClassLock) { ui = _Class; } return ui; } set { lock (ClassLock) { _Class = value; } } } public double CollisionHeight { get { double d; lock (CollisionHeightLock) { d = _CollisionHeight; } return d; } set { lock (CollisionHeightLock) { _CollisionHeight = value; } } } public double CollisionRadius { get { double d; lock (CollisionRadiusLock) { d = _CollisionRadius; } return d; } set { lock (CollisionRadiusLock) { _CollisionRadius = value; } } } public ushort CubicCount { get { ushort ush; lock (CubicCountLock) { ush = _CubicCount; } return ush; } set { lock (CubicCountLock) { _CubicCount = value; } } } public ArrayList Cubics { get { ArrayList arrayList; lock (CubicsLock) { arrayList = _Cubics; } return arrayList; } set { lock (CubicsLock) { _Cubics = value; } } } public uint Cur_CP { get { uint ui; lock (Cur_CPLock) { ui = _Cur_CP; } return ui; } set { lock (Cur_CPLock) { _Cur_CP = value; } } } public uint Cur_HP { get { uint ui; lock (Cur_HPLock) { ui = _Cur_HP; } return ui; } set { lock (Cur_HPLock) { _Cur_HP = value; } } } public uint Cur_MP { get { uint ui; lock (Cur_MPLock) { ui = _Cur_MP; } return ui; } set { lock (Cur_MPLock) { _Cur_MP = value; } } } public uint DemonSword { get { uint ui; lock (DemonSwordLock) { ui = _DemonSword; } return ui; } set { lock (DemonSwordLock) { _DemonSword = value; } } } public int Dest_X { get { int i; lock (Dest_XLock) { i = _Dest_X; } return i; } set { lock (Dest_XLock) { _Dest_X = value; } } } public int Dest_Y { get { int i; lock (Dest_YLock) { i = _Dest_Y; } return i; } set { lock (Dest_YLock) { _Dest_Y = value; } } } public int Dest_Z { get { int i; lock (Dest_ZLock) { i = _Dest_Z; } return i; } set { lock (Dest_ZLock) { _Dest_Z = value; } } } public uint DollFace { get { uint ui; lock (DollFaceLock) { ui = _DollFace; } return ui; } set { lock (DollFaceLock) { _DollFace = value; } } } public byte EnchantAmount { get { byte b; lock (EnchantAmountLock) { b = _EnchantAmount; } return b; } set { lock (EnchantAmountLock) { _EnchantAmount = value; } } } public uint Face { get { uint ui; lock (FaceLock) { ui = _Face; } return ui; } set { lock (FaceLock) { _Face = value; } } } public uint Feet { get { uint ui; lock (FeetLock) { ui = _Feet; } return ui; } set { lock (FeetLock) { _Feet = value; } } } public byte FindParty { get { byte b; lock (FindPartyLock) { b = _FindParty; } return b; } set { lock (FindPartyLock) { _FindParty = value; } } } public int FishX { get { int i; lock (FishXLock) { i = _FishX; } return i; } set { lock (FishXLock) { _FishX = value; } } } public int FishY { get { int i; lock (FishYLock) { i = _FishY; } return i; } set { lock (FishYLock) { _FishY = value; } } } public int FishZ { get { int i; lock (FishZLock) { i = _FishZ; } return i; } set { lock (FishZLock) { _FishZ = value; } } } public uint flRunSpeed { get { uint ui; lock (flRunSpeedLock) { ui = _flRunSpeed; } return ui; } set { lock (flRunSpeedLock) { _flRunSpeed = value; } } } public uint flWalkSpeed { get { uint ui; lock (flWalkSpeedLock) { ui = _flWalkSpeed; } return ui; } set { lock (flWalkSpeedLock) { _flWalkSpeed = value; } } } public uint FlyRunSpeed { get { uint ui; lock (FlyRunSpeedLock) { ui = _FlyRunSpeed; } return ui; } set { lock (FlyRunSpeedLock) { _FlyRunSpeed = value; } } } public uint FlyWalkSpeed { get { uint ui; lock (FlyWalkSpeedLock) { ui = _FlyWalkSpeed; } return ui; } set { lock (FlyWalkSpeedLock) { _FlyWalkSpeed = value; } } } public uint Gloves { get { uint ui; lock (GlovesLock) { ui = _Gloves; } return ui; } set { lock (GlovesLock) { _Gloves = value; } } } public uint Hair { get { uint ui; lock (HairLock) { ui = _Hair; } return ui; } set { lock (HairLock) { _Hair = value; } } } public uint HairColor { get { uint ui; lock (HairColorLock) { ui = _HairColor; } return ui; } set { lock (HairColorLock) { _HairColor = value; } } } public uint HairSytle { get { uint ui; lock (HairSytleLock) { ui = _HairSytle; } return ui; } set { lock (HairSytleLock) { _HairSytle = value; } } } public uint Head { get { uint ui; lock (HeadLock) { ui = _Head; } return ui; } set { lock (HeadLock) { _Head = value; } } } public int Heading { get { int i; lock (HeadingLock) { i = _Heading; } return i; } set { lock (HeadingLock) { _Heading = value; } } } public byte HeroGlow { get { byte b; lock (HeroGlowLock) { b = _HeroGlow; } return b; } set { lock (HeroGlowLock) { _HeroGlow = value; } } } public byte HeroIcon { get { byte b; lock (HeroIconLock) { b = _HeroIcon; } return b; } set { lock (HeroIconLock) { _HeroIcon = value; } } } public uint ID { get { uint ui; lock (IDLock) { ui = _ID; } return ui; } set { lock (IDLock) { _ID = value; } } } public byte Invisible { get { byte b; lock (InvisibleLock) { b = _Invisible; } return b; } set { lock (InvisibleLock) { _Invisible = value; } } } public byte isAlikeDead { get { byte b; lock (isAlikeDeadLock) { b = _isAlikeDead; } return b; } set { lock (isAlikeDeadLock) { _isAlikeDead = value; } } } public byte isFishing { get { byte b; lock (isFishingLock) { b = _isFishing; } return b; } set { lock (isFishingLock) { _isFishing = value; } } } public byte isInCombat { get { byte b; lock (isInCombatLock) { b = _isInCombat; } return b; } set { lock (isInCombatLock) { _isInCombat = value; } } } public byte isRunning { get { byte b; lock (isRunningLock) { b = _isRunning; } return b; } set { lock (isRunningLock) { _isRunning = value; } } } public byte isSitting { get { byte b; lock (isSittingLock) { b = _isSitting; } return b; } set { lock (isSittingLock) { _isSitting = value; } } } public uint Karma { get { uint ui; lock (KarmaLock) { ui = _Karma; } return ui; } set { lock (KarmaLock) { _Karma = value; } } } public uint Karma2 { get { uint ui; lock (Karma2Lock) { ui = _Karma2; } return ui; } set { lock (Karma2Lock) { _Karma2 = value; } } } public DateTime lastMoveTime { get { DateTime dateTime; lock (lastMoveTimeLock) { dateTime = _lastMoveTime; } return dateTime; } set { lock (lastMoveTimeLock) { _lastMoveTime = value; } } } public uint Legs { get { uint ui; lock (LegsLock) { ui = _Legs; } return ui; } set { lock (LegsLock) { _Legs = value; } } } public uint Level { get { uint ui; lock (LevelLock) { ui = _Level; } return ui; } set { lock (LevelLock) { _Level = value; } } } public uint LHand { get { uint ui; lock (LHandLock) { ui = _LHand; } return ui; } set { lock (LHandLock) { _LHand = value; } } } public uint LRHand { get { uint ui; lock (LRHandLock) { ui = _LRHand; } return ui; } set { lock (LRHandLock) { _LRHand = value; } } } public uint MatkSpeed { get { uint ui; lock (MatkSpeedLock) { ui = _MatkSpeed; } return ui; } set { lock (MatkSpeedLock) { _MatkSpeed = value; } } } public uint Max_CP { get { uint ui; lock (Max_CPLock) { ui = _Max_CP; } return ui; } set { lock (Max_CPLock) { _Max_CP = value; } } } public uint Max_HP { get { uint ui; lock (Max_HPLock) { ui = _Max_HP; } return ui; } set { lock (Max_HPLock) { _Max_HP = value; } } } public uint Max_MP { get { uint ui; lock (Max_MPLock) { ui = _Max_MP; } return ui; } set { lock (Max_MPLock) { _Max_MP = value; } } } public byte MountType { get { byte b; lock (MountTypeLock) { b = _MountType; } return b; } set { lock (MountTypeLock) { _MountType = value; } } } public double MoveSpeedMult { get { double d; lock (MoveSpeedMultLock) { d = _MoveSpeedMult; } return d; } set { lock (MoveSpeedMultLock) { _MoveSpeedMult = value; } } } public uint MoveTarget { get { uint ui; lock (MoveTargetLock) { ui = _MoveTarget; } return ui; } set { lock (MoveTargetLock) { _MoveTarget = value; } } } public int MoveTargetType { get { int i; lock (MoveTargetTypeLock) { i = _MoveTargetType; } return i; } set { lock (MoveTargetTypeLock) { _MoveTargetType = value; } } } public bool Moving { get { bool flag; lock (MovingLock) { flag = _Moving; } return flag; } set { lock (MovingLock) { _Moving = value; } } } public string Name { get { string s; lock (NameLock) { s = _Name; } return s; } set { lock (NameLock) { _Name = value; } } } public uint NameColor { get { uint ui; lock (NameColorLock) { ui = _NameColor; } return ui; } set { lock (NameColorLock) { _NameColor = value; } } } public uint PatkSpeed { get { uint ui; lock (PatkSpeedLock) { ui = _PatkSpeed; } return ui; } set { lock (PatkSpeedLock) { _PatkSpeed = value; } } } public uint PledgeClass { get { uint ui; lock (PledgeClassLock) { ui = _PledgeClass; } return ui; } set { lock (PledgeClassLock) { _PledgeClass = value; } } } public byte PrivateStoreType { get { byte b; lock (PrivateStoreTypeLock) { b = _PrivateStoreType; } return b; } set { lock (PrivateStoreTypeLock) { _PrivateStoreType = value; } } } public uint PvPFlag { get { uint ui; lock (PvPFlagLock) { ui = _PvPFlag; } return ui; } set { lock (PvPFlagLock) { _PvPFlag = value; } } } public uint PvPFlag2 { get { uint ui; lock (PvPFlag2Lock) { ui = _PvPFlag2; } return ui; } set { lock (PvPFlag2Lock) { _PvPFlag2 = value; } } } public uint Race { get { uint ui; lock (RaceLock) { ui = _Race; } return ui; } set { lock (RaceLock) { _Race = value; } } } public ushort RecAmount { get { ushort ush; lock (RecAmountLock) { ush = _RecAmount; } return ush; } set { lock (RecAmountLock) { _RecAmount = value; } } } public byte RecLeft { get { byte b; lock (RecLeftLock) { b = _RecLeft; } return b; } set { lock (RecLeftLock) { _RecLeft = value; } } } public uint RHand { get { uint ui; lock (RHandLock) { ui = _RHand; } return ui; } set { lock (RHandLock) { _RHand = value; } } } public uint RunSpeed { get { uint ui; lock (RunSpeedLock) { ui = _RunSpeed; } return ui; } set { lock (RunSpeedLock) { _RunSpeed = value; } } } public uint Sex { get { uint ui; lock (SexLock) { ui = _Sex; } return ui; } set { lock (SexLock) { _Sex = value; } } } public uint SiegeFlags { get { uint ui; lock (SiegeFlagsLock) { ui = _SiegeFlags; } return ui; } set { lock (SiegeFlagsLock) { _SiegeFlags = value; } } } public uint SwimRunSpeed { get { uint ui; lock (SwimRunSpeedLock) { ui = _SwimRunSpeed; } return ui; } set { lock (SwimRunSpeedLock) { _SwimRunSpeed = value; } } } public uint SwimWalkSpeed { get { uint ui; lock (SwimWalkSpeedLock) { ui = _SwimWalkSpeed; } return ui; } set { lock (SwimWalkSpeedLock) { _SwimWalkSpeed = value; } } } public uint TargetID { get { uint ui; lock (TargetIDLock) { ui = _TargetID; } return ui; } set { lock (TargetIDLock) { _TargetID = value; } } } public int TargetType { get { int i; lock (TargetTypeLock) { i = _TargetType; } return i; } set { lock (TargetTypeLock) { _TargetType = value; } } } public byte TeamCircle { get { byte b; lock (TeamCircleLock) { b = _TeamCircle; } return b; } set { lock (TeamCircleLock) { _TeamCircle = value; } } } public string Title { get { string s; lock (TitleLock) { s = _Title; } return s; } set { lock (TitleLock) { _Title = value; } } } public uint TitleColor { get { uint ui; lock (TitleColorLock) { ui = _TitleColor; } return ui; } set { lock (TitleColorLock) { _TitleColor = value; } } } public uint Underwear { get { uint ui; lock (UnderwearLock) { ui = _Underwear; } return ui; } set { lock (UnderwearLock) { _Underwear = value; } } } public uint UNKNOWN1 { get { uint ui; lock (UNKNOWN1Lock) { ui = _UNKNOWN1; } return ui; } set { lock (UNKNOWN1Lock) { _UNKNOWN1 = value; } } } public uint UNKNOWN2 { get { uint ui; lock (UNKNOWN2Lock) { ui = _UNKNOWN2; } return ui; } set { lock (UNKNOWN2Lock) { _UNKNOWN2 = value; } } } public uint UNKNOWN3 { get { uint ui; lock (UNKNOWN3Lock) { ui = _UNKNOWN3; } return ui; } set { lock (UNKNOWN3Lock) { _UNKNOWN3 = value; } } } public uint WalkSpeed { get { uint ui; lock (WalkSpeedLock) { ui = _WalkSpeed; } return ui; } set { lock (WalkSpeedLock) { _WalkSpeed = value; } } } public uint WarState { get { uint ui; lock (WarStateLock) { ui = _WarState; } return ui; } set { lock (WarStateLock) { _WarState = value; } } } public int X { get { int i; lock (XLock) { i = _X; } return i; } set { lock (XLock) { _X = value; } } } public int Y { get { int i; lock (YLock) { i = _Y; } return i; } set { lock (YLock) { _Y = value; } } } public int Z { get { int i; lock (ZLock) { i = _Z; } return i; } set { lock (ZLock) { _Z = value; } } } public CharInfo() { _WarState = 0; _Cur_HP = 0; _Max_HP = 0; _Cur_MP = 0; _Max_MP = 0; _Cur_CP = 0; _Max_CP = 0; my_buffsLock = new Object(); Max_CPLock = new Object(); Cur_CPLock = new Object(); Max_MPLock = new Object(); Cur_MPLock = new Object(); Max_HPLock = new Object(); Cur_HPLock = new Object(); TargetTypeLock = new Object(); TargetIDLock = new Object(); MoveTargetTypeLock = new Object(); MoveTargetLock = new Object(); lastMoveTimeLock = new Object(); MovingLock = new Object(); Dest_ZLock = new Object(); Dest_YLock = new Object(); Dest_XLock = new Object(); WarStateLock = new Object(); ZLock = new Object(); YLock = new Object(); XLock = new Object(); NameColorLock = new Object(); FishZLock = new Object(); FishYLock = new Object(); FishXLock = new Object(); isFishingLock = new Object(); HeroGlowLock = new Object(); HeroIconLock = new Object(); CollisionHeightLock = new Object(); CollisionRadiusLock = new Object(); AttackSpeedMultLock = new Object(); MoveSpeedMultLock = new Object(); FlyWalkSpeedLock = new Object(); FlyRunSpeedLock = new Object(); flWalkSpeedLock = new Object(); flRunSpeedLock = new Object(); SwimWalkSpeedLock = new Object(); SwimRunSpeedLock = new Object(); WalkSpeedLock = new Object(); RunSpeedLock = new Object(); ClanCrestIDLargeLock = new Object(); EnchantAmountLock = new Object(); RecAmountLock = new Object(); TeamCircleLock = new Object(); CurCPLock = new Object(); MaxCPLock = new Object(); UNKNOWN1Lock = new Object(); UNKNOWN2Lock = new Object(); UNKNOWN3Lock = new Object(); RecLeftLock = new Object(); AbnormalEffectsLock = new Object(); FindPartyLock = new Object(); CubicsLock = new Object(); CubicCountLock = new Object(); PrivateStoreTypeLock = new Object(); MountTypeLock = new Object(); InvisibleLock = new Object(); isAlikeDeadLock = new Object(); isInCombatLock = new Object(); isRunningLock = new Object(); isSittingLock = new Object(); SiegeFlagsLock = new Object(); AllyCrestIDLock = new Object(); AllyIDLock = new Object(); ClanCrestIDLock = new Object(); ClanIDLock = new Object(); TitleLock = new Object(); FaceLock = new Object(); HairColorLock = new Object(); HairSytleLock = new Object(); Karma2Lock = new Object(); PvPFlag2Lock = new Object(); PatkSpeedLock = new Object(); MatkSpeedLock = new Object(); KarmaLock = new Object(); PvPFlagLock = new Object(); HairLock = new Object(); DollFaceLock = new Object(); LRHandLock = new Object(); BackLock = new Object(); FeetLock = new Object(); LegsLock = new Object(); ChestLock = new Object(); GlovesLock = new Object(); LHandLock = new Object(); RHandLock = new Object(); HeadLock = new Object(); UnderwearLock = new Object(); ClassLock = new Object(); SexLock = new Object(); RaceLock = new Object(); NameLock = new Object(); IDLock = new Object(); HeadingLock = new Object(); LevelLock = new Object(); TitleColorLock = new Object(); PledgeClassLock = new Object(); DemonSwordLock = new Object(); Moving = false; peace = 0; } public uint FaceInv; public uint RHand2; public uint RLHand; public void Load(ByteBuffer buff) { X = buff.ReadInt32(); Y = buff.ReadInt32(); Z = buff.ReadInt32(); Heading = buff.ReadInt32(); ID = buff.ReadUInt32(); Name = buff.ReadString(); Race = buff.ReadUInt32(); Sex = buff.ReadUInt32(); Class = buff.ReadUInt32(); Underwear = buff.ReadUInt32(); Head = buff.ReadUInt32(); RHand = buff.ReadUInt32(); LHand = buff.ReadUInt32(); Gloves = buff.ReadUInt32(); Chest = buff.ReadUInt32(); Legs = buff.ReadUInt32(); Feet = buff.ReadUInt32(); Back = buff.ReadUInt32(); LRHand = buff.ReadUInt32(); Hair = buff.ReadUInt32(); FaceInv = buff.ReadUInt32(); for (int i = 0; i < 8; i++) buff.ReadUInt32(); for (int i = 0; i < 4; i++) buff.ReadUInt16(); RHand2 = buff.ReadUInt32(); for (int i = 0; i < 12; i++) buff.ReadUInt16(); RLHand = buff.ReadUInt32(); for (int i = 0; i < 4; i++) buff.ReadUInt16(); for (int i = 0; i < 16; i++) buff.ReadUInt16(); PvPFlag = buff.ReadUInt32(); Karma = buff.ReadUInt32(); MatkSpeed = buff.ReadUInt32(); PatkSpeed = buff.ReadUInt32(); PvPFlag2 = buff.ReadUInt32(); Karma2 = buff.ReadUInt32(); RunSpeed = buff.ReadUInt32(); WalkSpeed = buff.ReadUInt32(); SwimRunSpeed = buff.ReadUInt32(); SwimWalkSpeed = buff.ReadUInt32(); flRunSpeed = buff.ReadUInt32(); flWalkSpeed = buff.ReadUInt32(); FlyRunSpeed = buff.ReadUInt32(); FlyWalkSpeed = buff.ReadUInt32(); MoveSpeedMult = buff.ReadDouble(); AttackSpeedMult = buff.ReadDouble(); CollisionRadius = buff.ReadDouble(); CollisionHeight = buff.ReadDouble(); HairSytle = buff.ReadUInt32(); HairColor = buff.ReadUInt32(); Face = buff.ReadUInt32(); Title = buff.ReadString(); ClanID = buff.ReadUInt32(); ClanCrestID = buff.ReadUInt32(); AllyID = buff.ReadUInt32(); AllyCrestID = buff.ReadUInt32(); SiegeFlags = buff.ReadUInt32(); isSitting = buff.ReadByte(); isRunning = buff.ReadByte(); isInCombat = buff.ReadByte(); isAlikeDead = buff.ReadByte(); Invisible = buff.ReadByte(); MountType = buff.ReadByte(); PrivateStoreType = buff.ReadByte(); CubicCount = buff.ReadUInt16(); Cubics = new ArrayList(); for (int i = 0; (ushort)i < CubicCount; i++) { ushort ush = buff.ReadUInt16(); Cubics.Add(ush); } FindParty = buff.ReadByte(); AbnormalEffects = buff.ReadUInt32(); RecLeft = buff.ReadByte(); RecAmount = buff.ReadUInt16(); UNKNOWN3 = buff.ReadUInt32(); Max_CP = buff.ReadUInt32(); Cur_CP = buff.ReadUInt32(); EnchantAmount = buff.ReadByte(); TeamCircle = buff.ReadByte(); ClanCrestIDLarge = buff.ReadUInt32(); HeroIcon = buff.ReadByte(); HeroGlow = buff.ReadByte(); isFishing = buff.ReadByte(); FishX = buff.ReadInt32(); FishY = buff.ReadInt32(); FishZ = buff.ReadInt32(); NameColor = buff.ReadUInt32(); UNKNOWN1 = buff.ReadUInt32(); PledgeClass = buff.ReadUInt32(); UNKNOWN2 = buff.ReadUInt32(); TitleColor = buff.ReadUInt32(); UNKNOWN3 = buff.ReadUInt32(); DemonSword = buff.ReadUInt32(); // Console.WriteLine("Char {0} has status effect {1}", Name, AbnormalEffects); } public void Update(ByteBuffer buff) { uint num1 = buff.ReadUInt32(); uint num2 = buff.ReadUInt32(); switch (num1) { case 1: this.Level = num2; return; case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 13: case 14: case 15: case 0x10: case 0x11: case 0x13: case 20: case 0x15: case 0x16: case 0x17: case 0x19: case 0x1c: case 0x1d: case 30: case 0x1f: case 0x20: return; case 9: this.Cur_HP = num2; if (this.Cur_HP > 1) { isAlikeDead = 0; } if (this.Cur_HP < 1) { isAlikeDead = 1; } return; case 10: this.Max_HP = num2; return; case 11: this.Cur_MP = num2; return; case 12: this.Max_MP = num2; return; case 0x12: this.PatkSpeed = num2; return; case 0x18: this.MatkSpeed = num2; return; case 0x1a: this.PvPFlag = num2; return; case 0x1b: this.Karma = num2; return; case 0x21: this.Cur_CP = num2; return; case 0x22: this.Max_CP = num2; return; } } public override string ToString() { return _Name; } public double distance; public int peace; public int rauto; public int rkarma; public int rpvpflag; } // class CharInfo }
// ---------------------------------------------------------------------------------- // // 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.Azure.Commands.ResourceManager.Cmdlets.Implementation { using Commands.Common.Authentication.Abstractions; using Common.Tags; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; using Microsoft.Azure.Commands.ResourceManager.Common; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Threading.Tasks; /// <summary> /// Cmdlet to get existing resources from ARM cache. /// </summary> [Cmdlet(VerbsCommon.Find, "AzureRmResource", DefaultParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet), OutputType(typeof(PSObject))] public sealed class FindAzureResourceCmdlet : ResourceManagerCmdletBase { /// <summary> /// Contains the errors that encountered while satifying the request. /// </summary> private readonly ConcurrentBag<ErrorRecord> errors = new ConcurrentBag<ErrorRecord>(); /// <summary> /// The list resources parameter set. /// </summary> internal const string ListResourcesParameterSet = "Lists the resources based on the specified scope."; /// <summary> /// The list tenant resources parameter set. /// </summary> internal const string ListTenantResourcesParameterSet = "Lists the resources based on the specified scope at the tenant level."; /// <summary> /// The get tenant resource parameter set. /// </summary> internal const string MultiSubscriptionListResourcesParameterSet = "Get a resources using a multi-subscription query."; /// <summary> /// The list resources by tag object parameter set. /// </summary> internal const string ListResourcesByTagObjectParameterSet = "Lists resources by a tag object specified as a hashset."; /// <summary> /// The list resources by tag name-value parameter set. /// </summary> internal const string ListResourcesByTagNameValueParameterSet = "Lists resources by a tag specified as a individual name and value parameters."; /// <summary> /// Caches the current subscription ids to get all subscription ids in the pipeline. /// </summary> private readonly List<Guid> subscriptionIds = new List<Guid>(); /// <summary> /// Gets or sets the resource name for query as contains. /// </summary> [Alias("Name")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name substring. e.g. if your resource name is testResource, you can specify test.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name substring. e.g. if your resource name is testResource, you can specify test.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name substring. e.g. if your resource name is testResource, you can specify test.")] [ValidateNotNullOrEmpty] public string ResourceNameContains { get; set; } /// <summary> /// Gets or sets the resource name for query as equals. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name for a full match. e.g. if your resource name is testResource, you can specify testResource.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name for a full match. e.g. if your resource name is testResource, you can specify testResource.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name for a full match. e.g. if your resource name is testResource, you can specify testResource.")] [ValidateNotNullOrEmpty] public string ResourceNameEquals { get; set; } /// <summary> /// Gets or sets the resource type parameter. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")] [ValidateNotNullOrEmpty] public string ResourceType { get; set; } /// <summary> /// Gets or sets the extension resource type. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/{serverName}/Databases/myDatabase.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/{serverName}/Databases/myDatabase.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/{serverName}/Databases/myDatabase.")] [ValidateNotNullOrEmpty] public string ExtensionResourceType { get; set; } /// <summary> /// Gets or sets the top parameter. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesByTagObjectParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesByTagNameValueParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [ValidateNotNullOrEmpty] public int? Top { get; set; } /// <summary> /// Gets or sets the OData query parameter. /// </summary> [Parameter(Mandatory = false, HelpMessage = "An OData style filter which will be appended to the request in addition to any other filters.")] [ValidateNotNullOrEmpty] public string ODataQuery { get; set; } [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesByTagObjectParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The tag filter for the OData query. The expected format is @{tagName=$null} or @{tagName = 'tagValue'}.")] public Hashtable Tag { get; set; } /// <summary> /// Gets or sets the tag name. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesByTagNameValueParameterSet, Mandatory = false, HelpMessage = "The name of the tag to query by.")] [ValidateNotNullOrEmpty] public string TagName { get; set; } /// <summary> /// Gets or sets the tag value. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesByTagNameValueParameterSet, Mandatory = false, HelpMessage = "The value of the tag to query by.")] [ValidateNotNullOrEmpty] public string TagValue { get; set; } /// <summary> /// Gets or sets the resource group name for query as contains. /// </summary> [Alias("ResourceGroupName")] [Parameter(Mandatory = false, ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name substring.")] [Parameter(Mandatory = false, ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name substring.")] [ValidateNotNullOrEmpty] public string ResourceGroupNameContains { get; set; } /// <summary> /// Gets or sets the resource group name for query as equals. /// </summary> [Parameter(Mandatory = false, ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name for a full match.")] [Parameter(Mandatory = false, ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name for a full match.")] [ValidateNotNullOrEmpty] public string ResourceGroupNameEquals { get; set; } /// <summary> /// Gets or sets the expand properties property. /// </summary> [Parameter(Mandatory = false, HelpMessage = "When specified, expands the properties of the resource.")] public SwitchParameter ExpandProperties { get; set; } /// <summary> /// Gets or sets the tenant level parameter. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = true, HelpMessage = "Indicates that this is a tenant level operation.")] public SwitchParameter TenantLevel { get; set; } /// <summary> /// Gets or sets the subscription id. /// </summary> public Guid? SubscriptionId { get; set; } /// <summary> /// Gets or sets the default api-version to use. /// </summary> public string DefaultApiVersion { get; set; } /// <summary> /// Collects subscription ids from the pipeline. /// </summary> protected override void OnProcessRecord() { base.OnProcessRecord(); } /// <summary> /// Finishes the pipeline execution and runs the cmdlet. /// </summary> protected override void OnEndProcessing() { base.OnEndProcessing(); this.RunCmdlet(); } /// <summary> /// Contains the cmdlet's execution logic. /// </summary> private void RunCmdlet() { this.DefaultApiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ResourcesApiVersion : this.ApiVersion; if (!this.TenantLevel) { this.SubscriptionId = DefaultContext.Subscription.GetId(); } PaginatedResponseHelper.ForEach( getFirstPage: () => this.GetResources(), getNextPage: nextLink => this.GetNextLink<JObject>(nextLink), cancellationToken: this.CancellationToken, action: resources => { Resource<JToken> resource; if (resources.CoalesceEnumerable().FirstOrDefault().TryConvertTo(out resource)) { var genericResources = resources.CoalesceEnumerable().Where(res => res != null).SelectArray(res => res.ToResource()); foreach (var batch in genericResources.Batch()) { var items = batch; if (this.ExpandProperties) { items = this.GetPopulatedResource(batch).Result; } var powerShellObjects = items.SelectArray(genericResource => genericResource.ToPsObject()); this.WriteObject(sendToPipeline: powerShellObjects, enumerateCollection: true); } } else { this.WriteObject(sendToPipeline: resources.CoalesceEnumerable().SelectArray(res => res.ToPsObject()), enumerateCollection: true); } }); if (this.errors.Count != 0) { foreach (var error in this.errors) { this.WriteError(error); } } } /// <summary> /// Queries the ARM cache and returns the cached resource that match the query specified. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> GetResources() { if (this.IsResourceTypeCollectionGet()) { return await this.ListResourcesTypeCollection().ConfigureAwait(continueOnCapturedContext: false); } if (this.IsResourceGroupLevelQuery()) { return await this.ListResourcesInResourceGroup().ConfigureAwait(continueOnCapturedContext: false); } if (this.IsSubscriptionLevelQuery()) { return await this.ListResourcesInSubscription().ConfigureAwait(continueOnCapturedContext: false); } return await this.ListResourcesInTenant().ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Lists resources in a type collection. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesTypeCollection() { var resourceCollectionId = ResourceIdUtility.GetResourceId( subscriptionId: this.SubscriptionId.AsArray().CoalesceEnumerable().Cast<Guid?>().FirstOrDefault(), resourceGroupName: null, resourceType: this.ResourceType, resourceName: null, extensionResourceType: this.ExtensionResourceType, extensionResourceName: null); var odataQuery = QueryFilterBuilder.CreateFilter( subscriptionId: null, resourceGroup: this.ResourceGroupNameEquals, resourceType: null, resourceName: this.ResourceNameEquals, tagName: TagsHelper.GetTagNameFromParameters(this.Tag, this.TagName), tagValue: TagsHelper.GetTagValueFromParameters(this.Tag, this.TagValue), filter: this.ODataQuery, resourceGroupNameContains: this.ResourceGroupNameContains, nameContains: this.ResourceNameContains); return await this .GetResourcesClient() .ListObjectColleciton<JObject>( resourceCollectionId: resourceCollectionId, apiVersion: this.DefaultApiVersion, cancellationToken: this.CancellationToken.Value, odataQuery: odataQuery) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Lists the resources in the tenant. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesInTenant() { var filterQuery = QueryFilterBuilder .CreateFilter( subscriptionId: this.SubscriptionId.HasValue ? this.SubscriptionId.Value.ToString() : null, resourceGroup: this.ResourceGroupNameEquals, resourceType: this.ResourceType, resourceName: this.ResourceNameEquals, tagName: TagsHelper.GetTagNameFromParameters(this.Tag, this.TagName), tagValue: TagsHelper.GetTagValueFromParameters(this.Tag, this.TagValue), filter: this.ODataQuery, resourceGroupNameContains: this.ResourceGroupNameContains, nameContains: this.ResourceNameContains); return await this .GetResourcesClient() .ListResources<JObject>( apiVersion: this.DefaultApiVersion, top: this.Top, filter: filterQuery, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Lists the resources in a resource group. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesInResourceGroup() { var filterQuery = QueryFilterBuilder .CreateFilter( subscriptionId: null, resourceGroup: this.ResourceGroupNameEquals, resourceType: this.ResourceType, resourceName: this.ResourceNameEquals, tagName: TagsHelper.GetTagNameFromParameters(this.Tag, this.TagName), tagValue: TagsHelper.GetTagValueFromParameters(this.Tag, this.TagValue), filter: this.ODataQuery, resourceGroupNameContains: this.ResourceGroupNameContains, nameContains: this.ResourceNameContains); return await this .GetResourcesClient() .ListResources<JObject>( subscriptionId: this.SubscriptionId.Value, resourceGroupName: null, apiVersion: this.DefaultApiVersion, top: this.Top, filter: filterQuery, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Gets the resources in a subscription. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesInSubscription() { var filterQuery = QueryFilterBuilder .CreateFilter( subscriptionId: null, resourceGroup: null, resourceType: this.ResourceType, resourceName: this.ResourceNameEquals, tagName: TagsHelper.GetTagNameFromParameters(this.Tag, this.TagName), tagValue: TagsHelper.GetTagValueFromParameters(this.Tag, this.TagValue), filter: this.ODataQuery, nameContains: this.ResourceNameContains); return await this .GetResourcesClient() .ListResources<JObject>( subscriptionId: this.SubscriptionId.Value, apiVersion: this.DefaultApiVersion, top: this.Top, filter: filterQuery, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Gets the next set of resources using the <paramref name="nextLink"/> /// </summary> /// <param name="nextLink">The next link.</param> private Task<ResponseWithContinuation<TType[]>> GetNextLink<TType>(string nextLink) { return this .GetResourcesClient() .ListNextBatch<TType>(nextLink: nextLink, cancellationToken: this.CancellationToken.Value); } /// <summary> /// Populates the properties on an array of resources. /// </summary> /// <param name="resources">The resource.</param> private async Task<Resource<JToken>[]> GetPopulatedResource(IEnumerable<Resource<JToken>> resources) { return await resources .Select(resource => this.GetPopulatedResource(resource)) .WhenAllForAwait() .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Populates the properties of a single resource. /// </summary> /// <param name="resource">The resource.</param> private async Task<Resource<JToken>> GetPopulatedResource(Resource<JToken> resource) { try { var apiVersion = await this.DetermineApiVersion( resourceId: resource.Id, pre: this.Pre) .ConfigureAwait(continueOnCapturedContext: false); return await this .GetResourcesClient() .GetResource<Resource<JToken>>( resourceId: resource.Id, apiVersion: apiVersion, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { if (ex.IsFatal()) { throw; } ex = (ex is AggregateException) ? (ex as AggregateException).Flatten() : ex; this.errors.Add(new ErrorRecord(ex, "ErrorExpandingProperties", ErrorCategory.CloseError, resource)); } return resource; } /// <summary> /// Returns true if this is get on a resource type collection, at any scope. /// </summary> private bool IsResourceTypeCollectionGet() { return (this.TenantLevel) && (this.IsResourceGroupLevelResourceTypeCollectionGet() || this.IsSubscriptionLevelResourceTypeCollectionGet() || this.IsTenantLevelResourceTypeCollectionGet()); } /// <summary> /// Returns true if this is a get on a type collection that is at the subscription level. /// </summary> private bool IsSubscriptionLevelResourceTypeCollectionGet() { return this.SubscriptionId.HasValue && !this.ResourceGroupNameAvailable() && (this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if this is a get on a type collection that is at the resource group. /// </summary> private bool IsResourceGroupLevelResourceTypeCollectionGet() { return this.SubscriptionId.HasValue && this.ResourceGroupNameAvailable() && (this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if this is a tenant level resource type collection get (a get without a subscription or /// resource group or resource name but with a resource or extension type.) /// </summary> private bool IsTenantLevelResourceTypeCollectionGet() { return this.SubscriptionId == null && !this.ResourceGroupNameAvailable() && (this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if this is a subscription level query. /// </summary> private bool IsSubscriptionLevelQuery() { return this.SubscriptionId.HasValue && !this.ResourceGroupNameAvailable(); } /// <summary> /// Returns true if this is a resource group level query. /// </summary> private bool IsResourceGroupLevelQuery() { return this.SubscriptionId.HasValue && this.ResourceGroupNameAvailable() && (TagsHelper.GetTagNameFromParameters(this.Tag, this.TagName) != null || TagsHelper.GetTagValueFromParameters(this.Tag, this.TagValue) != null || this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if resource group name is availabe in parameters. /// </summary> private bool ResourceGroupNameAvailable() { return this.ResourceGroupNameContains != null || this.ResourceGroupNameEquals != 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartIndenterEnterOnTokenTests : FormatterTestsBase { [WorkItem(537808)] [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MethodBody1() { var code = @"class Class1 { void method() { } } "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 3, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Preprocessor1() { var code = @"class A { #region T #endregion } "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Preprocessor2() { var code = @"class A { #line 1 #lien 2 } "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Comments() { var code = @"using System; class Class { // Comments // Comments "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void UsingDirective() { var code = @"using System; using System.Linq; "; AssertIndentUsingSmartTokenFormatter( code, 'u', indentationLine: 1, expectedIndentation: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void DottedName() { var code = @"using System. Collection; "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 1, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Namespace() { var code = @"using System; namespace NS { "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 3, expectedIndentation: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void NamespaceDottedName() { var code = @"using System; namespace NS. NS2 "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void NamespaceBody() { var code = @"using System; namespace NS { class "; AssertIndentUsingSmartTokenFormatter( code, 'c', indentationLine: 4, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void NamespaceCloseBrace() { var code = @"using System; namespace NS { } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 4, expectedIndentation: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Class() { var code = @"using System; namespace NS { class Class { "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 5, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ClassBody() { var code = @"using System; namespace NS { class Class { int "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 6, expectedIndentation: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ClassCloseBrace() { var code = @"using System; namespace NS { class Class { } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 6, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Method() { var code = @"using System; namespace NS { class Class { void Method() { "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 7, expectedIndentation: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MethodBody() { var code = @"using System; namespace NS { class Class { void Method() { int "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 8, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MethodCloseBrace() { var code = @"using System; namespace NS { class Class { void Method() { } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 8, expectedIndentation: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Statement() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10; int "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 9, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MethodCall() { var code = @"class c { void Method() { M( a: 1, b: 1); } }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Switch() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 9, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void SwitchBody() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case "; AssertIndentUsingSmartTokenFormatter( code, 'c', indentationLine: 10, expectedIndentation: 16); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void SwitchCase() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : int "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 11, expectedIndentation: 20); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void SwitchCaseBlock() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 11, expectedIndentation: 20); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Block() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { int "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 12, expectedIndentation: 24); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MultilineStatement1() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 1 "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 9, expectedIndentation: 16); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MultilineStatement2() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 20 + 30 "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 10, expectedIndentation: 20); } // Bug number 902477 [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Comments2() { var code = @"class Class { void Method() { if (true) // Test int } } "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 5, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void AfterCompletedBlock() { var code = @"class Program { static void Main(string[] args) { foreach(var a in x) {} int } } "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 5, expectedIndentation: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void AfterTopLevelAttribute() { var code = @"class Program { [Attr] [ } "; AssertIndentUsingSmartTokenFormatter( code, '[', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537802)] [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void EmbededStatement() { var code = @"class Program { static void Main(string[] args) { if (true) Console.WriteLine(1); int } } "; AssertIndentUsingSmartTokenFormatter( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WorkItem(537808)] [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MethodBraces1() { var code = @"class Class1 { void method() { } } "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537808)] [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void MethodBraces2() { var code = @"class Class1 { void method() { } } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 4, expectedIndentation: 4); } [WorkItem(537795)] [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Property1() { var code = @"class C { string Name { get; set; } } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 6, expectedIndentation: 4); } [WorkItem(537563)] [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Class1() { var code = @"class C { } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 2, expectedIndentation: 0); } [Fact] [WorkItem(1070773)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ArrayInitializer1() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ArrayInitializer2() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 5, expectedIndentation: 4); } [Fact] [WorkItem(1070773)] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void ArrayInitializer3() { var code = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 7, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void QueryExpression2() { var code = @"class C { void Method() { var a = from c in b where } } "; AssertIndentUsingSmartTokenFormatter( code, 'w', indentationLine: 5, expectedIndentation: 16); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void QueryExpression3() { var code = @"class C { void Method() { var a = from c in b where select } } "; AssertIndentUsingSmartTokenFormatter( code, 'w', indentationLine: 5, expectedIndentation: 16); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void QueryExpression4() { var code = @"class C { void Method() { var a = from c in b where c > 10 select } } "; AssertIndentUsingSmartTokenFormatter( code, 's', indentationLine: 5, expectedIndentation: 16); } [Fact] [WorkItem(853748)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ArrayInitializer() { var code = @"class C { void Method() { var l = new int[] { } } } "; AssertIndentUsingSmartTokenFormatter( code, '}', indentationLine: 5, expectedIndentation: 8); } [Fact] [WorkItem(939305)] [WorkItem(1070773)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ArrayExpression() { var code = @"class C { void M(object[] q) { M( q: new object[] { }); } } "; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 6, expectedIndentation: 14); } [Fact] [WorkItem(1070773)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void CollectionExpression() { var code = @"class C { void M(List<int> e) { M( new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); } } "; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 6, expectedIndentation: 12); } [Fact] [WorkItem(1070773)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void ObjectInitializer() { var code = @"class C { void M(What dd) { M( new What { d = 3, dd = "" }); } } class What { public int d; public string dd; }"; AssertIndentUsingSmartTokenFormatter( code, '{', indentationLine: 6, expectedIndentation: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void Preprocessor() { var code = @" #line 1 """"Bar""""class Foo : [|IComparable|]#line default#line hidden"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 1, expectedIndentation: 0); } [Fact] [WorkItem(1070774)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInitializerWithTypeBody_Implicit() { var code = @"class X { int[] a = { 1, }; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 8); } [Fact] [WorkItem(1070774)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInitializerWithTypeBody_ImplicitNew() { var code = @"class X { int[] a = new[] { 1, }; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 8); } [Fact] [WorkItem(1070774)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInitializerWithTypeBody_Explicit() { var code = @"class X { int[] a = new int[] { 1, }; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 3, expectedIndentation: 8); } [Fact] [WorkItem(1070774)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInitializerWithTypeBody_Collection() { var code = @"using System.Collections.Generic; class X { private List<int> a = new List<int>() { 1, }; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 4, expectedIndentation: 8); } [Fact] [WorkItem(1070774)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInitializerWithTypeBody_ObjectInitializers() { var code = @"class C { private What sdfsd = new What { d = 3, } } class What { public int d; public string dd; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 8); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationString_1() { var code = @"class Program { static void Main(string[] args) { var s = $@"" {Program.number}""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 0); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationString_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment {Program.number}""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 0); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationString_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number} ""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 0); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationString_4() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here ""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 0); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void OutsideInterpolationString() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here"" ; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_1() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program.number}""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program .number}""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 6, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ }""; } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_4() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_5() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_6() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })) .Invoke(3):(408) ###-####}""); } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 12); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void InsideInterpolationSyntax_7() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 8); } [Fact] [WorkItem(872)] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public void IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine(((Func<int, int>)((int s) => { return number; })).Invoke(3)); } static int number; }"; AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( code, indentationLine: 5, expectedIndentation: 8); } private void AssertIndentUsingSmartTokenFormatter( string code, char ch, int indentationLine, int? expectedIndentation) { // create tree service using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code)) { var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax; Assert.True( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line, workspace.Options, CancellationToken.None)); var actualIndentation = GetSmartTokenFormatterIndentationWorker(workspace, buffer, indentationLine, ch); Assert.Equal(expectedIndentation.Value, actualIndentation); } } private void AssertIndentNotUsingSmartTokenFormatterButUsingIndenter( string code, int indentationLine, int? expectedIndentation) { // create tree service using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code)) { var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax; Assert.False( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line, workspace.Options, CancellationToken.None)); TestIndentation(indentationLine, expectedIndentation, workspace); } } } }
using sly.buildresult; using sly.lexer; using Xunit; namespace ParserTests.comments { public enum MultiLineCommentsToken { [Lexeme(GenericToken.Int)] INT, [Lexeme(GenericToken.Double)] DOUBLE, [Lexeme(GenericToken.Identifier)] ID, [MultiLineComment("/*", "*/")] COMMENT } public class MultiLineCommentsTest { [Fact] public void NotEndingMultiComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>; var dump = lexer.ToString(); var code = @"1 2 /* not ending comment"; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(4, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; Assert.Equal(MultiLineCommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(MultiLineCommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(MultiLineCommentsToken.COMMENT, token3.TokenID); Assert.Equal(@" not ending comment", token3.Value); Assert.Equal(1, token3.Position.Line); Assert.Equal(2, token3.Position.Column); } [Fact] public void TestGenericMultiLineComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>; var dump = lexer.ToString(); var code = @"1 2 /* multi line comment on 2 lines */ 3.0"; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(5, tokens.Count); var intToken1 = tokens[0]; var intToken2 = tokens[1]; var multiLineCommentToken = tokens[2]; var doubleToken = tokens[3]; Assert.Equal(MultiLineCommentsToken.INT, intToken1.TokenID); Assert.Equal("1", intToken1.Value); Assert.Equal(0, intToken1.Position.Line); Assert.Equal(0, intToken1.Position.Column); Assert.Equal(MultiLineCommentsToken.INT, intToken2.TokenID); Assert.Equal("2", intToken2.Value); Assert.Equal(1, intToken2.Position.Line); Assert.Equal(0, intToken2.Position.Column); Assert.Equal(MultiLineCommentsToken.COMMENT, multiLineCommentToken.TokenID); Assert.Equal(@" multi line comment on 2 lines ", multiLineCommentToken.Value); Assert.Equal(1, multiLineCommentToken.Position.Line); Assert.Equal(2, multiLineCommentToken.Position.Column); Assert.Equal(MultiLineCommentsToken.DOUBLE, doubleToken.TokenID); Assert.Equal("3.0", doubleToken.Value); Assert.Equal(2, doubleToken.Position.Line); Assert.Equal(22, doubleToken.Position.Column); } [Fact] public void TestGenericSingleLineComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>; var dump = lexer.ToString(); var r = lexer.Tokenize(@"1 2 // single line comment 3.0"); Assert.True(r.IsError); Assert.Equal('/', r.Error.UnexpectedChar); } [Fact] public void TestInnerMultiComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>; var dump = lexer.ToString(); var code = @"1 2 /* inner */ 3 4 "; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(6, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; var token4 = tokens[3]; var token5 = tokens[4]; Assert.Equal(MultiLineCommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(MultiLineCommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(MultiLineCommentsToken.COMMENT, token3.TokenID); Assert.Equal(@" inner ", token3.Value); Assert.Equal(1, token3.Position.Line); Assert.Equal(2, token3.Position.Column); Assert.Equal(MultiLineCommentsToken.INT, token4.TokenID); Assert.Equal("3", token4.Value); Assert.Equal(1, token4.Position.Line); Assert.Equal(14, token4.Position.Column); Assert.Equal(MultiLineCommentsToken.INT, token5.TokenID); Assert.Equal("4", token5.Value); Assert.Equal(2, token5.Position.Line); Assert.Equal(0, token5.Position.Column); } [Fact] public void TestMixedEOLComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<MultiLineCommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<MultiLineCommentsToken>; var dump = lexer.ToString(); var code = "1\n2\r\n/* multi line \rcomment on 2 lines */ 3.0"; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(5, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; var token4 = tokens[3]; Assert.Equal(MultiLineCommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(MultiLineCommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(MultiLineCommentsToken.COMMENT, token3.TokenID); Assert.Equal(" multi line \rcomment on 2 lines ", token3.Value); Assert.Equal(2, token3.Position.Line); Assert.Equal(0, token3.Position.Column); Assert.Equal(MultiLineCommentsToken.DOUBLE, token4.TokenID); Assert.Equal("3.0", token4.Value); Assert.Equal(3, token4.Position.Line); Assert.Equal(22, token4.Position.Column); } } }
using System; using System.Collections; using System.IO; using System.Text; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Cms; using Org.BouncyCastle.X509; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Pkix { /** * An immutable sequence of certificates (a certification path).<br /> * <br /> * This is an abstract class that defines the methods common to all CertPaths. * Subclasses can handle different kinds of certificates (X.509, PGP, etc.).<br /> * <br /> * All CertPath objects have a type, a list of Certificates, and one or more * supported encodings. Because the CertPath class is immutable, a CertPath * cannot change in any externally visible way after being constructed. This * stipulation applies to all public fields and methods of this class and any * added or overridden by subclasses.<br /> * <br /> * The type is a string that identifies the type of Certificates in the * certification path. For each certificate cert in a certification path * certPath, cert.getType().equals(certPath.getType()) must be true.<br /> * <br /> * The list of Certificates is an ordered List of zero or more Certificates. * This List and all of the Certificates contained in it must be immutable.<br /> * <br /> * Each CertPath object must support one or more encodings so that the object * can be translated into a byte array for storage or transmission to other * parties. Preferably, these encodings should be well-documented standards * (such as PKCS#7). One of the encodings supported by a CertPath is considered * the default encoding. This encoding is used if no encoding is explicitly * requested (for the {@link #getEncoded()} method, for instance).<br /> * <br /> * All CertPath objects are also Serializable. CertPath objects are resolved * into an alternate {@link CertPathRep} object during serialization. This * allows a CertPath object to be serialized into an equivalent representation * regardless of its underlying implementation.<br /> * <br /> * CertPath objects can be created with a CertificateFactory or they can be * returned by other classes, such as a CertPathBuilder.<br /> * <br /> * By convention, X.509 CertPaths (consisting of X509Certificates), are ordered * starting with the target certificate and ending with a certificate issued by * the trust anchor. That is, the issuer of one certificate is the subject of * the following one. The certificate representing the * {@link TrustAnchor TrustAnchor} should not be included in the certification * path. Unvalidated X.509 CertPaths may not follow these conventions. PKIX * CertPathValidators will detect any departure from these conventions that * cause the certification path to be invalid and throw a * CertPathValidatorException.<br /> * <br /> * <strong>Concurrent Access</strong><br /> * <br /> * All CertPath objects must be thread-safe. That is, multiple threads may * concurrently invoke the methods defined in this class on a single CertPath * object (or more than one) with no ill effects. This is also true for the List * returned by CertPath.getCertificates.<br /> * <br /> * Requiring CertPath objects to be immutable and thread-safe allows them to be * passed around to various pieces of code without worrying about coordinating * access. Providing this thread-safety is generally not difficult, since the * CertPath and List objects in question are immutable. * * @see CertificateFactory * @see CertPathBuilder */ /// <summary> /// CertPath implementation for X.509 certificates. /// </summary> public class PkixCertPath // : CertPath { internal static readonly IList certPathEncodings; static PkixCertPath() { IList encodings = Platform.CreateArrayList(); encodings.Add("PkiPath"); encodings.Add("PEM"); encodings.Add("PKCS7"); certPathEncodings = CollectionUtilities.ReadOnly(encodings); } private readonly IList certificates; /** * @param certs */ private static IList SortCerts( IList certs) { if (certs.Count < 2) return certs; X509Name issuer = ((X509Certificate)certs[0]).IssuerDN; bool okay = true; for (int i = 1; i != certs.Count; i++) { X509Certificate cert = (X509Certificate)certs[i]; if (issuer.Equivalent(cert.SubjectDN, true)) { issuer = ((X509Certificate)certs[i]).IssuerDN; } else { okay = false; break; } } if (okay) return certs; // find end-entity cert IList retList = Platform.CreateArrayList(certs.Count); IList orig = Platform.CreateArrayList(certs); for (int i = 0; i < certs.Count; i++) { X509Certificate cert = (X509Certificate)certs[i]; bool found = false; X509Name subject = cert.SubjectDN; foreach (X509Certificate c in certs) { if (c.IssuerDN.Equivalent(subject, true)) { found = true; break; } } if (!found) { retList.Add(cert); certs.RemoveAt(i); } } // can only have one end entity cert - something's wrong, give up. if (retList.Count > 1) return orig; for (int i = 0; i != retList.Count; i++) { issuer = ((X509Certificate)retList[i]).IssuerDN; for (int j = 0; j < certs.Count; j++) { X509Certificate c = (X509Certificate)certs[j]; if (issuer.Equivalent(c.SubjectDN, true)) { retList.Add(c); certs.RemoveAt(j); break; } } } // make sure all certificates are accounted for. if (certs.Count > 0) return orig; return retList; } /** * Creates a CertPath of the specified type. * This constructor is protected because most users should use * a CertificateFactory to create CertPaths. * @param type the standard name of the type of Certificatesin this path **/ public PkixCertPath( ICollection certificates) // : base("X.509") { this.certificates = SortCerts(Platform.CreateArrayList(certificates)); } public PkixCertPath( Stream inStream) : this(inStream, "PkiPath") { } /** * Creates a CertPath of the specified type. * This constructor is protected because most users should use * a CertificateFactory to create CertPaths. * * @param type the standard name of the type of Certificatesin this path **/ public PkixCertPath( Stream inStream, string encoding) // : base("X.509") { string upper = encoding.ToUpper(); IList certs; try { if (upper.Equals("PkiPath".ToUpper())) { Asn1InputStream derInStream = new Asn1InputStream(inStream); Asn1Object derObject = derInStream.ReadObject(); if (!(derObject is Asn1Sequence)) { throw new CertificateException( "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); } certs = Platform.CreateArrayList(); foreach (Asn1Encodable ae in (Asn1Sequence)derObject) { byte[] derBytes = ae.GetEncoded(Asn1Encodable.Der); Stream certInStream = new MemoryStream(derBytes, false); // TODO Is inserting at the front important (list will be sorted later anyway)? certs.Insert(0, new X509CertificateParser().ReadCertificate(certInStream)); } } else if (upper.Equals("PKCS7") || upper.Equals("PEM")) { certs = Platform.CreateArrayList(new X509CertificateParser().ReadCertificates(inStream)); } else { throw new CertificateException("unsupported encoding: " + encoding); } } catch (IOException ex) { throw new CertificateException( "IOException throw while decoding CertPath:\n" + ex.ToString()); } this.certificates = SortCerts(certs); } /** * Returns an iteration of the encodings supported by this * certification path, with the default encoding * first. Attempts to modify the returned Iterator via its * remove method result in an UnsupportedOperationException. * * @return an Iterator over the names of the supported encodings (as Strings) **/ public virtual IEnumerable Encodings { get { return new EnumerableProxy(certPathEncodings); } } /** * Compares this certification path for equality with the specified object. * Two CertPaths are equal if and only if their types are equal and their * certificate Lists (and by implication the Certificates in those Lists) * are equal. A CertPath is never equal to an object that is not a CertPath.<br /> * <br /> * This algorithm is implemented by this method. If it is overridden, the * behavior specified here must be maintained. * * @param other * the object to test for equality with this certification path * * @return true if the specified object is equal to this certification path, * false otherwise * * @see Object#hashCode() Object.hashCode() */ public override bool Equals( object obj) { if (this == obj) return true; PkixCertPath other = obj as PkixCertPath; if (other == null) return false; // if (!this.Type.Equals(other.Type)) // return false; //return this.Certificates.Equals(other.Certificates); // TODO Extract this to a utility class IList thisCerts = this.Certificates; IList otherCerts = other.Certificates; if (thisCerts.Count != otherCerts.Count) return false; IEnumerator e1 = thisCerts.GetEnumerator(); IEnumerator e2 = thisCerts.GetEnumerator(); while (e1.MoveNext()) { e2.MoveNext(); if (!Platform.Equals(e1.Current, e2.Current)) return false; } return true; } public override int GetHashCode() { // FIXME? return this.Certificates.GetHashCode(); } /** * Returns the encoded form of this certification path, using * the default encoding. * * @return the encoded bytes * @exception CertificateEncodingException if an encoding error occurs **/ public virtual byte[] GetEncoded() { foreach (object enc in Encodings) { if (enc is string) { return GetEncoded((string)enc); } } return null; } /** * Returns the encoded form of this certification path, using * the specified encoding. * * @param encoding the name of the encoding to use * @return the encoded bytes * @exception CertificateEncodingException if an encoding error * occurs or the encoding requested is not supported * */ public virtual byte[] GetEncoded( string encoding) { if (Platform.CompareIgnoreCase(encoding, "PkiPath") == 0) { Asn1EncodableVector v = new Asn1EncodableVector(); for (int i = certificates.Count - 1; i >= 0; i--) { v.Add(ToAsn1Object((X509Certificate)certificates[i])); } return ToDerEncoded(new DerSequence(v)); } else { if (Platform.CompareIgnoreCase(encoding, "PKCS7") == 0) { Asn1.Pkcs.ContentInfo encInfo = new Asn1.Pkcs.ContentInfo( PkcsObjectIdentifiers.Data, null); Asn1EncodableVector v = new Asn1EncodableVector(); for (int i = 0; i != certificates.Count; i++) { v.Add(ToAsn1Object((X509Certificate)certificates[i])); } Asn1.Pkcs.SignedData sd = new Asn1.Pkcs.SignedData( new DerInteger(1), new DerSet(), encInfo, new DerSet(v), null, new DerSet()); return ToDerEncoded(new Asn1.Pkcs.ContentInfo(PkcsObjectIdentifiers.SignedData, sd)); } if (Platform.CompareIgnoreCase(encoding, "PEM") == 0) { using (var bOut = new MemoryStream()) { using (var sWrt = new StreamWriter(bOut)) { var pWrt = new PemWriter(sWrt); try { for (var i = 0; i != certificates.Count; i++) { pWrt.WriteObject(certificates[i]); } } catch (Exception) { throw new CertificateEncodingException("can't encode certificate for PEM encoded path"); } } return bOut.ToArray(); } } else { throw new CertificateEncodingException("unsupported encoding: " + encoding); } } } /// <summary> /// Returns the list of certificates in this certification /// path. /// </summary> public virtual IList Certificates { get { return CollectionUtilities.ReadOnly(certificates); } } /** * Return a DERObject containing the encoded certificate. * * @param cert the X509Certificate object to be encoded * * @return the DERObject **/ private Asn1Object ToAsn1Object( X509Certificate cert) { try { return Asn1Object.FromByteArray(cert.GetEncoded()); } catch (Exception e) { throw new CertificateEncodingException("Exception while encoding certificate", e); } } private byte[] ToDerEncoded(Asn1Encodable obj) { try { return obj.GetEncoded(Asn1Encodable.Der); } catch (IOException e) { throw new CertificateEncodingException("Exception thrown", e); } } } }
namespace H3Control { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using Universe; public class CpuUsageListener_OnLinux { // static private long? PrevTime; static private CpuUsageModel PrevModel; // raw static private CpuUsageModel CurrentDelta; // delta static private long IntervalMssec = 500; static private readonly object Sync = new object(); static private Thread _thread; public static void Bind(long intervalMsec = 500) { lock (Sync) { IntervalMssec = intervalMsec; if (Environment.OSVersion.Platform == PlatformID.Win32NT) return; if (_thread == null) { PrevModel = GetLocalSnapshot(); Thread.Sleep(1); CurrentDelta = GetNextDelta(); _thread = new Thread(GathererRunner, 64*1024) {IsBackground = true}; _thread.Start(); } } } public static CpuUsageModel CpuUsage { get { if (Environment.OSVersion.Platform == PlatformID.Win32NT) return null; Bind(); CpuUsageModel ret; lock (Sync) { // we got delta!!!! // now convert ticks into per cents ret = CurrentDelta.Clone(); } TransormToPercents(ret.Total); foreach (var cpu1UsageModel in ret.Cores) TransormToPercents(cpu1UsageModel); return ret; } } static void GathererRunner() { while (true) { lock (Sync) { CurrentDelta = GetNextDelta(); } long copy; lock (Sync) copy = IntervalMssec; Thread.Sleep((int)Math.Max(100L, Math.Min(5000L, copy))); } } // RAW static CpuUsageModel GetNextDelta() { lock (Sync) { Stopwatch sw = Stopwatch.StartNew(); var next = GetLocalSnapshot(); var prev = PrevModel; CpuUsageModel delta = new CpuUsageModel { Total = GetDelta1(prev.Total, next.Total), Cores = new List<Cpu1UsageModel>(), }; var n = Math.Min(prev.Cores.Count, next.Cores.Count); for(int i=0; i<n; i++) delta.Cores.Add(GetDelta1(prev.Cores[i], next.Cores[i])); PrevModel = next; // NiceTrace.Message("CpuUsageListener_OnLinux.GetNextDelta() takes {0:n0} msec", sw.ElapsedMilliseconds); return delta; } } static Cpu1UsageModel GetDelta1(Cpu1UsageModel prev, Cpu1UsageModel next) { return new Cpu1UsageModel() { Idle = Math.Max((ulong) 0, next.Idle - prev.Idle), Nice = Math.Max((ulong) 0, next.Nice - prev.Nice), User = Math.Max((ulong) 0, next.User - prev.User), System = Math.Max((ulong) 0, next.System - prev.System), }; } static void TransormToPercents(Cpu1UsageModel m) { decimal total = m.Idle + m.Nice + m.System + m.User; if (total > 0) { m.Idle /= total * 0.01m; m.Nice /= total * 0.01m; m.System /= total * 0.01m; m.User /= total * 0.01m; } } public static CpuUsageModel GetLocalSnapshot() { CpuUsageModel ret = new CpuUsageModel() { Cores = new List<Cpu1UsageModel>() }; using (FileStream fs = new FileStream("/proc/stat", FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader rd = new StreamReader(fs, Encoding.UTF8)) { while (true) { string line = rd.ReadLine(); if (line == null) break; Cpu1UsageModel model; int? corePosition; if (ParseCpuLine(line, out model, out corePosition)) { if (!corePosition.HasValue) ret.Total = model; else ret.Cores.Add(model); } } } if (ret.Total == null || ret.Cores.Count == 0) ret = null; // Console.WriteLine("DONE: GetLocalSnapshot()"); return ret; } // corePosition starts from 0 private static bool ParseCpuLine(string line, out Cpu1UsageModel model1, out int? corePosition) { model1 = null; corePosition = null; if (line == null || line.Length <= 4 || !line.Substring(0, 3).Equals("cpu", StringComparison.InvariantCultureIgnoreCase)) return false; string strNumbers = line.Substring(3); ulong tmp; var numbers = strNumbers .Split(' ', '\t') .Where(x => ulong.TryParse(x, out tmp)) .Select(x => ulong.Parse(x)) .ToList(); if (strNumbers[0] == ' ') { // Avg All cores corePosition = null; } else { if (numbers.Count < 1) return false; corePosition = (int)numbers[0]; numbers.RemoveAt(0); } // cpu column removed. numbers starts with UserTime column if (numbers.Count < 4) return false; ulong longUserTime = numbers[0], longNiceTime = numbers[1], longSystemTime = numbers[2], longIdleTime = numbers[3]; model1 = new Cpu1UsageModel { Nice = longNiceTime, Idle = longIdleTime, User = longUserTime, System = longSystemTime, }; return true; } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneCaptureComponent.h:60 namespace UnrealEngine { public partial class USceneCaptureComponent : USceneComponent { public USceneCaptureComponent(IntPtr adress) : base(adress) { } public USceneCaptureComponent(UObject Parent = null, string Name = "SceneCaptureComponent") : base(IntPtr.Zero) { NativePointer = E_NewObject_USceneCaptureComponent(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_USceneCaptureComponent_bAlwaysPersistRenderingState_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_bAlwaysPersistRenderingState_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_USceneCaptureComponent_bCaptureEveryFrame_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_bCaptureEveryFrame_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_USceneCaptureComponent_bCaptureOnMovement_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_bCaptureOnMovement_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_USceneCaptureComponent_CaptureSortPriority_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_CaptureSortPriority_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_USceneCaptureComponent_LODDistanceFactor_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_LODDistanceFactor_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_USceneCaptureComponent_MaxViewDistanceOverride_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_MaxViewDistanceOverride_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_USceneCaptureComponent_PrimitiveRenderMode_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_PrimitiveRenderMode_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_PROP_USceneCaptureComponent_ProfilingEventName_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_USceneCaptureComponent_ProfilingEventName_SET(IntPtr Ptr, string Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_USceneCaptureComponent(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_ClearHiddenComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_ClearShowOnlyComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_USceneCaptureComponent_GetViewOwner(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_HideActorComponents(IntPtr self, IntPtr inActor); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_HideComponent(IntPtr self, IntPtr inComponent); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_RemoveShowOnlyActorComponents(IntPtr self, IntPtr inActor); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_RemoveShowOnlyComponent(IntPtr self, IntPtr inComponent); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_SetCaptureSortPriority(IntPtr self, int newCaptureSortPriority); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_ShowOnlyActorComponents(IntPtr self, IntPtr inActor); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_ShowOnlyComponent(IntPtr self, IntPtr inComponent); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_USceneCaptureComponent_UpdateShowFlags(IntPtr self); #endregion #region Property /// <summary> /// Whether to persist the rendering state even if bCaptureEveryFrame==false. This allows velocities for Motion Blur and Temporal AA to be computed. /// </summary> public bool bAlwaysPersistRenderingState { get => E_PROP_USceneCaptureComponent_bAlwaysPersistRenderingState_GET(NativePointer); set => E_PROP_USceneCaptureComponent_bAlwaysPersistRenderingState_SET(NativePointer, value); } /// <summary> /// Whether to update the capture's contents every frame. If disabled, the component will render once on load and then only when moved. /// </summary> public bool bCaptureEveryFrame { get => E_PROP_USceneCaptureComponent_bCaptureEveryFrame_GET(NativePointer); set => E_PROP_USceneCaptureComponent_bCaptureEveryFrame_SET(NativePointer, value); } /// <summary> /// Whether to update the capture's contents on movement. Disable if you are going to capture manually from blueprint. /// </summary> public bool bCaptureOnMovement { get => E_PROP_USceneCaptureComponent_bCaptureOnMovement_GET(NativePointer); set => E_PROP_USceneCaptureComponent_bCaptureOnMovement_SET(NativePointer, value); } /// <summary> /// Capture priority within the frame to sort scene capture on GPU to resolve interdependencies between multiple capture components. Highest come first. /// </summary> public int CaptureSortPriority { get => E_PROP_USceneCaptureComponent_CaptureSortPriority_GET(NativePointer); set => E_PROP_USceneCaptureComponent_CaptureSortPriority_SET(NativePointer, value); } /// <summary> /// Scales the distance used by LOD. Set to values greater than 1 to cause the scene capture to use lower LODs than the main view to speed up the scene capture pass. /// </summary> public float LODDistanceFactor { get => E_PROP_USceneCaptureComponent_LODDistanceFactor_GET(NativePointer); set => E_PROP_USceneCaptureComponent_LODDistanceFactor_SET(NativePointer, value); } /// <summary> /// if > 0, sets a maximum render distance override. Can be used to cull distant objects from a reflection if the reflecting plane is in an enclosed area like a hallway or room /// </summary> public float MaxViewDistanceOverride { get => E_PROP_USceneCaptureComponent_MaxViewDistanceOverride_GET(NativePointer); set => E_PROP_USceneCaptureComponent_MaxViewDistanceOverride_SET(NativePointer, value); } /// <summary> /// Controls what primitives get rendered into the scene capture. /// </summary> public ESceneCapturePrimitiveRenderMode PrimitiveRenderMode { get => (ESceneCapturePrimitiveRenderMode)E_PROP_USceneCaptureComponent_PrimitiveRenderMode_GET(NativePointer); set => E_PROP_USceneCaptureComponent_PrimitiveRenderMode_SET(NativePointer, (byte)value); } /// <summary> /// Name of the profiling event. /// </summary> public string ProfilingEventName { get => E_PROP_USceneCaptureComponent_ProfilingEventName_GET(NativePointer); set => E_PROP_USceneCaptureComponent_ProfilingEventName_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Clears the hidden list. /// </summary> public void ClearHiddenComponents() => E_USceneCaptureComponent_ClearHiddenComponents(this); /// <summary> /// Clears the Show Only list. /// </summary> public void ClearShowOnlyComponents() => E_USceneCaptureComponent_ClearShowOnlyComponents(this); /// <summary> /// To leverage a component's bOwnerNoSee/bOnlyOwnerSee properties, the capture view requires an "owner". Override this to set a "ViewActor" for the scene. /// </summary> public virtual AActor GetViewOwner() => E_USceneCaptureComponent_GetViewOwner(this); /// <summary> /// Adds all primitive components in the actor to our list of hidden components. /// </summary> public void HideActorComponents(AActor inActor) => E_USceneCaptureComponent_HideActorComponents(this, inActor); /// <summary> /// Adds the component to our list of hidden components. /// </summary> public void HideComponent(UPrimitiveComponent inComponent) => E_USceneCaptureComponent_HideComponent(this, inComponent); /// <summary> /// Removes a actor's components from the Show Only list. /// </summary> public void RemoveShowOnlyActorComponents(AActor inActor) => E_USceneCaptureComponent_RemoveShowOnlyActorComponents(this, inActor); /// <summary> /// Removes a component from the Show Only list. /// </summary> public void RemoveShowOnlyComponent(UPrimitiveComponent inComponent) => E_USceneCaptureComponent_RemoveShowOnlyComponent(this, inComponent); /// <summary> /// Changes the value of TranslucentSortPriority. /// </summary> public void SetCaptureSortPriority(int newCaptureSortPriority) => E_USceneCaptureComponent_SetCaptureSortPriority(this, newCaptureSortPriority); /// <summary> /// Adds all primitive components in the actor to our list of show-only components. /// </summary> public void ShowOnlyActorComponents(AActor inActor) => E_USceneCaptureComponent_ShowOnlyActorComponents(this, inActor); /// <summary> /// Adds the component to our list of show-only components. /// </summary> public void ShowOnlyComponent(UPrimitiveComponent inComponent) => E_USceneCaptureComponent_ShowOnlyComponent(this, inComponent); /// <summary> /// Update the show flags from our show flags settings (ideally, you'd be able to set this more directly, but currently unable to make FEngineShowFlags a UStruct to use it as a UProperty...) /// </summary> protected void UpdateShowFlags() => E_USceneCaptureComponent_UpdateShowFlags(this); #endregion public static implicit operator IntPtr(USceneCaptureComponent self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator USceneCaptureComponent(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<USceneCaptureComponent>(PtrDesc); } } }
/* Copyright 2014 David Bordoley Copyright 2014 Zumero, 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 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; using System.Collections.Generic; using System.IO; using System.Linq; namespace SQLitePCL.pretty { internal sealed class DatabaseBackupImpl : IDatabaseBackup { private readonly sqlite3_backup backup; private readonly SQLiteDatabaseConnection srcDb; private readonly SQLiteDatabaseConnection destDb; private readonly EventHandler dbDisposing; private bool disposed = false; internal DatabaseBackupImpl(sqlite3_backup backup, SQLiteDatabaseConnection srcDb, SQLiteDatabaseConnection destDb) { this.backup = backup; this.srcDb = srcDb; this.destDb = destDb; this.dbDisposing = (o, e) => Dispose(); this.srcDb.Disposing += dbDisposing; this.destDb.Disposing += dbDisposing; } public int PageCount { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return raw.sqlite3_backup_pagecount(backup); } } public int RemainingPages { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return raw.sqlite3_backup_remaining(backup); } } public void Dispose() { if (disposed) { return; } disposed = true; // FIXME: What to do about errors? raw.sqlite3_backup_finish(backup); srcDb.Disposing -= dbDisposing; destDb.Disposing -= dbDisposing; } public bool Step(int nPages) { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } int rc = raw.sqlite3_backup_step(backup, nPages); if (rc == raw.SQLITE_OK) { return true; } else if (rc == raw.SQLITE_DONE) { return false; } else { SQLiteException.CheckOk(rc); // Never happens, exception always thrown. return false; } } } internal sealed class StatementImpl : IStatement { private readonly sqlite3_stmt stmt; private readonly SQLiteDatabaseConnection db; private readonly EventHandler dbDisposing; private readonly IReadOnlyOrderedDictionary<string, IBindParameter> bindParameters; private readonly IReadOnlyList<ColumnInfo> columns; private readonly IReadOnlyList<IResultSetValue> current; private bool disposed = false; private bool mustReset = false; internal StatementImpl(sqlite3_stmt stmt, SQLiteDatabaseConnection db) { this.stmt = stmt; this.db = db; this.bindParameters = new BindParameterOrderedDictionaryImpl(this); this.columns = new ColumnsListImpl(this); this.current = new ResultSetImpl(this); this.dbDisposing = (o, e) => this.Dispose(); this.db.Disposing += dbDisposing; } internal sqlite3_stmt sqlite3_stmt { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return stmt; } } public IReadOnlyOrderedDictionary<string, IBindParameter> BindParameters { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return bindParameters; } } public IReadOnlyList<ColumnInfo> Columns { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return columns; } } public IReadOnlyList<IResultSetValue> Current { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return current; } } Object IEnumerator.Current { get { return this.Current; } } public string SQL { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return raw.sqlite3_sql(this.sqlite3_stmt); } } public bool IsReadOnly { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return raw.sqlite3_stmt_readonly(this.sqlite3_stmt) != 0; } } public bool IsBusy { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return raw.sqlite3_stmt_busy(this.sqlite3_stmt) != 0; } } public void ClearBindings() { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } int rc = raw.sqlite3_clear_bindings(this.sqlite3_stmt); SQLiteException.CheckOk(this.sqlite3_stmt, rc); } public void Dispose() { if (disposed) { return; } disposed = true; // FIXME: Handle errors? raw.sqlite3_finalize(stmt); db.Disposing -= dbDisposing; db.RemoveStatement(this); } public bool MoveNext() { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (mustReset) { return false; } int rc = raw.sqlite3_step(this.sqlite3_stmt); if (rc == raw.SQLITE_DONE) { mustReset = true; return false; } else if (rc == raw.SQLITE_ROW) { return true; } else { SQLiteException.CheckOk(this.sqlite3_stmt, rc); // Never gets returned return false; } } public void Reset() { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } // FIXME: Ignore the result code? // If the most recent call to sqlite3_step(S) for the prepared statement S // returned SQLITE_ROW or SQLITE_DONE, or if sqlite3_step(S) has never before been // called on S, then sqlite3_reset(S) returns SQLITE_OK. // If the most recent call to sqlite3_step(S) for the prepared statement S indicated an // error, then sqlite3_reset(S) returns an appropriate error code. mustReset = false; int rc = raw.sqlite3_reset(this.sqlite3_stmt); SQLiteException.CheckOk(stmt, rc); } public int Status(StatementStatusCode statusCode, bool reset) { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return raw.sqlite3_stmt_status(stmt, (int) statusCode, reset ? 1 : 0); } } internal sealed class BindParameterOrderedDictionaryImpl : IReadOnlyOrderedDictionary<string, IBindParameter> { private readonly StatementImpl stmt; internal BindParameterOrderedDictionaryImpl(StatementImpl stmt) { this.stmt = stmt; } private bool TryGetBindParameterIndex(string parameter, out int index) { index = raw.sqlite3_bind_parameter_index(stmt.sqlite3_stmt, parameter) - 1; return index >= 0; } public IBindParameter this[int index] { get { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(); } return new BindParameterImpl(stmt.sqlite3_stmt, index); } } public IBindParameter this[string key] { get { IBindParameter value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } } public int Count { get { return raw.sqlite3_bind_parameter_count(stmt.sqlite3_stmt); } } public IEnumerable<string> Keys { get { return this.Select(pair => pair.Key); } } public IEnumerable<IBindParameter> Values { get { return this.Select(pair => pair.Value); } } public bool ContainsKey(string key) { Contract.Requires(key != null); int i; return this.TryGetBindParameterIndex(key, out i); } public IEnumerator<KeyValuePair<string, IBindParameter>> GetEnumerator() { for (int i = 0; i < this.Count; i++) { var next = this[i]; yield return new KeyValuePair<string, IBindParameter>(next.Name, next); } } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); public bool TryGetValue(string key, out IBindParameter value) { int i; if (this.TryGetBindParameterIndex(key, out i)) { value = this[i]; return true; } value = null; return false; } } internal sealed class BindParameterImpl : IBindParameter { private readonly sqlite3_stmt stmt; private readonly int index; internal BindParameterImpl(sqlite3_stmt stmt, int index) { this.stmt = stmt; this.index = index; } public string Name { get { return raw.sqlite3_bind_parameter_name(stmt, index + 1); } } public void Bind(byte[] blob) { Contract.Requires(blob != null); int rc = raw.sqlite3_bind_blob(stmt, index + 1, blob); SQLiteException.CheckOk(stmt, rc); } public void Bind(double val) { int rc = raw.sqlite3_bind_double(stmt, index + 1, val); SQLiteException.CheckOk(stmt, rc); } public void Bind(int val) { int rc = raw.sqlite3_bind_int(stmt, index + 1, val); SQLiteException.CheckOk(stmt, rc); } public void Bind(long val) { int rc = raw.sqlite3_bind_int64(stmt, index + 1, val); SQLiteException.CheckOk(stmt, rc); } public void Bind(string text) { Contract.Requires(text != null); int rc = raw.sqlite3_bind_text(stmt, index + 1, text); SQLiteException.CheckOk(stmt, rc); } public void BindNull() { int rc = raw.sqlite3_bind_null(stmt, index + 1); SQLiteException.CheckOk(stmt, rc); } public void BindZeroBlob(int size) { Contract.Requires(size >= 0); int rc = raw.sqlite3_bind_zeroblob(stmt, index + 1, size); SQLiteException.CheckOk(stmt, rc); } } internal sealed class ColumnsListImpl : IReadOnlyList<ColumnInfo> { private readonly StatementImpl stmt; internal ColumnsListImpl(StatementImpl stmt) { this.stmt = stmt; } public ColumnInfo this[int index] { get { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(); } return ColumnInfo.Create(stmt, index); } } public int Count { get { return raw.sqlite3_column_count(stmt.sqlite3_stmt); } } public IEnumerator<ColumnInfo> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } internal sealed class ResultSetImpl : IReadOnlyList<IResultSetValue> { private readonly StatementImpl stmt; internal ResultSetImpl(StatementImpl stmt) { this.stmt = stmt; } public int Count { get { return raw.sqlite3_data_count(stmt.sqlite3_stmt); } } public IEnumerator<IResultSetValue> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); public IResultSetValue this[int index] { get { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(); } return stmt.ResultSetValueAt(index); } } } internal sealed class BlobStream : Stream { private static void CheckOkOrThrowIOException(int rc) { try { SQLiteException.CheckOk(rc); } catch (SQLiteException e) { throw new IOException("Received SQLiteExcepction", e); } } private readonly sqlite3_blob blob; private readonly SQLiteDatabaseConnection db; private readonly EventHandler dbDisposing; private readonly bool canWrite; private readonly int length; private bool disposed = false; private long position = 0; internal BlobStream(sqlite3_blob blob, SQLiteDatabaseConnection db, bool canWrite, int length) { this.blob = blob; this.db = db; this.canWrite = canWrite; this.length = length; this.dbDisposing = (o, e) => this.Dispose(true); this.db.Disposing += dbDisposing; } public override bool CanRead { get { return !disposed; } } public override bool CanSeek { get { return !disposed; } } public override bool CanWrite { get { return !disposed && canWrite; } } public override long Length { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return length; } } public override long Position { get { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } return position; } set { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (value < 0) { throw new ArgumentOutOfRangeException("value", "Position cannot be negative"); } position = value; } } // http://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx protected override void Dispose(bool disposing) { if (disposed) { return; } //FIXME: Handle errors? raw.sqlite3_blob_close(blob); disposed = true; db.Disposing -= dbDisposing; base.Dispose(disposing); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (position >= length) { return 0; } // At this point we're guaranteed that position is an int between 0 and length int numBytes = Math.Min(length - (int)position, count); int rc = raw.sqlite3_blob_read(blob, buffer, offset, numBytes, (int)position); CheckOkOrThrowIOException(rc); position += numBytes; return numBytes; } public override long Seek(long offset, SeekOrigin origin) { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } long newPosition; switch (origin) { case SeekOrigin.Begin: { newPosition = offset; break; } case SeekOrigin.Current: { newPosition = position + offset; break; } case SeekOrigin.End: { newPosition = length + offset; break; } default: { throw new ArgumentException(); } } if (newPosition < 0) { throw new IOException(); } position = newPosition; return position; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new NotSupportedException(); } if (position >= length) { return; } // At this point we're guaranteed that position is an int between 0 and length int numBytes = Math.Min(length - (int)position, count); int rc = raw.sqlite3_blob_write(blob, buffer, offset, numBytes, (int)position); CheckOkOrThrowIOException(rc); position += numBytes; } } internal sealed class DelegatingEnumerable<T> : IEnumerable<T> { private readonly Func<IEnumerator<T>> deleg; internal DelegatingEnumerable(Func<IEnumerator<T>> deleg) { this.deleg = deleg; } public IEnumerator<T> GetEnumerator() => deleg(); IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); } }
// 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.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { internal static class SslStreamPal { private const string SecurityPackage = "Microsoft Unified Security Protocol Provider"; private const Interop.SspiCli.ContextFlags RequiredFlags = Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.Confidentiality | Interop.SspiCli.ContextFlags.AllocateMemory; private const Interop.SspiCli.ContextFlags ServerRequiredFlags = RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream; public static Exception GetException(SecurityStatusPal status) { int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status); return new Win32Exception(win32Code); } internal const bool StartMutualAuthAsAnonymous = true; internal const bool CanEncryptEmptyMessage = true; public static void VerifyPackageInfo() { SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true); } public static byte[] ConvertAlpnProtocolListToByteArray(List<SslApplicationProtocol> protocols) { return Interop.Sec_Application_Protocols.ToByteArray(protocols); } public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags); int errorCode = SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPISecureChannel, credentialsHandle, ref context, ServerRequiredFlags | (sslAuthenticationOptions.RemoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero), Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, outputBuffer, ref unusedAttributes); return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, ref credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffer, outputBuffer, ref unusedAttributes); return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, outputBuffer, ref unusedAttributes); return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityBuffer[] GetIncomingSecurityBuffers(SslAuthenticationOptions options, ref SecurityBuffer incomingSecurity) { SecurityBuffer alpnBuffer = null; SecurityBuffer[] incomingSecurityBuffers = null; if (options.ApplicationProtocols != null && options.ApplicationProtocols.Count != 0) { byte[] alpnBytes = SslStreamPal.ConvertAlpnProtocolListToByteArray(options.ApplicationProtocols); alpnBuffer = new SecurityBuffer(alpnBytes, 0, alpnBytes.Length, SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS); } if (incomingSecurity != null) { if (alpnBuffer != null) { incomingSecurityBuffers = new SecurityBuffer[] { incomingSecurity, new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY), alpnBuffer }; } else { incomingSecurityBuffers = new SecurityBuffer[] { incomingSecurity, new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY) }; } } else if (alpnBuffer != null) { incomingSecurity = alpnBuffer; } return incomingSecurityBuffers; } public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCHANNEL_CRED.Flags flags; Interop.SspiCli.CredentialUse direction; if (!isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; // CoreFX: always opt-in SCH_USE_STRONG_CRYPTO except for SSL3. if (((protocolFlags == 0) || (protocolFlags & (Interop.SChannel.SP_PROT_TLS1_0 | Interop.SChannel.SP_PROT_TLS1_1 | Interop.SChannel.SP_PROT_TLS1_2)) != 0) && (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption)) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_USE_STRONG_CRYPTO; } } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; } if (NetEventSource.IsEnabled) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}"); Interop.SspiCli.SCHANNEL_CRED secureCredential = CreateSecureCredential( Interop.SspiCli.SCHANNEL_CRED.CurrentVersion, certificate, flags, protocolFlags, policy); return AcquireCredentialsHandle(direction, secureCredential); } internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context) { Interop.SecPkgContext_ApplicationProtocol alpnContext = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, context, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL) as Interop.SecPkgContext_ApplicationProtocol; // Check if the context returned is alpn data, with successful negotiation. if (alpnContext == null || alpnContext.ProtoNegoExt != Interop.ApplicationProtocolNegotiationExt.ALPN || alpnContext.ProtoNegoStatus != Interop.ApplicationProtocolNegotiationStatus.Success) { return null; } return alpnContext.Protocol; } public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, ReadOnlyMemory<byte> input, int headerSize, int trailerSize, ref byte[] output, out int resultSize) { // Ensure that there is sufficient space for the message output. int bufferSizeNeeded; try { bufferSizeNeeded = checked(input.Length + headerSize + trailerSize); } catch { NetEventSource.Fail(securityContext, "Arguments out of range"); throw; } if (output == null || output.Length < bufferSizeNeeded) { output = new byte[bufferSizeNeeded]; } // Copy the input into the output buffer to prepare for SCHANNEL's expectations input.Span.CopyTo(new Span<byte>(output, headerSize, input.Length)); const int NumSecBuffers = 4; // header + data + trailer + empty var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers); sdcInOut.pBuffers = unmanagedBuffer; fixed (byte* outputPtr = output) { Interop.SspiCli.SecBuffer* headerSecBuffer = &unmanagedBuffer[0]; headerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_HEADER; headerSecBuffer->pvBuffer = (IntPtr)outputPtr; headerSecBuffer->cbBuffer = headerSize; Interop.SspiCli.SecBuffer* dataSecBuffer = &unmanagedBuffer[1]; dataSecBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize); dataSecBuffer->cbBuffer = input.Length; Interop.SspiCli.SecBuffer* trailerSecBuffer = &unmanagedBuffer[2]; trailerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_TRAILER; trailerSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize + input.Length); trailerSecBuffer->cbBuffer = trailerSize; Interop.SspiCli.SecBuffer* emptySecBuffer = &unmanagedBuffer[3]; emptySecBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptySecBuffer->cbBuffer = 0; emptySecBuffer->pvBuffer = IntPtr.Zero; int errorCode = GlobalSSPI.SSPISecureChannel.EncryptMessage(securityContext, ref sdcInOut, 0); if (errorCode != 0) { if (NetEventSource.IsEnabled) NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}"); resultSize = 0; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } Debug.Assert(headerSecBuffer->cbBuffer >= 0 && dataSecBuffer->cbBuffer >= 0 && trailerSecBuffer->cbBuffer >= 0); Debug.Assert(checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer) <= output.Length); resultSize = checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer); return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } } public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count) { const int NumSecBuffers = 4; // data + empty + empty + empty var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers); sdcInOut.pBuffers = unmanagedBuffer; fixed (byte* bufferPtr = buffer) { Interop.SspiCli.SecBuffer* dataBuffer = &unmanagedBuffer[0]; dataBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataBuffer->pvBuffer = (IntPtr)bufferPtr + offset; dataBuffer->cbBuffer = count; for (int i = 1; i < NumSecBuffers; i++) { Interop.SspiCli.SecBuffer* emptyBuffer = &unmanagedBuffer[i]; emptyBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptyBuffer->pvBuffer = IntPtr.Zero; emptyBuffer->cbBuffer = 0; } Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext, ref sdcInOut, 0); // Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty. // We need to find the data. count = 0; for (int i = 0; i < NumSecBuffers; i++) { // Successfully decoded data and placed it at the following position in the buffer, if ((errorCode == Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_DATA) // or we failed to decode the data, here is the encoded data. || (errorCode != Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_EXTRA)) { offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferPtr); count = unmanagedBuffer[i].cbBuffer; Debug.Assert(offset >= 0 && count >= 0, $"Expected offset and count greater than 0, got {offset} and {count}"); Debug.Assert(checked(offset + count) <= buffer.Length, $"Expected offset+count <= buffer.Length, got {offset}+{count}>={buffer.Length}"); break; } } return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode); } } public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { Interop.SChannel.SCHANNEL_ALERT_TOKEN alertToken; alertToken.dwTokenType = Interop.SChannel.SCHANNEL_ALERT; alertToken.dwAlertType = (uint)alertType; alertToken.dwAlertNumber = (uint)alertMessage; var bufferDesc = new SecurityBuffer[1]; int alertTokenByteSize = Marshal.SizeOf<Interop.SChannel.SCHANNEL_ALERT_TOKEN>(); IntPtr p = Marshal.AllocHGlobal(alertTokenByteSize); try { var buffer = new byte[alertTokenByteSize]; Marshal.StructureToPtr<Interop.SChannel.SCHANNEL_ALERT_TOKEN>(alertToken, p, false); Marshal.Copy(p, buffer, 0, alertTokenByteSize); bufferDesc[0] = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, bufferDesc); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } finally { Marshal.FreeHGlobal(p); } } public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext) { int shutdownToken = Interop.SChannel.SCHANNEL_SHUTDOWN; var bufferDesc = new SecurityBuffer[1]; var buffer = BitConverter.GetBytes(shutdownToken); bufferDesc[0] = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, bufferDesc); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } public static unsafe SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); } public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes) { var interopStreamSizes = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES) as SecPkgContext_StreamSizes; streamSizes = new StreamSizes(interopStreamSizes); } public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo) { var interopConnectionInfo = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO) as SecPkgContext_ConnectionInfo; connectionInfo = new SslConnectionInfo(interopConnectionInfo); } private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer) { int protocolFlags = (int)protocols; if (isServer) { protocolFlags &= Interop.SChannel.ServerProtocolMask; } else { protocolFlags &= Interop.SChannel.ClientProtocolMask; } return protocolFlags; } private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential( int version, X509Certificate certificate, Interop.SspiCli.SCHANNEL_CRED.Flags flags, int protocols, EncryptionPolicy policy) { var credential = new Interop.SspiCli.SCHANNEL_CRED() { hRootStore = IntPtr.Zero, aphMappers = IntPtr.Zero, palgSupportedAlgs = IntPtr.Zero, paCred = IntPtr.Zero, cCreds = 0, cMappers = 0, cSupportedAlgs = 0, dwSessionLifespan = 0, reserved = 0 }; if (policy == EncryptionPolicy.RequireEncryption) { // Prohibit null encryption cipher. credential.dwMinimumCipherStrength = 0; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.NoEncryption) { // Suppress all encryption and require null encryption cipher only credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = -1; } else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } credential.dwVersion = version; credential.dwFlags = flags; credential.grbitEnabledProtocols = protocols; if (certificate != null) { credential.paCred = certificate.Handle; credential.cCreds = 1; } return credential; } // // Security: we temporarily reset thread token to open the handle under process account. // private static SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCHANNEL_CRED secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch (Exception ex) { Debug.Fail("AcquireCredentialsHandle failed.", ex.ToString()); return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.RecommendationEngine.V1Beta1 { /// <summary>Settings for <see cref="PredictionApiKeyRegistryClient"/> instances.</summary> public sealed partial class PredictionApiKeyRegistrySettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="PredictionApiKeyRegistrySettings"/>.</summary> /// <returns>A new instance of the default <see cref="PredictionApiKeyRegistrySettings"/>.</returns> public static PredictionApiKeyRegistrySettings GetDefault() => new PredictionApiKeyRegistrySettings(); /// <summary> /// Constructs a new <see cref="PredictionApiKeyRegistrySettings"/> object with default settings. /// </summary> public PredictionApiKeyRegistrySettings() { } private PredictionApiKeyRegistrySettings(PredictionApiKeyRegistrySettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CreatePredictionApiKeyRegistrationSettings = existing.CreatePredictionApiKeyRegistrationSettings; ListPredictionApiKeyRegistrationsSettings = existing.ListPredictionApiKeyRegistrationsSettings; DeletePredictionApiKeyRegistrationSettings = existing.DeletePredictionApiKeyRegistrationSettings; OnCopy(existing); } partial void OnCopy(PredictionApiKeyRegistrySettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PredictionApiKeyRegistryClient.CreatePredictionApiKeyRegistration</c> and /// <c>PredictionApiKeyRegistryClient.CreatePredictionApiKeyRegistrationAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 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: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreatePredictionApiKeyRegistrationSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PredictionApiKeyRegistryClient.ListPredictionApiKeyRegistrations</c> and /// <c>PredictionApiKeyRegistryClient.ListPredictionApiKeyRegistrationsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 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: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListPredictionApiKeyRegistrationsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PredictionApiKeyRegistryClient.DeletePredictionApiKeyRegistration</c> and /// <c>PredictionApiKeyRegistryClient.DeletePredictionApiKeyRegistrationAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 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: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeletePredictionApiKeyRegistrationSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), 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="PredictionApiKeyRegistrySettings"/> object.</returns> public PredictionApiKeyRegistrySettings Clone() => new PredictionApiKeyRegistrySettings(this); } /// <summary> /// Builder class for <see cref="PredictionApiKeyRegistryClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class PredictionApiKeyRegistryClientBuilder : gaxgrpc::ClientBuilderBase<PredictionApiKeyRegistryClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public PredictionApiKeyRegistrySettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public PredictionApiKeyRegistryClientBuilder() { UseJwtAccessWithScopes = PredictionApiKeyRegistryClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref PredictionApiKeyRegistryClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PredictionApiKeyRegistryClient> task); /// <summary>Builds the resulting client.</summary> public override PredictionApiKeyRegistryClient Build() { PredictionApiKeyRegistryClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<PredictionApiKeyRegistryClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<PredictionApiKeyRegistryClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private PredictionApiKeyRegistryClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return PredictionApiKeyRegistryClient.Create(callInvoker, Settings); } private async stt::Task<PredictionApiKeyRegistryClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return PredictionApiKeyRegistryClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => PredictionApiKeyRegistryClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => PredictionApiKeyRegistryClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => PredictionApiKeyRegistryClient.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>PredictionApiKeyRegistry client wrapper, for convenient use.</summary> /// <remarks> /// Service for registering API keys for use with the `predict` method. If you /// use an API key to request predictions, you must first register the API key. /// Otherwise, your prediction request is rejected. If you use OAuth to /// authenticate your `predict` method call, you do not need to register an API /// key. You can register up to 20 API keys per project. /// </remarks> public abstract partial class PredictionApiKeyRegistryClient { /// <summary> /// The default endpoint for the PredictionApiKeyRegistry service, which is a host of /// "recommendationengine.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "recommendationengine.googleapis.com:443"; /// <summary>The default PredictionApiKeyRegistry scopes.</summary> /// <remarks> /// The default PredictionApiKeyRegistry scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); 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="PredictionApiKeyRegistryClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="PredictionApiKeyRegistryClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="PredictionApiKeyRegistryClient"/>.</returns> public static stt::Task<PredictionApiKeyRegistryClient> CreateAsync(st::CancellationToken cancellationToken = default) => new PredictionApiKeyRegistryClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="PredictionApiKeyRegistryClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="PredictionApiKeyRegistryClientBuilder"/>. /// </summary> /// <returns>The created <see cref="PredictionApiKeyRegistryClient"/>.</returns> public static PredictionApiKeyRegistryClient Create() => new PredictionApiKeyRegistryClientBuilder().Build(); /// <summary> /// Creates a <see cref="PredictionApiKeyRegistryClient"/> 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="PredictionApiKeyRegistrySettings"/>.</param> /// <returns>The created <see cref="PredictionApiKeyRegistryClient"/>.</returns> internal static PredictionApiKeyRegistryClient Create(grpccore::CallInvoker callInvoker, PredictionApiKeyRegistrySettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } PredictionApiKeyRegistry.PredictionApiKeyRegistryClient grpcClient = new PredictionApiKeyRegistry.PredictionApiKeyRegistryClient(callInvoker); return new PredictionApiKeyRegistryClientImpl(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 PredictionApiKeyRegistry client</summary> public virtual PredictionApiKeyRegistry.PredictionApiKeyRegistryClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Register an API key for use with predict method. /// </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 PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Register an API key for use with predict method. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Register an API key for use with predict method. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest request, st::CancellationToken cancellationToken) => CreatePredictionApiKeyRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Register an API key for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`. /// </param> /// <param name="predictionApiKeyRegistration"> /// Required. The prediction API key registration. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(string parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) => CreatePredictionApiKeyRegistration(new CreatePredictionApiKeyRegistrationRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)), }, callSettings); /// <summary> /// Register an API key for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`. /// </param> /// <param name="predictionApiKeyRegistration"> /// Required. The prediction API key registration. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(string parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) => CreatePredictionApiKeyRegistrationAsync(new CreatePredictionApiKeyRegistrationRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)), }, callSettings); /// <summary> /// Register an API key for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`. /// </param> /// <param name="predictionApiKeyRegistration"> /// Required. The prediction API key registration. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(string parent, PredictionApiKeyRegistration predictionApiKeyRegistration, st::CancellationToken cancellationToken) => CreatePredictionApiKeyRegistrationAsync(parent, predictionApiKeyRegistration, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Register an API key for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`. /// </param> /// <param name="predictionApiKeyRegistration"> /// Required. The prediction API key registration. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(EventStoreName parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) => CreatePredictionApiKeyRegistration(new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)), }, callSettings); /// <summary> /// Register an API key for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`. /// </param> /// <param name="predictionApiKeyRegistration"> /// Required. The prediction API key registration. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(EventStoreName parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) => CreatePredictionApiKeyRegistrationAsync(new CreatePredictionApiKeyRegistrationRequest { ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)), }, callSettings); /// <summary> /// Register an API key for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`. /// </param> /// <param name="predictionApiKeyRegistration"> /// Required. The prediction API key registration. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(EventStoreName parent, PredictionApiKeyRegistration predictionApiKeyRegistration, st::CancellationToken cancellationToken) => CreatePredictionApiKeyRegistrationAsync(parent, predictionApiKeyRegistration, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// List the registered apiKeys for use with predict method. /// </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 pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public virtual gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// List the registered apiKeys for use with predict method. /// </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 pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// List the registered apiKeys for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent placement resource name such as /// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store` /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public virtual gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListPredictionApiKeyRegistrations(new ListPredictionApiKeyRegistrationsRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// List the registered apiKeys for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent placement resource name such as /// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store` /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListPredictionApiKeyRegistrationsAsync(new ListPredictionApiKeyRegistrationsRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// List the registered apiKeys for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent placement resource name such as /// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store` /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public virtual gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(EventStoreName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListPredictionApiKeyRegistrations(new ListPredictionApiKeyRegistrationsRequest { ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// List the registered apiKeys for use with predict method. /// </summary> /// <param name="parent"> /// Required. The parent placement resource name such as /// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store` /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(EventStoreName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListPredictionApiKeyRegistrationsAsync(new ListPredictionApiKeyRegistrationsRequest { ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Unregister an apiKey from using for predict method. /// </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 void DeletePredictionApiKeyRegistration(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Unregister an apiKey from using for predict method. /// </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 DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Unregister an apiKey from using for predict method. /// </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 DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest request, st::CancellationToken cancellationToken) => DeletePredictionApiKeyRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Unregister an apiKey from using for predict method. /// </summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&amp;lt;YOUR_API_KEY&amp;gt;` /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeletePredictionApiKeyRegistration(string name, gaxgrpc::CallSettings callSettings = null) => DeletePredictionApiKeyRegistration(new DeletePredictionApiKeyRegistrationRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Unregister an apiKey from using for predict method. /// </summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&amp;lt;YOUR_API_KEY&amp;gt;` /// </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 DeletePredictionApiKeyRegistrationAsync(string name, gaxgrpc::CallSettings callSettings = null) => DeletePredictionApiKeyRegistrationAsync(new DeletePredictionApiKeyRegistrationRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Unregister an apiKey from using for predict method. /// </summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&amp;lt;YOUR_API_KEY&amp;gt;` /// </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 DeletePredictionApiKeyRegistrationAsync(string name, st::CancellationToken cancellationToken) => DeletePredictionApiKeyRegistrationAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Unregister an apiKey from using for predict method. /// </summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&amp;lt;YOUR_API_KEY&amp;gt;` /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeletePredictionApiKeyRegistration(PredictionApiKeyRegistrationName name, gaxgrpc::CallSettings callSettings = null) => DeletePredictionApiKeyRegistration(new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Unregister an apiKey from using for predict method. /// </summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&amp;lt;YOUR_API_KEY&amp;gt;` /// </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 DeletePredictionApiKeyRegistrationAsync(PredictionApiKeyRegistrationName name, gaxgrpc::CallSettings callSettings = null) => DeletePredictionApiKeyRegistrationAsync(new DeletePredictionApiKeyRegistrationRequest { PredictionApiKeyRegistrationName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Unregister an apiKey from using for predict method. /// </summary> /// <param name="name"> /// Required. The API key to unregister including full resource path. /// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&amp;lt;YOUR_API_KEY&amp;gt;` /// </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 DeletePredictionApiKeyRegistrationAsync(PredictionApiKeyRegistrationName name, st::CancellationToken cancellationToken) => DeletePredictionApiKeyRegistrationAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>PredictionApiKeyRegistry client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service for registering API keys for use with the `predict` method. If you /// use an API key to request predictions, you must first register the API key. /// Otherwise, your prediction request is rejected. If you use OAuth to /// authenticate your `predict` method call, you do not need to register an API /// key. You can register up to 20 API keys per project. /// </remarks> public sealed partial class PredictionApiKeyRegistryClientImpl : PredictionApiKeyRegistryClient { private readonly gaxgrpc::ApiCall<CreatePredictionApiKeyRegistrationRequest, PredictionApiKeyRegistration> _callCreatePredictionApiKeyRegistration; private readonly gaxgrpc::ApiCall<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse> _callListPredictionApiKeyRegistrations; private readonly gaxgrpc::ApiCall<DeletePredictionApiKeyRegistrationRequest, wkt::Empty> _callDeletePredictionApiKeyRegistration; /// <summary> /// Constructs a client wrapper for the PredictionApiKeyRegistry service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="PredictionApiKeyRegistrySettings"/> used within this client. /// </param> public PredictionApiKeyRegistryClientImpl(PredictionApiKeyRegistry.PredictionApiKeyRegistryClient grpcClient, PredictionApiKeyRegistrySettings settings) { GrpcClient = grpcClient; PredictionApiKeyRegistrySettings effectiveSettings = settings ?? PredictionApiKeyRegistrySettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callCreatePredictionApiKeyRegistration = clientHelper.BuildApiCall<CreatePredictionApiKeyRegistrationRequest, PredictionApiKeyRegistration>(grpcClient.CreatePredictionApiKeyRegistrationAsync, grpcClient.CreatePredictionApiKeyRegistration, effectiveSettings.CreatePredictionApiKeyRegistrationSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreatePredictionApiKeyRegistration); Modify_CreatePredictionApiKeyRegistrationApiCall(ref _callCreatePredictionApiKeyRegistration); _callListPredictionApiKeyRegistrations = clientHelper.BuildApiCall<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse>(grpcClient.ListPredictionApiKeyRegistrationsAsync, grpcClient.ListPredictionApiKeyRegistrations, effectiveSettings.ListPredictionApiKeyRegistrationsSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListPredictionApiKeyRegistrations); Modify_ListPredictionApiKeyRegistrationsApiCall(ref _callListPredictionApiKeyRegistrations); _callDeletePredictionApiKeyRegistration = clientHelper.BuildApiCall<DeletePredictionApiKeyRegistrationRequest, wkt::Empty>(grpcClient.DeletePredictionApiKeyRegistrationAsync, grpcClient.DeletePredictionApiKeyRegistration, effectiveSettings.DeletePredictionApiKeyRegistrationSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeletePredictionApiKeyRegistration); Modify_DeletePredictionApiKeyRegistrationApiCall(ref _callDeletePredictionApiKeyRegistration); 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_CreatePredictionApiKeyRegistrationApiCall(ref gaxgrpc::ApiCall<CreatePredictionApiKeyRegistrationRequest, PredictionApiKeyRegistration> call); partial void Modify_ListPredictionApiKeyRegistrationsApiCall(ref gaxgrpc::ApiCall<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse> call); partial void Modify_DeletePredictionApiKeyRegistrationApiCall(ref gaxgrpc::ApiCall<DeletePredictionApiKeyRegistrationRequest, wkt::Empty> call); partial void OnConstruction(PredictionApiKeyRegistry.PredictionApiKeyRegistryClient grpcClient, PredictionApiKeyRegistrySettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC PredictionApiKeyRegistry client</summary> public override PredictionApiKeyRegistry.PredictionApiKeyRegistryClient GrpcClient { get; } partial void Modify_CreatePredictionApiKeyRegistrationRequest(ref CreatePredictionApiKeyRegistrationRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListPredictionApiKeyRegistrationsRequest(ref ListPredictionApiKeyRegistrationsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeletePredictionApiKeyRegistrationRequest(ref DeletePredictionApiKeyRegistrationRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Register an API key for use with predict method. /// </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 PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreatePredictionApiKeyRegistrationRequest(ref request, ref callSettings); return _callCreatePredictionApiKeyRegistration.Sync(request, callSettings); } /// <summary> /// Register an API key for use with predict method. /// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreatePredictionApiKeyRegistrationRequest(ref request, ref callSettings); return _callCreatePredictionApiKeyRegistration.Async(request, callSettings); } /// <summary> /// List the registered apiKeys for use with predict method. /// </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 pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public override gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPredictionApiKeyRegistrationsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration>(_callListPredictionApiKeyRegistrations, request, callSettings); } /// <summary> /// List the registered apiKeys for use with predict method. /// </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 pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPredictionApiKeyRegistrationsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration>(_callListPredictionApiKeyRegistrations, request, callSettings); } /// <summary> /// Unregister an apiKey from using for predict method. /// </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 void DeletePredictionApiKeyRegistration(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeletePredictionApiKeyRegistrationRequest(ref request, ref callSettings); _callDeletePredictionApiKeyRegistration.Sync(request, callSettings); } /// <summary> /// Unregister an apiKey from using for predict method. /// </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 DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeletePredictionApiKeyRegistrationRequest(ref request, ref callSettings); return _callDeletePredictionApiKeyRegistration.Async(request, callSettings); } } public partial class ListPredictionApiKeyRegistrationsRequest : gaxgrpc::IPageRequest { } public partial class ListPredictionApiKeyRegistrationsResponse : gaxgrpc::IPageResponse<PredictionApiKeyRegistration> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<PredictionApiKeyRegistration> GetEnumerator() => PredictionApiKeyRegistrations.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Image transformations with filtering. Span generator base class // //---------------------------------------------------------------------------- using image_subpixel_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_subpixel_scale_e; namespace MatterHackers.Agg { public interface ISpanGenerator { void prepare(); void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len); }; public abstract class span_image_filter : ISpanGenerator { private IImageBufferAccessor imageBufferAccessor; protected ISpanInterpolator m_interpolator; protected ImageFilterLookUpTable m_filter; private double m_dx_dbl; private double m_dy_dbl; private int m_dx_int; private int m_dy_int; public span_image_filter() { } public span_image_filter(IImageBufferAccessor src, ISpanInterpolator interpolator) : this(src, interpolator, null) { } public span_image_filter(IImageBufferAccessor src, ISpanInterpolator interpolator, ImageFilterLookUpTable filter) { imageBufferAccessor = src; m_interpolator = interpolator; m_filter = (filter); m_dx_dbl = (0.5); m_dy_dbl = (0.5); m_dx_int = ((int)image_subpixel_scale_e.image_subpixel_scale / 2); m_dy_int = ((int)image_subpixel_scale_e.image_subpixel_scale / 2); } public void attach(IImageBufferAccessor v) { imageBufferAccessor = v; } public abstract void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len); public IImageBufferAccessor GetImageBufferAccessor() { return imageBufferAccessor; } public ImageFilterLookUpTable filter() { return m_filter; } public int filter_dx_int() { return (int)m_dx_int; } public int filter_dy_int() { return (int)m_dy_int; } public double filter_dx_dbl() { return m_dx_dbl; } public double filter_dy_dbl() { return m_dy_dbl; } public void interpolator(ISpanInterpolator v) { m_interpolator = v; } public void filter(ImageFilterLookUpTable v) { m_filter = v; } public void filter_offset(double dx, double dy) { m_dx_dbl = dx; m_dy_dbl = dy; m_dx_int = (int)agg_basics.iround(dx * (int)image_subpixel_scale_e.image_subpixel_scale); m_dy_int = (int)agg_basics.iround(dy * (int)image_subpixel_scale_e.image_subpixel_scale); } public void filter_offset(double d) { filter_offset(d, d); } public ISpanInterpolator interpolator() { return m_interpolator; } public void prepare() { } } public interface ISpanGeneratorFloat { void prepare(); void generate(RGBA_Floats[] span, int spanIndex, int x, int y, int len); }; public abstract class span_image_filter_float : ISpanGeneratorFloat { private IImageBufferAccessorFloat m_ImageBufferAccessor; protected ISpanInterpolatorFloat m_interpolator; protected IImageFilterFunction m_filterFunction; private float m_dx_dbl; private float m_dy_dbl; public span_image_filter_float() { } public span_image_filter_float(IImageBufferAccessorFloat src, ISpanInterpolatorFloat interpolator) : this(src, interpolator, null) { } public span_image_filter_float(IImageBufferAccessorFloat src, ISpanInterpolatorFloat interpolator, IImageFilterFunction filterFunction) { m_ImageBufferAccessor = src; m_interpolator = interpolator; m_filterFunction = filterFunction; m_dx_dbl = (0.5f); m_dy_dbl = (0.5f); } public void attach(IImageBufferAccessorFloat v) { m_ImageBufferAccessor = v; } public abstract void generate(RGBA_Floats[] span, int spanIndex, int x, int y, int len); public IImageBufferAccessorFloat source() { return m_ImageBufferAccessor; } public IImageFilterFunction filterFunction() { return m_filterFunction; } public float filter_dx_dbl() { return m_dx_dbl; } public float filter_dy_dbl() { return m_dy_dbl; } public void interpolator(ISpanInterpolatorFloat v) { m_interpolator = v; } public void filterFunction(IImageFilterFunction v) { m_filterFunction = v; } public void filter_offset(float dx, float dy) { m_dx_dbl = dx; m_dy_dbl = dy; } public void filter_offset(float d) { filter_offset(d, d); } public ISpanInterpolatorFloat interpolator() { return m_interpolator; } public void prepare() { } } /* //==============================================span_image_resample_affine //template<class Source> public class span_image_resample_affine : span_image_filter//<Source, span_interpolator_linear<trans_affine> > { //typedef Source IImageAccessor; //typedef span_interpolator_linear<trans_affine> ISpanInterpolator; //typedef span_image_filter<source_type, ISpanInterpolator> base_type; //-------------------------------------------------------------------- public span_image_resample_affine() { m_scale_limit=(200.0); m_blur_x=(1.0); m_blur_y=(1.0); } //-------------------------------------------------------------------- public span_image_resample_affine(IImageAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter) : base(src, inter, filter) { m_scale_limit(200.0); m_blur_x(1.0); m_blur_y(1.0); } //-------------------------------------------------------------------- public int scale_limit() { return uround(m_scale_limit); } public void scale_limit(int v) { m_scale_limit = v; } //-------------------------------------------------------------------- public double blur_x() { return m_blur_x; } public double blur_y() { return m_blur_y; } public void blur_x(double v) { m_blur_x = v; } public void blur_y(double v) { m_blur_y = v; } public void blur(double v) { m_blur_x = m_blur_y = v; } //-------------------------------------------------------------------- public void prepare() { double scale_x; double scale_y; base_type::interpolator().transformer().scaling_abs(&scale_x, &scale_y); if(scale_x * scale_y > m_scale_limit) { scale_x = scale_x * m_scale_limit / (scale_x * scale_y); scale_y = scale_y * m_scale_limit / (scale_x * scale_y); } if(scale_x < 1) scale_x = 1; if(scale_y < 1) scale_y = 1; if(scale_x > m_scale_limit) scale_x = m_scale_limit; if(scale_y > m_scale_limit) scale_y = m_scale_limit; scale_x *= m_blur_x; scale_y *= m_blur_y; if(scale_x < 1) scale_x = 1; if(scale_y < 1) scale_y = 1; m_rx = uround( scale_x * (double)(image_subpixel_scale)); m_rx_inv = uround(1.0/scale_x * (double)(image_subpixel_scale)); m_ry = uround( scale_y * (double)(image_subpixel_scale)); m_ry_inv = uround(1.0/scale_y * (double)(image_subpixel_scale)); } protected int m_rx; protected int m_ry; protected int m_rx_inv; protected int m_ry_inv; private double m_scale_limit; private double m_blur_x; private double m_blur_y; }; */ //=====================================================span_image_resample public abstract class span_image_resample : span_image_filter { public span_image_resample(IImageBufferAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter) : base(src, inter, filter) { m_scale_limit = (20); m_blur_x = ((int)image_subpixel_scale_e.image_subpixel_scale); m_blur_y = ((int)image_subpixel_scale_e.image_subpixel_scale); } //public abstract void prepare(); //public abstract unsafe void generate(rgba8* span, int x, int y, int len); //-------------------------------------------------------------------- private int scale_limit() { return m_scale_limit; } private void scale_limit(int v) { m_scale_limit = v; } //-------------------------------------------------------------------- private double blur_x() { return (double)(m_blur_x) / (double)((int)image_subpixel_scale_e.image_subpixel_scale); } private double blur_y() { return (double)(m_blur_y) / (double)((int)image_subpixel_scale_e.image_subpixel_scale); } private void blur_x(double v) { m_blur_x = (int)agg_basics.uround(v * (double)((int)image_subpixel_scale_e.image_subpixel_scale)); } private void blur_y(double v) { m_blur_y = (int)agg_basics.uround(v * (double)((int)image_subpixel_scale_e.image_subpixel_scale)); } public void blur(double v) { m_blur_x = m_blur_y = (int)agg_basics.uround(v * (double)((int)image_subpixel_scale_e.image_subpixel_scale)); } protected void adjust_scale(ref int rx, ref int ry) { if (rx < (int)image_subpixel_scale_e.image_subpixel_scale) rx = (int)image_subpixel_scale_e.image_subpixel_scale; if (ry < (int)image_subpixel_scale_e.image_subpixel_scale) ry = (int)image_subpixel_scale_e.image_subpixel_scale; if (rx > (int)image_subpixel_scale_e.image_subpixel_scale * m_scale_limit) { rx = (int)image_subpixel_scale_e.image_subpixel_scale * m_scale_limit; } if (ry > (int)image_subpixel_scale_e.image_subpixel_scale * m_scale_limit) { ry = (int)image_subpixel_scale_e.image_subpixel_scale * m_scale_limit; } rx = (rx * m_blur_x) >> (int)image_subpixel_scale_e.image_subpixel_shift; ry = (ry * m_blur_y) >> (int)image_subpixel_scale_e.image_subpixel_shift; if (rx < (int)image_subpixel_scale_e.image_subpixel_scale) rx = (int)image_subpixel_scale_e.image_subpixel_scale; if (ry < (int)image_subpixel_scale_e.image_subpixel_scale) ry = (int)image_subpixel_scale_e.image_subpixel_scale; } private int m_scale_limit; private int m_blur_x; private int m_blur_y; } }
/* Copyright (c) 2006 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.IO; using System.Collections; using System.Text; using System.Net; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using System.Collections.Generic; namespace Google.YouTube { public class Complaint : Entry { /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new ComplaintEntry(); } } /// <summary> /// readonly accessor to the typed underlying atom object /// </summary> public ComplaintEntry ComplaintEntry { get { EnsureInnerObject(); return this.AtomEntry as ComplaintEntry; } } /// <summary> /// sets the type of the complaint /// </summary> public ComplaintEntry.ComplaintType Type { get { if (this.ComplaintEntry != null) { return this.ComplaintEntry.Type; } return ComplaintEntry.ComplaintType.UNKNOWN; } set { EnsureInnerObject(); this.ComplaintEntry.Type = value; } } /// <summary> /// sets the verbose part of the complaint, stored in the yt:content element /// </summary> public string ComplaintDescription { get { if (this.ComplaintEntry != null) { return this.ComplaintEntry.Complaint; } return null; } set { EnsureInnerObject(); this.ComplaintEntry.Complaint = value; } } } /// <summary> /// the Comment entry for a Comments Feed, a feed of Comment for YouTube /// </summary> public class Comment : Entry { /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new CommentEntry(); } } /// <summary> /// readonly accessor to the underlying CommentEntry object. /// </summary> public CommentEntry CommentEntry { get { EnsureInnerObject(); return this.AtomEntry as CommentEntry; } } /// <summary> /// adds the replyToLinks to this comment /// </summary> /// <param name="c">The comment this comment is replying to</param> public void ReplyTo(Comment c) { if (c == null || c.CommentEntry == null) { throw new ArgumentNullException("c can not be null or c.CommentEntry can not be null"); } EnsureInnerObject(); if (this.CommentEntry != null) { this.CommentEntry.ReplyTo(c.CommentEntry); } } } /// <summary> /// the subscription entry for a subscriptionfeed Feed /// </summary> public class Subscription : Entry { /// <summary> /// readonly accessor for the SubscriptionEntry that is underneath this object. /// </summary> /// <returns></returns> public SubscriptionEntry SubscriptionEntry { get { EnsureInnerObject(); return this.AtomEntry as SubscriptionEntry; } } /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new SubscriptionEntry(); } } /// <summary> /// returns the subscription type /// </summary> /// <returns></returns> public SubscriptionEntry.SubscriptionType Type { get { EnsureInnerObject(); return this.SubscriptionEntry.Type; } set { EnsureInnerObject(); this.SubscriptionEntry.Type = value; } } /// <summary> /// The user who is the owner of this subscription /// </summary> public string UserName { get { EnsureInnerObject(); return this.SubscriptionEntry.UserName; } set { EnsureInnerObject(); this.SubscriptionEntry.UserName = value; } } /// <summary> /// if the subscription is a keyword query, this will be the /// subscribed to query term /// </summary> public string QueryString { get { EnsureInnerObject(); return this.SubscriptionEntry.QueryString; } set { EnsureInnerObject(); this.SubscriptionEntry.QueryString = value; } } /// <summary> /// the id of the playlist you are subscriped to /// </summary> public string PlaylistId { get { EnsureInnerObject(); return this.SubscriptionEntry.PlaylistId; } set { EnsureInnerObject(); this.SubscriptionEntry.PlaylistId = value; } } /// <summary> /// the human readable name of the playlist you are subscribed to /// </summary> public string PlaylistTitle { get { EnsureInnerObject(); return this.SubscriptionEntry.PlaylistTitle; } set { EnsureInnerObject(); this.SubscriptionEntry.PlaylistTitle = value; } } } /// <summary> /// the Activity entry for an Activities Feed, a feed of activities for the friends/contacts /// of the logged in user /// </summary> /// <returns></returns> public class Activity : Entry { /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new ActivityEntry(); } } /// <summary> /// readonly accessor for the YouTubeEntry that is underneath this object. /// </summary> /// <returns></returns> public ActivityEntry ActivityEntry { get { EnsureInnerObject(); return this.AtomEntry as ActivityEntry; } } /// <summary> /// specifies a unique ID that YouTube uses to identify a video. /// </summary> /// <returns></returns> public string VideoId { get { EnsureInnerObject(); if (this.ActivityEntry.VideoId != null) { return this.ActivityEntry.VideoId.Value; } return null; } } /// <summary> /// the type of the activity /// </summary> public ActivityType Type { get { EnsureInnerObject(); return this.ActivityEntry.Type; } } /// <summary> /// the username of the friend who was added, /// or the user whom was subscribed to /// </summary> public string Username { get { EnsureInnerObject(); if (this.ActivityEntry.Username != null) { return this.ActivityEntry.Username.Value; } return null; } } } /// <summary> /// the Playlist entry for a Playlist Feed, a feed of Playlist for YouTube /// </summary> public class Playlist : Entry { /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new PlaylistsEntry(); } } /// <summary> /// returns the internal atomentry as a PlaylistsEntry /// </summary> /// <returns></returns> public PlaylistsEntry PlaylistsEntry { get { EnsureInnerObject(); return this.AtomEntry as PlaylistsEntry; } } /// <summary> /// specifies the number of entries in a playlist feed. This tag appears in the entries in a /// playlists feed, where each entry contains information about a single playlist. /// </summary> /// <returns></returns> public int CountHint { get { EnsureInnerObject(); return this.PlaylistsEntry.CountHint; } } } /// <summary> /// the Show entry in feed&lt;Shows&gt; for YouTube /// </summary> public class Show : Entry { /// <summary> /// creates the inner show object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new ShowEntry(); } } /// <summary> /// returns the internal atomentry as a ShowEntry /// </summary> /// <returns></returns> public ShowEntry ShowEntry { get { EnsureInnerObject(); return this.AtomEntry as ShowEntry; } } /// <summary> /// contains a summary or description of a show. /// </summary> /// <returns></returns> public string Description { get { if (this.ShowEntry != null && this.ShowEntry.Media != null && this.ShowEntry.Media.Description != null) { return this.ShowEntry.Media.Description.Value; } return null; } set { EnsureInnerObject(); if (this.ShowEntry.Media == null) { this.ShowEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.ShowEntry.Media.Description == null) { this.ShowEntry.Media.Description = new MediaDescription(); } this.ShowEntry.Media.Description.Value = value; } } /// <summary> /// returns the URL for a feed of show seasons /// </summary> /// <returns></returns> public string SeasonUrl { get { if (this.ShowEntry != null && this.ShowEntry.FeedLink != null) { try { return this.ShowEntry.FeedLink.Href; } catch (FormatException) { return null; } } return null; } } /// <summary> /// returns the keywords for the video, see MediaKeywords for more /// </summary> /// <returns></returns> public string Keywords { get { if (this.ShowEntry != null && this.ShowEntry.Media != null && this.ShowEntry.Media.Keywords != null) { return this.ShowEntry.Media.Keywords.Value; } return null; } set { EnsureInnerObject(); if (this.ShowEntry.Media == null) { this.ShowEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.ShowEntry.Media.Keywords == null) { this.ShowEntry.Media.Keywords = new MediaKeywords(); } this.ShowEntry.Media.Keywords.Value = value; } } /// <summary> /// the title of the show. Overloaded to keep entry.title and the media.title /// in sync. /// </summary> /// <returns></returns> public override string Title { get { return base.Title; } set { base.Title = value; EnsureInnerObject(); if (this.ShowEntry.Media == null) { this.ShowEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.ShowEntry.Media.Title == null) { this.ShowEntry.Media.Title = new MediaTitle(); } this.ShowEntry.Media.Title.Value = value; } } /// <summary> /// returns the collection of thumbnails for the show /// </summary> /// <returns></returns> public ExtensionCollection<MediaThumbnail> Thumbnails { get { if (this.ShowEntry != null) { if (this.ShowEntry.Media == null) { this.ShowEntry.Media = new Google.GData.YouTube.MediaGroup(); } return this.ShowEntry.Media.Thumbnails; } return null; } } } /// <summary> /// the Show entry in feed&lt;Shows&gt; for YouTube /// </summary> public class ShowSeason : Entry { /// <summary> /// creates the inner show season object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new ShowSeasonEntry(); } } /// <summary> /// returns the internal atomentry as a ShowSeasonEntry /// </summary> /// <returns></returns> public ShowSeasonEntry ShowSeasonEntry { get { EnsureInnerObject(); return this.AtomEntry as ShowSeasonEntry; } } /// <summary> /// returns the count of expected Clips for the season /// </summary> /// <returns></returns> public int ClipCount { get { EnsureInnerObject(); if (this.ShowSeasonEntry.ClipLink != null) { return this.ShowSeasonEntry.ClipLink.CountHint; } return 0; } } /// <summary> /// returns the feed URL for season Clips /// </summary> /// <returns></returns> public string ClipUrl { get { EnsureInnerObject(); if (this.ShowSeasonEntry.ClipLink != null) { return this.ShowSeasonEntry.ClipLink.Href; } return null; } } /// <summary> /// returns the count of expected Episodes for the season /// </summary> /// <returns></returns> public int EpisodeCount { get { EnsureInnerObject(); if (this.ShowSeasonEntry.EpisodeLink != null) { return this.ShowSeasonEntry.EpisodeLink.CountHint; } return 0; } } /// <summary> /// returns the feed URL for season Episodes /// </summary> /// <returns></returns> public string EpisodeUrl { get { EnsureInnerObject(); if (this.ShowSeasonEntry.EpisodeLink != null) { return this.ShowSeasonEntry.EpisodeLink.Href; } return null; } } } /// <summary>the Video Entry in feed&lt;Videos&gt; for YouTube /// </summary> public class Video : Entry { /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new YouTubeEntry(); } } /// <summary> /// readonly accessor for the YouTubeEntry that is underneath this object. /// </summary> /// <returns></returns> public YouTubeEntry YouTubeEntry { get { EnsureInnerObject(); return this.AtomEntry as YouTubeEntry; } } /// <summary> /// specifies a unique ID that YouTube uses to identify a video. /// </summary> /// <returns></returns> public string VideoId { get { EnsureInnerObject(); return this.YouTubeEntry.VideoId; } set { EnsureInnerObject(); this.YouTubeEntry.VideoId = value; } } /// <summary> /// contains a summary or description of a video. This field is required in requests to /// upload or update a video's metadata. The description should be sentence-based, /// rather than a list of keywords, and may be displayed in search results. The description has a /// maximum length of 5000 characters and may contain all valid UTF-8 characters except &lt; and &gt; /// </summary> /// <returns></returns> public string Description { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Media != null && this.YouTubeEntry.Media.Description != null) { return this.YouTubeEntry.Media.Description.Value; } return null; } set { EnsureInnerObject(); if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.YouTubeEntry.Media.Description == null) { this.YouTubeEntry.Media.Description = new MediaDescription(); } this.YouTubeEntry.Media.Description.Value = value; } } /// <summary> /// the title of the Video. Overloaded to keep entry.title and the media.title /// in sync. /// </summary> /// <returns></returns> public override string Title { get { return base.Title; } set { base.Title = value; EnsureInnerObject(); if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.YouTubeEntry.Media.Title == null) { this.YouTubeEntry.Media.Title = new MediaTitle(); } this.YouTubeEntry.Media.Title.Value = value; } } /// <summary> /// returns the categories for the video /// </summary> /// <returns></returns> public ExtensionCollection<MediaCategory> Tags { get { EnsureInnerObject(); if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } return this.YouTubeEntry.Media.Categories; } } /// <summary> /// returns the keywords for the video, see MediaKeywords for more /// </summary> /// <returns></returns> public string Keywords { get { if (this.YouTubeEntry != null) { if (this.YouTubeEntry.Media != null) { if (this.YouTubeEntry.Media.Keywords != null) { return this.YouTubeEntry.Media.Keywords.Value; } } } return null; } set { EnsureInnerObject(); if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.YouTubeEntry.Media.Keywords == null) { this.YouTubeEntry.Media.Keywords = new MediaKeywords(); } this.YouTubeEntry.Media.Keywords.Value = value; } } /// <summary> /// returns the collection of thumbnails for the video /// </summary> /// <returns></returns> public ExtensionCollection<MediaThumbnail> Thumbnails { get { if (this.YouTubeEntry != null) { if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } return this.YouTubeEntry.Media.Thumbnails; } return null; } } /// <summary> /// returns the collection of thumbnails for the vido /// </summary> /// <returns></returns> public ExtensionCollection<Google.GData.YouTube.MediaContent> Contents { get { if (this.YouTubeEntry != null) { if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } return this.YouTubeEntry.Media.Contents; } return null; } } /// <summary> /// specifies a URL where the full-length video is available through a media player that runs /// inside a web browser. In a YouTube Data API response, this specifies the URL for the page /// on YouTube's website that plays the video /// </summary> /// <returns></returns> public Uri WatchPage { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Media != null && this.YouTubeEntry.Media.Player != null) { return new Uri(this.YouTubeEntry.Media.Player.Url); } return null; } } /// <summary> /// identifies the owner of a video. /// </summary> /// <returns></returns> public string Uploader { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Media != null && this.YouTubeEntry.Media.Credit != null) { return this.YouTubeEntry.Media.Credit.Value; } return null; } set { EnsureInnerObject(); if (this.YouTubeEntry.Media == null) { this.YouTubeEntry.Media = new Google.GData.YouTube.MediaGroup(); } if (this.YouTubeEntry.Media.Credit == null) { this.YouTubeEntry.Media.Credit = new Google.GData.YouTube.MediaCredit(); } this.YouTubeEntry.Media.Credit.Value = value; } } /// <summary> /// access to the Media group subelement /// </summary> public Google.GData.YouTube.MediaGroup Media { get { if (this.YouTubeEntry != null) { return this.YouTubeEntry.Media; } return null; } set { EnsureInnerObject(); this.YouTubeEntry.Media = value; } } /// <summary> /// returns the viewcount for the video /// </summary> /// <returns></returns> public int ViewCount { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Statistics != null) { return Int32.Parse(this.YouTubeEntry.Statistics.ViewCount); } return -1; } } /// <summary> /// returns the number of comments for the video /// </summary> /// <returns></returns> public int CommmentCount { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Comments != null && this.YouTubeEntry.Comments.FeedLink != null) { return this.YouTubeEntry.Comments.FeedLink.CountHint; } return -1; } } /// <summary> /// returns the rating for a video /// </summary> /// <returns></returns> public int Rating { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Rating != null) { try { return this.YouTubeEntry.Rating.Value; } catch (FormatException) { return -1; } } return -1; } set { EnsureInnerObject(); if (this.YouTubeEntry.Rating == null) { this.YouTubeEntry.Rating = new Rating(); } this.YouTubeEntry.Rating.Value = (int)value; } } /// <summary> /// returns the average rating for a video /// </summary> /// <returns></returns> public double RatingAverage { get { if (this.YouTubeEntry != null && this.YouTubeEntry.Rating != null) { return this.YouTubeEntry.Rating.Average; } return -1; } } /// <summary> /// returns the ratings Uri, to post a rating to. /// </summary> public Uri RatingsUri { get { Uri ratings = null; if (this.YouTubeEntry != null) { AtomUri r = this.YouTubeEntry.RatingsLink; if (r != null) { ratings = new Uri(r.ToString()); } } return ratings; } } /// <summary> /// returns the response Uri, to post a video response to. /// </summary> public Uri ResponseUri { get { Uri response = null; if (this.YouTubeEntry != null) { AtomUri r = this.YouTubeEntry.VideoResponsesUri.ToString(); if (r != null) { response = new Uri(r.ToString()); } } return response; } } /// <summary> /// returns the complaint Uri, to post a complaint to. /// </summary> public Uri ComplaintUri { get { Uri uri = null; if (this.YouTubeEntry != null) { AtomUri r = this.YouTubeEntry.ComplaintUri; if (r != null) { uri = new Uri(r.ToString()); } } return uri; } } /// <summary> /// boolean property shortcut to set the mediagroup/yt:private element. Setting this to true /// adds the element, if not already there (otherwise nothing happens) /// setting this to false, removes it /// </summary> /// <returns></returns> public bool Private { get { if (this.YouTubeEntry != null) { return this.YouTubeEntry.Private; } return false; } set { EnsureInnerObject(); this.YouTubeEntry.Private = value; } } /// <summary> /// The yt:state tag contains information that describes the status of a video. /// Video entries that contain a yt:state tag are not playable. /// For videos that failed to upload or were rejected after the upload process, the reasonCode /// attribute and the tag value provide insight into the reason for the upload problem. /// Deleted entries only appear in playlist and inbox feeds and are only visible to the playlist /// or inbox owner. /// </summary> public State Status { get { EnsureInnerObject(); return this.YouTubeEntry.State; } } public int? EpisodeNumber { get { EnsureInnerObject(); if (this.YouTubeEntry.Episode != null) { return this.YouTubeEntry.Episode.Number; } return null; } } } /// <summary> /// subclass of a video to represent a video that is part of a playlist /// </summary> public class PlayListMember : Video { /// <summary> /// creates the inner contact object when needed /// </summary> /// <returns></returns> protected override void EnsureInnerObject() { if (this.AtomEntry == null) { this.AtomEntry = new PlaylistEntry(); } } /// <summary> /// readonly accessor for the YouTubeEntry that is underneath this object. /// </summary> /// <returns></returns> public PlaylistEntry PlaylistEntry { get { EnsureInnerObject(); return this.AtomEntry as PlaylistEntry; } } /// <summary> /// if the video is a playlist reference, gets and sets its position in the playlist /// </summary> public int Position { get { if (this.PlaylistEntry != null) { return this.PlaylistEntry.Position; } return -1; } set { EnsureInnerObject(); this.PlaylistEntry.Position = value; } } } /// <summary> /// YouTube specific class for request settings, /// adds support for developer key and clientid /// </summary> /// <returns></returns> public class YouTubeRequestSettings : RequestSettings { private string developerKey; /// <summary> /// A constructor for a readonly scenario. /// </summary> /// <param name="applicationName">The name of the application</param> /// <param name="developerKey">the developer key to use</param> /// <returns></returns> public YouTubeRequestSettings(string applicationName, string developerKey) : base(applicationName) { this.developerKey = developerKey; } /// <summary> /// A constructor for a client login scenario /// </summary> /// <param name="applicationName">The name of the application</param> /// <param name="developerKey">the developer key to use</param> /// <param name="userName">the username</param> /// <param name="passWord">the password</param> /// <returns></returns> public YouTubeRequestSettings(string applicationName, string developerKey, string userName, string passWord) : base(applicationName, userName, passWord) { this.developerKey = developerKey; } /// <summary> /// a constructor for a web application authentication scenario /// </summary> /// <param name="applicationName">The name of the application</param> /// <param name="developerKey">the developer key to use</param> /// <param name="authSubToken">the authentication token</param> /// <returns></returns> public YouTubeRequestSettings(string applicationName, string developerKey, string authSubToken) : base(applicationName, authSubToken) { this.developerKey = developerKey; } /// <summary> /// a constructor for OpenAuthentication login use cases using 2 or 3 legged oAuth /// </summary> /// <param name="applicationName">The name of the application</param> /// <param name="developerKey">the developer key to use</param> /// <param name="consumerKey">the consumerKey to use</param> /// <param name="consumerSecret">the consumerSecret to use</param> /// <param name="token">The token to be used</param> /// <param name="tokenSecret">The tokenSecret to be used</param> /// <param name="user">the username to use</param> /// <param name="domain">the domain to use</param> /// <returns></returns> public YouTubeRequestSettings(string applicationName, string developerKey, string consumerKey, string consumerSecret, string token, string tokenSecret, string user, string domain) : base(applicationName, consumerKey, consumerSecret, token, tokenSecret, user, domain) { this.developerKey = developerKey; } /// <summary> /// returns the developer key /// </summary> /// <returns></returns> public string DeveloperKey { get { return this.developerKey; } } } /// <summary> /// The YouTube Data API allows applications to perform functions normally /// executed on the YouTube website. The API enables your application to search /// for YouTube videos and to retrieve standard video feeds, comments and video /// responses. /// In addition, the API lets your application upload videos to YouTube or /// update existing videos. Your can also retrieve playlists, subscriptions, /// user profiles and more. Finally, your application can submit /// authenticated requests to enable users to create playlists, /// subscriptions, contacts and other account-specific entities. /// </summary> /// <example> /// The following code illustrates a possible use of /// the <c>YouTubeRequest</c> object: /// <code> /// YouTubeRequestSettings settings = new YouTubeRequestSettings("yourApp", "yourClient", "yourKey"); /// settings.PageSize = 50; /// settings.AutoPaging = true; /// YouTubeRequest f = new YouTubeRequest(settings); /// Feed<Video> feed = f.GetStandardFeed(YouTubeQuery.MostPopular); /// /// foreach (Video v in feed.Entries) /// { /// Feed<Comment> list= f.GetComments(v); /// foreach (Comment c in list.Entries) /// { /// Console.WriteLine(c.Title); /// } /// } /// </code> /// </example> public class YouTubeRequest : FeedRequest<YouTubeService> { /// <summary> /// default constructor for a YouTubeRequest /// </summary> /// <param name="settings"></param> public YouTubeRequest(YouTubeRequestSettings settings) : base(settings) { if (settings.DeveloperKey != null) { this.Service = new YouTubeService(settings.Application, settings.DeveloperKey); } else { this.Service = new YouTubeService(settings.Application); } PrepareService(); } /// <summary> /// returns a Feed of videos for a given username /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Videos</returns> public Feed<Video> GetVideoFeed(string user) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(YouTubeQuery.CreateUserUri(user)); return PrepareFeed<Video>(q); } /// <summary> /// returns one of the youtube default feeds. /// </summary> /// <param name="feedspec">the string representation of the URI to use</param> /// <returns>a feed of Videos</returns> public Feed<Video> GetStandardFeed(string feedspec) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(feedspec); return PrepareFeed<Video>(q); } /// <summary> /// returns the youtube standard show feed. /// </summary> /// <param name="feedspec">the string representation of the URI to use</param> /// <returns>a feed of Videos</returns> public Feed<Show> GetStandardShowFeed(string feedspec) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(feedspec); return PrepareFeed<Show>(q); } /// <summary> /// returns a Feed of favorite videos for a given username /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Videos</returns> public Feed<Video> GetFavoriteFeed(string user) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(YouTubeQuery.CreateFavoritesUri(user)); return PrepareFeed<Video>(q); } /// <summary> /// returns a Feed of subscriptions for a given username /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Videos</returns> public Feed<Subscription> GetSubscriptionsFeed(string user) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(YouTubeQuery.CreateSubscriptionUri(user)); return PrepareFeed<Subscription>(q); } /// <summary> /// returns a Feed of playlists for a given username /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Videos</returns> public Feed<Playlist> GetPlaylistsFeed(string user) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(YouTubeQuery.CreatePlaylistsUri(user)); return PrepareFeed<Playlist>(q); } /// <summary> /// returns a Feed of shows for a given username /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Shows</returns> public Feed<Show> GetShowsFeed(string user) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(YouTubeQuery.CreateShowsUri(user)); return PrepareFeed<Show>(q); } /// <summary> /// returns a Feed of seasons for a given show /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Shows</returns> public Feed<ShowSeason> GetShowSeasonFeed(string uri) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(uri); return PrepareFeed<ShowSeason>(q); } /// <summary> /// returns a Feed of videos for a given show season /// </summary> /// <param name="user">the username</param> /// <returns>a feed of Shows</returns> public Feed<Video> GetShowSeasonVideos(string uri) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(uri); return PrepareFeed<Video>(q); } /// <summary> /// returns the related videos for a given video /// </summary> /// <param name="v"></param> /// <returns></returns> public Feed<Video> GetRelatedVideos(Video v) { if (v.YouTubeEntry != null) { if (v.YouTubeEntry.RelatedVideosUri != null) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(v.YouTubeEntry.RelatedVideosUri.ToString()); return PrepareFeed<Video>(q); } } return null; } /// <summary> /// gets the response videos for a given video /// </summary> /// <param name="v"></param> /// <returns></returns> public Feed<Video> GetResponseVideos(Video v) { if (v.YouTubeEntry != null) { if (v.YouTubeEntry.VideoResponsesUri != null) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(v.YouTubeEntry.VideoResponsesUri.ToString()); return PrepareFeed<Video>(q); } } return null; } /// <summary> /// gets the comments for a given video /// </summary> /// <param name="v"></param> /// <returns></returns> public Feed<Comment> GetComments(Video v) { if (v.YouTubeEntry != null && v.YouTubeEntry.Comments != null && v.YouTubeEntry.Comments.FeedLink != null && v.YouTubeEntry.Comments.FeedLink.Href != null) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(v.YouTubeEntry.Comments.FeedLink.Href); return PrepareFeed<Comment>(q); } return new Feed<Comment>(null); } /// <summary> /// gets the activities that your contacts/friends did recently /// </summary> /// <returns></returns> public Feed<Activity> GetActivities() { return GetActivities(DateTime.MinValue); } /// <summary> /// gets the activities for a list of users /// </summary> /// <param name="youTubeUsers">The list of youtube user ids</param> /// <returns></returns> public Feed<Activity> GetActivities(List<string> youTubeUsers) { return GetActivities(youTubeUsers, DateTime.MinValue); } /// <summary> /// gets the activities for a list of users /// </summary> /// <param name="youTubeUsers">The list of youtube user ids</param> /// <returns></returns> public Feed<Activity> GetActivities(List<string> youTubeUsers, DateTime since) { if (this.Settings == null) { return new Feed<Activity>(null); } UserActivitiesQuery q = new UserActivitiesQuery(); q.ModifiedSince = since; q.Authors = youTubeUsers; PrepareQuery(q); return PrepareFeed<Activity>(q); } /// <summary> /// gets the activities that your contacts/friends did recently, from the /// given datetime point /// </summary> /// <returns></returns> public Feed<Activity> GetActivities(DateTime since) { if (this.Settings == null) { return new Feed<Activity>(null); } ActivitiesQuery q = new ActivitiesQuery(); q.ModifiedSince = since; PrepareQuery(q); return PrepareFeed<Activity>(q); } /** <summary> returns the feed of videos for a given playlist </summary> <example> The following code illustrates a possible use of the <c>GetPlaylist</c> method: <code> YouTubeRequestSettings settings = new YouTubeRequestSettings("yourApp", "yourClient", "yourKey", "username", "pwd"); YouTubeRequest f = new YouTubeRequest(settings); Feed&lt;Playlist&gt; feed = f.GetPlaylistsFeed(null); </code> </example> <param name="p">the playlist to get the videos for</param> <returns></returns> */ public Feed<PlayListMember> GetPlaylist(Playlist p) { if (p.AtomEntry != null && p.AtomEntry.Content != null && p.AtomEntry.Content.AbsoluteUri != null) { YouTubeQuery q = PrepareQuery<YouTubeQuery>(p.AtomEntry.Content.AbsoluteUri); return PrepareFeed<PlayListMember>(q); } return new Feed<PlayListMember>(null); } /// <summary> /// uploads or inserts a new video for the default authenticated user. /// </summary> /// <param name="v">the created video to be used</param> /// <returns></returns> public Video Upload(Video v) { return Upload(null, v); } /// <summary> /// uploads or inserts a new video for a given user. /// </summary> /// <param name="userName">if this is null the default authenticated user will be used</param> /// <param name="v">the created video to be used</param> /// <returns></returns> public Video Upload(string userName, Video v) { Video rv = null; YouTubeEntry e = this.Service.Upload(userName, v.YouTubeEntry); if (e != null) { rv = new Video(); rv.AtomEntry = e; } return rv; } /// <summary> /// creates the form upload token for a video /// </summary> /// <param name="v">the created video to be used</param> /// <returns></returns> public FormUploadToken CreateFormUploadToken(Video v) { if (v.YouTubeEntry.MediaSource != null) { throw new ArgumentException("The Video should not have a media file attached to it"); } return this.Service.FormUpload(v.YouTubeEntry); } /// <summary> /// returns the video this activity was related to /// </summary> /// <param name="activity"></param> /// <returns></returns> public Video GetVideoForActivity(Activity activity) { Video rv = null; if (activity.ActivityEntry != null) { AtomUri address = activity.ActivityEntry.VideoLink; YouTubeQuery q = PrepareQuery<YouTubeQuery>(address.ToString()); YouTubeFeed f = this.Service.Query(q); if (f != null && f.Entries.Count > 0) { rv = new Video(); rv.AtomEntry = f.Entries[0]; } } return rv; } /// <summary> /// adds a comment to a video /// </summary> /// <param name="v">the video you want to comment on</param> /// <param name="c">the comment you want to post</param> /// <returns></returns> public Comment AddComment(Video v, Comment c) { Comment rc = null; if (v.YouTubeEntry != null && v.YouTubeEntry.Comments != null && v.YouTubeEntry.Comments.FeedLink != null) { Uri target = CreateUri(v.YouTubeEntry.Comments.FeedLink.Href); rc = new Comment(); rc.AtomEntry = this.Service.Insert(target, c.AtomEntry); } return rc; } /// <summary> /// adds a video to an existing playlist /// </summary> /// <param name="m">the new playlistmember</param> /// <param name="p">the playlist to add tot</param> /// <returns></returns> public PlayListMember AddToPlaylist(Playlist p, PlayListMember m) { PlayListMember newMember = null; if (p.PlaylistsEntry != null && p.PlaylistsEntry.Content != null && p.PlaylistsEntry.Content.Src != null) { Uri target = CreateUri(p.PlaylistsEntry.Content.Src.Content); newMember = new PlayListMember(); newMember.AtomEntry = this.Service.Insert(target, m.AtomEntry); } return newMember; } /// <summary> /// Takes a list of activities, and gets the video meta data from youtube /// for those activites that identify a video /// </summary> /// <param name="list">a list of activities</param> /// <returns>a video feed, with no entries, if there were no video related activities</returns> public Feed<Video> GetVideoMetaData(List<Activity> list) { Feed<Video> meta = null; if (list.Count > 0) { List<Video> videos = new List<Video>(); foreach (Activity a in list) { if (a.VideoId != null) { Video v = new Video(); v.Id = YouTubeQuery.CreateVideoUri(a.VideoId); videos.Add(v); } } if (videos.Count > 0) { meta = this.Batch(videos, CreateUri(YouTubeQuery.BatchVideoUri), GDataBatchOperationType.query); } } return meta == null ? new Feed<Video>(null) : meta; } /// <summary> /// returns a single Video (the first) from that stream. Usefull to parse insert/update /// response streams /// </summary> /// <param name="inputStream"></param> /// <returns></returns> public Video ParseVideo(Stream inputStream) { return ParseEntry<Video>(inputStream, new Uri(YouTubeQuery.DefaultVideoUri)); } } }
// Copyright (c) 2013-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using System.Collections.Generic; using System.Threading.Tasks; using SharpNav.Geometry; #if MONOGAME using Vector3 = Microsoft.Xna.Framework.Vector3; #elif OPENTK using Vector3 = OpenTK.Vector3; #elif SHARPDX using Vector3 = SharpDX.Vector3; #endif namespace SharpNav { /// <summary> /// A Heightfield represents a "voxel" grid represented as a 2-dimensional grid of <see cref="Cell"/>s. /// </summary> public partial class Heightfield { private BBox3 bounds; private int width, height, length; private float cellSize, cellHeight; private Cell[] cells; /// <summary> /// Initializes a new instance of the <see cref="Heightfield"/> class. /// </summary> /// <param name="b">The world-space bounds.</param> /// <param name="settings">The settings to build with.</param> public Heightfield(BBox3 b, NavMeshGenerationSettings settings) : this(b, settings.CellSize, settings.CellHeight) { } /// <summary> /// Initializes a new instance of the <see cref="Heightfield"/> class. /// </summary> /// <param name="b">The world-space bounds.</param> /// <param name="cellSize">The world-space size of each cell in the XZ plane.</param> /// <param name="cellHeight">The world-space height of each cell.</param> public Heightfield(BBox3 b, float cellSize, float cellHeight) { if (!BBox3.IsValid(ref bounds)) throw new ArgumentException("The bounds are considered invalid. See BBox3.IsValid for details."); if (cellSize <= 0) throw new ArgumentOutOfRangeException("cellSize", "Cell size must be greater than 0."); if (cellHeight <= 0) throw new ArgumentOutOfRangeException("cellHeight", "Cell height must be greater than 0."); this.cellSize = cellSize; this.cellHeight = cellHeight; this.bounds = b; //make sure the bbox contains all the possible voxels. width = (int)Math.Ceiling((b.Max.X - b.Min.X) / cellSize); height = (int)Math.Ceiling((b.Max.Y - b.Min.Y) / cellHeight); length = (int)Math.Ceiling((b.Max.Z - b.Min.Z) / cellSize); bounds.Max.X = bounds.Min.X + width * cellSize; bounds.Max.Y = bounds.Min.Y + height * cellHeight; bounds.Max.Z = bounds.Min.Z + length * cellSize; cells = new Cell[width * length]; for (int i = 0; i < cells.Length; i++) cells[i] = new Cell(height); } /// <summary> /// Gets the bounding box of the heightfield. /// </summary> public BBox3 Bounds { get { return bounds; } } /// <summary> /// Gets the world-space minimum. /// </summary> /// <value>The minimum.</value> public Vector3 Minimum { get { return bounds.Min; } } /// <summary> /// Gets the world-space maximum. /// </summary> /// <value>The maximum.</value> public Vector3 Maximum { get { return bounds.Max; } } /// <summary> /// Gets the number of cells in the X direction. /// </summary> /// <value>The width.</value> public int Width { get { return width; } } /// <summary> /// Gets the number of cells in the Y (up) direction. /// </summary> /// <value>The height.</value> public int Height { get { return height; } } /// <summary> /// Gets the number of cells in the Z direction. /// </summary> /// <value>The length.</value> public int Length { get { return length; } } /// <summary> /// Gets the size of a cell (voxel). /// </summary> /// <value>The size of the cell.</value> public Vector3 CellSize { get { return new Vector3(cellSize, cellHeight, cellSize); } } /// <summary> /// Gets the size of a cell on the X and Z axes. /// </summary> public float CellSizeXZ { get { return cellSize; } } /// <summary> /// Gets the size of a cell on the Y axis. /// </summary> public float CellHeight { get { return cellHeight; } } /// <summary> /// Gets the total number of spans. /// </summary> public int SpanCount { get { int count = 0; for (int i = 0; i < cells.Length; i++) count += cells[i].WalkableSpanCount; return count; } } /// <summary> /// Gets the <see cref="Cell"/> at the specified coordinate. /// </summary> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <returns>The cell at [x, y].</returns> public Cell this[int x, int y] { get { if (x < 0 || x >= width || y < 0 || y >= length) throw new ArgumentOutOfRangeException(); return cells[y * width + x]; } } /// <summary> /// Gets the <see cref="Cell"/> at the specified index. /// </summary> /// <param name="i">The index.</param> /// <returns>The cell at index i.</returns> public Cell this[int i] { get { if (i < 0 || i >= cells.Length) throw new ArgumentOutOfRangeException(); return cells[i]; } } /// <summary> /// Gets the <see cref="Span"/> at the reference. /// </summary> /// <param name="spanRef">A reference to a span.</param> /// <returns>The span at the reference.</returns> public Span this[SpanReference spanRef] { get { return cells[spanRef.Y * width + spanRef.X].Spans[spanRef.Index]; } } /// <summary> /// Filters the heightmap to allow two neighboring spans have a small difference in maximum height (such as /// stairs) to be walkable. /// </summary> /// <remarks> /// This filter may override the results of <see cref="FilterLedgeSpans"/>. /// </remarks> /// <param name="walkableClimb">The maximum difference in height to filter.</param> public void FilterLowHangingWalkableObstacles(int walkableClimb) { //Loop through every cell in the Heightfield for (int i = 0; i < cells.Length; i++) { Cell c = cells[i]; List<Span> spans = c.MutableSpans; //store the first span's data as the "previous" data Area prevArea = Area.Null; bool prevWalkable = prevArea != Area.Null; int prevMax = 0; //iterate over all the spans in the cell for (int j = 0; j < spans.Count; j++) { Span s = spans[j]; bool walkable = s.Area != Area.Null; //if the current span isn't walkable but there's a walkable span right below it, //mark this span as walkable too. if (!walkable && prevWalkable) { if (Math.Abs(s.Maximum - prevMax) < walkableClimb) s.Area = prevArea; } //save changes back to the span list. spans[j] = s; //set the previous data for the next iteration prevArea = s.Area; prevWalkable = walkable; prevMax = s.Maximum; } } } /// <summary> /// If two spans have little vertical space in between them, /// then span is considered unwalkable /// </summary> /// <param name="walkableHeight">The clearance.</param> public void FilterWalkableLowHeightSpans(int walkableHeight) { for (int i = 0; i < cells.Length; i++) { Cell c = cells[i]; List<Span> spans = c.MutableSpans; //Iterate over all spans for (int j = 0; j < spans.Count - 1; j++) { Span currentSpan = spans[j]; //too low, not enough space to walk through if ((spans[j + 1].Minimum - currentSpan.Maximum) <= walkableHeight) { currentSpan.Area = Area.Null; spans[j] = currentSpan; } } } } /// <summary> /// A ledge is unwalkable because the difference between the maximum height of two spans /// is too large of a drop (i.e. greater than walkableClimb). /// </summary> /// <param name="walkableHeight">The maximum walkable height to filter.</param> /// <param name="walkableClimb">The maximum walkable climb to filter.</param> public void FilterLedgeSpans(int walkableHeight, int walkableClimb) { //Mark border spans. Parallel.For(0, length, y => { //for (int y = 0; y < length; y++) //{ for (int x = 0; x < width; x++) { Cell c = cells[x + y * width]; List<Span> spans = c.MutableSpans; //Examine all the spans in each cell for (int i = 0; i < spans.Count; i++) { Span currentSpan = spans[i]; // Skip non walkable spans. if (currentSpan.Area == Area.Null) continue; int bottom = (int)currentSpan.Maximum; int top = (i == spans.Count - 1) ? int.MaxValue : spans[i + 1].Minimum; // Find neighbours minimum height. int minHeight = int.MaxValue; // Min and max height of accessible neighbours. int accessibleMin = currentSpan.Maximum; int accessibleMax = currentSpan.Maximum; for (var dir = Direction.West; dir <= Direction.South; dir++) { int dx = x + dir.GetHorizontalOffset(); int dy = y + dir.GetVerticalOffset(); // Skip neighbours which are out of bounds. if (dx < 0 || dy < 0 || dx >= width || dy >= length) { minHeight = Math.Min(minHeight, -walkableClimb - bottom); continue; } // From minus infinity to the first span. Cell neighborCell = cells[dy * width + dx]; List<Span> neighborSpans = neighborCell.MutableSpans; int neighborBottom = -walkableClimb; int neighborTop = neighborSpans.Count > 0 ? neighborSpans[0].Minimum : int.MaxValue; // Skip neightbour if the gap between the spans is too small. if (Math.Min(top, neighborTop) - Math.Max(bottom, neighborBottom) > walkableHeight) minHeight = Math.Min(minHeight, neighborBottom - bottom); // Rest of the spans. for (int j = 0; j < neighborSpans.Count; j++) { Span currentNeighborSpan = neighborSpans[j]; neighborBottom = currentNeighborSpan.Maximum; neighborTop = (j == neighborSpans.Count - 1) ? int.MaxValue : neighborSpans[j + 1].Minimum; // Skip neightbour if the gap between the spans is too small. if (Math.Min(top, neighborTop) - Math.Max(bottom, neighborBottom) > walkableHeight) { minHeight = Math.Min(minHeight, neighborBottom - bottom); // Find min/max accessible neighbour height. if (Math.Abs(neighborBottom - bottom) <= walkableClimb) { if (neighborBottom < accessibleMin) accessibleMin = neighborBottom; if (neighborBottom > accessibleMax) accessibleMax = neighborBottom; } } } } // The current span is close to a ledge if the drop to any // neighbour span is less than the walkableClimb. if (minHeight < -walkableClimb) currentSpan.Area = Area.Null; // If the difference between all neighbours is too large, // we are at steep slope, mark the span as ledge. if ((accessibleMax - accessibleMin) > walkableClimb) currentSpan.Area = Area.Null; //save span data spans[i] = currentSpan; } } //} }); } } }
// // 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 Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql.LegacySdk; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql.LegacySdk { /// <summary> /// Represents all the operations of Azure SQL Database that interact with /// Azure Key Vault Server Keys. Contains operations to: Add, Delete, and /// Retrieve Server Ke. /// </summary> internal partial class ServerKeyOperations : IServiceOperations<SqlManagementClient>, IServerKeyOperations { /// <summary> /// Initializes a new instance of the ServerKeyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServerKeyOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Begins creating a new Azure SQL Server Key or updating an existing /// Azure SQL Server Key. To determine the status of the operation /// call GetCreateOrUpdateOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which to add the /// Server Key. /// </param> /// <param name='keyName'> /// Required. The name of the Azure SQL Server Key. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// Server Key. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Azure Sql Server Key operation request. /// </returns> public async Task<ServerKeyCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string keyName, ServerKeyCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (keyName == null) { throw new ArgumentNullException("keyName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("keyName", keyName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/keys/"; url = url + Uri.EscapeDataString(keyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serverKeyCreateOrUpdateParametersValue = new JObject(); requestDoc = serverKeyCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); serverKeyCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.Uri != null) { propertiesValue["uri"] = parameters.Properties.Uri; } if (parameters.Properties.ServerKeyType != null) { propertiesValue["serverKeyType"] = parameters.Properties.ServerKeyType; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerKeyCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerKeyCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken operationValue = responseDoc["operation"]; if (operationValue != null && operationValue.Type != JTokenType.Null) { string operationInstance = ((string)operationValue); result.Operation = operationInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); result.StartTime = startTimeInstance; } ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } ServerKey serverKeyInstance = new ServerKey(); result.ServerKey = serverKeyInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ServerKeyProperties propertiesInstance = new ServerKeyProperties(); serverKeyInstance.Properties = propertiesInstance; JToken serverKeyTypeValue = propertiesValue2["serverKeyType"]; if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null) { string serverKeyTypeInstance = ((string)serverKeyTypeValue); propertiesInstance.ServerKeyType = serverKeyTypeInstance; } JToken uriValue = propertiesValue2["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { string uriInstance = ((string)uriValue); propertiesInstance.Uri = uriInstance; } JToken thumbprintValue = propertiesValue2["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); propertiesInstance.Thumbprint = thumbprintInstance; } JToken creationDateValue = propertiesValue2["creationDate"]; if (creationDateValue != null && creationDateValue.Type != JTokenType.Null) { DateTime creationDateInstance = ((DateTime)creationDateValue); propertiesInstance.CreationDate = creationDateInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverKeyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverKeyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverKeyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverKeyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverKeyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begins deleting an existing Azure SQL Server Key.To determine the /// status of the operation call GetDeleteOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Key belongs /// </param> /// <param name='keyName'> /// Required. The name of the Azure SQL Server Key. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to an Azure Sql Server Key Delete request. /// </returns> public async Task<ServerKeyDeleteResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (keyName == null) { throw new ArgumentNullException("keyName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("keyName", keyName); TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/keys/"; url = url + Uri.EscapeDataString(keyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerKeyDeleteResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerKeyDeleteResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken operationValue = responseDoc["operation"]; if (operationValue != null && operationValue.Type != JTokenType.Null) { string operationInstance = ((string)operationValue); result.Operation = operationInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); result.StartTime = startTimeInstance; } ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates a new Azure SQL Server Key or updates an existing Azure SQL /// Server Key. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which to add the /// Server Key. /// </param> /// <param name='keyName'> /// Required. The name of the Azure SQL Server Key. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// Server Key. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Azure Sql Server Key operation request. /// </returns> public async Task<ServerKeyCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string keyName, ServerKeyCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("keyName", keyName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ServerKeyCreateOrUpdateResponse response = await client.ServerKey.BeginCreateOrUpdateAsync(resourceGroupName, serverName, keyName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ServerKeyCreateOrUpdateResponse result = await client.ServerKey.GetCreateOrUpdateOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 5; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await Task.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.ServerKey.GetCreateOrUpdateOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Deletes an existing Azure SQL Server Key. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server to which the Azure SQL /// Server Key belongs /// </param> /// <param name='keyName'> /// Required. The name of the Azure SQL Server Key to be deleted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to an Azure Sql Server Key Delete request. /// </returns> public async Task<ServerKeyDeleteResponse> DeleteAsync(string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("keyName", keyName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ServerKeyDeleteResponse response = await client.ServerKey.BeginDeleteAsync(resourceGroupName, serverName, keyName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ServerKeyDeleteResponse result = await client.ServerKey.GetDeleteOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 5; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await Task.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.ServerKey.GetDeleteOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Gets an Azure Sql Server Key. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that has the /// key. /// </param> /// <param name='keyName'> /// Required. The name of the Azure Key Vault Key to be retrieved from /// the Azure SQL Database Server. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server Key request. /// </returns> public async Task<ServerKeyGetResponse> GetAsync(string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (keyName == null) { throw new ArgumentNullException("keyName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("keyName", keyName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/keys/"; url = url + Uri.EscapeDataString(keyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.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) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerKeyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerKeyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ServerKey serverKeyInstance = new ServerKey(); result.ServerKey = serverKeyInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerKeyProperties propertiesInstance = new ServerKeyProperties(); serverKeyInstance.Properties = propertiesInstance; JToken serverKeyTypeValue = propertiesValue["serverKeyType"]; if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null) { string serverKeyTypeInstance = ((string)serverKeyTypeValue); propertiesInstance.ServerKeyType = serverKeyTypeInstance; } JToken uriValue = propertiesValue["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { string uriInstance = ((string)uriValue); propertiesInstance.Uri = uriInstance; } JToken thumbprintValue = propertiesValue["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); propertiesInstance.Thumbprint = thumbprintInstance; } JToken creationDateValue = propertiesValue["creationDate"]; if (creationDateValue != null && creationDateValue.Type != JTokenType.Null) { DateTime creationDateInstance = ((DateTime)creationDateValue); propertiesInstance.CreationDate = creationDateInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverKeyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverKeyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverKeyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverKeyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverKeyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure SQL Server Key create or update /// operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Azure Sql Server Key operation request. /// </returns> public async Task<ServerKeyCreateOrUpdateResponse> GetCreateOrUpdateOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetCreateOrUpdateOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerKeyCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerKeyCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken operationValue = responseDoc["operation"]; if (operationValue != null && operationValue.Type != JTokenType.Null) { string operationInstance = ((string)operationValue); result.Operation = operationInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); result.StartTime = startTimeInstance; } ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } ServerKey serverKeyInstance = new ServerKey(); result.ServerKey = serverKeyInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerKeyProperties propertiesInstance = new ServerKeyProperties(); serverKeyInstance.Properties = propertiesInstance; JToken serverKeyTypeValue = propertiesValue["serverKeyType"]; if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null) { string serverKeyTypeInstance = ((string)serverKeyTypeValue); propertiesInstance.ServerKeyType = serverKeyTypeInstance; } JToken uriValue = propertiesValue["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { string uriInstance = ((string)uriValue); propertiesInstance.Uri = uriInstance; } JToken thumbprintValue = propertiesValue["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); propertiesInstance.Thumbprint = thumbprintInstance; } JToken creationDateValue = propertiesValue["creationDate"]; if (creationDateValue != null && creationDateValue.Type != JTokenType.Null) { DateTime creationDateInstance = ((DateTime)creationDateValue); propertiesInstance.CreationDate = creationDateInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverKeyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverKeyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverKeyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverKeyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverKeyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure SQL Server Key delete operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to an Azure Sql Server Key Delete request. /// </returns> public async Task<ServerKeyDeleteResponse> GetDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetDeleteOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerKeyDeleteResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerKeyDeleteResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken operationValue = responseDoc["operation"]; if (operationValue != null && operationValue.Type != JTokenType.Null) { string operationInstance = ((string)operationValue); result.Operation = operationInstance; } JToken startTimeValue = responseDoc["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); result.StartTime = startTimeInstance; } ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets all Azure SQL Database Server Keys for a server. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server Key request. /// </returns> public async Task<ServerKeyListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/keys"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.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) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerKeyListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerKeyListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ServerKey serverKeyInstance = new ServerKey(); result.ServerKeys.Add(serverKeyInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerKeyProperties propertiesInstance = new ServerKeyProperties(); serverKeyInstance.Properties = propertiesInstance; JToken serverKeyTypeValue = propertiesValue["serverKeyType"]; if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null) { string serverKeyTypeInstance = ((string)serverKeyTypeValue); propertiesInstance.ServerKeyType = serverKeyTypeInstance; } JToken uriValue = propertiesValue["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { string uriInstance = ((string)uriValue); propertiesInstance.Uri = uriInstance; } JToken thumbprintValue = propertiesValue["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); propertiesInstance.Thumbprint = thumbprintInstance; } JToken creationDateValue = propertiesValue["creationDate"]; if (creationDateValue != null && creationDateValue.Type != JTokenType.Null) { DateTime creationDateInstance = ((DateTime)creationDateValue); propertiesInstance.CreationDate = creationDateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverKeyInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverKeyInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverKeyInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverKeyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverKeyInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ //#define USESPINLOCK using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Collections.Concurrent; using Microsoft.Research.Naiad.Diagnostics; namespace Microsoft.Research.Naiad.Scheduling { internal class EventCount { internal class WaitBlock { public int waiters; public ManualResetEvent ev; public WaitBlock next; public WaitBlock() { this.waiters = 0; this.ev = new ManualResetEvent(false); this.next = null; } } #if USESPINLOCK private SpinLock m_lock; #endif private long value; private WaitBlock current; private WaitBlock freelist; public EventCount() { #if USESPINLOCK this.m_lock = new SpinLock(); Console.Error.WriteLine("Using EventCount with spinlock"); #else Console.Error.WriteLine("Using EventCount with monitor"); #endif this.value = 0; this.current = null; this.freelist = null; } public long Read() { return this.value; } public void Await(AutoResetEvent selectiveEvent, long waitfor) { //Tracing.Trace("{Await"); // Repeatedly wait until the condition is satisfied while (waitfor > this.value) { WaitBlock wb; #if !USESPINLOCK lock (this) { #else bool taken = false; m_lock.Enter(ref taken); #endif //Console.WriteLine("Awaiting for {0}, currently {1}", waitfor, this.value); // Check condition again, now we hold the lock if (this.value >= waitfor) { #if USESPINLOCK m_lock.Exit(); #endif break; } // Make sure there is a waitblock if (this.current == null) { if (this.freelist != null) { this.current = this.freelist; this.freelist = this.freelist.next; } else { KernelLoggerTracing.PostKernelLoggerMarkEvent("Await new waitblock"); Console.Error.WriteLine("EventCount Await(): NEW WAITBLOCK"); this.current = new WaitBlock(); } } wb = this.current; Logging.Assert(wb.waiters >= 0); wb.waiters++; #if USESPINLOCK m_lock.Exit(); #else } #endif // Do the wait int wokenBy = WaitHandle.WaitAny(new WaitHandle[] { selectiveEvent, wb.ev }); if (wokenBy == 0) { // We were woken by the selective event so we need to work out the status // of the eventcount #if !USESPINLOCK lock (this) { #else taken = false; m_lock.Enter(ref taken); #endif if (wb == this.current) { // Not signalled so we can back out of the wait wb.waiters--; //Tracing.Trace("}Await"); #if USESPINLOCK m_lock.Exit(); #endif return; } #if !USESPINLOCK } #endif } // Last man standing frees the waitblock if (Interlocked.Decrement(ref wb.waiters) == 0) { // re-initialize the waitblock and put on the freelist wb.ev.Reset(); #if !USESPINLOCK lock (this) { #else taken = false; m_lock.Enter(ref taken); #endif wb.next = this.freelist; this.freelist = wb; #if USESPINLOCK m_lock.Exit(); #else } #endif } if (wokenBy == 0) { //Tracing.Trace("}Await"); #if USESPINLOCK m_lock.Exit(); #endif return; } } //Tracing.Trace("}Await"); } public void Advance() { WaitBlock wb; #if !USESPINLOCK lock (this) { #else bool taken = false; m_lock.Enter(ref taken); #endif // Advance the count this.value++; //Console.WriteLine("Advance {0}", this.value); // If we have waiters then we will wake them outside the lock wb = this.current; this.current = null; #if USESPINLOCK m_lock.Exit(); #else } #endif // Unblock the waiters if (wb != null) { NaiadTracing.Trace.RegionStart(NaiadTracingRegion.SetEvent); wb.ev.Set(); NaiadTracing.Trace.RegionStop(NaiadTracingRegion.SetEvent); } } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <content> /// Contains nested type SearchFilter.SearchFilterCollection. /// </content> public abstract partial class SearchFilter { /// <summary> /// Represents a collection of search filters linked by a logical operator. Applications can /// use SearchFilterCollection to define complex search filters such as "Condition1 AND Condition2". /// </summary> public sealed class SearchFilterCollection : SearchFilter, IEnumerable<SearchFilter> { private List<SearchFilter> searchFilters = new List<SearchFilter>(); private LogicalOperator logicalOperator = LogicalOperator.And; /// <summary> /// Initializes a new instance of the <see cref="SearchFilterCollection"/> class. /// The LogicalOperator property is initialized to LogicalOperator.And. /// </summary> public SearchFilterCollection() : base() { } /// <summary> /// Initializes a new instance of the <see cref="SearchFilterCollection"/> class. /// </summary> /// <param name="logicalOperator">The logical operator used to initialize the collection.</param> public SearchFilterCollection(LogicalOperator logicalOperator) : base() { this.logicalOperator = logicalOperator; } /// <summary> /// Initializes a new instance of the <see cref="SearchFilterCollection"/> class. /// </summary> /// <param name="logicalOperator">The logical operator used to initialize the collection.</param> /// <param name="searchFilters">The search filters to add to the collection.</param> public SearchFilterCollection(LogicalOperator logicalOperator, params SearchFilter[] searchFilters) : this(logicalOperator) { this.AddRange(searchFilters); } /// <summary> /// Initializes a new instance of the <see cref="SearchFilterCollection"/> class. /// </summary> /// <param name="logicalOperator">The logical operator used to initialize the collection.</param> /// <param name="searchFilters">The search filters to add to the collection.</param> public SearchFilterCollection(LogicalOperator logicalOperator, IEnumerable<SearchFilter> searchFilters) : this(logicalOperator) { this.AddRange(searchFilters); } /// <summary> /// Validate instance. /// </summary> internal override void InternalValidate() { for (int i = 0; i < this.Count; i++) { try { this[i].InternalValidate(); } catch (ServiceValidationException e) { throw new ServiceValidationException(string.Format(Strings.SearchFilterAtIndexIsInvalid, i), e); } } } /// <summary> /// A search filter has changed. /// </summary> /// <param name="complexProperty">The complex property.</param> private void SearchFilterChanged(ComplexProperty complexProperty) { this.Changed(); } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name.</returns> internal override string GetXmlElementName() { return this.LogicalOperator.ToString(); } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { this.Add(SearchFilter.LoadFromXml(reader)); return true; } /// <summary> /// Writes the elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { foreach (SearchFilter searchFilter in this) { searchFilter.WriteToXml(writer); } } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteToXml(EwsServiceXmlWriter writer) { // If there is only one filter in the collection, which developers tend to do, // we need to not emit the collection and instead only emit the one filter within // the collection. This is to work around the fact that EWS does not allow filter // collections that have less than two elements. if (this.Count == 1) { this[0].WriteToXml(writer); } else { base.WriteToXml(writer); } } /// <summary> /// Adds a search filter of any type to the collection. /// </summary> /// <param name="searchFilter">The search filter to add. Available search filter classes include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection.</param> public void Add(SearchFilter searchFilter) { if (searchFilter == null) { throw new ArgumentNullException("searchFilter"); } searchFilter.OnChange += this.SearchFilterChanged; this.searchFilters.Add(searchFilter); this.Changed(); } /// <summary> /// Adds multiple search filters to the collection. /// </summary> /// <param name="searchFilters">The search filters to add. Available search filter classes include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection.</param> public void AddRange(IEnumerable<SearchFilter> searchFilters) { if (searchFilters == null) { throw new ArgumentNullException("searchFilters"); } foreach (SearchFilter searchFilter in searchFilters) { searchFilter.OnChange += this.SearchFilterChanged; } this.searchFilters.AddRange(searchFilters); this.Changed(); } /// <summary> /// Clears the collection. /// </summary> public void Clear() { if (this.Count > 0) { foreach (SearchFilter searchFilter in this) { searchFilter.OnChange -= this.SearchFilterChanged; } this.searchFilters.Clear(); this.Changed(); } } /// <summary> /// Determines whether a specific search filter is in the collection. /// </summary> /// <param name="searchFilter">The search filter to locate in the collection.</param> /// <returns>True is the search filter was found in the collection, false otherwise.</returns> public bool Contains(SearchFilter searchFilter) { return this.searchFilters.Contains(searchFilter); } /// <summary> /// Removes a search filter from the collection. /// </summary> /// <param name="searchFilter">The search filter to remove.</param> public void Remove(SearchFilter searchFilter) { if (searchFilter == null) { throw new ArgumentNullException("searchFilter"); } if (this.Contains(searchFilter)) { searchFilter.OnChange -= this.SearchFilterChanged; this.searchFilters.Remove(searchFilter); this.Changed(); } } /// <summary> /// Removes the search filter at the specified index from the collection. /// </summary> /// <param name="index">The zero-based index of the search filter to remove.</param> public void RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange); } this[index].OnChange -= this.SearchFilterChanged; this.searchFilters.RemoveAt(index); this.Changed(); } /// <summary> /// Gets the total number of search filters in the collection. /// </summary> public int Count { get { return this.searchFilters.Count; } } /// <summary> /// Gets or sets the search filter at the specified index. /// </summary> /// <param name="index">The zero-based index of the search filter to get or set.</param> /// <returns>The search filter at the specified index.</returns> public SearchFilter this[int index] { get { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange); } return this.searchFilters[index]; } set { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange); } this.searchFilters[index] = value; } } /// <summary> /// Gets or sets the logical operator that links the serach filters in this collection. /// </summary> public LogicalOperator LogicalOperator { get { return this.logicalOperator; } set { this.logicalOperator = value; } } #region IEnumerable<SearchCondition> Members /// <summary> /// Gets an enumerator that iterates through the elements of the collection. /// </summary> /// <returns>An IEnumerator for the collection.</returns> public IEnumerator<SearchFilter> GetEnumerator() { return this.searchFilters.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Gets an enumerator that iterates through the elements of the collection. /// </summary> /// <returns>An IEnumerator for the collection.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.searchFilters.GetEnumerator(); } #endregion } } }
/* 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.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using ESRI.ArcGIS.PublisherControls; namespace GlobeTools { /// <summary> /// Summary description for Form1. /// </summary> public class GlobeTools : System.Windows.Forms.Form { private ESRI.ArcGIS.PublisherControls.AxArcReaderGlobeControl axArcReaderGlobeControl1; internal System.Windows.Forms.RadioButton optTool4; internal System.Windows.Forms.RadioButton optTool3; internal System.Windows.Forms.RadioButton optTool2; internal System.Windows.Forms.RadioButton optTool1; internal System.Windows.Forms.RadioButton optTool0; internal System.Windows.Forms.Button btnFullExtent; internal System.Windows.Forms.Button btnLoad; private System.Windows.Forms.OpenFileDialog openFileDialog1; private esriARGlobeTool arGlobeTool; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public GlobeTools() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <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(GlobeTools)); this.axArcReaderGlobeControl1 = new ESRI.ArcGIS.PublisherControls.AxArcReaderGlobeControl(); this.optTool4 = new System.Windows.Forms.RadioButton(); this.optTool3 = new System.Windows.Forms.RadioButton(); this.optTool2 = new System.Windows.Forms.RadioButton(); this.optTool1 = new System.Windows.Forms.RadioButton(); this.optTool0 = new System.Windows.Forms.RadioButton(); this.btnFullExtent = new System.Windows.Forms.Button(); this.btnLoad = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.axArcReaderGlobeControl1)).BeginInit(); this.SuspendLayout(); // // axArcReaderGlobeControl1 // this.axArcReaderGlobeControl1.Location = new System.Drawing.Point(12, 68); this.axArcReaderGlobeControl1.Name = "axArcReaderGlobeControl1"; this.axArcReaderGlobeControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axArcReaderGlobeControl1.OcxState"))); this.axArcReaderGlobeControl1.Size = new System.Drawing.Size(524, 332); this.axArcReaderGlobeControl1.TabIndex = 0; this.axArcReaderGlobeControl1.OnDocumentUnloaded += new System.EventHandler(this.axArcReaderGlobeControl1_OnDocumentUnloaded); this.axArcReaderGlobeControl1.OnDocumentLoaded += new ESRI.ArcGIS.PublisherControls.IARGlobeControlEvents_Ax_OnDocumentLoadedEventHandler(this.axArcReaderGlobeControl1_OnDocumentLoaded); // // optTool4 // this.optTool4.Appearance = System.Windows.Forms.Appearance.Button; this.optTool4.Location = new System.Drawing.Point(372, 12); this.optTool4.Name = "optTool4"; this.optTool4.Size = new System.Drawing.Size(84, 44); this.optTool4.TabIndex = 14; this.optTool4.Text = "Zoom In\\Out"; this.optTool4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTool4.Click += new System.EventHandler(this.MixedControls_Click); // // optTool3 // this.optTool3.Appearance = System.Windows.Forms.Appearance.Button; this.optTool3.Location = new System.Drawing.Point(300, 12); this.optTool3.Name = "optTool3"; this.optTool3.Size = new System.Drawing.Size(72, 44); this.optTool3.TabIndex = 13; this.optTool3.Text = "Target"; this.optTool3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTool3.Click += new System.EventHandler(this.MixedControls_Click); // // optTool2 // this.optTool2.Appearance = System.Windows.Forms.Appearance.Button; this.optTool2.Location = new System.Drawing.Point(228, 12); this.optTool2.Name = "optTool2"; this.optTool2.Size = new System.Drawing.Size(72, 44); this.optTool2.TabIndex = 12; this.optTool2.Text = "Navigate"; this.optTool2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTool2.Click += new System.EventHandler(this.MixedControls_Click); // // optTool1 // this.optTool1.Appearance = System.Windows.Forms.Appearance.Button; this.optTool1.Location = new System.Drawing.Point(156, 12); this.optTool1.Name = "optTool1"; this.optTool1.Size = new System.Drawing.Size(72, 44); this.optTool1.TabIndex = 11; this.optTool1.Text = "Pivot"; this.optTool1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTool1.Click += new System.EventHandler(this.MixedControls_Click); // // optTool0 // this.optTool0.Appearance = System.Windows.Forms.Appearance.Button; this.optTool0.Location = new System.Drawing.Point(84, 12); this.optTool0.Name = "optTool0"; this.optTool0.Size = new System.Drawing.Size(72, 44); this.optTool0.TabIndex = 10; this.optTool0.Text = "Pan"; this.optTool0.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.optTool0.Click += new System.EventHandler(this.MixedControls_Click); // // btnFullExtent // this.btnFullExtent.Location = new System.Drawing.Point(452, 12); this.btnFullExtent.Name = "btnFullExtent"; this.btnFullExtent.Size = new System.Drawing.Size(84, 44); this.btnFullExtent.TabIndex = 9; this.btnFullExtent.Text = "Full Extent"; this.btnFullExtent.Click += new System.EventHandler(this.btnFullExtent_Click); // // btnLoad // this.btnLoad.Location = new System.Drawing.Point(12, 12); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(72, 44); this.btnLoad.TabIndex = 8; this.btnLoad.Text = "Load"; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // GlobeTools // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(544, 410); this.Controls.Add(this.optTool4); this.Controls.Add(this.optTool3); this.Controls.Add(this.optTool2); this.Controls.Add(this.optTool1); this.Controls.Add(this.optTool0); this.Controls.Add(this.btnFullExtent); this.Controls.Add(this.btnLoad); this.Controls.Add(this.axArcReaderGlobeControl1); this.Name = "GlobeTools"; this.Text = "GlobeTools"; this.Closing += new System.ComponentModel.CancelEventHandler(this.GlobeTools_Closing); this.Load += new System.EventHandler(this.GlobeTools_Load); ((System.ComponentModel.ISupportInitialize)(this.axArcReaderGlobeControl1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.ArcReader)) { if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new GlobeTools()); } private void btnLoad_Click(object sender, System.EventArgs e) { //Open a file dialog for selecting map documents openFileDialog1.Title = "Select Published Map Document"; openFileDialog1.Filter = "Published Map Documents (*.pmf)|*.pmf"; openFileDialog1.ShowDialog(); //Exit if no map document is selected string sFilePath = openFileDialog1.FileName; if (sFilePath == "") return; //Load the specified pmf if (axArcReaderGlobeControl1.CheckDocument(sFilePath) == true) { axArcReaderGlobeControl1.LoadDocument(sFilePath,""); } else { System.Windows.Forms.MessageBox.Show("This document cannot be loaded!"); return; } } private void MixedControls_Click(object sender, System.EventArgs e) { RadioButton b = (RadioButton) sender; //Set current tool switch (b.Name) { case "optTool0": axArcReaderGlobeControl1.CurrentARGlobeTool = esriARGlobeTool.esriARGlobeToolPan; break; case "optTool1": axArcReaderGlobeControl1.CurrentARGlobeTool = esriARGlobeTool.esriARGlobeToolPivot; break; case "optTool2": axArcReaderGlobeControl1.CurrentARGlobeTool = esriARGlobeTool.esriARGlobeToolNavigate; break; case "optTool3": axArcReaderGlobeControl1.CurrentARGlobeTool = esriARGlobeTool.esriARGlobeToolTarget; break; case "optTool4": axArcReaderGlobeControl1.CurrentARGlobeTool = esriARGlobeTool.esriARGlobeToolZoomInOut; break; } //Remember the current tool arGlobeTool = axArcReaderGlobeControl1.CurrentARGlobeTool; } private void GlobeTools_Closing(object sender, System.ComponentModel.CancelEventArgs e) { //Release COM objects ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); } private void GlobeTools_Load(object sender, System.EventArgs e) { //Disable controls optTool0.Enabled = false; optTool1.Enabled = false; optTool2.Enabled = false; optTool3.Enabled = false; optTool4.Enabled = false; btnFullExtent.Enabled = false; } private void axArcReaderGlobeControl1_OnDocumentLoaded(object sender, ESRI.ArcGIS.PublisherControls.IARGlobeControlEvents_OnDocumentLoadedEvent e) { //Enable Tools optTool0.Enabled = true; optTool1.Enabled = true; optTool2.Enabled = true; optTool3.Enabled = true; optTool4.Enabled = true; btnFullExtent.Enabled = true; } private void axArcReaderGlobeControl1_OnDocumentUnloaded(object sender, System.EventArgs e) { //Enable Tools optTool0.Enabled = false; optTool1.Enabled = false; optTool2.Enabled = false; optTool3.Enabled = false; optTool4.Enabled = false; btnFullExtent.Enabled = false; } private void btnFullExtent_Click(object sender, System.EventArgs e) { //Zoom to Full Extent axArcReaderGlobeControl1.ARGlobe.ZoomToFullExtent(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Internal; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; namespace System.Composition.Convention { /// <summary> /// Entry point for defining rules that configure plain-old-CLR-objects as MEF parts. /// </summary> public class ConventionBuilder : AttributedModelProvider { private static readonly List<object> s_emptyList = new List<object>(); private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private readonly List<PartConventionBuilder> _conventions = new List<PartConventionBuilder>(); private readonly Dictionary<MemberInfo, List<Attribute>> _memberInfos = new Dictionary<MemberInfo, List<Attribute>>(); private readonly Dictionary<ParameterInfo, List<Attribute>> _parameters = new Dictionary<ParameterInfo, List<Attribute>>(); /// <summary> /// Construct a new <see cref="ConventionBuilder"/>. /// </summary> public ConventionBuilder() { } /// <summary> /// Define a rule that will apply to all types that /// derive from (or implement) the specified type. /// </summary> /// <typeparam name="T">The type from which matching types derive.</typeparam> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder<T> ForTypesDerivedFrom<T>() { var partBuilder = new PartConventionBuilder<T>((t) => IsDescendentOf(t, typeof(T))); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to all types that /// derive from (or implement) the specified type. /// </summary> /// <param name="type">The type from which matching types derive.</param> /// <returns>A <see cref="PartConventionBuilder"/> that must be used to specify the rule.</returns> public PartConventionBuilder ForTypesDerivedFrom(Type type) { Requires.NotNull(type, nameof(type)); var partBuilder = new PartConventionBuilder((t) => IsDescendentOf(t, type)); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to the types <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to which the rule applies.</typeparam> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder<T> ForType<T>() { var partBuilder = new PartConventionBuilder<T>((t) => t == typeof(T)); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to the types <paramref name="type"/>. /// </summary> /// <param name="type">The type to which the rule applies.</param> /// <returns>A <see cref="PartConventionBuilder"/> that must be used to specify the rule.</returns> public PartConventionBuilder ForType(Type type) { Requires.NotNull(type, nameof(type)); var partBuilder = new PartConventionBuilder((t) => t == type); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to types assignable to <typeparamref name="T"/> that /// match the supplied predicate. /// </summary> /// <param name="typeFilter">A predicate that selects matching types.</param> /// <typeparam name="T">The type to which the rule applies.</typeparam> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder<T> ForTypesMatching<T>(Predicate<Type> typeFilter) { Requires.NotNull(typeFilter, nameof(typeFilter)); var partBuilder = new PartConventionBuilder<T>(typeFilter); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to types that /// match the supplied predicate. /// </summary> /// <param name="typeFilter">A predicate that selects matching types.</param> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder ForTypesMatching(Predicate<Type> typeFilter) { Requires.NotNull(typeFilter, nameof(typeFilter)); var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; } private IEnumerable<Tuple<object, List<Attribute>>> EvaluateThisTypeInfoAgainstTheConvention(TypeInfo typeInfo) { List<Tuple<object, List<Attribute>>> results = new List<Tuple<object, List<Attribute>>>(); List<Attribute> attributes = new List<Attribute>(); var configuredMembers = new List<Tuple<object, List<Attribute>>>(); bool specifiedConstructor = false; bool matchedConvention = false; var type = typeInfo.AsType(); foreach (var builder in _conventions.Where(c => c.SelectType(type))) { attributes.AddRange(builder.BuildTypeAttributes(type)); specifiedConstructor |= builder.BuildConstructorAttributes(type, ref configuredMembers); builder.BuildPropertyAttributes(type, ref configuredMembers); builder.BuildOnImportsSatisfiedNotification(type, ref configuredMembers); matchedConvention = true; } if (matchedConvention && !specifiedConstructor) { // DefaultConstructor PartConventionBuilder.BuildDefaultConstructorAttributes(type, ref configuredMembers); } configuredMembers.Add(Tuple.Create((object)type.GetTypeInfo(), attributes)); return configuredMembers; } /// <summary> /// Provide the list of attributes applied to the specified member. /// </summary> /// <param name="reflectedType">The reflectedType the type used to retrieve the memberInfo.</param> /// <param name="member">The member to supply attributes for.</param> /// <returns>The list of applied attributes.</returns> public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { Requires.NotNull(member, nameof(member)); // Now edit the attributes returned from the base type List<Attribute> cachedAttributes = null; var typeInfo = member as TypeInfo; if (typeInfo != null) { var memberInfo = typeInfo as MemberInfo; _lock.EnterReadLock(); try { _memberInfos.TryGetValue(memberInfo, out cachedAttributes); } finally { _lock.ExitReadLock(); } if (cachedAttributes == null) { _lock.EnterWriteLock(); try { //Double check locking another thread may have inserted one while we were away. if (!_memberInfos.TryGetValue(memberInfo, out cachedAttributes)) { List<Attribute> attributeList; foreach (var element in EvaluateThisTypeInfoAgainstTheConvention(typeInfo)) { attributeList = element.Item2; if (attributeList != null) { var mi = element.Item1 as MemberInfo; if (mi != null) { List<Attribute> memberAttributes; if (mi != null && (mi.IsMemberInfoForConstructor() || mi.IsMemberInfoForType() || mi.IsMemberInfoForProperty() || mi.IsMemberInfoForMethod())) { if (!_memberInfos.TryGetValue(mi, out memberAttributes)) { _memberInfos.Add(mi, element.Item2); } } } else { var pi = element.Item1 as ParameterInfo; Assumes.NotNull(pi); List<Attribute> parameterAttributes; // Item contains as Constructor parameter to configure if (!_parameters.TryGetValue(pi, out parameterAttributes)) { _parameters.Add(pi, element.Item2); } } } } } // We will have updated all of the MemberInfos by now so lets reload cachedAttributes with the current store _memberInfos.TryGetValue(memberInfo, out cachedAttributes); } finally { _lock.ExitWriteLock(); } } } else if (member.IsMemberInfoForProperty() || member.IsMemberInfoForConstructor() || member.IsMemberInfoForMethod()) { cachedAttributes = ReadMemberCustomAttributes(reflectedType, member); } IEnumerable<Attribute> appliedAttributes; if (!(member is TypeInfo) && member.DeclaringType != reflectedType) appliedAttributes = Enumerable.Empty<Attribute>(); else appliedAttributes = member.GetCustomAttributes<Attribute>(false); return cachedAttributes == null ? appliedAttributes : appliedAttributes.Concat(cachedAttributes); } private List<Attribute> ReadMemberCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { List<Attribute> cachedAttributes = null; bool getMemberAttributes = false; // Now edit the attributes returned from the base type _lock.EnterReadLock(); try { if (!_memberInfos.TryGetValue(member, out cachedAttributes)) { // If there is nothing for this member Cache any attributes for the DeclaringType if (reflectedType != null && !_memberInfos.TryGetValue(member.DeclaringType.GetTypeInfo() as MemberInfo, out cachedAttributes)) { // If there is nothing for this parameter look to see if the declaring Member has been cached yet? // need to do it outside of the lock, so set the flag we'll check it in a bit getMemberAttributes = true; } cachedAttributes = null; } } finally { _lock.ExitReadLock(); } if (getMemberAttributes) { GetCustomAttributes(null, reflectedType.GetTypeInfo() as MemberInfo); // We should have run the rules for the enclosing parameter so we can again _lock.EnterReadLock(); try { _memberInfos.TryGetValue(member, out cachedAttributes); } finally { _lock.ExitReadLock(); } } return cachedAttributes; } /// <summary> /// Provide the list of attributes applied to the specified parameter. /// </summary> /// <param name="reflectedType">The reflectedType the type used to retrieve the parameterInfo.</param> /// <param name="parameter">The parameter to supply attributes for.</param> /// <returns>The list of applied attributes.</returns> public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { Requires.NotNull(parameter, nameof(parameter)); var attributes = parameter.GetCustomAttributes<Attribute>(false); List<Attribute> cachedAttributes = ReadParameterCustomAttributes(reflectedType, parameter); return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes); } private List<Attribute> ReadParameterCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { List<Attribute> cachedAttributes = null; bool getMemberAttributes = false; // Now edit the attributes returned from the base type _lock.EnterReadLock(); try { if (!_parameters.TryGetValue(parameter, out cachedAttributes)) { // If there is nothing for this parameter Cache any attributes for the DeclaringType if (reflectedType != null && !_memberInfos.TryGetValue(reflectedType.GetTypeInfo() as MemberInfo, out cachedAttributes)) { // If there is nothing for this parameter look to see if the declaring Member has been cached yet? // need to do it outside of the lock, so set the flag we'll check it in a bit getMemberAttributes = true; } cachedAttributes = null; } } finally { _lock.ExitReadLock(); } if (getMemberAttributes) { GetCustomAttributes(null, reflectedType.GetTypeInfo() as MemberInfo); // We should have run the rules for the enclosing parameter so we can again _lock.EnterReadLock(); try { _parameters.TryGetValue(parameter, out cachedAttributes); } finally { _lock.ExitReadLock(); } } return cachedAttributes; } private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseType) { if (derivedType.BaseType == null) return false; if (derivedType.BaseType == baseType.AsType()) return true; foreach (var iface in derivedType.ImplementedInterfaces) { if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == baseType.AsType()) return true; } return IsGenericDescendentOf(derivedType.BaseType.GetTypeInfo(), baseType); } private static bool IsDescendentOf(Type type, Type baseType) { if (type == baseType || type == typeof(object) || type == null) { return false; } var ti = type.GetTypeInfo(); var bti = baseType.GetTypeInfo(); // The baseType can be an open generic, in that case this ensures // that the derivedType is checked against it if (ti.IsGenericTypeDefinition || bti.IsGenericTypeDefinition) { return IsGenericDescendentOf(ti, bti); } return bti.IsAssignableFrom(ti); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; namespace NPOI.POIFS.Storage { /** * Wraps a <c>byte</c> array and provides simple data input access. * Internally, this class maintains a buffer read index, so that for the most part, primitive * data can be read in a data-input-stream-like manner.<p/> * * Note - the calling class should call the {@link #available()} method to detect end-of-buffer * and Move to the next data block when the current is exhausted. * For optimisation reasons, no error handling is performed in this class. Thus, mistakes in * calling code ran may raise ugly exceptions here, like {@link ArrayIndexOutOfBoundsException}, * etc .<p/> * * The multi-byte primitive input methods ({@link #readUshortLE()}, {@link #readIntLE()} and * {@link #readLongLE()}) have corresponding 'spanning Read' methods which (when required) perform * a read across the block boundary. These spanning read methods take the previous * {@link DataInputBlock} as a parameter. * Reads of larger amounts of data (into <c>byte</c> array buffers) must be managed by the caller * since these could conceivably involve more than two blocks. * * @author Josh Micich */ internal class DataInputBlock { /** * Possibly any size (usually 512K or 64K). Assumed to be at least 8 bytes for all blocks * before the end of the stream. The last block in the stream can be any size except zero. */ private byte[] _buf; private int _readIndex; private int _maxIndex; internal DataInputBlock(byte[] data, int startOffset) { _buf = data; _readIndex = startOffset; _maxIndex = _buf.Length; } public int Available() { return _maxIndex - _readIndex; } public int ReadUByte() { return _buf[_readIndex++] & 0xFF; } /** * Reads a <c>short</c> which was encoded in <em>little endian</em> format. */ public int ReadUshortLE() { int i = _readIndex; int b0 = _buf[i++] & 0xFF; int b1 = _buf[i++] & 0xFF; _readIndex = i; return (b1 << 8) + (b0 << 0); } /** * Reads a <c>short</c> which spans the end of <c>prevBlock</c> and the start of this block. */ public int ReadUshortLE(DataInputBlock prevBlock) { // simple case - will always be one byte in each block int i = prevBlock._buf.Length - 1; int b0 = prevBlock._buf[i++] & 0xFF; int b1 = _buf[_readIndex++] & 0xFF; return (b1 << 8) + (b0 << 0); } /** * Reads an <c>int</c> which was encoded in <em>little endian</em> format. */ public int ReadIntLE() { int i = _readIndex; int b0 = _buf[i++] & 0xFF; int b1 = _buf[i++] & 0xFF; int b2 = _buf[i++] & 0xFF; int b3 = _buf[i++] & 0xFF; _readIndex = i; return (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0); } /** * Reads an <c>int</c> which spans the end of <c>prevBlock</c> and the start of this block. */ public int ReadIntLE(DataInputBlock prevBlock, int prevBlockAvailable) { byte[] buf = new byte[4]; ReadSpanning(prevBlock, prevBlockAvailable, buf); int b0 = buf[0] & 0xFF; int b1 = buf[1] & 0xFF; int b2 = buf[2] & 0xFF; int b3 = buf[3] & 0xFF; return (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0); } /** * Reads a <c>long</c> which was encoded in <em>little endian</em> format. */ public long ReadLongLE() { int i = _readIndex; int b0 = _buf[i++] & 0xFF; int b1 = _buf[i++] & 0xFF; int b2 = _buf[i++] & 0xFF; int b3 = _buf[i++] & 0xFF; int b4 = _buf[i++] & 0xFF; int b5 = _buf[i++] & 0xFF; int b6 = _buf[i++] & 0xFF; int b7 = _buf[i++] & 0xFF; _readIndex = i; return (((long)b7 << 56) + ((long)b6 << 48) + ((long)b5 << 40) + ((long)b4 << 32) + ((long)b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0)); } /** * Reads a <c>long</c> which spans the end of <c>prevBlock</c> and the start of this block. */ public long ReadLongLE(DataInputBlock prevBlock, int prevBlockAvailable) { byte[] buf = new byte[8]; ReadSpanning(prevBlock, prevBlockAvailable, buf); int b0 = buf[0] & 0xFF; int b1 = buf[1] & 0xFF; int b2 = buf[2] & 0xFF; int b3 = buf[3] & 0xFF; int b4 = buf[4] & 0xFF; int b5 = buf[5] & 0xFF; int b6 = buf[6] & 0xFF; int b7 = buf[7] & 0xFF; return (((long)b7 << 56) + ((long)b6 << 48) + ((long)b5 << 40) + ((long)b4 << 32) + ((long)b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0)); } /** * Reads a small amount of data from across the boundary between two blocks. * The {@link #_readIndex} of this (the second) block is updated accordingly. * Note- this method (and other code) assumes that the second {@link DataInputBlock} * always is big enough to complete the read without being exhausted. */ private void ReadSpanning(DataInputBlock prevBlock, int prevBlockAvailable, byte[] buf) { Array.Copy(prevBlock._buf, prevBlock._readIndex, buf, 0, prevBlockAvailable); int secondReadLen = buf.Length - prevBlockAvailable; Array.Copy(_buf, 0, buf, prevBlockAvailable, secondReadLen); _readIndex = secondReadLen; } /** * Reads <c>len</c> bytes from this block into the supplied buffer. */ public void ReadFully(byte[] buf, int off, int len) { Array.Copy(_buf, _readIndex, buf, off, len); _readIndex += len; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the importexport-2010-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ImportExport.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.ImportExport.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UpdateJob operation /// </summary> public class UpdateJobResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { UpdateJobResponse response = new UpdateJobResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("UpdateJobResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, UpdateJobResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("ArtifactList/member", targetDepth)) { var unmarshaller = ArtifactUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); response.ArtifactList.Add(item); continue; } if (context.TestExpression("Success", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.Success = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("WarningMessage", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.WarningMessage = unmarshaller.Unmarshall(context); continue; } } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("BucketPermissionException")) { return new BucketPermissionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("CanceledJobIdException")) { return new CanceledJobIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ExpiredJobIdException")) { return new ExpiredJobIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidAccessKeyIdException")) { return new InvalidAccessKeyIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidAddressException")) { return new InvalidAddressException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidCustomsException")) { return new InvalidCustomsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidFileSystemException")) { return new InvalidFileSystemException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidJobIdException")) { return new InvalidJobIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidManifestFieldException")) { return new InvalidManifestFieldException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException")) { return new InvalidParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidVersionException")) { return new InvalidVersionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MalformedManifestException")) { return new MalformedManifestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingCustomsException")) { return new MissingCustomsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingManifestFieldException")) { return new MissingManifestFieldException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameterException")) { return new MissingParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("MultipleRegionsException")) { return new MultipleRegionsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchBucketException")) { return new NoSuchBucketException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnableToUpdateJobIdException")) { return new UnableToUpdateJobIdException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonImportExportException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static UpdateJobResponseUnmarshaller _instance = new UpdateJobResponseUnmarshaller(); internal static UpdateJobResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateJobResponseUnmarshaller Instance { get { return _instance; } } } }
using System; using System.Collections.ObjectModel; using System.Windows.Input; using Afnor.Silverlight.Toolkit.ViewServices; using EspaceClient.BackOffice.Domaine.Criterias; using EspaceClient.BackOffice.Silverlight.Business; using EspaceClient.BackOffice.Silverlight.Business.Depots; using EspaceClient.BackOffice.Silverlight.Business.Interfaces; using EspaceClient.BackOffice.Silverlight.Business.Loader; using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity; using EspaceClient.BackOffice.Silverlight.ViewModels.Messages; using EspaceClient.FrontOffice.Domaine; using nRoute.Components; using nRoute.Components.Composition; using OGDC.Silverlight.Toolkit.Services.Services; namespace EspaceClient.BackOffice.Silverlight.ViewModels.Common.Selecteur.SelecteurSocietePopUp.Tabs { /// <summary> /// ViewModel de la vue <see cref="SearchView"/> /// </summary> public class SearchViewModel : TabBase { private readonly IResourceWrapper _resourceWrapper; private readonly IDepotSelligent _selligent; private readonly IMessenging _messengingService; private readonly IApplicationContext _applicationContext; private readonly ILoaderReferentiel _referentiel; private readonly INotificationViewService _notification; private ObservableCollection<SocieteDto> _searchResult; private ICommand _searchCommand; private ICommand _resetCommand; private ICommand _doubleClickCommand; private SearchSocieteCriteriasDto _criteres; private SocieteDto _selectedSociete; private bool _isLoading; [ResolveConstructor] public SearchViewModel(IResourceWrapper resourceWrapper, IDepotSelligent selligent, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, INotificationViewService notification) : base(applicationContext, messengingService) { _resourceWrapper = resourceWrapper; _selligent = selligent; _messengingService = messengingService; _applicationContext = applicationContext; _referentiel = referentiel; _notification = notification; InitializeCommands(); InitializeUI(); } public ObservableCollection<SocieteDto> SearchResult { get { return _searchResult; } set { if (_searchResult != value) { _searchResult = value; NotifyPropertyChanged(() => SearchResult); } } } public SearchSocieteCriteriasDto Criteres { get { return _criteres; } set { _criteres = value; NotifyPropertyChanged(() => Criteres); } } public SocieteDto SelectedSociete { get { return _selectedSociete; } set { if (_selectedSociete != value) { _selectedSociete = value; NotifyPropertyChanged(() => SelectedSociete); } } } #region Commands /// <summary> /// Command de recherche des utilisateurs /// </summary> public ICommand SearchCommand { get { return _searchCommand; } } public ICommand DoubleClickCommand { get { return _doubleClickCommand; } } public ICommand ResetCommand { get { return _resetCommand; } } #endregion public bool IsLoading { get { return _isLoading; } set { if (_isLoading != value) { _isLoading = value; NotifyPropertyChanged(() => IsLoading); } } } private void InitializeCommands() { _searchCommand = new ActionCommand(OnSearch); _resetCommand = new ActionCommand(OnReset); } private void InitializeUI() { OnReset(); SearchResult = new ObservableCollection<SocieteDto>(); } private void OnReset() { Criteres = new SearchSocieteCriteriasDto() { strCC = "", strCP = "", strSIRET = "", strSociete = "" }; } private void OnSearch() { if (Criteres.strCC == "" && Criteres.strCP == "" && Criteres.strSIRET == "" && Criteres.strSociete == "") { _notification.ShowNotification(_resourceWrapper.ErrorsResourceManager.GetString("ERROR_NO_CRITERES")); } else { IsLoading = true; _selligent.SearchSocieteByMulti(Criteres, r => { IsLoading = false; if (r == null) { _notification.ShowNotification(_resourceWrapper.ErrorsResourceManager.GetString("ERROR_NO_RESULT")); } else { SearchResult.Clear(); foreach (var u in r) SearchResult.Add(u); } }, error => { _messengingService.Publish(new ErrorMessage(error)); IsLoading = false; }); } } public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback) { throw new NotImplementedException(); } protected override void OnRefreshTabCompleted(Action callback) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace Internal.Cryptography.Pal { internal sealed partial class StorePal { private static CollectionBackedStoreProvider s_machineRootStore; private static CollectionBackedStoreProvider s_machineIntermediateStore; private static readonly object s_machineLoadLock = new object(); public static IStorePal FromHandle(IntPtr storeHandle) { throw new PlatformNotSupportedException(); } public static ILoaderPal FromBlob(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); ICertificatePal singleCert; if (CertificatePal.TryReadX509Der(rawData, out singleCert) || CertificatePal.TryReadX509Pem(rawData, out singleCert)) { // The single X509 structure methods shouldn't return true and out null, only empty // collections have that behavior. Debug.Assert(singleCert != null); return SingleCertToLoaderPal(singleCert); } List<ICertificatePal> certPals; if (PkcsFormatReader.TryReadPkcs7Der(rawData, out certPals) || PkcsFormatReader.TryReadPkcs7Pem(rawData, out certPals) || PkcsFormatReader.TryReadPkcs12(rawData, password, out certPals)) { Debug.Assert(certPals != null); return ListToLoaderPal(certPals); } throw Interop.Crypto.CreateOpenSslCryptographicException(); } public static ILoaderPal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { using (SafeBioHandle bio = Interop.Crypto.BioNewFile(fileName, "rb")) { Interop.Crypto.CheckValidOpenSslHandle(bio); return FromBio(bio, password); } } private static ILoaderPal FromBio(SafeBioHandle bio, SafePasswordHandle password) { int bioPosition = Interop.Crypto.BioTell(bio); Debug.Assert(bioPosition >= 0); ICertificatePal singleCert; if (CertificatePal.TryReadX509Pem(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (CertificatePal.TryReadX509Der(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); List<ICertificatePal> certPals; if (PkcsFormatReader.TryReadPkcs7Pem(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (PkcsFormatReader.TryReadPkcs7Der(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (PkcsFormatReader.TryReadPkcs12(bio, password, out certPals)) { return ListToLoaderPal(certPals); } // Since we aren't going to finish reading, leaving the buffer where it was when we got // it seems better than leaving it in some arbitrary other position. // // But, before seeking back to start, save the Exception representing the last reported // OpenSSL error in case the last BioSeek would change it. Exception openSslException = Interop.Crypto.CreateOpenSslCryptographicException(); // Use BioSeek directly for the last seek attempt, because any failure here should instead // report the already created (but not yet thrown) exception. Interop.Crypto.BioSeek(bio, bioPosition); throw openSslException; } public static IExportPal FromCertificate(ICertificatePal cert) { return new ExportProvider(cert); } public static IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates) { return new ExportProvider(certificates); } public static IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags) { if (storeLocation == StoreLocation.CurrentUser) { if (X509Store.DisallowedStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_NoDisallowedStore); } return new DirectoryBasedStoreProvider(storeName, openFlags); } Debug.Assert(storeLocation == StoreLocation.LocalMachine); if ((openFlags & OpenFlags.ReadWrite) == OpenFlags.ReadWrite) { throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresReadOnly); } // The static store approach here is making an optimization based on not // having write support. Once writing is permitted the stores would need // to fresh-read whenever being requested. if (s_machineRootStore == null) { lock (s_machineLoadLock) { if (s_machineRootStore == null) { LoadMachineStores(); } } } if (X509Store.RootStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return s_machineRootStore; } if (X509Store.IntermediateCAStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return s_machineIntermediateStore; } throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresRootOnly); } private static ILoaderPal SingleCertToLoaderPal(ICertificatePal singleCert) { return new SingleCertLoader(singleCert); } private static ILoaderPal ListToLoaderPal(List<ICertificatePal> certPals) { return new CertCollectionLoader(certPals); } private static void LoadMachineStores() { Debug.Assert( Monitor.IsEntered(s_machineLoadLock), "LoadMachineStores assumes a lock(s_machineLoadLock)"); var rootStore = new List<X509Certificate2>(); var intermedStore = new List<X509Certificate2>(); DirectoryInfo rootStorePath = null; IEnumerable<FileInfo> trustedCertFiles; try { rootStorePath = new DirectoryInfo(Interop.Crypto.GetX509RootStorePath()); } catch (ArgumentException) { // If SSL_CERT_DIR is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStorePath value is ignored. } if (rootStorePath != null && rootStorePath.Exists) { trustedCertFiles = rootStorePath.EnumerateFiles(); } else { trustedCertFiles = Array.Empty<FileInfo>(); } FileInfo rootStoreFile = null; try { rootStoreFile = new FileInfo(Interop.Crypto.GetX509RootStoreFile()); } catch (ArgumentException) { // If SSL_CERT_FILE is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } if (rootStoreFile != null && rootStoreFile.Exists) { trustedCertFiles = Append(trustedCertFiles, rootStoreFile); } HashSet<X509Certificate2> uniqueRootCerts = new HashSet<X509Certificate2>(); HashSet<X509Certificate2> uniqueIntermediateCerts = new HashSet<X509Certificate2>(); foreach (FileInfo file in trustedCertFiles) { using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(file.FullName, "rb")) { ICertificatePal pal; while (CertificatePal.TryReadX509Pem(fileBio, out pal) || CertificatePal.TryReadX509Der(fileBio, out pal)) { X509Certificate2 cert = new X509Certificate2(pal); // The HashSets are just used for uniqueness filters, they do not survive this method. if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer)) { if (uniqueRootCerts.Add(cert)) { rootStore.Add(cert); continue; } } else { if (uniqueIntermediateCerts.Add(cert)) { intermedStore.Add(cert); continue; } } // There's a good chance we'll encounter duplicates on systems that have both one-cert-per-file // and one-big-file trusted certificate stores. Anything that wasn't unique will end up here. cert.Dispose(); } } } var rootStorePal = new CollectionBackedStoreProvider(rootStore); s_machineIntermediateStore = new CollectionBackedStoreProvider(intermedStore); // s_machineRootStore's nullarity is the loaded-state sentinel, so write it with Volatile. Debug.Assert(Monitor.IsEntered(s_machineLoadLock), "LoadMachineStores assumes a lock(s_machineLoadLock)"); Volatile.Write(ref s_machineRootStore, rootStorePal); } private static IEnumerable<T> Append<T>(IEnumerable<T> current, T addition) { foreach (T element in current) yield return element; yield return addition; } } }
namespace Nancy.Testing { using System; using Nancy.Bootstrapper; /// <summary> /// Provides the capability of executing a request with Nancy, using a specific configuration provided by an <see cref="INancyBootstrapper"/> instance. /// </summary> [Obsolete("Use Browser instead.", error: false)] public class LegacyBrowser : IHideObjectMembers { private readonly Browser browser; /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class, with the /// provided <see cref="ConfigurableBootstrapper"/> configuration. /// </summary> /// <param name="action">The <see cref="ConfigurableBootstrapper"/> configuration that should be used by the bootstrapper.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> [Obsolete("Use Browser instead.", error: false)] public LegacyBrowser(Action<ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator> action, Action<BrowserContext> defaults = null) : this(new ConfigurableBootstrapper(action), defaults) { } /// <summary> /// Initializes a new instance of the <see cref="LegacyBrowser"/> class. /// </summary> /// <param name="bootstrapper">A <see cref="INancyBootstrapper"/> instance that determines the Nancy configuration that should be used by the browser.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> [Obsolete("Use Browser instead.", error: false)] public LegacyBrowser(INancyBootstrapper bootstrapper, Action<BrowserContext> defaults = null) { this.browser = new Browser(bootstrapper, defaults); } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Delete(string path, Action<BrowserContext> browserContext = null) { return this.browser.Delete(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Delete(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Delete(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Get(string path, Action<BrowserContext> browserContext = null) { return this.browser.Get(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Get(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Get(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Head(string path, Action<BrowserContext> browserContext = null) { return this.browser.Head(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Head(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Head(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Options(string path, Action<BrowserContext> browserContext = null) { return this.browser.Options(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Options(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Options(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Patch(string path, Action<BrowserContext> browserContext = null) { return this.browser.Patch(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Patch(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Patch(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Post(string path, Action<BrowserContext> browserContext = null) { return this.browser.Post(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Post(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Post(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Put(string path, Action<BrowserContext> browserContext = null) { return this.browser.Put(path, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> [Obsolete("Use Browser instead.", error: false)] public BrowserResponse Put(Url url, Action<BrowserContext> browserContext = null) { return this.browser.Put(url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a request of the HTTP <paramref name="method"/>, on the given <paramref name="url"/>, using the /// provided <paramref name="browserContext"/> configuration. /// </summary> /// <param name="method">HTTP method to send the request as.</param> /// <param name="url">The URl of the request.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse HandleRequest(string method, Url url, Action<BrowserContext> browserContext) { return this.browser.HandleRequest(method, url, browserContext).GetAwaiter().GetResult(); } /// <summary> /// Performs a request of the HTTP <paramref name="method"/>, on the given <paramref name="path"/>, using the /// provided <paramref name="browserContext"/> configuration. /// </summary> /// <param name="method">HTTP method to send the request as.</param> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse HandleRequest(string method, string path, Action<BrowserContext> browserContext) { return this.browser.HandleRequest(method, path, browserContext).GetAwaiter().GetResult(); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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. *********************************************************************/ #region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using Axiom.Core; using Axiom.Collections; using Axiom.MathLib; using Axiom.Graphics; namespace Axiom.SceneManagers.Multiverse { public class StitchRenderable : IRenderable, IDisposable { #region Fields /// <summary> /// Reference to the parent TerrainPatch. /// </summary> protected TerrainPatch parent; /// <summary> /// Detail to be used for rendering this sub entity. /// </summary> protected SceneDetailLevel renderDetail; /// <summary> /// Flag indicating whether this sub entity should be rendered or not. /// </summary> protected bool isVisible; /// <summary> /// the renderop holds the geometry for the stitch /// </summary> protected RenderOperation renderOp; protected Hashtable customParams; // // These are used to check if the stitching needs to be redone // protected int numSamples; protected int southMetersPerSample; protected int eastMetersPerSample; #endregion Fields #region Constructor /// <summary> /// Internal constructor, only allows creation of StitchRenderables within the scene manager. /// </summary> internal StitchRenderable(TerrainPatch terrainPatch, VertexData vertexData, IndexData indexData, int numSamples, int southMetersPerSample, int eastMetersPerSample) { renderDetail = SceneDetailLevel.Solid; parent = terrainPatch; renderOp = new RenderOperation(); renderOp.operationType = OperationType.TriangleList; renderOp.useIndices = true; renderOp.vertexData = vertexData; renderOp.indexData = indexData; isVisible = true; this.numSamples = numSamples; this.southMetersPerSample = southMetersPerSample; this.eastMetersPerSample = eastMetersPerSample; } #endregion #region Properties /// <summary> /// Gets a flag indicating whether or not this sub entity should be rendered or not. /// </summary> public bool IsVisible { get { return isVisible; } } /// <summary> /// Gets/Sets the parent terrainPatch. /// </summary> public TerrainPatch Parent { get { return parent; } } #endregion #region Methods public bool IsValid(int numSamples, int southMetersPerSample, int eastMetersPerSample) { return ( numSamples == this.numSamples ) && ( southMetersPerSample == this.southMetersPerSample ) && ( eastMetersPerSample == this.eastMetersPerSample ); } #endregion Methods #region IRenderable Members public bool CastsShadows { get { return parent.CastShadows;; } } public Material Material { get { return parent.Material; } } public bool NormalizeNormals { get { return false; } } public Technique Technique { get { return parent.Technique; } } /// <summary> /// /// </summary> /// <param name="op"></param> public void GetRenderOperation(RenderOperation op) { Debug.Assert(renderOp.vertexData != null, "attempting to render stitch with no vertexData"); Debug.Assert(renderOp.indexData != null, "attempting to render stitch with no indexData"); op.useIndices = this.renderOp.useIndices; op.operationType = this.renderOp.operationType; op.vertexData = this.renderOp.vertexData; op.indexData = this.renderOp.indexData; } Material IRenderable.Material { get { return parent.Material; } } /// <summary> /// /// </summary> /// <param name="matrices"></param> public void GetWorldTransforms(Matrix4[] matrices) { matrices[0] = parent.ParentFullTransform; } /// <summary> /// /// </summary> public ushort NumWorldTransforms { get { return 1; } } /// <summary> /// /// </summary> public bool UseIdentityProjection { get { return false; } } /// <summary> /// /// </summary> public bool UseIdentityView { get { return false; } } /// <summary> /// /// </summary> public SceneDetailLevel RenderDetail { get { return renderDetail; } set { renderDetail = value; } } /// <summary> /// /// </summary> /// <param name="camera"></param> /// <returns></returns> public float GetSquaredViewDepth(Camera camera) { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return node.GetSquaredViewDepth(camera); } /// <summary> /// /// </summary> public Quaternion WorldOrientation { get { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return parent.ParentNode.DerivedOrientation; } } /// <summary> /// /// </summary> public Vector3 WorldPosition { get { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return parent.ParentNode.DerivedPosition; } } /// <summary> /// /// </summary> public List<Light> Lights { get { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return parent.ParentNode.Lights; } } public Vector4 GetCustomParameter(int index) { if( ( customParams == null ) || ( customParams[index] == null ) ) { throw new Exception("A parameter was not found at the given index"); } else { return (Vector4)customParams[index]; } } public void SetCustomParameter(int index, Vector4 val) { if ( customParams == null ) { customParams = new Hashtable(); } customParams[index] = val; } public void UpdateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry entry, GpuProgramParameters gpuParams) { if( ( customParams != null ) && ( customParams[entry.data] != null ) ) { gpuParams.SetConstant(entry.index, (Vector4)customParams[entry.data]); } } #endregion #region IDisposable Members public void Dispose() { renderOp.indexData = null; if ( renderOp.vertexData != null ) { renderOp.vertexData.vertexBufferBinding.GetBuffer(0).Dispose(); renderOp.vertexData.vertexBufferBinding.SetBinding(0, null); renderOp.vertexData = null; } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Test for task and job adapter. /// </summary> public class FailoverTaskSelfTest : AbstractTaskTest { /** */ static volatile string _gridName; /** */ static volatile int _cnt; /// <summary> /// Constructor. /// </summary> public FailoverTaskSelfTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected FailoverTaskSelfTest(bool fork) : base(fork) { } /// <summary> /// Test for GridComputeJobFailoverException. /// </summary> [Test] public void TestClosureFailoverException() { for (int i = 0; i < 20; i++) { int res = Grid1.GetCompute().Call(new TestClosure()); Assert.AreEqual(2, res); Cleanup(); } } /// <summary> /// Test for GridComputeJobFailoverException with serializable job. /// </summary> [Test] public void TestTaskAdapterFailoverExceptionSerializable() { TestTaskAdapterFailoverException(true); } /// <summary> /// Test for GridComputeJobFailoverException with binary job. /// </summary> [Test] public void TestTaskAdapterFailoverExceptionBinarizable() { TestTaskAdapterFailoverException(false); } /// <summary> /// Test for GridComputeJobFailoverException. /// </summary> private void TestTaskAdapterFailoverException(bool serializable) { int res = Grid1.GetCompute().Execute(new TestTask(), new Tuple<bool, bool>(serializable, true)); Assert.AreEqual(2, res); Cleanup(); res = Grid1.GetCompute().Execute(new TestTask(), new Tuple<bool, bool>(serializable, false)); Assert.AreEqual(2, res); } /// <summary> /// Cleanup. /// </summary> [TearDown] public void Cleanup() { _cnt = 0; _gridName = null; } /// <summary> /// Test task. /// </summary> private class TestTask : ComputeTaskAdapter<Tuple<bool, bool>, int, int> { /** <inheritDoc /> */ public override IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, bool> arg) { Assert.AreEqual(2, subgrid.Count); var serializable = arg.Item1; var local = arg.Item2; var job = serializable ? (IComputeJob<int>) new TestSerializableJob() : new TestBinarizableJob(); var node = subgrid.Single(x => x.IsLocal == local); return new Dictionary<IComputeJob<int>, IClusterNode> {{job, node}}; } /** <inheritDoc /> */ public override int Reduce(IList<IComputeJobResult<int>> results) { Assert.AreEqual(1, results.Count); return results[0].Data; } } /// <summary> /// /// </summary> [Serializable] private class TestClosure : IComputeFunc<int> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ public int Invoke() { return FailoverJob(_grid); } } /// <summary> /// /// </summary> [Serializable] private class TestSerializableJob : IComputeJob<int> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ public int Execute() { return FailoverJob(_grid); } /** <inheritDoc /> */ public void Cancel() { // No-op. } } /// <summary> /// /// </summary> private class TestBinarizableJob : IComputeJob<int> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ public int Execute() { return FailoverJob(_grid); } public void Cancel() { // No-op. } } /// <summary> /// Throws GridComputeJobFailoverException on first call. /// </summary> private static int FailoverJob(IIgnite grid) { Assert.NotNull(grid); _cnt++; if (_gridName == null) { _gridName = grid.Name; throw new ComputeJobFailoverException("Test error."); } Assert.AreNotEqual(_gridName, grid.Name); return _cnt; } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A lock-free, concurrent queue primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; namespace System.Collections.Concurrent { /// <summary> /// Represents a thread-safe first-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the queue.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] [HostProtection(Synchronization = true, ExternalThreading = true)] [Serializable] public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { //fields of ConcurrentQueue [NonSerialized] private volatile Segment m_head; [NonSerialized] private volatile Segment m_tail; private T[] m_serializationArray; // Used for custom serialization. private const int SEGMENT_SIZE = 32; //number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot. [NonSerialized] internal volatile int m_numSnapshotTakers = 0; /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class. /// </summary> public ConcurrentQueue() { m_head = m_tail = new Segment(0, this); } /// <summary> /// Initializes the contents of the queue from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor m_head = localTail; int index = 0; foreach (T element in collection) { Contract.Assert(index >= 0 && index < SEGMENT_SIZE); localTail.UnsafeAdd(element); index++; if (index >= SEGMENT_SIZE) { localTail = localTail.UnsafeGrow(); index = 0; } } m_tail = localTail; } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> /// class that contains elements copied from the specified collection /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentQueue{T}"/>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is /// null.</exception> public ConcurrentQueue(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } InitializeFromCollection(collection); } /// <summary> /// Get the data array to be serialized /// </summary> [OnSerializing] private void OnSerializing(StreamingContext context) { // save the data into the serialization array to be saved m_serializationArray = ToArray(); } /// <summary> /// Construct the queue from a previously seiralized one /// </summary> [OnDeserialized] private void OnDeserialized(StreamingContext context) { Contract.Assert(m_serializationArray != null); InitializeFromCollection(m_serializationArray); m_serializationArray = null; } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported")); } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } /// <summary> /// Attempts to add an object to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the /// end of the <see cref="ConcurrentQueue{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Enqueue(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object /// from the beginning of the <see cref="ConcurrentQueue{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryDequeue(out item); } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { get { Segment head = m_head; if (!head.IsEmpty) //fast route 1: //if current head is not empty, then queue is not empty return false; else if (head.Next == null) //fast route 2: //if current head is empty and it's the last segment //then queue is empty return true; else //slow route: //current head is empty and it is NOT the last segment, //it means another thread is growing new segment { SpinWait spin = new SpinWait(); while (head.IsEmpty) { if (head.Next == null) return true; spin.SpinOnce(); head = m_head; } return false; } } } /// <summary> /// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentQueue{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see /// cref="T:System.Collections.Generic.List{T}"/>. /// </summary> /// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of /// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns> private List<T> ToList() { // Increments the number of active snapshot takers. This increment must happen before the snapshot is // taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. Interlocked.Increment(ref m_numSnapshotTakers); List<T> list = new List<T>(); try { //store head and tail positions in buffer, Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); if (head == tail) { head.AddToList(list, headLow, tailHigh); } else { head.AddToList(list, headLow, SEGMENT_SIZE - 1); Segment curr = head.Next; while (curr != tail) { curr.AddToList(list, 0, SEGMENT_SIZE - 1); curr = curr.Next; } //Add tail segment tail.AddToList(list, 0, tailHigh); } } finally { // This Decrement must happen after copying is over. Interlocked.Decrement(ref m_numSnapshotTakers); } return list; } /// <summary> /// Store the position of the current head and tail positions. /// </summary> /// <param name="head">return the head segment</param> /// <param name="tail">return the tail segment</param> /// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param> /// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param> private void GetHeadTailPositions(out Segment head, out Segment tail, out int headLow, out int tailHigh) { head = m_head; tail = m_tail; headLow = head.Low; tailHigh = tail.High; SpinWait spin = new SpinWait(); //we loop until the observed values are stable and sensible. //This ensures that any update order by other methods can be tolerated. while ( //if head and tail changed, retry head != m_head || tail != m_tail //if low and high pointers, retry || headLow != head.Low || tailHigh != tail.High //if head jumps ahead of tail because of concurrent grow and dequeue, retry || head.m_index > tail.m_index) { spin.SpinOnce(); head = m_head; tail = m_tail; headLow = head.Low; tailHigh = tail.High; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { get { //store head and tail positions in buffer, Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); if (head == tail) { return tailHigh - headLow + 1; } //head segment int count = SEGMENT_SIZE - headLow; //middle segment(s), if any, are full. //We don't deal with overflow to be consistent with the behavior of generic types in CLR. count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1)); //tail segment count += tailHigh + 1; return count; } } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array">Array</see>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentQueue{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the queue. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the queue. /// </remarks> public IEnumerator<T> GetEnumerator() { // Increments the number of active snapshot takers. This increment must happen before the snapshot is // taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. Interlocked.Increment(ref m_numSnapshotTakers); // Takes a snapshot of the queue. // A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot // wrap the following with a try/finally block, otherwise the decrement will happen before the yield return // statements in the GetEnumerator (head, tail, headLow, tailHigh) method. Segment head, tail; int headLow, tailHigh; GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of // the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called. // This is inconsistent with existing generic collections. In order to prevent it, we capture the // value of m_head in a buffer and call out to a helper method. //The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an // unnecessary perfomance hit. return GetEnumerator(head, tail, headLow, tailHigh); } /// <summary> /// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation. /// </summary> private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh) { try { SpinWait spin = new SpinWait(); if (head == tail) { for (int i = headLow; i <= tailHigh; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!head.m_state[i].m_value) { spin.SpinOnce(); } yield return head.m_array[i]; } } else { //iterate on head segment for (int i = headLow; i < SEGMENT_SIZE; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!head.m_state[i].m_value) { spin.SpinOnce(); } yield return head.m_array[i]; } //iterate on middle segments Segment curr = head.Next; while (curr != tail) { for (int i = 0; i < SEGMENT_SIZE; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!curr.m_state[i].m_value) { spin.SpinOnce(); } yield return curr.m_array[i]; } curr = curr.Next; } //iterate on tail segment for (int i = 0; i <= tailHigh; i++) { // If the position is reserved by an Enqueue operation, but the value is not written into, // spin until the value is available. spin.Reset(); while (!tail.m_state[i].m_value) { spin.SpinOnce(); } yield return tail.m_array[i]; } } } finally { // This Decrement must happen after the enumeration is over. Interlocked.Decrement(ref m_numSnapshotTakers); } } /// <summary> /// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="item">The object to add to the end of the <see /// cref="ConcurrentQueue{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types. /// </param> public void Enqueue(T item) { SpinWait spin = new SpinWait(); while (true) { Segment tail = m_tail; if (tail.TryAppend(item)) return; spin.SpinOnce(); } } /// <summary> /// Attempts to remove and return the object at the beginning of the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the beggining of the <see /// cref="ConcurrentQueue{T}"/> /// succesfully; otherwise, false.</returns> public bool TryDequeue(out T result) { while (!IsEmpty) { Segment head = m_head; if (head.TryRemove(out result)) return true; //since method IsEmpty spins, we don't need to spin in the while loop } result = default(T); return false; } /// <summary> /// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an /// unspecified value if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { Interlocked.Increment(ref m_numSnapshotTakers); while (!IsEmpty) { Segment head = m_head; if (head.TryPeek(out result)) { Interlocked.Decrement(ref m_numSnapshotTakers); return true; } //since method IsEmpty spins, we don't need to spin in the while loop } result = default(T); Interlocked.Decrement(ref m_numSnapshotTakers); return false; } /// <summary> /// private class for ConcurrentQueue. /// a queue is a linked list of small arrays, each node is called a segment. /// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording /// the first and last valid elements of the array. /// </summary> private class Segment { //we define two volatile arrays: m_array and m_state. Note that the accesses to the array items //do not get volatile treatment. But we don't need to worry about loading adjacent elements or //store/load on adjacent elements would suffer reordering. // - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe. // - Two loads: because one item from two volatile arrays are accessed, the loads of the array references // are sufficient to prevent reordering of the loads of the elements. internal volatile T[] m_array; // For each entry in m_array, the corresponding entry in m_state indicates whether this position contains // a valid value. m_state is initially all false. internal volatile VolatileBool[] m_state; //pointer to the next segment. null if the current segment is the last segment private volatile Segment m_next; //We use this zero based index to track how many segments have been created for the queue, and //to compute how many active segments are there currently. // * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1; // * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely // assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4 // billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years. internal readonly long m_index; //indices of where the first and last valid values // - m_low points to the position of the next element to pop from this segment, range [0, infinity) // m_low >= SEGMENT_SIZE implies the segment is disposable // - m_high points to the position of the latest pushed element, range [-1, infinity) // m_high == -1 implies the segment is new and empty // m_high >= SEGMENT_SIZE-1 means this segment is ready to grow. // and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment // - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty // - initially m_low =0 and m_high=-1; private volatile int m_low; private volatile int m_high; private volatile ConcurrentQueue<T> m_source; /// <summary> /// Create and initialize a segment with the specified index. /// </summary> internal Segment(long index, ConcurrentQueue<T> source) { m_array = new T[SEGMENT_SIZE]; m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false m_high = -1; Contract.Assert(index >= 0); m_index = index; m_source = source; } /// <summary> /// return the next segment /// </summary> internal Segment Next { get { return m_next; } } /// <summary> /// return true if the current segment is empty (doesn't have any element available to dequeue, /// false otherwise /// </summary> internal bool IsEmpty { get { return (Low > High); } } /// <summary> /// Add an element to the tail of the current segment /// exclusively called by ConcurrentQueue.InitializedFromCollection /// InitializeFromCollection is responsible to guaratee that there is no index overflow, /// and there is no contention /// </summary> /// <param name="value"></param> internal void UnsafeAdd(T value) { Contract.Assert(m_high < SEGMENT_SIZE - 1); m_high++; m_array[m_high] = value; m_state[m_high].m_value = true; } /// <summary> /// Create a new segment and append to the current one /// Does not update the m_tail pointer /// exclusively called by ConcurrentQueue.InitializedFromCollection /// InitializeFromCollection is responsible to guaratee that there is no index overflow, /// and there is no contention /// </summary> /// <returns>the reference to the new Segment</returns> internal Segment UnsafeGrow() { Contract.Assert(m_high >= SEGMENT_SIZE - 1); Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; return newSegment; } /// <summary> /// Create a new segment and append to the current one /// Update the m_tail pointer /// This method is called when there is no contention /// </summary> internal void Grow() { //no CAS is needed, since there is no contention (other threads are blocked, busy waiting) Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow m_next = newSegment; Contract.Assert(m_source.m_tail == this); m_source.m_tail = m_next; } /// <summary> /// Try to append an element at the end of this segment. /// </summary> /// <param name="value">the element to append</param> /// <param name="tail">The tail.</param> /// <returns>true if the element is appended, false if the current segment is full</returns> /// <remarks>if appending the specified element succeeds, and after which the segment is full, /// then grow the segment</remarks> internal bool TryAppend(T value) { //quickly check if m_high is already over the boundary, if so, bail out if (m_high >= SEGMENT_SIZE - 1) { return false; } //Now we will use a CAS to increment m_high, and store the result in newhigh. //Depending on how many free spots left in this segment and how many threads are doing this Increment //at this time, the returning "newhigh" can be // 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value // 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment // 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to // Queue.Enqueue method, telling it to try again in the next segment. int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary //We need do Interlocked.Increment and value/state update in a finally block to ensure that they run //without interuption. This is to prevent anything from happening between them, and another dequeue //thread maybe spinning forever to wait for m_state[] to be true; try { } finally { newhigh = Interlocked.Increment(ref m_high); if (newhigh <= SEGMENT_SIZE - 1) { m_array[newhigh] = value; m_state[newhigh].m_value = true; } //if this thread takes up the last slot in the segment, then this thread is responsible //to grow a new segment. Calling Grow must be in the finally block too for reliability reason: //if thread abort during Grow, other threads will be left busy spinning forever. if (newhigh == SEGMENT_SIZE - 1) { Grow(); } } //if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot return newhigh <= SEGMENT_SIZE - 1; } /// <summary> /// try to remove an element from the head of current segment /// </summary> /// <param name="result">The result.</param> /// <param name="head">The head.</param> /// <returns>return false only if the current segment is empty</returns> internal bool TryRemove(out T result) { SpinWait spin = new SpinWait(); int lowLocal = Low, highLocal = High; while (lowLocal <= highLocal) { //try to update m_low if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal) { //if the specified value is not available (this spot is taken by a push operation, // but the value is not written into yet), then spin SpinWait spinLocal = new SpinWait(); while (!m_state[lowLocal].m_value) { spinLocal.SpinOnce(); } result = m_array[lowLocal]; // If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null. // It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include // the deleted entry at m_array[lowLocal]. if (m_source.m_numSnapshotTakers <= 0) { m_array[lowLocal] = default(T); //release the reference to the object. } //if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes //disposable, then this thread is responsible to dispose this segment, and reset m_head if (lowLocal + 1 >= SEGMENT_SIZE) { // Invariant: we only dispose the current m_head, not any other segment // In usual situation, disposing a segment is simply seting m_head to m_head.m_next // But there is one special case, where m_head and m_tail points to the same and ONLY //segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow, //while the *current* thread is doing *this* Dequeue operation, and finds that it needs to //dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its //Grow operation, this is the reason of having the following while loop spinLocal = new SpinWait(); while (m_next == null) { spinLocal.SpinOnce(); } Contract.Assert(m_source.m_head == this); m_source.m_head = m_next; } return true; } else { //CAS failed due to contention: spin briefly and retry spin.SpinOnce(); lowLocal = Low; highLocal = High; } }//end of while result = default(T); return false; } /// <summary> /// try to peek the current segment /// </summary> /// <param name="result">holds the return value of the element at the head position, /// value set to default(T) if there is no such an element</param> /// <returns>true if there are elements in the current segment, false otherwise</returns> internal bool TryPeek(out T result) { result = default(T); int lowLocal = Low; if (lowLocal > High) return false; SpinWait spin = new SpinWait(); while (!m_state[lowLocal].m_value) { spin.SpinOnce(); } result = m_array[lowLocal]; return true; } /// <summary> /// Adds part or all of the current segment into a List. /// </summary> /// <param name="list">the list to which to add</param> /// <param name="start">the start position</param> /// <param name="end">the end position</param> internal void AddToList(List<T> list, int start, int end) { for (int i = start; i <= end; i++) { SpinWait spin = new SpinWait(); while (!m_state[i].m_value) { spin.SpinOnce(); } list.Add(m_array[i]); } } /// <summary> /// return the position of the head of the current segment /// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty /// </summary> internal int Low { get { return Math.Min(m_low, SEGMENT_SIZE); } } /// <summary> /// return the logical position of the tail of the current segment /// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet /// </summary> internal int High { get { //if m_high > SEGMENT_SIZE, it means it's out of range, we should return //SEGMENT_SIZE-1 as the logical position return Math.Min(m_high, SEGMENT_SIZE - 1); } } } }//end of class Segment /// <summary> /// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile /// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile /// </summary> struct VolatileBool { public VolatileBool(bool value) { m_value = value; } public volatile bool m_value; } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 Burrows.NewIds.NewIdFormatters; using Burrows.NewIds.NewIdProviders; namespace Burrows.NewIds { /// <summary> /// A NewId is a type that fits into the same space as a Guid/Uuid/uniqueidentifier, /// but is guaranteed to be both unique and ordered, assuming it is generated using /// a single instance of the generator for each network address used. /// </summary> public struct NewId : IEquatable<NewId>, IComparable<NewId>, IComparable, IFormattable { public static readonly NewId Empty = new NewId(0, 0, 0, 0); static readonly INewIdFormatter _braceFormatter = new DashedHexFormatter('{', '}'); static readonly INewIdFormatter _dashedHexFormatter = new DashedHexFormatter(); static NewIdGenerator _generator; static readonly INewIdFormatter _hexFormatter = new HexFormatter(); static readonly INewIdFormatter _parenFormatter = new DashedHexFormatter('(', ')'); static ITickProvider _tickProvider; static IWorkerIdProvider _workerIdProvider; private readonly Int32 _a; private readonly Int32 _b; private readonly Int32 _c; private readonly Int32 _d; /// <summary> /// Creates a NewId using the specified byte array. /// </summary> /// <param name="bytes"></param> public NewId(byte[] bytes) { if (bytes == null) throw new ArgumentNullException("bytes"); if (bytes.Length != 16) throw new ArgumentException("Exactly 16 bytes expected", "bytes"); FromByteArray(bytes, out _a, out _b, out _c, out _d); } public NewId(string value) { if(string.IsNullOrEmpty(value)) throw new ArgumentException("must not be null or empty", "value"); var guid = new Guid(value); byte[] bytes = guid.ToByteArray(); FromByteArray(bytes, out _a, out _b, out _c, out _d); } public NewId(int a, int b, int c, int d) { _a = a; _b = b; _c = c; _d = d; } public NewId(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (f << 24) | (g << 16) | (h << 8) | i; _b = (j << 24) | (k << 16) | (d << 8) | e; _c = (c << 16) | b; _d = a; } static NewIdGenerator Generator { get { return _generator ?? (_generator = new NewIdGenerator(TickProvider, WorkerIdProvider)); } } static IWorkerIdProvider WorkerIdProvider { get { return _workerIdProvider ?? (_workerIdProvider = new BestPossibleWorkerIdProvider()); } } static ITickProvider TickProvider { get { return _tickProvider ?? (_tickProvider = new StopwatchTickProvider()); } } public DateTime Timestamp { get { var ticks = (long)(((ulong)_a) << 32 | (uint)_b); return new DateTime(ticks, DateTimeKind.Utc); } } public int CompareTo(object obj) { if (obj == null) return 1; if (!(obj is NewId)) throw new ArgumentException("Argument must be a NewId"); return CompareTo((NewId)obj); } public int CompareTo(NewId other) { if (_a != other._a) return ((uint)_a < (uint)other._a) ? -1 : 1; if (_b != other._b) return ((uint)_b < (uint)other._b) ? -1 : 1; if (_c != other._c) return ((uint)_c < (uint)other._c) ? -1 : 1; if (_d != other._d) return ((uint)_d < (uint)other._d) ? -1 : 1; return 0; } public bool Equals(NewId other) { return other._a == _a && other._b == _b && other._c == _c && other._d == _d; } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) format = "D"; bool sequential = false; if (format.Length == 2 && (format[1] == 'S' || format[1] == 's')) sequential = true; else if (format.Length != 1) throw new FormatException("The format string must be exactly one character or null"); char formatCh = format[0]; byte[] bytes = sequential ? GetSequentialFormatteryArray() : GetFormatteryArray(); if (formatCh == 'B' || formatCh == 'b') return _braceFormatter.Format(bytes); if (formatCh == 'P' || formatCh == 'p') return _parenFormatter.Format(bytes); if (formatCh == 'D' || formatCh == 'd') return _dashedHexFormatter.Format(bytes); if (formatCh == 'N' || formatCh == 'n') return _hexFormatter.Format(bytes); throw new FormatException("The format string was not valid"); } public string ToString(INewIdFormatter formatter, bool sequential = false) { byte[] bytes = sequential ? GetSequentialFormatteryArray() : GetFormatteryArray(); return formatter.Format(bytes); } byte[] GetFormatteryArray() { var bytes = new byte[16]; bytes[0] = (byte)(_d >> 24); bytes[1] = (byte)(_d >> 16); bytes[2] = (byte)(_d >> 8); bytes[3] = (byte)_d; bytes[4] = (byte)(_c >> 8); bytes[5] = (byte)_c; bytes[6] = (byte)(_c >> 24); bytes[7] = (byte)(_c >> 16); bytes[8] = (byte)(_b >> 8); bytes[9] = (byte)_b; bytes[10] = (byte)(_a >> 24); bytes[11] = (byte)(_a >> 16); bytes[12] = (byte)(_a >> 8); bytes[13] = (byte)_a; bytes[14] = (byte)(_b >> 24); bytes[15] = (byte)(_b >> 16); return bytes; } byte[] GetSequentialFormatteryArray() { var bytes = new byte[16]; bytes[0] = (byte)(_a >> 24); bytes[1] = (byte)(_a >> 16); bytes[2] = (byte)(_a >> 8); bytes[3] = (byte)_a; bytes[4] = (byte)(_b >> 24); bytes[5] = (byte)(_b >> 16); bytes[6] = (byte)(_b >> 8); bytes[7] = (byte)_b; bytes[8] = (byte)(_c >> 24); bytes[9] = (byte)(_c >> 16); bytes[10] = (byte)(_c >> 8); bytes[11] = (byte)_c; bytes[12] = (byte)(_d >> 24); bytes[13] = (byte)(_d >> 16); bytes[14] = (byte)(_d >> 8); bytes[15] = (byte)_d; return bytes; } public Guid ToGuid() { int a = _d; var b = (short)_c; var c = (short)(_c >> 16); var d = (byte)(_b >> 8); var e = (byte)_b; var f = (byte)(_a >> 24); var g = (byte)(_a >> 16); var h = (byte)(_a >> 8); var i = (byte)_a; var j = (byte)(_b >> 24); var k = (byte)(_b >> 16); return new Guid(a, b, c, d, e, f, g, h, i, j, k); } public Guid ToSequentialGuid() { int a = _a; var b = (short)(_b >> 16); var c = (short)_b; var d = (byte)(_c >> 24); var e = (byte)(_c >> 16); var f = (byte)(_c >> 8); var g = (byte)(_c); var h = (byte)(_d >> 24); var i = (byte)(_d >> 16); var j = (byte)(_d >> 8); var k = (byte)(_d); return new Guid(a, b, c, d, e, f, g, h, i, j, k); } public byte[] ToByteArray() { var bytes = new byte[16]; bytes[0] = (byte)(_d); bytes[1] = (byte)(_d >> 8); bytes[2] = (byte)(_d >> 16); bytes[3] = (byte)(_d >> 24); bytes[4] = (byte)(_c); bytes[5] = (byte)(_c >> 8); bytes[6] = (byte)(_c >> 16); bytes[7] = (byte)(_c >> 24); bytes[8] = (byte)(_b >> 8); bytes[9] = (byte)(_b); bytes[10] = (byte)(_a >> 24); bytes[11] = (byte)(_a >> 16); bytes[12] = (byte)(_a >> 8); bytes[13] = (byte)(_a); bytes[14] = (byte)(_b >> 24); bytes[15] = (byte)(_b >> 16); return bytes; } public override string ToString() { return ToString("D", null); } public string ToString(string format) { return ToString(format, null); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != typeof(NewId)) return false; return Equals((NewId)obj); } public override int GetHashCode() { unchecked { int result = _a; result = (result * 397) ^ _b; result = (result * 397) ^ _c; result = (result * 397) ^ _d; return result; } } public static bool operator ==(NewId left, NewId right) { return left._a == right._a && left._b == right._b && left._c == right._c && left._d == right._d; } public static bool operator !=(NewId left, NewId right) { return !(left == right); } public static void SetGenerator(NewIdGenerator generator) { _generator = generator; } public static void SetWorkerIdProvider(IWorkerIdProvider provider) { _workerIdProvider = provider; } public static void SetTickProvider(ITickProvider provider) { _tickProvider = provider; } public static NewId Next() { return Generator.Next(); } public static Guid NextGuid() { return Generator.Next().ToGuid(); } static void FromByteArray(byte[] bytes, out Int32 a, out Int32 b, out Int32 c, out Int32 d) { a = bytes[10] << 24 | bytes[11] << 16 | bytes[12] << 8 | bytes[13]; b = bytes[14] << 24 | bytes[15] << 16 | bytes[8] << 8 | bytes[9]; c = bytes[7] << 24 | bytes[6] << 16 | bytes[5] << 8 | bytes[4]; d = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; } } }
// // (c) 2007 - 2011 Joshua R. Rodgers under the terms of the Ms-PL license. using System; namespace AW { partial class Instance { #region Instance manage methods /// <summary> /// Logs the instance into the universe using the Attributes.LoginOwner, Attributes.LoginPrivilegePassword, Attributes.LoginName, and Attributes.LoginApplication that were set earlier. /// If CallbackLogin is not set, this is a blocking operation. /// </summary> public Result Login() { SetInstance(); return (Result)NativeMethods.aw_login(); } /// <summary> /// Causes the instance to enter the specified world. /// If CallbackEnter is not set, this is a blocking operation. /// </summary> /// <param name="world">The name of the world to enter.</param> public Result Enter(string world) { SetInstance(); return (Result)NativeMethods.aw_enter(world); } ///<summary> /// Causes the instance to leave the current world. /// It is not necessary to call this method when disconnecting or changing worlds. ///</summary> public Result Exit() { SetInstance(); return (Result)NativeMethods.aw_exit(); } /// <summary> /// Causes the instance to change state within the world. /// </summary> public Result StateChange() { SetInstance(); return (Result)NativeMethods.aw_state_change(); } #endregion #region Event manipulation methods public Result ObjectClick() { SetInstance(); return (Result)NativeMethods.aw_object_click(); } public Result ObjectSelect() { SetInstance(); return (Result)NativeMethods.aw_object_select(); } public Result AvatarClick(int session) { SetInstance(); return (Result)NativeMethods.aw_avatar_click(session); } public Result UrlSend(int session, string url, string target) { SetInstance(); return (Result)NativeMethods.aw_url_send(session, url, target); } public Result UrlClick(string url) { SetInstance(); return (Result)NativeMethods.aw_url_click(url); } public Result Teleport(int session) { SetInstance(); return (Result)NativeMethods.aw_teleport(session); } public Result AvatarSet(int session) { SetInstance(); return (Result)NativeMethods.aw_avatar_set(session); } public Result AvatarReload(int citizen, int session) { SetInstance(); return (Result)NativeMethods.aw_avatar_reload(citizen, session); } public Result ToolbarClick() { SetInstance(); return (Result)NativeMethods.aw_toolbar_click(); } public Result Noise(int session) { SetInstance(); return (Result)NativeMethods.aw_noise(session); } public Result CameraSet(int session) { SetInstance(); return (Result)NativeMethods.aw_camera_set(session); } public Result BotmenuSend() { SetInstance(); return (Result)NativeMethods.aw_botmenu_send(); } public Result ObjectBump() { SetInstance(); return (Result)NativeMethods.aw_object_bump(); } #endregion #region Information query methods public Result WorldList() { SetInstance(); return (Result)NativeMethods.aw_world_list(); } public Result Address(int session) { SetInstance(); return (Result)NativeMethods.aw_address(session); } public Result UserList() { SetInstance(); return (Result)NativeMethods.aw_user_list(); } public Result AvatarLocation(int citizen, int sessionId, string name) { SetInstance(); return (Result)NativeMethods.aw_avatar_location(citizen, sessionId, name); } #endregion #region Communication methods public Result Say(string message) { SetInstance(); return (Result)NativeMethods.aw_say(message); } public Result Say(string message, object arg0) { SetInstance(); return (Result)NativeMethods.aw_say(string.Format(message, arg0)); } public Result Say(string message, object arg0, object arg1) { SetInstance(); return (Result)NativeMethods.aw_say(string.Format(message, arg0, arg1)); } public Result Say(string message, object arg0, object arg1, object arg2) { SetInstance(); return (Result)NativeMethods.aw_say(string.Format(message, arg0, arg1, arg2)); } public Result Say(string message, params object[] args) { SetInstance(); return (Result)NativeMethods.aw_say(string.Format(message, args)); } public Result Whisper(int session, string message) { SetInstance(); return (Result)NativeMethods.aw_whisper(session, message); } public Result Whisper(int session, string message, object arg0) { SetInstance(); return (Result)NativeMethods.aw_whisper(session, string.Format(message, arg0)); } public Result Whisper(int session, string message, object arg0, object arg1) { SetInstance(); return (Result)NativeMethods.aw_whisper(session, string.Format(message, arg0, arg1)); } public Result Whisper(int session, string message, object arg0, object arg1, object arg2) { SetInstance(); return (Result)NativeMethods.aw_whisper(session, string.Format(message, arg0, arg1, arg2)); } public Result Whisper(int session, string message, params object[] args) { SetInstance(); return (Result)NativeMethods.aw_whisper(session, string.Format(message, args)); } public Result ConsoleMessage(int session) { SetInstance(); return (Result)NativeMethods.aw_console_message(session); } public Result BotgramSend() { SetInstance(); return (Result)NativeMethods.aw_botgram_send(); } #endregion #region Property methods public Result Query(int xSector, int zSector, int[,] sequence) { SetInstance(); return (Result)NativeMethods.aw_query(xSector, zSector, sequence); } public Result Query5x5(int xSector, int zSector, int[,] sequence) { SetInstance(); return (Result)NativeMethods.aw_query_5x5(xSector, zSector, sequence); } public Result ObjectQuery() { SetInstance(); return (Result)NativeMethods.aw_object_query(); } public Result CellNext() { SetInstance(); return (Result)NativeMethods.aw_cell_next(); } public Result ObjectAdd() { SetInstance(); return (Result)NativeMethods.aw_object_add(); } public Result ObjectChange() { SetInstance(); return (Result)NativeMethods.aw_object_change(); } public Result ObjectDelete() { SetInstance(); return (Result)NativeMethods.aw_object_delete(); } public Result ObjectLoad() { SetInstance(); return (Result)NativeMethods.aw_object_load(); } public Result DeleteAllObjects() { SetInstance(); return (Result)NativeMethods.aw_delete_all_objects(); } #endregion #region Terrain methods public Result TerrainSet(int x, int z, int texture, int[] heights) { SetInstance(); return (Result)NativeMethods.aw_terrain_set(x, z, heights.Length, texture, heights); } public Result TerrainQuery(int pageX, int pageZ, long sequence) { SetInstance(); return (Result)NativeMethods.aw_terrain_query(pageX, pageZ, sequence); } public Result TerrainNext() { SetInstance(); return (Result)NativeMethods.aw_terrain_next(); } public Result TerrainDeleteAll() { SetInstance(); return (Result)NativeMethods.aw_terrain_delete_all(); } public Result TerrainLoadNode() { SetInstance(); return (Result)NativeMethods.aw_terrain_load_node(); } #endregion #region Mover methods public Result MoverSetState(int id, int state, int modelNum) { SetInstance(); return (Result)NativeMethods.aw_mover_set_state(id, state, modelNum); } public Result MoverSetPosition(int id, int x, int y, int z, int yaw, int pitch, int roll) { SetInstance(); return (Result)NativeMethods.aw_mover_set_position(id, x, y, z, yaw, pitch, roll); } public Result MoverRiderAdd(int id, int session, int dist, int angle, int yDelta, int yawDelta, int pitchDelta) { SetInstance(); return (Result)NativeMethods.aw_mover_rider_add(id, session, dist, angle, yDelta, yawDelta, pitchDelta); } public Result MoverRiderChange(int id, int session, int dist, int angle, int yDelta, int yawDelta, int pitchDelta) { SetInstance(); return (Result)NativeMethods.aw_mover_rider_change(id, session, dist, angle, yDelta, yawDelta, pitchDelta); } public Result MoverRiderDelete(int id, int session) { SetInstance(); return (Result)NativeMethods.aw_mover_rider_delete(id, session); } public Result MoverLinks(int id) { SetInstance(); return (Result)NativeMethods.aw_mover_links(id); } #endregion #region HUD methods public Result HudCreate() { SetInstance(); return (Result)NativeMethods.aw_hud_create(); } public Result HudClick() { SetInstance(); return (Result)NativeMethods.aw_hud_click(); } public Result HudDestroy(int session, int id) { SetInstance(); return (Result)NativeMethods.aw_hud_destroy(session, id); } public Result HudClear(int session) { SetInstance(); return (Result)NativeMethods.aw_hud_clear(session); } public Result TrafficCount(out int inTraffic, out int outTraffic) { SetInstance(); return (Result)NativeMethods.aw_traffic_count(out inTraffic, out outTraffic); } #endregion #region CAV manipulation methods public Result CavRequest(int citizen, int session) { SetInstance(); return (Result)NativeMethods.aw_cav_request(citizen, session); } public Result CavChange() { SetInstance(); return (Result)NativeMethods.aw_cav_change(); } public Result CavDelete() { SetInstance(); return (Result)NativeMethods.aw_cav_delete(); } public Result WorldCavRequest(int citizen, int session) { SetInstance(); return (Result)NativeMethods.aw_world_cav_request(citizen, session); } public Result WorldCavChange() { SetInstance(); return (Result)NativeMethods.aw_world_cav_change(); } public Result WorldCavDelete() { SetInstance(); return (Result)NativeMethods.aw_world_cav_delete(); } #endregion #region Universe related methods #region Universe management methods public Result UniverseAttributesChange() { SetInstance(); return (Result)NativeMethods.aw_universe_attributes_change(); } public Result UniverseEjectionAdd() { SetInstance(); return (Result)NativeMethods.aw_universe_ejection_add(); } public Result UniverseEjectionDelete(int address) { SetInstance(); return (Result)NativeMethods.aw_universe_ejection_delete(address); } public Result UniverseEjectionLookup() { SetInstance(); return (Result)NativeMethods.aw_universe_ejection_lookup(); } public Result UniverseEjectionNext() { SetInstance(); return (Result)NativeMethods.aw_universe_ejection_next(); } public Result UniverseEjectionPrevious() { SetInstance(); return (Result)NativeMethods.aw_universe_ejection_previous(); } #endregion #region Citizen methods public Result CitizenAttributesByName(string name) { SetInstance(); return (Result)NativeMethods.aw_citizen_attributes_by_name(name); } public Result CitizenAttributesByNumber(int citizen) { SetInstance(); return (Result)NativeMethods.aw_citizen_attributes_by_number(citizen); } public Result CitizenAdd() { SetInstance(); return (Result)NativeMethods.aw_citizen_add(); } public Result CitizenChange() { SetInstance(); return (Result)NativeMethods.aw_citizen_change(); } public Result CitizenDelete(int citizen) { SetInstance(); return (Result)NativeMethods.aw_citizen_delete(citizen); } public Result CitizenNext() { SetInstance(); return (Result)NativeMethods.aw_citizen_next(); } public Result CitizenPrevious() { SetInstance(); return (Result)NativeMethods.aw_citizen_previous(); } #endregion #region World license methods public Result LicenseAdd() { SetInstance(); return (Result)NativeMethods.aw_license_add(); } public Result LicenseAttributes(string name) { SetInstance(); return (Result)NativeMethods.aw_license_attributes(name); } public Result LicenseChange() { SetInstance(); return (Result)NativeMethods.aw_license_change(); } public Result LicenseDelete(string name) { SetInstance(); return (Result)NativeMethods.aw_license_delete(name); } public Result LicenseNext() { SetInstance(); return (Result)NativeMethods.aw_license_next(); } public Result LicensePrevious() { SetInstance(); return (Result)NativeMethods.aw_license_previous(); } #endregion #endregion #region World related methods #region World management methods public Result WorldAttributesChange() { SetInstance(); return (Result)NativeMethods.aw_world_attributes_change(); } public Result WorldEject() { SetInstance(); return (Result)NativeMethods.aw_world_eject(); } public Result WorldReloadRegistry() { SetInstance(); return (Result)NativeMethods.aw_world_reload_registry(); } public Result WorldAttributesReset() { SetInstance(); return (Result)NativeMethods.aw_world_attributes_reset(); } public Result WorldInstanceSet(int citizen, int worldInstance) { SetInstance(); return (Result)NativeMethods.aw_world_instance_set(citizen, worldInstance); } public Result WorldInstanceGet(int citizen) { SetInstance(); return (Result)NativeMethods.aw_world_instance_get(citizen); } public Result WorldAttributesSend(int session) { SetInstance(); return (Result)NativeMethods.aw_world_attributes_send(session); } public Result WorldEjectionAdd() { SetInstance(); return (Result)NativeMethods.aw_world_ejection_add(); } public Result WorldEjectionDelete() { SetInstance(); return (Result)NativeMethods.aw_world_ejection_delete(); } public Result WorldEjectionLookup() { SetInstance(); return (Result)NativeMethods.aw_world_ejection_lookup(); } public Result WorldEjectionNext() { SetInstance(); return (Result)NativeMethods.aw_world_ejection_next(); } public Result WorldEjectionPrevious() { SetInstance(); return (Result)NativeMethods.aw_world_ejection_previous(); } public Result WorldAttributeSet(int attribute, string value) { SetInstance(); return (Result)NativeMethods.aw_world_attribute_set(attribute, value); } public Result WorldAttributeGet(int attribute, out bool readOnly, string value) { SetInstance(); int ro; int ret = NativeMethods.aw_world_attribute_get(attribute, out ro, value); readOnly = ro != 0; return (Result)ret; } #endregion #region Rights Checking Methods public bool CheckRight(int citizen, string rightString) { SetInstance(); return NativeMethods.aw_check_right(citizen, rightString); } public bool CheckRightAll(string rightString) { SetInstance(); return NativeMethods.aw_check_right_all(rightString); } public bool HasWorldRight(int citizen, Attributes right) { SetInstance(); return NativeMethods.aw_has_world_right(citizen, right); } public bool HasWorldRightAll(Attributes right) { SetInstance(); return NativeMethods.aw_has_world_right_all(right); } #endregion #endregion #region World server management methods public Result ServerWorldAdd() { SetInstance(); return (Result)NativeMethods.aw_server_world_add(); } public Result ServerWorldDelete(int id) { SetInstance(); return (Result)NativeMethods.aw_server_world_delete(id); } public Result ServerWorldChange(int id) { SetInstance(); return (Result)NativeMethods.aw_server_world_change(id); } public Result ServerWorldList() { SetInstance(); return (Result)NativeMethods.aw_server_world_list(); } public Result ServerWorldStart(int id) { SetInstance(); return (Result)NativeMethods.aw_server_world_start(id); } public Result ServerWorldStop(int id) { SetInstance(); return (Result)NativeMethods.aw_server_world_stop(id); } public Result ServerWorldSet(int id) { SetInstance(); return (Result)NativeMethods.aw_server_world_set(id); } public Result ServerWorldInstanceSet(int id) { SetInstance(); return (Result)NativeMethods.aw_server_world_instance_set(id); } public Result ServerWorldInstanceAdd(int id, int instanceId) { SetInstance(); return (Result)NativeMethods.aw_server_world_instance_add(id, instanceId); } public Result ServerWorldInstanceDelete(int id, int instanceId) { SetInstance(); return (Result)NativeMethods.aw_server_world_instance_delete(id, instanceId); } #endregion #region Laser Beam methods public Result LaserBeam() { SetInstance(); return (Result)NativeMethods.aw_laser_beam(); } public Result Listen(ChatChannels channels) { SetInstance(); return (Result)NativeMethods.aw_listen((int) channels); } public Result SayChannel(ChatChannels channel, string message) { SetInstance(); return (Result)NativeMethods.aw_say_channel(string.Format(message), (int)channel); } public Result SayChannel(ChatChannels channel, string message, object arg0) { SetInstance(); return (Result)NativeMethods.aw_say_channel(string.Format(message, arg0), (int)channel); } public Result SayChannel(ChatChannels channel, string message, object arg0, object arg1) { SetInstance(); return (Result)NativeMethods.aw_say_channel(string.Format(message, arg0, arg1), (int)channel); } public Result SayChannel(ChatChannels channel, string message, object arg0, object arg1, object arg2) { SetInstance(); return (Result)NativeMethods.aw_say_channel(string.Format(message, arg0, arg1, arg2), (int)channel); } public Result SayChannel(ChatChannels channel, string message, params object[] args) { SetInstance(); return (Result)NativeMethods.aw_say_channel(string.Format(message, args), (int)channel); } public Result ObjectAddSession(int session) { SetInstance(); return (Result) NativeMethods.aw_object_add_session(session); } public Result ObjectDeleteSession(int session) { SetInstance(); return (Result) NativeMethods.aw_object_delete_session(session); } public Result ServerWorldGet() { SetInstance(); return (Result) NativeMethods.aw_server_world_get(); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="OLEDB_Util.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.OleDb { using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; internal static class ODB { // OleDbCommand static internal void CommandParameterStatus(StringBuilder builder, int index, DBStatus status) { switch (status) { case DBStatus.S_OK: case DBStatus.S_ISNULL: case DBStatus.S_IGNORE: break; case DBStatus.E_BADACCESSOR: builder.Append(Res.GetString(Res.OleDb_CommandParameterBadAccessor,index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_CANTCONVERTVALUE: builder.Append(Res.GetString(Res.OleDb_CommandParameterCantConvertValue,index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_SIGNMISMATCH: builder.Append(Res.GetString(Res.OleDb_CommandParameterSignMismatch,index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_DATAOVERFLOW: builder.Append(Res.GetString(Res.OleDb_CommandParameterDataOverflow,index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_CANTCREATE: Debug.Assert(false, "CommandParameterStatus: unexpected E_CANTCREATE"); goto default; case DBStatus.E_UNAVAILABLE: builder.Append(Res.GetString(Res.OleDb_CommandParameterUnavailable,index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; case DBStatus.E_PERMISSIONDENIED: Debug.Assert(false, "CommandParameterStatus: unexpected E_PERMISSIONDENIED"); goto default; case DBStatus.E_INTEGRITYVIOLATION: Debug.Assert(false, "CommandParameterStatus: unexpected E_INTEGRITYVIOLATION"); goto default; case DBStatus.E_SCHEMAVIOLATION: Debug.Assert(false, "CommandParameterStatus: unexpected E_SCHEMAVIOLATION"); goto default; case DBStatus.E_BADSTATUS: Debug.Assert(false, "CommandParameterStatus: unexpected E_BADSTATUS"); goto default; case DBStatus.S_DEFAULT: // MDAC 66626 builder.Append(Res.GetString(Res.OleDb_CommandParameterDefault,index.ToString(CultureInfo.InvariantCulture), "")); builder.Append(Environment.NewLine); break; default: builder.Append(Res.GetString(Res.OleDb_CommandParameterError, index.ToString(CultureInfo.InvariantCulture), status.ToString())); builder.Append(Environment.NewLine); break; } } static internal Exception CommandParameterStatus(string value, Exception inner) { if (ADP.IsEmpty(value)) { return inner; } return ADP.InvalidOperation(value, inner); } static internal Exception UninitializedParameters(int index, OleDbType dbtype) { return ADP.InvalidOperation(Res.GetString(Res.OleDb_UninitializedParameters, index.ToString(CultureInfo.InvariantCulture), dbtype.ToString())); } static internal Exception BadStatus_ParamAcc(int index, DBBindStatus status) { return ADP.DataAdapter(Res.GetString(Res.OleDb_BadStatus_ParamAcc, index.ToString(CultureInfo.InvariantCulture), status.ToString())); } static internal Exception NoProviderSupportForParameters(string provider, Exception inner) { return ADP.DataAdapter(Res.GetString(Res.OleDb_NoProviderSupportForParameters, provider), inner); } static internal Exception NoProviderSupportForSProcResetParameters(string provider) { return ADP.DataAdapter(Res.GetString(Res.OleDb_NoProviderSupportForSProcResetParameters, provider)); } // OleDbProperties static internal void PropsetSetFailure(StringBuilder builder, string description, OleDbPropertyStatus status) { if (OleDbPropertyStatus.Ok == status) { return; } switch (status) { case OleDbPropertyStatus.NotSupported: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyNotSupported, description)); break; case OleDbPropertyStatus.BadValue: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyBadValue, description)); break; case OleDbPropertyStatus.BadOption: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyBadOption, description)); break; case OleDbPropertyStatus.BadColumn: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyBadColumn, description)); break; case OleDbPropertyStatus.NotAllSettable: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyNotAllSettable, description)); break; case OleDbPropertyStatus.NotSettable: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyNotSettable, description)); break; case OleDbPropertyStatus.NotSet: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyNotSet, description)); break; case OleDbPropertyStatus.Conflicting: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyConflicting, description)); break; case OleDbPropertyStatus.NotAvailable: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyNotAvailable, description)); break; default: if (0 < builder.Length) { builder.Append(Environment.NewLine); } builder.Append(Res.GetString(Res.OleDb_PropertyStatusUnknown, ((int) status).ToString(CultureInfo.InvariantCulture))); break; } } static internal Exception PropsetSetFailure(string value, Exception inner) { if (ADP.IsEmpty(value)) { return inner; } return ADP.InvalidOperation(value, inner); } // OleDbConnection static internal ArgumentException SchemaRowsetsNotSupported(string provider) { return ADP.Argument(Res.GetString(Res.OleDb_SchemaRowsetsNotSupported, "IDBSchemaRowset", provider)); } static internal OleDbException NoErrorInformation(string provider, OleDbHResult hr, Exception inner) { OleDbException e; if (!ADP.IsEmpty(provider)) { e = new OleDbException(Res.GetString(Res.OleDb_NoErrorInformation2, provider, ODB.ELookup(hr)), hr, inner); } else { e = new OleDbException(Res.GetString(Res.OleDb_NoErrorInformation, ODB.ELookup(hr)), hr, inner); } ADP.TraceExceptionAsReturnValue(e); return e; } static internal InvalidOperationException MDACNotAvailable(Exception inner) { return ADP.DataAdapter(Res.GetString(Res.OleDb_MDACNotAvailable), inner); } static internal ArgumentException MSDASQLNotSupported() { return ADP.Argument(Res.GetString(Res.OleDb_MSDASQLNotSupported)); // MDAC 69975 } static internal InvalidOperationException CommandTextNotSupported(string provider, Exception inner) { return ADP.DataAdapter(Res.GetString(Res.OleDb_CommandTextNotSupported, provider), inner); // 72632 } static internal InvalidOperationException PossiblePromptNotUserInteractive() { return ADP.DataAdapter(Res.GetString(Res.OleDb_PossiblePromptNotUserInteractive)); } static internal InvalidOperationException ProviderUnavailable(string provider, Exception inner) { //return new OleDbException(Res.GetString(Res.OleDb_ProviderUnavailable, provider), (int)OleDbHResult.CO_E_CLASSSTRING, inner); return ADP.DataAdapter(Res.GetString(Res.OleDb_ProviderUnavailable, provider), inner); } static internal InvalidOperationException TransactionsNotSupported(string provider, Exception inner) { return ADP.DataAdapter(Res.GetString(Res.OleDb_TransactionsNotSupported, provider), inner); // 72632 } static internal ArgumentException AsynchronousNotSupported() { return ADP.Argument(Res.GetString(Res.OleDb_AsynchronousNotSupported)); } static internal ArgumentException NoProviderSpecified() { return ADP.Argument(Res.GetString(Res.OleDb_NoProviderSpecified)); } static internal ArgumentException InvalidProviderSpecified() { return ADP.Argument(Res.GetString(Res.OleDb_InvalidProviderSpecified)); } static internal ArgumentException InvalidRestrictionsDbInfoKeywords(string parameter) { return ADP.Argument(Res.GetString(Res.OleDb_InvalidRestrictionsDbInfoKeywords), parameter); } static internal ArgumentException InvalidRestrictionsDbInfoLiteral(string parameter) { return ADP.Argument(Res.GetString(Res.OleDb_InvalidRestrictionsDbInfoLiteral), parameter); } static internal ArgumentException InvalidRestrictionsSchemaGuids(string parameter) { return ADP.Argument(Res.GetString(Res.OleDb_InvalidRestrictionsSchemaGuids), parameter); } static internal ArgumentException NotSupportedSchemaTable(Guid schema, OleDbConnection connection) { return ADP.Argument(Res.GetString(Res.OleDb_NotSupportedSchemaTable, OleDbSchemaGuid.GetTextFromValue(schema), connection.Provider)); } // OleDbParameter static internal Exception InvalidOleDbType(OleDbType value) { return ADP.InvalidEnumerationValue(typeof(OleDbType), (int)value); } // Getting Data static internal InvalidOperationException BadAccessor() { return ADP.DataAdapter(Res.GetString(Res.OleDb_BadAccessor)); } static internal InvalidCastException ConversionRequired() { return ADP.InvalidCast(); } static internal InvalidCastException CantConvertValue() { return ADP.InvalidCast(Res.GetString(Res.OleDb_CantConvertValue)); } static internal InvalidOperationException SignMismatch(Type type) { return ADP.DataAdapter(Res.GetString(Res.OleDb_SignMismatch, type.Name)); } static internal InvalidOperationException DataOverflow(Type type) { return ADP.DataAdapter(Res.GetString(Res.OleDb_DataOverflow, type.Name)); } static internal InvalidOperationException CantCreate(Type type) { return ADP.DataAdapter(Res.GetString(Res.OleDb_CantCreate, type.Name)); } static internal InvalidOperationException Unavailable(Type type) { return ADP.DataAdapter(Res.GetString(Res.OleDb_Unavailable, type.Name)); } static internal InvalidOperationException UnexpectedStatusValue(DBStatus status) { return ADP.DataAdapter(Res.GetString(Res.OleDb_UnexpectedStatusValue, status.ToString())); } static internal InvalidOperationException GVtUnknown(int wType) { return ADP.DataAdapter(Res.GetString(Res.OleDb_GVtUnknown, wType.ToString("X4", CultureInfo.InvariantCulture), wType.ToString(CultureInfo.InvariantCulture))); } static internal InvalidOperationException SVtUnknown(int wType) { return ADP.DataAdapter(Res.GetString(Res.OleDb_SVtUnknown, wType.ToString("X4", CultureInfo.InvariantCulture), wType.ToString(CultureInfo.InvariantCulture))); } // OleDbDataReader static internal InvalidOperationException BadStatusRowAccessor(int i, DBBindStatus rowStatus) { return ADP.DataAdapter(Res.GetString(Res.OleDb_BadStatusRowAccessor, i.ToString(CultureInfo.InvariantCulture), rowStatus.ToString())); } static internal InvalidOperationException ThreadApartmentState(Exception innerException) { return ADP.InvalidOperation(Res.GetString(Res.OleDb_ThreadApartmentState), innerException); } // OleDbDataAdapter static internal ArgumentException Fill_NotADODB(string parameter) { return ADP.Argument(Res.GetString(Res.OleDb_Fill_NotADODB), parameter); } static internal ArgumentException Fill_EmptyRecordSet(string parameter, Exception innerException) { return ADP.Argument(Res.GetString(Res.OleDb_Fill_EmptyRecordSet, "IRowset"), parameter, innerException); } static internal ArgumentException Fill_EmptyRecord(string parameter, Exception innerException) { return ADP.Argument(Res.GetString(Res.OleDb_Fill_EmptyRecord), parameter, innerException); } static internal string NoErrorMessage(OleDbHResult errorcode) { return Res.GetString(Res.OleDb_NoErrorMessage, ODB.ELookup(errorcode)); } static internal string FailedGetDescription(OleDbHResult errorcode) { return Res.GetString(Res.OleDb_FailedGetDescription, ODB.ELookup(errorcode)); } static internal string FailedGetSource(OleDbHResult errorcode) { return Res.GetString(Res.OleDb_FailedGetSource, ODB.ELookup(errorcode)); } static internal InvalidOperationException DBBindingGetVector() { return ADP.InvalidOperation(Res.GetString(Res.OleDb_DBBindingGetVector)); } static internal OleDbHResult GetErrorDescription(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult hresult, out string message) { Bid.Trace("<oledb.IErrorInfo.GetDescription|API|OS>\n"); OleDbHResult hr = errorInfo.GetDescription(out message); Bid.Trace("<oledb.IErrorInfo.GetDescription|API|OS|RET> %08X{HRESULT}, Message='%ls'\n", hr, message); if (((int)hr < 0) && ADP.IsEmpty(message)) { message = FailedGetDescription(hr) + Environment.NewLine + ODB.ELookup(hresult); } if (ADP.IsEmpty(message)) { message = ODB.ELookup(hresult); } return hr; } // OleDbEnumerator internal static ArgumentException ISourcesRowsetNotSupported() { throw ADP.Argument(Res.OleDb_ISourcesRowsetNotSupported); } // OleDbMetaDataFactory static internal InvalidOperationException IDBInfoNotSupported() { return ADP.InvalidOperation(Res.GetString(Res.OleDb_IDBInfoNotSupported)); } // explictly used error codes internal const int ADODB_AlreadyClosedError = unchecked((int)0x800A0E78); internal const int ADODB_NextResultError = unchecked((int)0x800A0CB3); // internal command states internal const int InternalStateExecuting = (int) (ConnectionState.Open | ConnectionState.Executing); internal const int InternalStateFetching = (int) (ConnectionState.Open | ConnectionState.Fetching); internal const int InternalStateClosed = (int) (ConnectionState.Closed); internal const int ExecutedIMultipleResults = 0; internal const int ExecutedIRowset = 1; internal const int ExecutedIRow = 2; internal const int PrepareICommandText = 3; // internal connection states, a superset of the command states internal const int InternalStateExecutingNot = (int) ~(ConnectionState.Executing); internal const int InternalStateFetchingNot = (int) ~(ConnectionState.Fetching); internal const int InternalStateConnecting = (int) (ConnectionState.Connecting); internal const int InternalStateOpen = (int) (ConnectionState.Open); // constants used to trigger from binding as WSTR to BYREF|WSTR // used by OleDbCommand, OleDbDataReader internal const int LargeDataSize = (1 << 13); // 8K internal const int CacheIncrement = 10; // constants used by OleDbDataReader internal static readonly IntPtr DBRESULTFLAG_DEFAULT = IntPtr.Zero; internal const short VARIANT_TRUE = -1; internal const short VARIANT_FALSE = 0; // OleDbConnection constants internal const int CLSCTX_ALL = /*CLSCTX_INPROC_SERVER*/1 | /*CLSCTX_INPROC_HANDLER*/2 | /*CLSCTX_LOCAL_SERVER*/4 | /*CLSCTX_REMOTE_SERVER*/16; internal const int MaxProgIdLength = 255; internal const int DBLITERAL_CATALOG_SEPARATOR = 3; internal const int DBLITERAL_QUOTE_PREFIX = 15; internal const int DBLITERAL_QUOTE_SUFFIX = 28; internal const int DBLITERAL_SCHEMA_SEPARATOR = 27; internal const int DBLITERAL_TABLE_NAME = 17; internal const int DBPROP_ACCESSORDER = 0xe7; internal const int DBPROP_AUTH_CACHE_AUTHINFO = 0x5; internal const int DBPROP_AUTH_ENCRYPT_PASSWORD= 0x6; internal const int DBPROP_AUTH_INTEGRATED = 0x7; internal const int DBPROP_AUTH_MASK_PASSWORD = 0x8; internal const int DBPROP_AUTH_PASSWORD = 0x9; internal const int DBPROP_AUTH_PERSIST_ENCRYPTED = 0xa; internal const int DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO = 0xb; internal const int DBPROP_AUTH_USERID = 0xc; internal const int DBPROP_CATALOGLOCATION = 0x16; internal const int DBPROP_COMMANDTIMEOUT = 0x22; internal const int DBPROP_CONNECTIONSTATUS = 0xf4; internal const int DBPROP_CURRENTCATALOG = 0x25; internal const int DBPROP_DATASOURCENAME = 0x26; internal const int DBPROP_DBMSNAME = 0x28; internal const int DBPROP_DBMSVER = 0x29; internal const int DBPROP_GROUPBY = 0x2c; internal const int DBPROP_HIDDENCOLUMNS = 0x102; internal const int DBPROP_IColumnsRowset = 0x7b; internal const int DBPROP_IDENTIFIERCASE = 0x2e; internal const int DBPROP_INIT_ASYNCH = 0xc8; internal const int DBPROP_INIT_BINDFLAGS = 0x10e; internal const int DBPROP_INIT_CATALOG = 0xe9; internal const int DBPROP_INIT_DATASOURCE = 0x3b; internal const int DBPROP_INIT_GENERALTIMEOUT = 0x11c; internal const int DBPROP_INIT_HWND = 0x3c; internal const int DBPROP_INIT_IMPERSONATION_LEVEL = 0x3d; internal const int DBPROP_INIT_LCID = 0xba; internal const int DBPROP_INIT_LOCATION = 0x3e; internal const int DBPROP_INIT_LOCKOWNER = 0x10f; internal const int DBPROP_INIT_MODE = 0x3f; internal const int DBPROP_INIT_OLEDBSERVICES = 0xf8; internal const int DBPROP_INIT_PROMPT = 0x40; internal const int DBPROP_INIT_PROTECTION_LEVEL= 0x41; internal const int DBPROP_INIT_PROVIDERSTRING = 0xa0; internal const int DBPROP_INIT_TIMEOUT = 0x42; internal const int DBPROP_IRow = 0x107; internal const int DBPROP_MAXROWS = 0x49; internal const int DBPROP_MULTIPLERESULTS = 0xc4; internal const int DBPROP_ORDERBYCOLUNSINSELECT= 0x55; internal const int DBPROP_PROVIDERFILENAME = 0x60; internal const int DBPROP_QUOTEDIDENTIFIERCASE = 0x64; internal const int DBPROP_RESETDATASOURCE = 0xf7; internal const int DBPROP_SQLSUPPORT = 0x6d; internal const int DBPROP_UNIQUEROWS = 0xee; // property status internal const int DBPROPSTATUS_OK = 0; internal const int DBPROPSTATUS_NOTSUPPORTED = 1; internal const int DBPROPSTATUS_BADVALUE = 2; internal const int DBPROPSTATUS_BADOPTION = 3; internal const int DBPROPSTATUS_BADCOLUMN = 4; internal const int DBPROPSTATUS_NOTALLSETTABLE = 5; internal const int DBPROPSTATUS_NOTSETTABLE = 6; internal const int DBPROPSTATUS_NOTSET = 7; internal const int DBPROPSTATUS_CONFLICTING = 8; internal const int DBPROPSTATUS_NOTAVAILABLE = 9; internal const int DBPROPOPTIONS_REQUIRED = 0; internal const int DBPROPOPTIONS_OPTIONAL = 1; internal const int DBPROPFLAGS_WRITE = 0x400; internal const int DBPROPFLAGS_SESSION = 0x1000; // misc. property values internal const int DBPROPVAL_AO_RANDOM = 2; internal const int DBPROPVAL_CL_END = 2; internal const int DBPROPVAL_CL_START = 1; internal const int DBPROPVAL_CS_COMMUNICATIONFAILURE = 2; internal const int DBPROPVAL_CS_INITIALIZED = 1; internal const int DBPROPVAL_CS_UNINITIALIZED = 0; internal const int DBPROPVAL_GB_COLLATE = 16; internal const int DBPROPVAL_GB_CONTAINS_SELECT = 4; internal const int DBPROPVAL_GB_EQUALS_SELECT = 2; internal const int DBPROPVAL_GB_NO_RELATION = 8; internal const int DBPROPVAL_GB_NOT_SUPPORTED = 1; internal const int DBPROPVAL_IC_LOWER = 2; internal const int DBPROPVAL_IC_MIXED = 8; internal const int DBPROPVAL_IC_SENSITIVE = 4; internal const int DBPROPVAL_IC_UPPER = 1; internal const int DBPROPVAL_IN_ALLOWNULL = 0x00000000; /*internal const int DBPROPVAL_IN_DISALLOWNULL = 0x00000001; internal const int DBPROPVAL_IN_IGNORENULL = 0x00000002; internal const int DBPROPVAL_IN_IGNOREANYNULL = 0x00000004;*/ internal const int DBPROPVAL_MR_NOTSUPPORTED = 0; internal const int DBPROPVAL_RD_RESETALL = unchecked((int) 0xffffffff); internal const int DBPROPVAL_OS_RESOURCEPOOLING = 0x00000001; internal const int DBPROPVAL_OS_TXNENLISTMENT = 0x00000002; internal const int DBPROPVAL_OS_CLIENTCURSOR = 0x00000004; internal const int DBPROPVAL_OS_AGR_AFTERSESSION = 0x00000008; internal const int DBPROPVAL_SQL_ODBC_MINIMUM = 1; internal const int DBPROPVAL_SQL_ESCAPECLAUSES = 0x00000100; // OLE DB providers never return pGuid-style bindings. // They are provided as a convenient shortcut for consumers supplying bindings all covered by the same GUID (for example, when creating bindings to access data). internal const int DBKIND_GUID_NAME = 0; internal const int DBKIND_GUID_PROPID = 1; internal const int DBKIND_NAME = 2; internal const int DBKIND_PGUID_NAME = 3; internal const int DBKIND_PGUID_PROPID = 4; internal const int DBKIND_PROPID = 5; internal const int DBKIND_GUID = 6; internal const int DBCOLUMNFLAGS_ISBOOKMARK = 0x01; internal const int DBCOLUMNFLAGS_ISLONG = 0x80; internal const int DBCOLUMNFLAGS_ISFIXEDLENGTH = 0x10; internal const int DBCOLUMNFLAGS_ISNULLABLE = 0x20; internal const int DBCOLUMNFLAGS_ISROWSET = 0x100000; internal const int DBCOLUMNFLAGS_ISROW = 0x200000; internal const int DBCOLUMNFLAGS_ISROWSET_DBCOLUMNFLAGS_ISROW = /*DBCOLUMNFLAGS_ISROWSET*/0x100000 | /*DBCOLUMNFLAGS_ISROW*/0x200000; internal const int DBCOLUMNFLAGS_ISLONG_DBCOLUMNFLAGS_ISSTREAM = /*DBCOLUMNFLAGS_ISLONG*/0x80 | /*DBCOLUMNFLAGS_ISSTREAM*/0x80000; internal const int DBCOLUMNFLAGS_ISROWID_DBCOLUMNFLAGS_ISROWVER = /*DBCOLUMNFLAGS_ISROWID*/0x100 | /*DBCOLUMNFLAGS_ISROWVER*/0x200; internal const int DBCOLUMNFLAGS_WRITE_DBCOLUMNFLAGS_WRITEUNKNOWN = /*DBCOLUMNFLAGS_WRITE*/0x4 | /*DBCOLUMNFLAGS_WRITEUNKNOWN*/0x8; internal const int DBCOLUMNFLAGS_ISNULLABLE_DBCOLUMNFLAGS_MAYBENULL = /*DBCOLUMNFLAGS_ISNULLABLE*/0x20 | /*DBCOLUMNFLAGS_MAYBENULL*/0x40; // accessor constants internal const int DBACCESSOR_ROWDATA = 0x2; internal const int DBACCESSOR_PARAMETERDATA = 0x4; // commandbuilder constants internal const int DBPARAMTYPE_INPUT = 0x01; internal const int DBPARAMTYPE_INPUTOUTPUT = 0x02; internal const int DBPARAMTYPE_OUTPUT = 0x03; internal const int DBPARAMTYPE_RETURNVALUE = 0x04; // parameter constants /*internal const int DBPARAMIO_NOTPARAM = 0; internal const int DBPARAMIO_INPUT = 0x1; internal const int DBPARAMIO_OUTPUT = 0x2;*/ /*internal const int DBPARAMFLAGS_ISINPUT = 0x1; internal const int DBPARAMFLAGS_ISOUTPUT = 0x2; internal const int DBPARAMFLAGS_ISSIGNED = 0x10; internal const int DBPARAMFLAGS_ISNULLABLE = 0x40; internal const int DBPARAMFLAGS_ISLONG = 0x80;*/ internal const int ParameterDirectionFlag = 3; // values of the searchable column in the provider types schema rowset internal const uint DB_UNSEARCHABLE = 1; internal const uint DB_LIKE_ONLY = 2; internal const uint DB_ALL_EXCEPT_LIKE = 3; internal const uint DB_SEARCHABLE = 4; static internal readonly IntPtr DB_INVALID_HACCESSOR = ADP.PtrZero; static internal readonly IntPtr DB_NULL_HCHAPTER = ADP.PtrZero; static internal readonly IntPtr DB_NULL_HROW = ADP.PtrZero; /*static internal readonly int SizeOf_tagDBPARAMINFO = Marshal.SizeOf(typeof(tagDBPARAMINFO));*/ static internal readonly int SizeOf_tagDBBINDING = Marshal.SizeOf(typeof(tagDBBINDING)); static internal readonly int SizeOf_tagDBCOLUMNINFO = Marshal.SizeOf(typeof(tagDBCOLUMNINFO)); static internal readonly int SizeOf_tagDBLITERALINFO = Marshal.SizeOf(typeof(tagDBLITERALINFO)); static internal readonly int SizeOf_tagDBPROPSET = Marshal.SizeOf(typeof(tagDBPROPSET)); static internal readonly int SizeOf_tagDBPROP = Marshal.SizeOf(typeof(tagDBPROP)); static internal readonly int SizeOf_tagDBPROPINFOSET = Marshal.SizeOf(typeof(tagDBPROPINFOSET)); static internal readonly int SizeOf_tagDBPROPINFO = Marshal.SizeOf(typeof(tagDBPROPINFO)); static internal readonly int SizeOf_tagDBPROPIDSET = Marshal.SizeOf(typeof(tagDBPROPIDSET)); static internal readonly int SizeOf_Guid = Marshal.SizeOf(typeof(Guid)); static internal readonly int SizeOf_Variant = 8 + (2 * ADP.PtrSize); // 16 on 32bit, 24 on 64bit static internal readonly int OffsetOf_tagDBPROP_Status = Marshal.OffsetOf(typeof(tagDBPROP), "dwStatus").ToInt32(); static internal readonly int OffsetOf_tagDBPROP_Value = Marshal.OffsetOf(typeof(tagDBPROP), "vValue").ToInt32(); static internal readonly int OffsetOf_tagDBPROPSET_Properties = Marshal.OffsetOf(typeof(tagDBPROPSET), "rgProperties").ToInt32(); static internal readonly int OffsetOf_tagDBPROPINFO_Value = Marshal.OffsetOf(typeof(tagDBPROPINFO), "vValue").ToInt32(); static internal readonly int OffsetOf_tagDBPROPIDSET_PropertySet = Marshal.OffsetOf(typeof(tagDBPROPIDSET), "guidPropertySet").ToInt32(); static internal readonly int OffsetOf_tagDBLITERALINFO_it = Marshal.OffsetOf(typeof(tagDBLITERALINFO), "it").ToInt32(); static internal readonly int OffsetOf_tagDBBINDING_obValue = Marshal.OffsetOf(typeof(tagDBBINDING), "obValue").ToInt32(); static internal readonly int OffsetOf_tagDBBINDING_wType = Marshal.OffsetOf(typeof(tagDBBINDING), "wType").ToInt32(); static internal Guid IID_NULL = Guid.Empty; static internal Guid IID_IUnknown = new Guid(0x00000000,0x0000,0x0000,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46); static internal Guid IID_IDBInitialize = new Guid(0x0C733A8B,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_IDBCreateSession = new Guid(0x0C733A5D,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_IDBCreateCommand = new Guid(0x0C733A1D,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_ICommandText = new Guid(0x0C733A27,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_IMultipleResults = new Guid(0x0C733A90,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_IRow = new Guid(0x0C733AB4,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_IRowset = new Guid(0x0C733A7C,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid IID_ISQLErrorInfo = new Guid(0x0C733A74,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal Guid CLSID_DataLinks = new Guid(0x2206CDB2,0x19C1,0x11D1,0x89,0xE0,0x00,0xC0,0x4F,0xD7,0xA8,0x29); static internal Guid DBGUID_DEFAULT = new Guid(0xc8b521fb,0x5cf3,0x11ce,0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d); static internal Guid DBGUID_ROWSET = new Guid(0xc8b522f6,0x5cf3,0x11ce,0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d); static internal Guid DBGUID_ROW = new Guid(0xc8b522f7,0x5cf3,0x11ce,0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d); static internal Guid DBGUID_ROWDEFAULTSTREAM = new Guid(0x0C733AB7,0x2A1C,0x11CE,0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D); static internal readonly Guid CLSID_MSDASQL = new Guid(0xc8b522cb,0x5cf3,0x11ce,0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d); static internal readonly object DBCOL_SPECIALCOL = new Guid(0xc8b52232,0x5cf3,0x11ce,0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d); static internal readonly char[] ErrorTrimCharacters = new char[] { '\r', '\n', '\0' }; // MDAC 73707 // used by ConnectionString hashtable, must be all lowercase internal const string Asynchronous_Processing = "asynchronous processing"; internal const string AttachDBFileName = "attachdbfilename"; internal const string Connect_Timeout = "connect timeout"; internal const string Data_Source = "data source"; internal const string File_Name = "file name"; internal const string Initial_Catalog = "initial catalog"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Provider = "provider"; internal const string Pwd = "pwd"; internal const string User_ID = "user id"; // used by OleDbConnection as property names internal const string Current_Catalog = "current catalog"; internal const string DBMS_Version = "dbms version"; internal const string Properties = "Properties"; // used by OleDbConnection to create and verify OLE DB Services internal const string DataLinks_CLSID = "CLSID\\{2206CDB2-19C1-11D1-89E0-00C04FD7A829}\\InprocServer32"; internal const string OLEDB_SERVICES = "OLEDB_SERVICES"; // used by OleDbConnection to eliminate post-open detection of 'Microsoft OLE DB Provider for ODBC Drivers' internal const string DefaultDescription_MSDASQL = "microsoft ole db provider for odbc drivers"; internal const string MSDASQL = "msdasql"; internal const string MSDASQLdot = "msdasql."; // used by OleDbPermission internal const string _Add = "add"; internal const string _Keyword = "keyword"; internal const string _Name = "name"; internal const string _Value = "value"; // IColumnsRowset column names internal const string DBCOLUMN_BASECATALOGNAME = "DBCOLUMN_BASECATALOGNAME"; internal const string DBCOLUMN_BASECOLUMNNAME = "DBCOLUMN_BASECOLUMNNAME"; internal const string DBCOLUMN_BASESCHEMANAME = "DBCOLUMN_BASESCHEMANAME"; internal const string DBCOLUMN_BASETABLENAME = "DBCOLUMN_BASETABLENAME"; internal const string DBCOLUMN_COLUMNSIZE = "DBCOLUMN_COLUMNSIZE"; internal const string DBCOLUMN_FLAGS = "DBCOLUMN_FLAGS"; internal const string DBCOLUMN_GUID = "DBCOLUMN_GUID"; internal const string DBCOLUMN_IDNAME = "DBCOLUMN_IDNAME"; internal const string DBCOLUMN_ISAUTOINCREMENT = "DBCOLUMN_ISAUTOINCREMENT"; internal const string DBCOLUMN_ISUNIQUE = "DBCOLUMN_ISUNIQUE"; internal const string DBCOLUMN_KEYCOLUMN = "DBCOLUMN_KEYCOLUMN"; internal const string DBCOLUMN_NAME = "DBCOLUMN_NAME"; internal const string DBCOLUMN_NUMBER = "DBCOLUMN_NUMBER"; internal const string DBCOLUMN_PRECISION = "DBCOLUMN_PRECISION"; internal const string DBCOLUMN_PROPID = "DBCOLUMN_PROPID"; internal const string DBCOLUMN_SCALE = "DBCOLUMN_SCALE"; internal const string DBCOLUMN_TYPE = "DBCOLUMN_TYPE"; internal const string DBCOLUMN_TYPEINFO = "DBCOLUMN_TYPEINFO"; // ISchemaRowset.GetRowset(OleDbSchemaGuid.Indexes) column names internal const string PRIMARY_KEY = "PRIMARY_KEY"; internal const string UNIQUE = "UNIQUE"; internal const string COLUMN_NAME = "COLUMN_NAME"; internal const string NULLS = "NULLS"; internal const string INDEX_NAME = "INDEX_NAME"; // ISchemaRowset.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters) column names internal const string PARAMETER_NAME = "PARAMETER_NAME"; internal const string ORDINAL_POSITION = "ORDINAL_POSITION"; internal const string PARAMETER_TYPE = "PARAMETER_TYPE"; internal const string IS_NULLABLE = "IS_NULLABLE"; internal const string DATA_TYPE = "DATA_TYPE"; internal const string CHARACTER_MAXIMUM_LENGTH = "CHARACTER_MAXIMUM_LENGTH"; internal const string NUMERIC_PRECISION = "NUMERIC_PRECISION"; internal const string NUMERIC_SCALE = "NUMERIC_SCALE"; internal const string TYPE_NAME = "TYPE_NAME"; // DataTable.Select to sort on ordinal position for OleDbSchemaGuid.Procedure_Parameters internal const string ORDINAL_POSITION_ASC = "ORDINAL_POSITION ASC"; // OleDbConnection.GetOleDbSchemmaTable(OleDbSchemaGuid.SchemaGuids) table and column names internal const string SchemaGuids = "SchemaGuids"; internal const string Schema = "Schema"; internal const string RestrictionSupport = "RestrictionSupport"; // OleDbConnection.GetOleDbSchemmaTable(OleDbSchemaGuid.DbInfoKeywords) table and column names internal const string DbInfoKeywords = "DbInfoKeywords"; internal const string Keyword = "Keyword"; // Debug error string writeline static internal string ELookup(OleDbHResult hr) { StringBuilder builder = new StringBuilder(); builder.Append(hr.ToString()); if ((0 < builder.Length) && Char.IsDigit(builder[0])) { builder.Length = 0; } builder.Append("(0x"); builder.Append(((int)hr).ToString("X8", CultureInfo.InvariantCulture)); builder.Append(")"); return builder.ToString(); } #if DEBUG static readonly private Hashtable g_wlookpup = new Hashtable(); static internal string WLookup(short id) { string value = (string)g_wlookpup[id]; if (null == value) { value = "0x" + ((short) id).ToString("X2", CultureInfo.InvariantCulture) + " " + ((short) id); value += " " + ((DBTypeEnum) id).ToString(); g_wlookpup[id] = value; } return value; } private enum DBTypeEnum { EMPTY = 0, // NULL = 1, // I2 = 2, // I4 = 3, // R4 = 4, // R8 = 5, // CY = 6, // DATE = 7, // BSTR = 8, // IDISPATCH = 9, // ERROR = 10, // BOOL = 11, // VARIANT = 12, // IUNKNOWN = 13, // DECIMAL = 14, // I1 = 16, // UI1 = 17, // UI2 = 18, // UI4 = 19, // I8 = 20, // UI8 = 21, // FILETIME = 64, // 2.0 GUID = 72, // BYTES = 128, // STR = 129, // WSTR = 130, // NUMERIC = 131, // with potential overflow UDT = 132, // should never be encountered DBDATE = 133, // DBTIME = 134, // DBTIMESTAMP = 135, // granularity reduced from 1ns to 100ns (sql is 3.33 milli seconds) HCHAPTER = 136, // 1.5 PROPVARIANT = 138, // 2.0 - as variant VARNUMERIC = 139, // 2.0 - as string else ConversionException BYREF_I2 = 0x4002, BYREF_I4 = 0x4003, BYREF_R4 = 0x4004, BYREF_R8 = 0x4005, BYREF_CY = 0x4006, BYREF_DATE = 0x4007, BYREF_BSTR = 0x4008, BYREF_IDISPATCH = 0x4009, BYREF_ERROR = 0x400a, BYREF_BOOL = 0x400b, BYREF_VARIANT = 0x400c, BYREF_IUNKNOWN = 0x400d, BYREF_DECIMAL = 0x400e, BYREF_I1 = 0x4010, BYREF_UI1 = 0x4011, BYREF_UI2 = 0x4012, BYREF_UI4 = 0x4013, BYREF_I8 = 0x4014, BYREF_UI8 = 0x4015, BYREF_FILETIME = 0x4040, BYREF_GUID = 0x4048, BYREF_BYTES = 0x4080, BYREF_STR = 0x4081, BYREF_WSTR = 0x4082, BYREF_NUMERIC = 0x4083, BYREF_UDT = 0x4084, BYREF_DBDATE = 0x4085, BYREF_DBTIME = 0x4086, BYREF_DBTIMESTAMP = 0x4087, BYREF_HCHAPTER = 0x4088, BYREF_PROPVARIANT = 0x408a, BYREF_VARNUMERIC = 0x408b, VECTOR = 0x1000, ARRAY = 0x2000, BYREF = 0x4000, // RESERVED = 0x8000, // SystemException } #endif } }
using System; using System.Collections; using System.IO; using BigMath; using NUnit.Framework; using Raksha.Asn1.X509; using Raksha.Math; using Raksha.Utilities.Date; using Raksha.Tests.Utilities; using Raksha.X509; using Raksha.X509.Store; namespace Raksha.Tests.Misc { [TestFixture] public class X509StoreTest : SimpleTest { private void certPairTest() { X509CertificateParser certParser = new X509CertificateParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); // Testing CollectionCertStore generation from List X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert); IList certList = new ArrayList(); certList.Add(pair1); certList.Add(new X509CertificatePair(interCert, finalCert)); IX509Store certStore = X509StoreFactory.Create( "CertificatePair/Collection", new X509CollectionStoreParameters(certList)); X509CertPairStoreSelector selector = new X509CertPairStoreSelector(); X509CertStoreSelector fwSelector = new X509CertStoreSelector(); fwSelector.SerialNumber = rootCert.SerialNumber; fwSelector.Subject = rootCert.IssuerDN; selector.ForwardSelector = fwSelector; IList col = new ArrayList(certStore.GetMatches(selector)); if (col.Count != 1 || !col.Contains(pair1)) { Fail("failed pair1 test"); } col = new ArrayList(certStore.GetMatches(null)); if (col.Count != 2) { Fail("failed null test"); } } public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin); X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin); // Testing CollectionCertStore generation from List IList certList = new ArrayList(); certList.Add(rootCert); certList.Add(interCert); certList.Add(finalCert); IX509Store certStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // set default to be the same as for SUN X500 name X509Name.DefaultReverse = true; // Searching for rootCert by subjectDN X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); IList certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by subjectDN"); } // Searching for rootCert by subjectDN encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded subjectDN"); } X509Name.DefaultReverse = false; // Searching for rootCert by public key encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.SubjectPublicKey = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey()); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded public key"); } // Searching for interCert by issuerDN targetConstraints = new X509CertStoreSelector(); targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 2) { Fail("did not found 2 certs"); } if (!certs.Contains(rootCert)) { Fail("rootCert not found"); } if (!certs.Contains(interCert)) { Fail("interCert not found"); } // Searching for rootCrl by issuerDN IList crlList = new ArrayList(); crlList.Add(rootCrl); crlList.Add(interCrl); IX509Store store = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector(); ArrayList issuers = new ArrayList(); issuers.Add(rootCrl.IssuerDN); targetConstraintsCRL.Issuers = issuers; IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL)); if (crls.Count != 1 || !crls.Contains(rootCrl)) { Fail("rootCrl not found"); } crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL)); if (crls.Count != 0) { Fail("error using wrong selector (CRL)"); } certs = new ArrayList(store.GetMatches(targetConstraints)); if (certs.Count != 0) { Fail("error using wrong selector (certs)"); } // Searching for attribute certificates X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); IList attrList = new ArrayList(); attrList.Add(attrCert); attrList.Add(attrCert2); store = X509StoreFactory.Create( "AttributeCertificate/Collection", new X509CollectionStoreParameters(attrList)); X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector(); attrSelector.Holder = attrCert.Holder; if (!attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } IList attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on holder"); } attrSelector.Holder = attrCert2.Holder; if (attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on holder"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.Issuer = attrCert.Issuer; if (!attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on issuer"); } attrSelector.Issuer = attrCert2.Issuer; if (attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on issuer"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCert = attrCert; if (!attrSelector.AttributeCert.Equals(attrCert)) { Fail("attrCert get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on attrCert"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.SerialNumber = attrCert.SerialNumber; if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone(); if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore); if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore) { Fail("valid get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on valid"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on before"); } attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on after"); } attrSelector.SerialNumber = BigInteger.ValueOf(10000); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on wrong serial number"); } attrSelector.AttributeCert = null; attrSelector.AttributeCertificateValid = null; attrSelector.Holder = null; attrSelector.Issuer = null; attrSelector.SerialNumber = null; if (attrSelector.AttributeCert != null) { Fail("null attrCert"); } if (attrSelector.AttributeCertificateValid != null) { Fail("null attrCertValid"); } if (attrSelector.Holder != null) { Fail("null attrCert holder"); } if (attrSelector.Issuer != null) { Fail("null attrCert issuer"); } if (attrSelector.SerialNumber != null) { Fail("null attrCert serial"); } attrs = new ArrayList(certStore.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("error using wrong selector (attrs)"); } certPairTest(); } public override string Name { get { return "IX509Store"; } } public static void Main( string[] args) { RunTest(new X509StoreTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.ReminderService { internal class AzureBasedReminderTable : IReminderTable { private TraceLogger logger; private RemindersTableManager remTableManager; public async Task Init(GlobalConfiguration config, TraceLogger logger) { this.logger = logger; remTableManager = await RemindersTableManager.GetManager(config.ServiceId, config.DeploymentId, config.DataConnectionStringForReminders); } #region Utility methods private ReminderTableData ConvertFromTableEntryList(IEnumerable<Tuple<ReminderTableEntry, string>> entries) { var remEntries = new List<ReminderEntry>(); foreach (var entry in entries) { try { ReminderEntry converted = ConvertFromTableEntry(entry.Item1, entry.Item2); remEntries.Add(converted); } catch (Exception) { // Ignoring... } } return new ReminderTableData(remEntries); } private ReminderEntry ConvertFromTableEntry(ReminderTableEntry tableEntry, string eTag) { try { return new ReminderEntry { GrainRef = GrainReference.FromKeyString(tableEntry.GrainReference), ReminderName = tableEntry.ReminderName, StartAt = TraceLogger.ParseDate(tableEntry.StartAt), Period = TimeSpan.Parse(tableEntry.Period), ETag = eTag, }; } catch (Exception exc) { var error = String.Format( "Failed to parse ReminderTableEntry: {0}. This entry is corrupt, going to ignore it.", tableEntry); logger.Error(ErrorCode.AzureTable_49, error, exc); throw; } finally { string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(remTableManager.ServiceId); if (!tableEntry.ServiceId.Equals(serviceIdStr)) { var error = String.Format( "Read a reminder entry for wrong Service id. Read {0}, but my service id is {1}. Going to discard it.", tableEntry, serviceIdStr); logger.Warn(ErrorCode.AzureTable_ReadWrongReminder, error); throw new OrleansException(error); } } } private static ReminderTableEntry ConvertToTableEntry(ReminderEntry remEntry, Guid serviceId, string deploymentId) { string partitionKey = ReminderTableEntry.ConstructPartitionKey(serviceId, remEntry.GrainRef); string rowKey = ReminderTableEntry.ConstructRowKey(remEntry.GrainRef, remEntry.ReminderName); string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(serviceId); var consistentHash = remEntry.GrainRef.GetUniformHashCode(); return new ReminderTableEntry { PartitionKey = partitionKey, RowKey = rowKey, ServiceId = serviceIdStr, DeploymentId = deploymentId, GrainReference = remEntry.GrainRef.ToKeyString(), ReminderName = remEntry.ReminderName, StartAt = TraceLogger.PrintDate(remEntry.StartAt), Period = remEntry.Period.ToString(), GrainRefConsistentHash = String.Format("{0:X8}", consistentHash), ETag = remEntry.ETag, }; } #endregion public Task TestOnlyClearTable() { return remTableManager.DeleteTableEntries(); } public async Task<ReminderTableData> ReadRows(GrainReference key) { try { var entries = await remTableManager.FindReminderEntries(key); ReminderTableData data = ConvertFromTableEntryList(entries); if (logger.IsVerbose2) logger.Verbose2("Read for grain {0} Table=" + Environment.NewLine + "{1}", key, data.ToString()); return data; } catch (Exception exc) { logger.Warn(ErrorCode.AzureTable_47, String.Format("Intermediate error reading reminders for grain {0} in table {1}.", key, remTableManager.TableName), exc); throw; } } public async Task<ReminderTableData> ReadRows(uint begin, uint end) { try { var entries = await remTableManager.FindReminderEntries(begin, end); ReminderTableData data = ConvertFromTableEntryList(entries); if (logger.IsVerbose2) logger.Verbose2("Read in {0} Table=" + Environment.NewLine + "{1}", RangeFactory.CreateRange(begin, end), data); return data; } catch (Exception exc) { logger.Warn(ErrorCode.AzureTable_40, String.Format("Intermediate error reading reminders in range {0} for table {1}.", RangeFactory.CreateRange(begin, end), remTableManager.TableName), exc); throw; } } public async Task<ReminderEntry> ReadRow(GrainReference grainRef, string reminderName) { try { if (logger.IsVerbose) logger.Verbose("ReadRow grainRef = {0} reminderName = {1}", grainRef, reminderName); var result = await remTableManager.FindReminderEntry(grainRef, reminderName); return ConvertFromTableEntry(result.Item1, result.Item2); } catch (Exception exc) { logger.Warn(ErrorCode.AzureTable_46, String.Format("Intermediate error reading row with grainId = {0} reminderName = {1} from table {2}.", grainRef, reminderName, remTableManager.TableName), exc); throw; } } public async Task<string> UpsertRow(ReminderEntry entry) { try { if (logger.IsVerbose) logger.Verbose("UpsertRow entry = {0}", entry.ToString()); ReminderTableEntry remTableEntry = ConvertToTableEntry(entry, remTableManager.ServiceId, remTableManager.DeploymentId); string result = await remTableManager.UpsertRow(remTableEntry); if (result == null) { logger.Warn(ErrorCode.AzureTable_45, String.Format("Upsert failed on the reminder table. Will retry. Entry = {0}", entry.ToString())); } return result; } catch (Exception exc) { logger.Warn(ErrorCode.AzureTable_42, String.Format("Intermediate error upserting reminder entry {0} to the table {1}.", entry.ToString(), remTableManager.TableName), exc); throw; } } public async Task<bool> RemoveRow(GrainReference grainRef, string reminderName, string eTag) { var entry = new ReminderTableEntry { PartitionKey = ReminderTableEntry.ConstructPartitionKey(remTableManager.ServiceId, grainRef), RowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName), ETag = eTag, }; try { if (logger.IsVerbose2) logger.Verbose2("RemoveRow entry = {0}", entry.ToString()); bool result = await remTableManager.DeleteReminderEntryConditionally(entry, eTag); if (result == false) { logger.Warn(ErrorCode.AzureTable_43, String.Format("Delete failed on the reminder table. Will retry. Entry = {0}", entry)); } return result; } catch (Exception exc) { logger.Warn(ErrorCode.AzureTable_44, String.Format("Intermediate error when deleting reminder entry {0} to the table {1}.", entry, remTableManager.TableName), exc); throw; } } } }
// 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.Globalization { using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Threading; using System.Diagnostics.Contracts; // // Data table for encoding classes. Used by System.Text.Encoding. // This class contains two hashtables to allow System.Text.Encoding // to retrieve the data item either by codepage value or by webName. // // Only statics, does not need to be marked with the serializable attribute internal static class EncodingTable { //This number is the size of the table in native. The value is retrieved by //calling the native GetNumEncodingItems(). private static int lastEncodingItem = GetNumEncodingItems() - 1; //This number is the size of the code page table. Its generated when we walk the table the first time. private static volatile int lastCodePageItem; // // This points to a native data table which maps an encoding name to the correct code page. // [SecurityCritical] unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData(); // // This points to a native data table which stores the properties for the code page, and // the table is indexed by code page. // [SecurityCritical] unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData(); // // This caches the mapping of an encoding name to a code page. // private static Hashtable hashByName = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase)); // // THe caches the data item which is indexed by the code page value. // private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable()); [System.Security.SecuritySafeCritical] // static constructors should be safe to call static EncodingTable() { } // Find the data item by binary searching the table that we have in native. // nativeCompareOrdinalWC is an internal-only function. [System.Security.SecuritySafeCritical] // auto-generated unsafe private static int internalGetCodePageFromName(String name) { int left = 0; int right = lastEncodingItem; int index; int result; //Binary search the array until we have only a couple of elements left and then //just walk those elements. while ((right - left)>3) { index = ((right - left)/2) + left; result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName); if (result == 0) { //We found the item, return the associated codepage. return (encodingDataPtr[index].codePage); } else if (result<0) { //The name that we're looking for is less than our current index. right = index; } else { //The name that we're looking for is greater than our current index left = index; } } //Walk the remaining elements (it'll be 3 or fewer). for (; left<=right; left++) { if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0) { return (encodingDataPtr[left].codePage); } } // The encoding name is not valid. throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name)); } // Return a list of all EncodingInfo objects describing all of our encodings [System.Security.SecuritySafeCritical] // auto-generated internal static unsafe EncodingInfo[] GetEncodings() { if (lastCodePageItem == 0) { int count; for (count = 0; codePageDataPtr[count].codePage != 0; count++) { // Count them } lastCodePageItem = count; } EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem]; int i; for (i = 0; i < lastCodePageItem; i++) { arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0), Environment.GetResourceString("Globalization.cp_" + codePageDataPtr[i].codePage)); } return arrayEncodingInfo; } /*=================================GetCodePageFromName========================== **Action: Given a encoding name, return the correct code page number for this encoding. **Returns: The code page for the encoding. **Arguments: ** name the name of the encoding **Exceptions: ** ArgumentNullException if name is null. ** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name. ============================================================================*/ internal static int GetCodePageFromName(String name) { if (name==null) { throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); Object codePageObj; // // The name is case-insensitive, but ToLower isn't free. Check for // the code page in the given capitalization first. // codePageObj = hashByName[name]; if (codePageObj!=null) { return ((int)codePageObj); } //Okay, we didn't find it in the hash table, try looking it up in the //unmanaged data. int codePage = internalGetCodePageFromName(name); hashByName[name] = codePage; return codePage; } [System.Security.SecuritySafeCritical] // auto-generated unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) { CodePageDataItem dataItem; // We synchronize around dictionary gets/sets. There's still a possibility that two threads // will create a CodePageDataItem and the second will clobber the first in the dictionary. // However, that's acceptable because the contents are correct and we make no guarantees // other than that. //Look up the item in the hashtable. dataItem = (CodePageDataItem)hashByCodePage[codepage]; //If we found it, return it. if (dataItem!=null) { return dataItem; } //If we didn't find it, try looking it up now. //If we find it, add it to the hashtable. //This is a linear search, but we probably won't be doing it very often. // int i = 0; int data; while ((data = codePageDataPtr[i].codePage) != 0) { if (data == codepage) { dataItem = new CodePageDataItem(i); hashByCodePage[codepage] = dataItem; return (dataItem); } i++; } //Nope, we didn't find it. return null; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalEncodingDataItem *GetEncodingData(); // // Return the number of encoding data items. // [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetNumEncodingItems(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalCodePageDataItem* GetCodePageData(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern byte* nativeCreateOpenFileMapping( String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle); } /*=================================InternalEncodingDataItem========================== **Action: This is used to map a encoding name to a correct code page number. By doing this, ** we can get the properties of this encoding via the InternalCodePageDataItem. ** ** We use this structure to access native data exposed by the native side. ============================================================================*/ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalEncodingDataItem { [SecurityCritical] internal sbyte * webName; internal UInt16 codePage; } /*=================================InternalCodePageDataItem========================== **Action: This is used to access the properties related to a code page. ** We use this structure to access native data exposed by the native side. ============================================================================*/ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalCodePageDataItem { internal UInt16 codePage; internal UInt16 uiFamilyCodePage; internal uint flags; [SecurityCritical] internal sbyte * Names; } }
using System; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Uts { public class DynBindMgr { public class MInfo { public Type classType; public MethodInfo method; public MInfo(Type classType, MethodInfo method) { this.classType = classType; this.method = method; } } private static Dictionary<string, MInfo> _map = new Dictionary<string, MInfo>(); public static MInfo GetMethodInfo(string keyName) { MInfo minfo = null; _map.TryGetValue(keyName, out minfo); return minfo; } public static void SetMethodInfo(string keyName, Type classType, MethodInfo m) { _map[keyName] = new MInfo(classType, m); } } public class DynBind { static private int matchType(IntPtr ctx, int pos, Type type) { int top = Native.duk_get_top(ctx); if (pos >= top) return -1; DUK_TYPE tsType = (DUK_TYPE)Native.duk_get_type(ctx, pos++); if (tsType == DUK_TYPE.STRING && type.Name == "String" ) { return pos; } else if (tsType == DUK_TYPE.NUMBER && (type.Name == "Int16" ||type.Name == "Int32" ||type.Name == "Int64" ||type.Name == "UInt16" ||type.Name == "UInt32" ||type.Name == "UInt64" ||type.Name == "Float" ||type.Name == "Double" )){ return pos; } else if (tsType == DUK_TYPE.OBJECT) { // read object type if (pos >= top) return -1; ARG_TYPE rtType = (ARG_TYPE)Native.duk_require_int(ctx, pos++); if (rtType == ARG_TYPE.CALLBACK) { if (pos >= top) return -1; int argsCount = Native.duk_require_int(ctx, pos++); pos += argsCount; if (pos > top) return -1; } return pos; } return -1; } static private bool matchArgs(IntPtr ctx, int from, ParameterInfo[] pis) { int top = Native.duk_get_top(ctx); int pos = from; for (int i = 0; i < pis.Length; i++) { pos = matchType(ctx, pos, pis[i].ParameterType); if ( pos < 0 ) return false; } return (pos == top); } static private MethodInfo getMethod(IntPtr ctx, string member, int fromStackPos, Type type) { MethodInfo m; MemberInfo[] mis = type.GetMember(member, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < mis.Length; i++) { m = (MethodInfo)mis[i]; if (matchArgs(ctx, fromStackPos, m.GetParameters())) { return m; } } return null; } static private ConstructorInfo getConstructor(IntPtr ctx, int fromStackPos, ConstructorInfo[] ctors) { if (ctors.Length == 1) { return ctors[0]; } ConstructorInfo ctor = null; for (int i = 0; i < ctors.Length; i++) { ctor = ctors[i]; if (matchArgs(ctx, fromStackPos, ctor.GetParameters())) { return ctor; } } return null; } static private TsDelegate makeCallBack(Context context, int funref, int pos, int argsCount) { IntPtr ctx = context.ptr; TsDelegate td = new TsDelegate(context, funref, argsCount); for (int i = 0; i < argsCount; i++) { DUK_TYPE tsType = (DUK_TYPE)Native.duk_get_type(ctx, pos); if (tsType == DUK_TYPE.OBJECT) { Native.duk_dup(ctx, pos); int argref = Native.duv_ref(ctx); pos++; td.AddArgType(i, ARG_TYPE.OBJECT, argref); } else { ARG_TYPE argType = (ARG_TYPE)Native.duk_require_int(ctx, pos++); td.AddArgType(i, argType, 0); } } return td; } static private int fillArg(IntPtr ctx, int pos, Type argType, out object arg) { arg = null; DUK_TYPE tsType = (DUK_TYPE)Native.duk_get_type(ctx, pos); if (tsType == DUK_TYPE.NUMBER) { arg = Native.duk_require_int(ctx, pos++); } else if (tsType == DUK_TYPE.STRING) { arg = Native.duk_require_string_s(ctx, pos++); } else if (tsType == DUK_TYPE.OBJECT) { IntPtr ptr = Native.duk_get_heapptr(ctx, pos++); arg = BindObjectsMgr.GetCsObject(ptr); // read object type ARG_TYPE rtType = (ARG_TYPE)Native.duk_require_int(ctx, pos++); if (rtType == ARG_TYPE.OBJECT) { if (arg == null) { throw new Exception("Can not find arg in bindmgr!"); } } else if (rtType == ARG_TYPE.CALLBACK) { int argsCount = Native.duk_require_int(ctx, pos++); Native.duk_push_heapptr(ctx, ptr); int funref = Native.duv_ref(ctx); Context context = Engine.GetContent(ctx); if (context == null) { throw new Exception("Get context failed!"); } TsDelegate td = makeCallBack(context, funref, pos, argsCount); arg = Delegate.CreateDelegate(argType, td, "Deleg", true, true); pos += argsCount; } } return pos; } static private void fillArgs(IntPtr ctx, int from, ParameterInfo[] ps, out object[] args) { args = new object[ps.Length]; for (int i = 0, pos = from; i < ps.Length; i++) { object arg; pos = fillArg(ctx, pos, ps[i].ParameterType, out arg); args[i] = arg; } } static private string getMemberKey(object csObject, bool isStaticCall, string member, int memberid) { StringBuilder sb = new StringBuilder(); if (!isStaticCall) { sb.Append(csObject.GetType().FullName).Append(".").Append(member).Append(memberid).ToString(); } else { sb.Append(member).Append(memberid); } return sb.ToString(); } static private void getNeedInfo(object csObject, bool isStaticCall, string member, int memberid, out string methodName, out Type type) { if (!isStaticCall) { type = csObject.GetType(); methodName = member; } else { string[] paths = member.Split('.'); methodName = paths[paths.Length - 1]; string className = member.Substring(0, member.Length - methodName.Length - 1); type = Type.GetType(className); if (type == null) { throw new Exception(string.Format("Not find class {0} type.", className)); } } } static private int pushRetVal(IntPtr ctx, object ret, RET_TYPE retType, string member, Type type, int tsTypePos) { Type t = ret.GetType(); if (retType == RET_TYPE.CLASSOBJECT) { Bind.PushDynCsObject(ctx, ret, tsTypePos); } else if (t.IsEnum || t.Name == "Int32") { Native.duk_push_int(ctx, Convert.ToInt32(ret)); } else if (t.Name == "String") { Native.duk_push_string_u(ctx, Convert.ToString(ret)); } else { throw new Exception(string.Format("Return value is invalid! attr<{0}> in {1} return type is {2}.", member, type.Name, t.Name)); } return 1; } [InvokeCallback(typeof(cs_function))] static public int __call(IntPtr ctx) { try { // read params int memberid = Native.duk_require_int(ctx, 0); string member = Native.duk_require_string_s(ctx, 1); bool isStaticCall = member.IndexOf(".") > 0; object csObject = isStaticCall ? null : Bind.RequireThis(ctx); RET_TYPE retType = (RET_TYPE)Native.duk_require_int(ctx, 2); int fromStackPos = retType == RET_TYPE.CLASSOBJECT ? 4 : 3; MethodInfo m = null; Type type = null; string memberKey = getMemberKey(csObject, isStaticCall, member, memberid); DynBindMgr.MInfo mInfo = DynBindMgr.GetMethodInfo(memberKey); if (mInfo == null) { string methodName = null; getNeedInfo(csObject, isStaticCall, member, memberid, out methodName, out type); m = getMethod(ctx, methodName, fromStackPos, type); DynBindMgr.SetMethodInfo(memberKey, type, m); } else { type = mInfo.classType; m = mInfo.method; } if (m == null) { throw new Exception(string.Format("Not find method[{0}] in {1}.", member, type.Name)); } // handle args object[] args; fillArgs(ctx, fromStackPos, m.GetParameters(), out args); object ret = m.Invoke(m.IsStatic ? null : csObject, args); if (ret == null) { return 0; } // handle return value return pushRetVal(ctx, ret, retType, member, type, 3); } catch (Exception e) { return Native.duk_throw_error(ctx, e.ToString()); } } [InvokeCallback(typeof(cs_function))] static public int __set(IntPtr ctx) { try { // read params object csObject = Bind.RequireThis(ctx); string member = Native.duk_require_string_s(ctx, 0); Type type = csObject.GetType(); FieldInfo finfo = null; PropertyInfo prop = type.GetProperty(member); if (prop == null) { finfo = type.GetField(member); } if (finfo == null && prop == null) { throw new Exception(string.Format("Attr<{0}> not in {1} !", member, type.Name)); } Type valType = prop != null ? prop.GetType() : finfo.GetType(); object value = null; fillArg(ctx, 1, valType, out value); if (prop != null) prop.SetValue(csObject, value, null); else finfo.SetValue(csObject, value); return 0; } catch (Exception e) { return Native.duk_throw_error(ctx, e.ToString()); } } [InvokeCallback(typeof(cs_function))] static public int __get(IntPtr ctx) { try { // read params object csObject = Bind.RequireThis(ctx); string member = Native.duk_require_string_s(ctx, 0); RET_TYPE retType = (RET_TYPE)Native.duk_require_int(ctx, 1); Type type = csObject.GetType(); FieldInfo finfo = null; PropertyInfo prop = type.GetProperty(member); if (prop == null) { finfo = type.GetField(member); } if (finfo == null && prop == null) { throw new Exception(string.Format("Attr<{0}> not in {1} !", member, type.Name)); } object ret = (prop != null) ? prop.GetValue(csObject, null) : finfo.GetValue(csObject); // handle return value return pushRetVal(ctx, ret, retType, member, type, 2); } catch (Exception e) { return Native.duk_throw_error(ctx, Convert.ToString(e)); } } [InvokeCallback(typeof(cs_function))] static public int __as(IntPtr ctx) { try { // read params IntPtr optr = Native.duk_get_heapptr(ctx, 0); object o = BindObjectsMgr.GetCsObject(optr); string sretType = Native.duk_require_string_s(ctx, 1); // stack.pos2 is tsToTypeClass Type retType = Type.GetType(sretType); if (retType == null) { throw new Exception(string.Format("Not find class {0} type when as op.", sretType)); } BindObjectsMgr.RemoveByCsObject(o); Bind.PushDynCsObject(ctx, Convert.ChangeType(o, retType), 2); return 1; } catch (Exception e) { return Native.duk_throw_error(ctx, Convert.ToString(e)); } } [InvokeCallback(typeof(cs_function))] static public int ctor_DynBind(IntPtr ctx) { try { if (Native.duk_is_string(ctx, 0) != 1) { return 0; // use default ctor: _super.apply(this, arguments); } string className = Native.duk_require_string_s(ctx, 0); int fromStackPos = 1; Type type = Type.GetType(className); if (type == null ) { throw new Exception(string.Format("Not find class {0} type in ctor.", className)); } ConstructorInfo ctor = getConstructor(ctx, fromStackPos, type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)); if (ctor == null) { throw new Exception(string.Format("Not find ctor in {0} !", type.Name)); } // handle args object[] args; fillArgs(ctx, fromStackPos, ctor.GetParameters(), out args); object csObject = ctor.Invoke(args); IntPtr ptr = IntPtr.Zero; ptr = Native.duk_require_this(ctx); BindObjectsMgr.Bind(ptr, csObject); return 0; } catch (Exception e) { return Native.duk_throw_error(ctx, e.ToString()); } } static public void Register(IntPtr ctx) { Bind.RegClassStart(ctx, "__DynBind", "", ctor_DynBind, -1); Bind.RegCsFunction(ctx, "__call", __call, -1); Bind.RegStaticCsFunction(ctx, "__call", __call, -1); Bind.RegCsFunction(ctx, "__set", __set, 2); Bind.RegCsFunction(ctx, "__get", __get, -1); Bind.RegStaticCsFunction(ctx, "__as", __as, 3); Bind.RegClassEnd(ctx); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Routing.Constraints; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Linq; using Xunit; namespace Microsoft.AspNetCore.Routing.Patterns { public class DefaultRoutePatternTransformerTest { public DefaultRoutePatternTransformerTest() { var services = new ServiceCollection(); services.AddRouting(); services.AddOptions(); Transformer = services.BuildServiceProvider().GetRequiredService<RoutePatternTransformer>(); } public RoutePatternTransformer Transformer { get; } [Fact] public void SubstituteRequiredValues_CanAcceptNullForAnyKey() { // Arrange var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new { }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { a = (string)null, b = "", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("a", null), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("b", string.Empty), kvp)); } [Fact] public void SubstituteRequiredValues_RejectsNullForParameter() { // Arrange var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new { }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = string.Empty, }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Null(actual); } [Fact] public void SubstituteRequiredValues_AllowRequiredValueAnyForParameter() { // Arrange var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new { }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = RoutePattern.RequiredValueAny, }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.Defaults.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); // default is preserved Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", RoutePattern.RequiredValueAny), kvp)); } [Fact] public void SubstituteRequiredValues_RejectsNullForOutOfLineDefault() { // Arrange var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new { area = "Admin" }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { area = string.Empty, }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Null(actual); } [Fact] public void SubstituteRequiredValues_RejectsRequiredValueAnyForOutOfLineDefault() { // Arrange var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new { area = RoutePattern.RequiredValueAny }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { area = string.Empty, }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Null(actual); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForParameter() { // Arrange var template = "{controller}/{action}/{id?}"; var defaults = new { }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForParameter_WithSameDefault() { // Arrange var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new { }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); // We should not need to rewrite anything in this case. Assert.Same(actual.Defaults, original.Defaults); Assert.Same(actual.Parameters, original.Parameters); Assert.Same(actual.PathSegments, original.PathSegments); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForParameter_WithDifferentDefault() { // Arrange var template = "{controller=Blog}/{action=ReadPost}/{id?}"; var defaults = new { area = "Admin", }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { area = "Admin", controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("area", "Admin"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); // We should not need to rewrite anything in this case. Assert.NotSame(actual.Defaults, original.Defaults); Assert.NotSame(actual.Parameters, original.Parameters); Assert.NotSame(actual.PathSegments, original.PathSegments); // other defaults were wiped out Assert.Equal(new KeyValuePair<string, object>("area", "Admin"), Assert.Single(actual.Defaults)); Assert.Null(actual.GetParameter("controller").Default); Assert.False(actual.Defaults.ContainsKey("controller")); Assert.Null(actual.GetParameter("action").Default); Assert.False(actual.Defaults.ContainsKey("action")); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForParameter_WithMatchingConstraint() { // Arrange var template = "{controller}/{action}/{id?}"; var defaults = new { }; var policies = new { controller = "Home", action = new RegexRouteConstraint("Index"), }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); } [Fact] public void SubstituteRequiredValues_CanRejectValueForParameter_WithNonMatchingConstraint() { // Arrange var template = "{controller}/{action}/{id?}"; var defaults = new { }; var policies = new { controller = "Home", action = new RegexRouteConstraint("Index"), }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Blog", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Null(actual); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForDefault_WithSameValue() { // Arrange var template = "Home/Index/{id?}"; var defaults = new { controller = "Home", action = "Index", }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); } [Fact] public void SubstituteRequiredValues_CanRejectValueForDefault_WithDifferentValue() { // Arrange var template = "Home/Index/{id?}"; var defaults = new { controller = "Home", action = "Index", }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Blog", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Null(actual); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForDefault_WithSameValue_Null() { // Arrange var template = "Home/Index/{id?}"; var defaults = new { controller = (string)null, action = "", }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = string.Empty, action = (string)null, }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", null), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", ""), kvp)); } [Fact] public void SubstituteRequiredValues_CanAcceptValueForDefault_WithSameValue_WithMatchingConstraint() { // Arrange var template = "Home/Index/{id?}"; var defaults = new { controller = "Home", action = "Index", }; var policies = new { controller = "Home", }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); } [Fact] public void SubstituteRequiredValues_CanRejectValueForDefault_WithSameValue_WithNonMatchingConstraint() { // Arrange var template = "Home/Index/{id?}"; var defaults = new { controller = "Home", action = "Index", }; var policies = new { controller = "Home", }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); } [Fact] public void SubstituteRequiredValues_CanMergeExistingRequiredValues() { // Arrange var template = "Home/Index/{id?}"; var defaults = new { area = "Admin", controller = "Home", action = "Index", }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies, new { area = "Admin", controller = "Home", }); var requiredValues = new { controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Collection( actual.RequiredValues.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("action", "Index"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("area", "Admin"), kvp), kvp => Assert.Equal(new KeyValuePair<string, object>("controller", "Home"), kvp)); } [Fact] public void SubstituteRequiredValues_NullRequiredValueParameter_Fail() { // Arrange var template = "PageRoute/Attribute/{page}"; var defaults = new { area = (string)null, page = (string)null, controller = "Home", action = "Index", }; var policies = new { }; var original = RoutePatternFactory.Parse(template, defaults, policies); var requiredValues = new { area = (string)null, page = (string)null, controller = "Home", action = "Index", }; // Act var actual = Transformer.SubstituteRequiredValues(original, requiredValues); // Assert Assert.Null(actual); } } }
using System.Collections.Generic; using System.IO; using Microsoft.Build.Utilities; using NUnit.Framework; namespace MSBuild.Community.Tasks.Tests { [TestFixture] public class TemplateFileTest { private static string _template = @" Template File 1 ${TemplateItem} = TemplateItem {Non-TemplateItem} = NonTemplateItem ${item2} ${CASEInsenSiTiveTest} ${Template.Item.With.Dot} "; private static string _templateReplaced = _template.Replace("${TemplateItem}", "**Item1**").Replace("${item2}", "**Item2**") .Replace("${CASEInsenSiTiveTest}", "**Item3**") .Replace("${Template.Item.With.Dot}", "**Item4**"); private static string _templateFilename; private string _replacedFilename; [OneTimeSetUp] public void FixtureInit() { MockBuild buildEngine = new MockBuild(); TaskUtility.makeTestDirectory(buildEngine); _templateFilename = Path.Combine(TaskUtility.TestDirectory, typeof(TemplateFileTest).Name + ".txt"); } [SetUp] public void Setup() { File.WriteAllText(_templateFilename, _template); _replacedFilename = null; } [TearDown] public void Teardown() { if (_replacedFilename != null && File.Exists(_replacedFilename)) { File.Delete(_replacedFilename); } } private void SetMetaData(TaskItem item, string data, bool set) { if (set) { item.SetMetadata(TemplateFile.MetadataValueTag, data); } } private TaskItem[] GetTaskItems() { return GetTaskItems(true); } private TaskItem[] GetTaskItems(bool includeMetaData) { List<TaskItem> result = new List<TaskItem>(); TaskItem item = new TaskItem("TemplateItem"); SetMetaData(item, "**Item1**", includeMetaData); result.Add(item); item = new TaskItem("item2"); SetMetaData(item, "**Item2**", includeMetaData); result.Add(item); item = new TaskItem("caseInsensitiveTest"); SetMetaData(item, "**Item3**", includeMetaData); result.Add(item); item = new TaskItem("Template.Item.With.Dot"); SetMetaData(item, "**Item4**", includeMetaData); result.Add(item); return result.ToArray(); } private TaskItem[] GetTaskItemsMissing() { List<TaskItem> result = new List<TaskItem>(); TaskItem item = new TaskItem("TemplateItem"); SetMetaData(item, "**Item1**", true); result.Add(item); item = new TaskItem("caseInsensitiveTest"); SetMetaData(item, "**Item3**", true); result.Add(item); return result.ToArray(); } [Test] public void TemplateFileDefault() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem(_templateFilename); tf.Tokens = GetTaskItems(); Assert.IsTrue(tf.Execute()); Assert.IsNotNull(tf.OutputFile); Assert.IsTrue(File.Exists(tf.OutputFile.ItemSpec)); _replacedFilename = tf.OutputFile.ItemSpec; Assert.AreEqual(Path.ChangeExtension(_templateFilename, ".out"), _replacedFilename); string replaced = File.ReadAllText(tf.OutputFile.ItemSpec); Assert.AreEqual(_templateReplaced, replaced); } [Test] public void TemplateFileInvalidTemplate() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem("non_existant_file"); tf.Tokens = GetTaskItems(); Assert.IsFalse(tf.Execute()); Assert.AreEqual(1, build.ErrorCount); } [Test] public void TemplateFileNewFilename() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem(_templateFilename); string outputfile = Path.Combine(Path.GetDirectoryName(_templateFilename), "Replacement.file"); tf.OutputFilename = outputfile; tf.Tokens = GetTaskItems(); Assert.IsTrue(tf.Execute()); Assert.IsNotNull(tf.OutputFile); Assert.IsTrue(File.Exists(tf.OutputFile.ItemSpec)); _replacedFilename = tf.OutputFile.ItemSpec; Assert.AreEqual(outputfile, _replacedFilename); string replaced = File.ReadAllText(tf.OutputFile.ItemSpec); Assert.AreEqual(_templateReplaced, replaced); } [Test] public void TemplateFileNoMetaData() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem(_templateFilename); tf.Tokens = GetTaskItems(false); Assert.IsTrue(tf.Execute()); Assert.IsNotNull(tf.OutputFile); Assert.IsTrue(File.Exists(tf.OutputFile.ItemSpec)); _replacedFilename = tf.OutputFile.ItemSpec; Assert.AreEqual(Path.ChangeExtension(_templateFilename, ".out"), _replacedFilename); string replaced = File.ReadAllText(tf.OutputFile.ItemSpec); string shouldBeReplaced = _template.Replace("${TemplateItem}", "").Replace("${item2}", "").Replace("${CASEInsenSiTiveTest}", "") .Replace("${Template.Item.With.Dot}", ""); Assert.AreEqual(shouldBeReplaced, replaced); } [Test] public void TemplateFileNoTokens() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem(_templateFilename); Assert.IsTrue(tf.Execute()); Assert.IsNotNull(tf.OutputFile); Assert.IsTrue(File.Exists(tf.OutputFile.ItemSpec)); _replacedFilename = tf.OutputFile.ItemSpec; Assert.AreEqual(Path.ChangeExtension(_templateFilename, ".out"), _replacedFilename); string replaced = File.ReadAllText(tf.OutputFile.ItemSpec); Assert.AreEqual(_template, replaced); } [Test] public void TemplateFileMissingToken() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem(_templateFilename); tf.Tokens = GetTaskItemsMissing(); Assert.IsTrue(tf.Execute()); Assert.IsNotNull(tf.OutputFile); Assert.IsTrue(File.Exists(tf.OutputFile.ItemSpec)); _replacedFilename = tf.OutputFile.ItemSpec; Assert.AreEqual(Path.ChangeExtension(_templateFilename, ".out"), _replacedFilename); string replaced = File.ReadAllText(tf.OutputFile.ItemSpec); string shouldBeReplaced = _template.Replace("${TemplateItem}", "**Item1**") .Replace("${CASEInsenSiTiveTest}", "**Item3**"); Assert.AreEqual(shouldBeReplaced, replaced); } [Test] public void TemplateFileReplace() { MockBuild build = new MockBuild(); TemplateFile tf = new TemplateFile(); tf.BuildEngine = build; tf.Template = new TaskItem(_templateFilename); tf.OutputFilename = _templateFilename; tf.Tokens = GetTaskItems(); Assert.IsTrue(tf.Execute()); Assert.IsNotNull(tf.OutputFile); Assert.IsTrue(File.Exists(tf.OutputFile.ItemSpec)); _replacedFilename = tf.OutputFile.ItemSpec; Assert.AreEqual(_templateFilename, _replacedFilename); string replaced = File.ReadAllText(tf.OutputFile.ItemSpec); Assert.AreEqual(_templateReplaced, replaced); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Linq; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.Mapping { /// <summary> /// A MetaModel is an abstraction representing the mapping between a database and domain objects /// </summary> public abstract class MetaModel { /// <summary> /// The mapping source that originated this model. /// </summary> public abstract MappingSource MappingSource { get; } /// <summary> /// The type of DataContext type this model describes. /// </summary> public abstract Type ContextType { get; } /// <summary> /// The name of the database. /// </summary> public abstract string DatabaseName { get; } /// <summary> /// The CLR type that implements IProvider to use as a provider. /// </summary> public abstract Type ProviderType { get; } /// <summary> /// Gets the MetaTable associated with a given type. /// </summary> /// <param name="rowType">The CLR row type.</param> /// <returns>The MetaTable if one exists, otherwise null.</returns> public abstract MetaTable GetTable(Type rowType); /// <summary> /// Gets the MetaFunction corresponding to a database function: user-defined function, table-valued function or stored-procedure. /// </summary> /// <param name="method">The method defined on the DataContext or subordinate class that represents the database function.</param> /// <returns>The MetaFunction if one exists, otherwise null.</returns> public abstract MetaFunction GetFunction(MethodInfo method); /// <summary> /// Get an enumeration of all tables. /// </summary> /// <returns>An enumeration of all the MetaTables</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Non-trivial operations are not suitable for properties.")] public abstract IEnumerable<MetaTable> GetTables(); /// <summary> /// Get an enumeration of all functions. /// </summary> /// <returns>An enumeration of all the MetaFunctions</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Non-trivial operations are not suitable for properties.")] public abstract IEnumerable<MetaFunction> GetFunctions(); /// <summary> /// This method discovers the MetaType for the given Type. /// </summary> public abstract MetaType GetMetaType(Type type); /// <summary> /// Internal value used to determine a reference identity for comparing meta models /// without needing to keep track of the actual meta model reference. /// </summary> private object identity = new object(); internal object Identity { get { return this.identity; } } } /// <summary> /// A MetaTable represents an abstraction of a database table (or view) /// </summary> public abstract class MetaTable { /// <summary> /// The MetaModel containing this MetaTable. /// </summary> public abstract MetaModel Model { get; } /// <summary> /// The name of the table as defined by the database. /// </summary> public abstract string TableName { get; } /// <summary> /// The MetaType describing the type of the rows of the table. /// </summary> public abstract MetaType RowType { get; } /// <summary> /// The DataContext method used to perform insert operations /// </summary> public abstract MethodInfo InsertMethod { get; } /// <summary> /// The DataContext method used to perform update operations /// </summary> public abstract MethodInfo UpdateMethod { get; } /// <summary> /// The DataContext method used to perform delete operations /// </summary> public abstract MethodInfo DeleteMethod { get; } } /// <summary> /// A MetaType represents the mapping of a domain object type onto a database table's columns. /// </summary> public abstract class MetaType { /// <summary> /// The MetaModel containing this MetaType. /// </summary> public abstract MetaModel Model { get; } /// <summary> /// The MetaTable using this MetaType for row definition. /// </summary> public abstract MetaTable Table { get; } /// <summary> /// The underlying CLR type. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The contexts in which this is available are fairly specific.")] public abstract Type Type { get; } /// <summary> /// The name of the MetaType (same as the CLR type's name). /// </summary> public abstract string Name { get; } /// <summary> /// True if the MetaType is an entity type. /// </summary> public abstract bool IsEntity { get; } /// <summary> /// True if the underlying type can be instantiated as the result of a query. /// </summary> public abstract bool CanInstantiate { get; } /// <summary> /// The member that represents the auto-generated identity column, or null if there is none. /// </summary> public abstract MetaDataMember DBGeneratedIdentityMember { get; } /// <summary> /// The member that represents the row-version or timestamp column, or null if there is none. /// </summary> public abstract MetaDataMember VersionMember { get; } /// <summary> /// The member that represents the inheritance discriminator column, or null if there is none. /// </summary> public abstract MetaDataMember Discriminator { get; } /// <summary> /// True if the type has any persistent member with an UpdateCheck policy other than Never. /// </summary> public abstract bool HasUpdateCheck { get; } /// <summary> /// True if the type is part of a mapped inheritance hierarchy. /// </summary> public abstract bool HasInheritance { get; } /// <summary> /// True if this type defines an inheritance code. /// </summary> public abstract bool HasInheritanceCode { get; } /// <summary> /// The inheritance code defined by this type. /// </summary> public abstract object InheritanceCode { get; } /// <summary> /// True if this type is used as the default of an inheritance hierarchy. /// </summary> public abstract bool IsInheritanceDefault { get; } /// <summary> /// The root type of the inheritance hierarchy. /// </summary> public abstract MetaType InheritanceRoot { get; } /// <summary> /// The base metatype in the inheritance hierarchy. /// </summary> public abstract MetaType InheritanceBase { get; } /// <summary> /// The type that is the default of the inheritance hierarchy. /// </summary> public abstract MetaType InheritanceDefault { get; } /// <summary> /// Gets the MetaType for an inheritance sub type. /// </summary> /// <param name="type">The root or sub type of the inheritance hierarchy.</param> /// <returns>The MetaType.</returns> public abstract MetaType GetInheritanceType(Type type); /// <summary> /// Gets type associated with the specified inheritance code. /// </summary> /// <param name="code">The inheritance code</param> /// <returns>The MetaType.</returns> public abstract MetaType GetTypeForInheritanceCode(object code); /// <summary> /// Gets an enumeration of all types defined by an inheritance hierarchy. /// </summary> /// <returns>Enumeration of MetaTypes.</returns> public abstract ReadOnlyCollection<MetaType> InheritanceTypes { get; } /// <summary> /// Returns true if the MetaType or any base MetaType has an OnLoaded method. /// </summary> public abstract bool HasAnyLoadMethod { get; } /// <summary> /// Returns true if the MetaType or any base MetaType has an OnValidate method. /// </summary> public abstract bool HasAnyValidateMethod { get; } /// <summary> /// Gets an enumeration of the immediate derived types in an inheritance hierarchy. /// </summary> /// <returns>Enumeration of MetaTypes.</returns> public abstract ReadOnlyCollection<MetaType> DerivedTypes { get; } /// <summary> /// Gets an enumeration of all the data members (fields and properties). /// </summary> public abstract ReadOnlyCollection<MetaDataMember> DataMembers { get; } /// <summary> /// Gets an enumeration of all the persistent data members (fields and properties mapped into database columns). /// </summary> public abstract ReadOnlyCollection<MetaDataMember> PersistentDataMembers { get; } /// <summary> /// Gets an enumeration of all the data members that define up the unique identity of the type. /// </summary> public abstract ReadOnlyCollection<MetaDataMember> IdentityMembers { get; } /// <summary> /// Gets an enumeration of all the associations. /// </summary> public abstract ReadOnlyCollection<MetaAssociation> Associations { get; } /// <summary> /// Gets the MetaDataMember associated with the specified member. /// </summary> /// <param name="member">The CLR member.</param> /// <returns>The MetaDataMember if there is one, otherwise null.</returns> public abstract MetaDataMember GetDataMember(MemberInfo member); /// <summary> /// The method called when the entity is first loaded. /// </summary> public abstract MethodInfo OnLoadedMethod { get; } /// <summary> /// The method called to ensure the entity is in a valid state. /// </summary> public abstract MethodInfo OnValidateMethod { get; } } /// <summary> /// A MetaDataMember represents the mapping between a domain object's field or property into a database table's column. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "MetaData", Justification = "The capitalization was deliberately chosen.")] public abstract class MetaDataMember { /// <summary> /// The MetaType containing this data member. /// </summary> public abstract MetaType DeclaringType { get; } /// <summary> /// The underlying MemberInfo. /// </summary> public abstract MemberInfo Member { get; } /// <summary> /// The member that actually stores this member's data. /// </summary> public abstract MemberInfo StorageMember { get; } /// <summary> /// The name of the member, same as the MemberInfo name. /// </summary> public abstract string Name { get; } /// <summary> /// The name of the column (or constraint) in the database. /// </summary> public abstract string MappedName { get; } /// <summary> /// The oridinal position of this member in the default layout of query results. /// </summary> public abstract int Ordinal { get; } /// <summary> /// The type of this member. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The contexts in which this is available are fairly specific.")] public abstract Type Type { get; } /// <summary> /// True if this member is declared by the specified type. /// </summary> /// <param name="type">Type to check.</param> public abstract bool IsDeclaredBy(MetaType type); /// <summary> /// The accessor used to get/set the value of this member. /// </summary> public abstract MetaAccessor MemberAccessor { get; } /// <summary> /// The accessor used to get/set the storage value of this member. /// </summary> public abstract MetaAccessor StorageAccessor { get; } /// <summary> /// The accessor used to get/set the deferred value of this member (without causing fetch). /// </summary> public abstract MetaAccessor DeferredValueAccessor { get; } /// <summary> /// The accessor used to get/set the deferred source of this member. /// </summary> public abstract MetaAccessor DeferredSourceAccessor { get; } /// <summary> /// True if this member is defer-loaded by default. /// </summary> public abstract bool IsDeferred { get; } /// <summary> /// True if this member is mapped to a column (or constraint). /// </summary> public abstract bool IsPersistent { get; } /// <summary> /// True if this member defines an association relationship. /// </summary> public abstract bool IsAssociation { get; } /// <summary> /// True if this member is part of the type's identity. /// </summary> public abstract bool IsPrimaryKey { get; } /// <summary> /// True if this member is automatically generated by the database. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db", Justification = "Conforms to legacy spelling.")] public abstract bool IsDbGenerated { get; } /// <summary> /// True if this member represents the row version or timestamp. /// </summary> public abstract bool IsVersion { get; } /// <summary> /// True if this member represents the inheritance discriminator. /// </summary> public abstract bool IsDiscriminator { get; } /// <summary> /// True if this member's value can be assigned the null value. /// </summary> public abstract bool CanBeNull { get; } /// <summary> /// The type of the database column. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db", Justification = "Conforms to legacy spelling.")] public abstract string DbType { get; } /// <summary> /// Expression defining a computed column. /// </summary> public abstract string Expression { get; } /// <summary> /// The optimistic concurrency check policy for this member. /// </summary> public abstract UpdateCheck UpdateCheck { get; } /// <summary> /// Specifies for inserts and updates when this member should be read back after the /// operation completes. /// </summary> public abstract AutoSync AutoSync { get; } /// <summary> /// The MetaAssociation corresponding to this member, or null if there is none. /// </summary> public abstract MetaAssociation Association { get; } /// <summary> /// The DataContext method used to perform load operations /// </summary> public abstract MethodInfo LoadMethod { get; } } /// <summary> /// A MetaFunction represents the mapping between a context method and a database function. /// </summary> public abstract class MetaFunction { /// <summary> /// The MetaModel containing this function. /// </summary> public abstract MetaModel Model { get; } /// <summary> /// The underlying context method. /// </summary> public abstract MethodInfo Method { get; } /// <summary> /// The name of the method (same as the MethodInfo's name). /// </summary> public abstract string Name { get; } /// <summary> /// The name of the database function or procedure. /// </summary> public abstract string MappedName { get; } /// <summary> /// True if the function can be composed within a query /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Composable", Justification="Spelling is correct.")] public abstract bool IsComposable { get; } /// <summary> /// Gets an enumeration of the function parameters. /// </summary> /// <returns></returns> public abstract ReadOnlyCollection<MetaParameter> Parameters { get; } /// <summary> /// The return parameter /// </summary> public abstract MetaParameter ReturnParameter { get; } /// <summary> /// True if the stored procedure has multiple result types. /// </summary> public abstract bool HasMultipleResults { get; } /// <summary> /// An enumeration of all the known result row types of a stored-procedure. /// </summary> /// <returns>Enumeration of possible result row types.</returns> public abstract ReadOnlyCollection<MetaType> ResultRowTypes { get; } } /// <summary> /// A MetaParameter represents the mapping between a method parameter and a database function parameter. /// </summary> public abstract class MetaParameter { /// <summary> /// The underlying method parameter. /// </summary> public abstract ParameterInfo Parameter { get; } /// <summary> /// The name of the parameter (same as the ParameterInfo's name). /// </summary> public abstract string Name { get; } /// <summary> /// The name of the database function's parameter. /// </summary> public abstract string MappedName { get; } /// <summary> /// The CLR type of the parameter. /// </summary> public abstract Type ParameterType { get; } /// <summary> /// The database type of the parameter. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db", Justification = "Conforms to legacy spelling.")] public abstract string DbType { get; } } /// <summary> /// A MetaAssociation represents an association relationship between two entity types. /// </summary> public abstract class MetaAssociation { /// <summary> /// The type on the other end of the association. /// </summary> public abstract MetaType OtherType { get; } /// <summary> /// The member on this side that represents the association. /// </summary> public abstract MetaDataMember ThisMember { get; } /// <summary> /// The member on the other side of this association that represents the reverse association (may be null). /// </summary> public abstract MetaDataMember OtherMember { get; } /// <summary> /// A list of members representing the values on this side of the association. /// </summary> public abstract ReadOnlyCollection<MetaDataMember> ThisKey { get; } /// <summary> /// A list of members representing the values on the other side of the association. /// </summary> public abstract ReadOnlyCollection<MetaDataMember> OtherKey { get; } /// <summary> /// True if the association is OneToMany. /// </summary> public abstract bool IsMany { get; } /// <summary> /// True if the other type is the parent of this type. /// </summary> public abstract bool IsForeignKey { get; } /// <summary> /// True if the association is unique (defines a uniqueness constraint). /// </summary> public abstract bool IsUnique { get; } /// <summary> /// True if the association may be null (key values). /// </summary> public abstract bool IsNullable { get; } /// <summary> /// True if the ThisKey forms the identity (primary key) of the this type. /// </summary> public abstract bool ThisKeyIsPrimaryKey { get; } /// <summary> /// True if the OtherKey forms the identity (primary key) of the other type. /// </summary> public abstract bool OtherKeyIsPrimaryKey { get; } /// <summary> /// Specifies the behavior when the child is deleted (e.g. CASCADE, SET NULL). /// Returns null if no action is specified on delete. /// </summary> public abstract string DeleteRule { get; } /// <summary> /// Specifies whether the object should be deleted when this association /// is set to null. /// </summary> public abstract bool DeleteOnNull { get; } } /// <summary> /// A MetaAccessor /// </summary> public abstract class MetaAccessor { /// <summary> /// The type of the member accessed by this accessor. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The contexts in which this is available are fairly specific.")] public abstract Type Type { get; } /// <summary> /// Gets the value as an object. /// </summary> /// <param name="instance">The instance to get the value from.</param> /// <returns>Value.</returns> public abstract object GetBoxedValue(object instance); /// <summary> /// Sets the value as an object. /// </summary> /// <param name="instance">The instance to set the value into.</param> /// <param name="value">The value to set.</param> [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="[....]: Needs to handle classes and structs.")] [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification="Unknown reason.")] public abstract void SetBoxedValue(ref object instance, object value); /// <summary> /// True if the instance has a loaded or assigned value. /// </summary> public virtual bool HasValue(object instance) { return true; } /// <summary> /// True if the instance has an assigned value. /// </summary> public virtual bool HasAssignedValue(object instance) { return true; } /// <summary> /// True if the instance has a value loaded from a deferred source. /// </summary> public virtual bool HasLoadedValue(object instance) { return false; } } /// <summary> /// A strongly-typed MetaAccessor. Used for reading from and writing to /// CLR objects. /// </summary> /// <typeparam name="T">The type of the object</typeparam> /// <typeparam name="V">The type of the accessed member</typeparam> public abstract class MetaAccessor<TEntity, TMember> : MetaAccessor { /// <summary> /// The underlying CLR type. /// </summary> public override Type Type { get { return typeof(TMember); } } /// <summary> /// Set the boxed value on an instance. /// </summary> public override void SetBoxedValue(ref object instance, object value) { TEntity tInst = (TEntity)instance; this.SetValue(ref tInst, (TMember)value); instance = tInst; } /// <summary> /// Retrieve the boxed value. /// </summary> public override object GetBoxedValue(object instance) { return this.GetValue((TEntity)instance); } /// <summary> /// Gets the strongly-typed value. /// </summary> public abstract TMember GetValue(TEntity instance); /// <summary> /// Sets the strongly-typed value /// </summary> [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "Unknown reason.")] public abstract void SetValue(ref TEntity instance, TMember value); } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace UnrealBuildTool { /** The platforms that may be compilation targets for C++ files. */ public enum CPPTargetPlatform { Win32, Win64, UWP, Mac, XboxOne, PS4, Android, WinRT, WinRT_ARM, IOS, HTML5, Linux, } /** The optimization level that may be compilation targets for C++ files. */ public enum CPPTargetConfiguration { Debug, Development, Shipping } /** The optimization level that may be compilation targets for C# files. */ public enum CSharpTargetConfiguration { Debug, Development, } /** The possible interactions between a precompiled header and a C++ file being compiled. */ public enum PrecompiledHeaderAction { None, Include, Create } /** Whether the Common Language Runtime is enabled when compiling C++ targets (enables C++/CLI) */ public enum CPPCLRMode { CLRDisabled, CLREnabled, } /** Encapsulates the compilation output of compiling a set of C++ files. */ public class CPPOutput { public List<FileItem> ObjectFiles = new List<FileItem>(); public List<FileItem> DebugDataFiles = new List<FileItem>(); public FileItem PrecompiledHeaderFile = null; } public class PrivateAssemblyInfoConfiguration { /** True if the assembly should be copied to an output folder. Often, referenced assemblies must be loaded from the directory that the main executable resides in (or a sub-folder). Note that PDB files will be copied as well. */ public bool bShouldCopyToOutputDirectory = false; /** Optional sub-directory to copy the assembly to */ public string DestinationSubDirectory = ""; } /** Describes a private assembly dependency */ public class PrivateAssemblyInfo { /** The file item for the reference assembly on disk */ public FileItem FileItem = null; /** The configuration of the private assembly info */ public PrivateAssemblyInfoConfiguration Config = new PrivateAssemblyInfoConfiguration(); } /** Encapsulates the environment that a C# file is compiled in. */ public class CSharpEnvironment { /** The configuration to be compiled for. */ public CSharpTargetConfiguration TargetConfiguration; /** The target platform used to set the environment. Doesn't affect output. */ public CPPTargetPlatform EnvironmentTargetPlatform; } public abstract class NativeBuildEnvironmentConfiguration { public class TargetInfo { /** The platform to be compiled/linked for. */ public CPPTargetPlatform Platform; /** The architecture that is being compiled/linked (empty string by default) */ public string Architecture; /** The configuration to be compiled/linked for. */ public CPPTargetConfiguration Configuration; public TargetInfo() { Architecture = ""; } public TargetInfo(TargetInfo Target) { Platform = Target.Platform; Architecture = Target.Architecture; Configuration = Target.Configuration; } } public TargetInfo Target; [Obsolete("Use Target.Platform instead")] public CPPTargetPlatform TargetPlatform { get { return Target.Platform; } set { Target.Platform = value; } } [Obsolete("Use Target.Architecture instead")] public string TargetArchitecture { get { return Target.Architecture; } set { Target.Architecture = value; } } [Obsolete("Use Target.Configuration instead")] public CPPTargetConfiguration TargetConfiguration { get { return Target.Configuration; } set { Target.Configuration = value; } } protected NativeBuildEnvironmentConfiguration() { Target = new TargetInfo(); } protected NativeBuildEnvironmentConfiguration(NativeBuildEnvironmentConfiguration Configuration) { Target = new TargetInfo(Configuration.Target); } } /** Encapsulates the configuration of an environment that a C++ file is compiled in. */ public class CPPEnvironmentConfiguration : NativeBuildEnvironmentConfiguration { /** The directory to put the output object/debug files in. */ public string OutputDirectory = null; /** The directory to shadow source files in for syncing to remote compile servers */ public string LocalShadowDirectory = null; /** PCH header file name as it appears in an #include statement in source code (might include partial, or no relative path.) This is needed by some compilers to use PCH features. */ public string PCHHeaderNameInCode; /** The name of the header file which is precompiled. */ public string PrecompiledHeaderIncludeFilename = null; /** Whether the compilation should create, use, or do nothing with the precompiled header. */ public PrecompiledHeaderAction PrecompiledHeaderAction = PrecompiledHeaderAction.None; /** True if the precompiled header needs to be "force included" by the compiler. This is usually used with the "Shared PCH" feature of UnrealBuildTool. Note that certain platform toolchains *always* force include PCH header files first. */ public bool bForceIncludePrecompiledHeader = false; /** Use run time type information */ public bool bUseRTTI = false; /** Use AVX instructions */ public bool bUseAVX = false; /** Enable buffer security checks. This should usually be enabled as it prevents severe security risks. */ public bool bEnableBufferSecurityChecks = true; /** If true and unity builds are enabled, this module will build without unity. */ public bool bFasterWithoutUnity = false; /** Overrides BuildConfiguration.MinFilesUsingPrecompiledHeader if non-zero. */ public int MinFilesUsingPrecompiledHeaderOverride = 0; /** Module uses a #import so must be built locally when compiling with SN-DBS */ public bool bBuildLocallyWithSNDBS = false; /** Enable exception handling */ public bool bEnableExceptions = false; /** Whether to warn about the use of shadow variables */ public bool bEnableShadowVariableWarning = false; /** True if the environment contains performance critical code. */ public ModuleRules.CodeOptimization OptimizeCode = ModuleRules.CodeOptimization.Default; /** True if debug info should be created. */ public bool bCreateDebugInfo = true; /** True if we're compiling .cpp files that will go into a library (.lib file) */ public bool bIsBuildingLibrary = false; /** True if we're compiling a DLL */ public bool bIsBuildingDLL = false; /** Whether we should compile using the statically-linked CRT. This is not widely supported for the whole engine, but is required for programs that need to run without dependencies. */ public bool bUseStaticCRT = false; /** Whether the CLR (Common Language Runtime) support should be enabled for C++ targets (C++/CLI). */ public CPPCLRMode CLRMode = CPPCLRMode.CLRDisabled; /** The include paths to look for included files in. */ public readonly CPPIncludeInfo CPPIncludeInfo = new CPPIncludeInfo(); /** Paths where .NET framework assembly references are found, when compiling CLR applications. */ public List<string> SystemDotNetAssemblyPaths = new List<string>(); /** Full path and file name of .NET framework assemblies we're referencing */ public List<string> FrameworkAssemblyDependencies = new List<string>(); /** List of private CLR assemblies that, when modified, will force recompilation of any CLR source files */ public List<PrivateAssemblyInfoConfiguration> PrivateAssemblyDependencies = new List<PrivateAssemblyInfoConfiguration>(); /** The C++ preprocessor definitions to use. */ public List<string> Definitions = new List<string>(); /** Additional arguments to pass to the compiler. */ public string AdditionalArguments = ""; /** A list of additional frameworks whose include paths are needed. */ public List<UEBuildFramework> AdditionalFrameworks = new List<UEBuildFramework>(); /** Default constructor. */ public CPPEnvironmentConfiguration() { } /** Copy constructor. */ public CPPEnvironmentConfiguration(CPPEnvironmentConfiguration InCopyEnvironment): base(InCopyEnvironment) { OutputDirectory = InCopyEnvironment.OutputDirectory; LocalShadowDirectory = InCopyEnvironment.LocalShadowDirectory; PCHHeaderNameInCode = InCopyEnvironment.PCHHeaderNameInCode; PrecompiledHeaderIncludeFilename = InCopyEnvironment.PrecompiledHeaderIncludeFilename; PrecompiledHeaderAction = InCopyEnvironment.PrecompiledHeaderAction; bForceIncludePrecompiledHeader = InCopyEnvironment.bForceIncludePrecompiledHeader; bUseRTTI = InCopyEnvironment.bUseRTTI; bUseAVX = InCopyEnvironment.bUseAVX; bFasterWithoutUnity = InCopyEnvironment.bFasterWithoutUnity; MinFilesUsingPrecompiledHeaderOverride = InCopyEnvironment.MinFilesUsingPrecompiledHeaderOverride; bBuildLocallyWithSNDBS = InCopyEnvironment.bBuildLocallyWithSNDBS; bEnableExceptions = InCopyEnvironment.bEnableExceptions; bEnableShadowVariableWarning = InCopyEnvironment.bEnableShadowVariableWarning; OptimizeCode = InCopyEnvironment.OptimizeCode; bCreateDebugInfo = InCopyEnvironment.bCreateDebugInfo; bIsBuildingLibrary = InCopyEnvironment.bIsBuildingLibrary; bIsBuildingDLL = InCopyEnvironment.bIsBuildingDLL; bUseStaticCRT = InCopyEnvironment.bUseStaticCRT; CLRMode = InCopyEnvironment.CLRMode; CPPIncludeInfo.IncludePaths .UnionWith(InCopyEnvironment.CPPIncludeInfo.IncludePaths); CPPIncludeInfo.SystemIncludePaths .UnionWith(InCopyEnvironment.CPPIncludeInfo.SystemIncludePaths); SystemDotNetAssemblyPaths .AddRange(InCopyEnvironment.SystemDotNetAssemblyPaths); FrameworkAssemblyDependencies.AddRange(InCopyEnvironment.FrameworkAssemblyDependencies); PrivateAssemblyDependencies .AddRange(InCopyEnvironment.PrivateAssemblyDependencies); Definitions .AddRange(InCopyEnvironment.Definitions); AdditionalArguments = InCopyEnvironment.AdditionalArguments; AdditionalFrameworks .AddRange(InCopyEnvironment.AdditionalFrameworks); } } /// <summary> /// Info about a "Shared PCH" header, including which module it is associated with and all of that module's dependencies /// </summary> public class SharedPCHHeaderInfo { /// The actual header file that the PCH will be created from public FileItem PCHHeaderFile; /// The module this header belongs to public UEBuildModuleCPP Module; /// All dependent modules public Dictionary<string, UEBuildModule> Dependencies; /// Performance diagnostics: The number of modules using this shared PCH header public int NumModulesUsingThisPCH = 0; } /** Encapsulates the environment that a C++ file is compiled in. */ public partial class CPPEnvironment { /** The file containing the precompiled header data. */ public FileItem PrecompiledHeaderFile = null; /** List of private CLR assemblies that, when modified, will force recompilation of any CLR source files */ public List<PrivateAssemblyInfo> PrivateAssemblyDependencies = new List<PrivateAssemblyInfo>(); public CPPEnvironmentConfiguration Config = new CPPEnvironmentConfiguration(); /** List of available shared global PCH headers */ public List<SharedPCHHeaderInfo> SharedPCHHeaderFiles = new List<SharedPCHHeaderInfo>(); /** List of "shared" precompiled header environments, potentially shared between modules */ public readonly List<PrecompileHeaderEnvironment> SharedPCHEnvironments = new List<PrecompileHeaderEnvironment>(); // Whether or not UHT is being built public bool bHackHeaderGenerator; /** Default constructor. */ public CPPEnvironment() {} /** Copy constructor. */ protected CPPEnvironment(CPPEnvironment InCopyEnvironment) { PrecompiledHeaderFile = InCopyEnvironment.PrecompiledHeaderFile; PrivateAssemblyDependencies.AddRange(InCopyEnvironment.PrivateAssemblyDependencies); SharedPCHHeaderFiles.AddRange( InCopyEnvironment.SharedPCHHeaderFiles ); SharedPCHEnvironments.AddRange( InCopyEnvironment.SharedPCHEnvironments ); bHackHeaderGenerator = InCopyEnvironment.bHackHeaderGenerator; Config = new CPPEnvironmentConfiguration(InCopyEnvironment.Config); } /** * Creates actions to compile a set of C++ source files. * @param CPPFiles - The C++ source files to compile. * @param ModuleName - Name of the module these files are associated with * @return The object files produced by the actions. */ public CPPOutput CompileFiles(UEBuildTarget Target, List<FileItem> CPPFiles, string ModuleName) { return UEToolChain.GetPlatformToolChain(Config.Target.Platform).CompileCPPFiles(Target, this, CPPFiles, ModuleName); } /** * Creates actions to compile a set of Windows resource script files. * @param RCFiles - The resource script files to compile. * @return The compiled resource (.res) files produced by the actions. */ public CPPOutput CompileRCFiles(UEBuildTarget Target, List<FileItem> RCFiles) { return UEToolChain.GetPlatformToolChain(Config.Target.Platform).CompileRCFiles(Target, this, RCFiles); } /** * Whether to use PCH files with the current target * * @return true if PCH files should be used, false otherwise */ public bool ShouldUsePCHs() { return UEBuildPlatform.GetBuildPlatformForCPPTargetPlatform(Config.Target.Platform).ShouldUsePCHFiles(Config.Target.Platform, Config.Target.Configuration); } public void AddPrivateAssembly( string FilePath ) { PrivateAssemblyInfo NewPrivateAssembly = new PrivateAssemblyInfo(); NewPrivateAssembly.FileItem = FileItem.GetItemByPath( FilePath ); PrivateAssemblyDependencies.Add( NewPrivateAssembly ); } /// <summary> /// Performs a deep copy of this CPPEnvironment object. /// </summary> /// <returns>Copied new CPPEnvironment object.</returns> public virtual CPPEnvironment DeepCopy() { return new CPPEnvironment(this); } }; }
using Magnesium; using System; using System.Runtime.InteropServices; using System.Diagnostics; namespace Magnesium.Vulkan { public class VkCommandBuffer : IMgCommandBuffer { internal IntPtr Handle { get; private set; } internal VkCommandBuffer(IntPtr handle) { Handle = handle; } public Result BeginCommandBuffer(MgCommandBufferBeginInfo pBeginInfo) { IntPtr inheritanceInfo = IntPtr.Zero; try { var param_0 = new VkCommandBufferBeginInfo(); param_0.sType = VkStructureType.StructureTypeCommandBufferBeginInfo; param_0.pNext = IntPtr.Zero; param_0.flags = (VkCommandBufferUsageFlags)pBeginInfo.Flags; if (pBeginInfo.InheritanceInfo != null) { var ihData = new VkCommandBufferInheritanceInfo(); ihData.sType = VkStructureType.StructureTypeCommandBufferInheritanceInfo; ihData.pNext = IntPtr.Zero; { UInt64 internalPtr = 0UL; var container = pBeginInfo.InheritanceInfo.RenderPass; if (container != null) { var rp = (VkRenderPass) container; Debug.Assert(rp != null); internalPtr = rp.Handle; } ihData.renderPass = internalPtr; } ihData.subpass = pBeginInfo.InheritanceInfo.Subpass; { UInt64 internalPtr = 0UL; var container = pBeginInfo.InheritanceInfo.Framebuffer; if (container != null) { var fb = (VkFramebuffer) container; Debug.Assert(fb != null); internalPtr = fb.Handle; } ihData.framebuffer = internalPtr; } ihData.occlusionQueryEnable = new VkBool32 { Value = pBeginInfo.InheritanceInfo.OcclusionQueryEnable ? 1U : 0U }; ihData.queryFlags = (VkQueryControlFlags)pBeginInfo.InheritanceInfo.QueryFlags; ihData.pipelineStatistics = (VkQueryPipelineStatisticFlags)pBeginInfo.InheritanceInfo.PipelineStatistics; // Copy data inheritanceInfo = Marshal.AllocHGlobal(Marshal.SizeOf(ihData)); Marshal.StructureToPtr(ihData, inheritanceInfo, false); } param_0.pInheritanceInfo = inheritanceInfo; return Interops.vkBeginCommandBuffer(this.Handle, ref param_0); } finally { if (inheritanceInfo != IntPtr.Zero) { Marshal.FreeHGlobal(inheritanceInfo); } } } public Result EndCommandBuffer() { return Interops.vkEndCommandBuffer(this.Handle); } public Result ResetCommandBuffer(MgCommandBufferResetFlagBits flags) { return Interops.vkResetCommandBuffer(this.Handle, (VkCommandBufferResetFlags)flags); } public void CmdBindPipeline(MgPipelineBindPoint pipelineBindPoint, IMgPipeline pipeline) { var bPipeline = (VkPipeline) pipeline; Debug.Assert(bPipeline != null); Interops.vkCmdBindPipeline(this.Handle, (VkPipelineBindPoint)pipelineBindPoint, bPipeline.Handle); } public void CmdSetViewport(UInt32 firstViewport, MgViewport[] pViewports) { var viewportHandle = GCHandle.Alloc(pViewports, GCHandleType.Pinned); try { unsafe { var viewportCount = (UInt32)pViewports.Length; var pinnedObject = viewportHandle.AddrOfPinnedObject(); var viewports = (MgViewport*)pinnedObject.ToPointer(); Interops.vkCmdSetViewport(this.Handle, firstViewport, viewportCount, viewports); } } finally { viewportHandle.Free(); } } public void CmdSetScissor(UInt32 firstScissor, MgRect2D[] pScissors) { var scissorHandle = GCHandle.Alloc(pScissors, GCHandleType.Pinned); try { unsafe { var count = (UInt32)pScissors.Length; var pinnedObject = scissorHandle.AddrOfPinnedObject(); var scissors = (MgRect2D*)pinnedObject.ToPointer(); Interops.vkCmdSetScissor(this.Handle, firstScissor, count, scissors); } } finally { scissorHandle.Free(); } } public void CmdSetLineWidth(float lineWidth) { Interops.vkCmdSetLineWidth(this.Handle, lineWidth); } public void CmdSetDepthBias(float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor) { Interops.vkCmdSetDepthBias(this.Handle, depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor); } public void CmdSetBlendConstants(MgColor4f blendConstants) { var color = new float[4]; color[0] = blendConstants.R; color[1] = blendConstants.G; color[2] = blendConstants.B; color[3] = blendConstants.A; // TODO : figure a way to directly pass in Interops.vkCmdSetBlendConstants(this.Handle, color); } public void CmdSetDepthBounds(float minDepthBounds, float maxDepthBounds) { Interops.vkCmdSetDepthBounds(this.Handle, minDepthBounds, maxDepthBounds); } public void CmdSetStencilCompareMask(MgStencilFaceFlagBits faceMask, UInt32 compareMask) { Interops.vkCmdSetStencilCompareMask(this.Handle, (VkStencilFaceFlags)faceMask, compareMask); } public void CmdSetStencilWriteMask(MgStencilFaceFlagBits faceMask, UInt32 writeMask) { Interops.vkCmdSetStencilWriteMask(this.Handle, (VkStencilFaceFlags)faceMask, writeMask); } public void CmdSetStencilReference(MgStencilFaceFlagBits faceMask, UInt32 reference) { Interops.vkCmdSetStencilReference(this.Handle, (VkStencilFaceFlags)faceMask, reference); } public void CmdBindDescriptorSets(MgPipelineBindPoint pipelineBindPoint, IMgPipelineLayout layout, UInt32 firstSet, UInt32 descriptorSetCount, IMgDescriptorSet[] pDescriptorSets, UInt32[] pDynamicOffsets) { var bLayout = (VkPipelineLayout)layout; Debug.Assert(bLayout != null); var stride = Marshal.SizeOf(typeof(IntPtr)); IntPtr sets = Marshal.AllocHGlobal((int)(stride * descriptorSetCount)); var src = new ulong[descriptorSetCount]; for (uint i = 0; i < descriptorSetCount; ++i) { var bDescSet = (VkDescriptorSet)pDescriptorSets[i]; Debug.Assert(bDescSet != null); src[i] = bDescSet.Handle; } // var dynamic (uint)pDynamicOffsets.Length uint dynamicOffsetCount = pDynamicOffsets != null ? (uint)pDynamicOffsets.Length : 0U; Interops.vkCmdBindDescriptorSets(this.Handle, (VkPipelineBindPoint)pipelineBindPoint, bLayout.Handle, firstSet, descriptorSetCount, src, dynamicOffsetCount, pDynamicOffsets); } public void CmdBindIndexBuffer(IMgBuffer buffer, UInt64 offset, MgIndexType indexType) { var bBuffer = (VkBuffer) buffer; Debug.Assert(bBuffer != null); Interops.vkCmdBindIndexBuffer(this.Handle, bBuffer.Handle, offset, (VkIndexType)indexType); } public void CmdBindVertexBuffers(UInt32 firstBinding, IMgBuffer[] pBuffers, UInt64[] pOffsets) { var bindingCount = (uint) pBuffers.Length; var src = new ulong[pBuffers.Length]; for (uint i = 0; i < bindingCount; ++i) { var bBuffer = (VkBuffer) pBuffers[i]; Debug.Assert(bBuffer != null); src[i] = bBuffer.Handle; } Interops.vkCmdBindVertexBuffers(this.Handle, firstBinding, bindingCount, src, pOffsets); } public void CmdDraw(UInt32 vertexCount, UInt32 instanceCount, UInt32 firstVertex, UInt32 firstInstance) { Interops.vkCmdDraw(this.Handle, vertexCount, instanceCount, firstVertex, firstInstance); } public void CmdDrawIndexed(UInt32 indexCount, UInt32 instanceCount, UInt32 firstIndex, Int32 vertexOffset, UInt32 firstInstance) { Interops.vkCmdDrawIndexed(this.Handle, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance); } public void CmdDrawIndirect(IMgBuffer buffer, UInt64 offset, UInt32 drawCount, UInt32 stride) { var bBuffer = (VkBuffer) buffer; Debug.Assert(bBuffer != null); Interops.vkCmdDrawIndirect(this.Handle, bBuffer.Handle, offset, drawCount, stride); } public void CmdDrawIndexedIndirect(IMgBuffer buffer, UInt64 offset, UInt32 drawCount, UInt32 stride) { var bBuffer = (VkBuffer) buffer; Debug.Assert(bBuffer != null); Interops.vkCmdDrawIndexedIndirect(this.Handle, bBuffer.Handle, offset, drawCount, stride); } public void CmdDispatch(UInt32 x, UInt32 y, UInt32 z) { Interops.vkCmdDispatch(this.Handle, x, y, z); } public void CmdDispatchIndirect(IMgBuffer buffer, UInt64 offset) { var bBuffer = (VkBuffer) buffer; Debug.Assert(bBuffer != null); Interops.vkCmdDispatchIndirect(this.Handle, bBuffer.Handle, offset); } public void CmdCopyBuffer(IMgBuffer srcBuffer, IMgBuffer dstBuffer, MgBufferCopy[] pRegions) { var bBuffer_src = (VkBuffer) srcBuffer; Debug.Assert(bBuffer_src != null); var bBuffer_dst = (VkBuffer) dstBuffer; Debug.Assert(bBuffer_dst != null); var handle = GCHandle.Alloc(pRegions, GCHandleType.Pinned); try { unsafe { var regionCount = (uint)pRegions.Length; var region = handle.AddrOfPinnedObject(); MgBufferCopy* regions = (MgBufferCopy*)region.ToPointer(); Interops.vkCmdCopyBuffer(this.Handle, bBuffer_src.Handle, bBuffer_dst.Handle, regionCount, regions); } } finally { handle.Free(); } } public void CmdCopyImage(IMgImage srcImage, MgImageLayout srcImageLayout, IMgImage dstImage, MgImageLayout dstImageLayout, MgImageCopy[] pRegions) { var bSrcImage = (VkImage) srcImage; Debug.Assert(bSrcImage != null); var bDstImage = (VkImage) dstImage; Debug.Assert(bDstImage != null); var handle = GCHandle.Alloc(pRegions, GCHandleType.Pinned); try { unsafe { var regionCount = (uint)pRegions.Length; var region = handle.AddrOfPinnedObject(); MgImageCopy* regions = (MgImageCopy*)region.ToPointer(); Interops.vkCmdCopyImage(this.Handle, bSrcImage.Handle, (VkImageLayout)srcImageLayout, bDstImage.Handle, (VkImageLayout)dstImageLayout, regionCount, regions); } } finally { handle.Free(); } } public void CmdBlitImage(IMgImage srcImage, MgImageLayout srcImageLayout, IMgImage dstImage, MgImageLayout dstImageLayout, MgImageBlit[] pRegions, MgFilter filter) { var bSrcImage = (VkImage) srcImage; Debug.Assert(bSrcImage != null); var bDstImage = (VkImage) dstImage; Debug.Assert(bDstImage != null); Interops.vkCmdBlitImage(this.Handle, bSrcImage.Handle, srcImageLayout, bDstImage.Handle, dstImageLayout, (uint)pRegions.Length, pRegions, (VkFilter)filter); } public void CmdCopyBufferToImage(IMgBuffer srcBuffer, IMgImage dstImage, MgImageLayout dstImageLayout, MgBufferImageCopy[] pRegions) { var bSrcBuffer = (VkBuffer) srcBuffer; Debug.Assert(bSrcBuffer != null); var bDstImage = (VkImage) dstImage; Debug.Assert(bDstImage != null); var handle = GCHandle.Alloc(pRegions, GCHandleType.Pinned); try { unsafe { var regionCount = (uint)pRegions.Length; var region = handle.AddrOfPinnedObject(); var regions = (MgBufferImageCopy*)region.ToPointer(); Interops.vkCmdCopyBufferToImage(this.Handle, bSrcBuffer.Handle, bDstImage.Handle, dstImageLayout, regionCount, regions); } } finally { handle.Free(); } } public void CmdCopyImageToBuffer(IMgImage srcImage, MgImageLayout srcImageLayout, IMgBuffer dstBuffer, MgBufferImageCopy[] pRegions) { var bSrcImage = (VkImage) srcImage; Debug.Assert(bSrcImage != null); var bDstBuffer = (VkBuffer) dstBuffer; Debug.Assert(bDstBuffer != null); var handle = GCHandle.Alloc(pRegions, GCHandleType.Pinned); try { unsafe { var regionCount = (uint)pRegions.Length; var regionAddress = handle.AddrOfPinnedObject(); var pinnedArray = (MgBufferImageCopy*)regionAddress.ToPointer(); Interops.vkCmdCopyImageToBuffer(this.Handle, bSrcImage.Handle, srcImageLayout, bDstBuffer.Handle, regionCount, pinnedArray); } } finally { handle.Free(); } } public void CmdUpdateBuffer(IMgBuffer dstBuffer, UInt64 dstOffset, UInt64 dataSize, IntPtr pData) { var bDstBuffer = (VkBuffer) dstBuffer; Debug.Assert(bDstBuffer != null); Interops.vkCmdUpdateBuffer(this.Handle, bDstBuffer.Handle, dstOffset, dataSize, pData); } public void CmdFillBuffer(IMgBuffer dstBuffer, UInt64 dstOffset, UInt64 size, UInt32 data) { var bDstBuffer = (VkBuffer) dstBuffer; Debug.Assert(bDstBuffer != null); Interops.vkCmdFillBuffer(this.Handle, bDstBuffer.Handle, dstOffset, size, data); } public void CmdClearColorImage(IMgImage image, MgImageLayout imageLayout, MgClearColorValue pColor, MgImageSubresourceRange[] pRanges) { var bImage = (VkImage) image; Debug.Assert(bImage != null); Interops.vkCmdClearColorImage(this.Handle, bImage.Handle, imageLayout, pColor, (uint)pRanges.Length, pRanges); } public void CmdClearDepthStencilImage(IMgImage image, MgImageLayout imageLayout, MgClearDepthStencilValue pDepthStencil, MgImageSubresourceRange[] pRanges) { var bImage = (VkImage) image; Debug.Assert(bImage != null); Interops.vkCmdClearDepthStencilImage(this.Handle, bImage.Handle, imageLayout, pDepthStencil, (uint)pRanges.Length, pRanges); } public void CmdClearAttachments(MgClearAttachment[] pAttachments, MgClearRect[] pRects) { var attachmentHandle = GCHandle.Alloc(pAttachments, GCHandleType.Pinned); var rectsHandle = GCHandle.Alloc(pRects, GCHandleType.Pinned); try { unsafe { var attachmentCount = (uint)pAttachments.Length; var attachment = attachmentHandle.AddrOfPinnedObject(); var rectCount = (uint)pRects.Length; var rects = rectsHandle.AddrOfPinnedObject(); Interops.vkCmdClearAttachments(this.Handle, attachmentCount, (Magnesium.MgClearAttachment*)attachment.ToPointer(), rectCount, (Magnesium.MgClearRect*)rects.ToPointer()); } } finally { rectsHandle.Free(); attachmentHandle.Free(); } } public void CmdResolveImage(IMgImage srcImage, MgImageLayout srcImageLayout, IMgImage dstImage, MgImageLayout dstImageLayout, MgImageResolve[] pRegions) { var bSrcImage = (VkImage) srcImage; Debug.Assert(bSrcImage != null); var bDstImage = (VkImage) dstImage; Debug.Assert(bDstImage != null); var handle = GCHandle.Alloc(pRegions, GCHandleType.Pinned); try { unsafe { var regionCount = (uint)pRegions.Length; var regionAddress = handle.AddrOfPinnedObject(); var pinnedArray = (MgImageResolve*)regionAddress.ToPointer(); Interops.vkCmdResolveImage(this.Handle, bSrcImage.Handle, srcImageLayout, bDstImage.Handle, dstImageLayout, regionCount, pinnedArray); } } finally { handle.Free(); } } public void CmdSetEvent(IMgEvent @event, MgPipelineStageFlagBits stageMask) { var bEvent = (VkEvent) @event; Debug.Assert(bEvent != null); Interops.vkCmdSetEvent(this.Handle, bEvent.Handle, (VkPipelineStageFlags)stageMask); } public void CmdResetEvent(IMgEvent @event, MgPipelineStageFlagBits stageMask) { var bEvent = (VkEvent) @event; Debug.Assert(bEvent != null); Interops.vkCmdResetEvent(this.Handle, bEvent.Handle, (VkPipelineStageFlags)stageMask); } public void CmdWaitEvents(IMgEvent[] pEvents, MgPipelineStageFlagBits srcStageMask, MgPipelineStageFlagBits dstStageMask, MgMemoryBarrier[] pMemoryBarriers, MgBufferMemoryBarrier[] pBufferMemoryBarriers, MgImageMemoryBarrier[] pImageMemoryBarriers) { unsafe { var eventHandles = stackalloc UInt64[pEvents.Length]; var eventCount = (uint)pEvents.Length; for (var i = 0; i < eventCount; ++i) { var bEvent = (VkEvent) pEvents[i]; Debug.Assert(bEvent != null); eventHandles[i] = bEvent.Handle; } var memBarrierCount = 0U; VkMemoryBarrier* pMemBarriers = null; if (pMemoryBarriers != null) { memBarrierCount = (uint)pMemoryBarriers.Length; var tempMem = stackalloc VkMemoryBarrier[pMemoryBarriers.Length]; for (var i = 0; i < memBarrierCount; ++i) { tempMem[i] = new VkMemoryBarrier { sType = VkStructureType.StructureTypeMemoryBarrier, pNext = IntPtr.Zero, srcAccessMask = (VkAccessFlags)pMemoryBarriers[i].SrcAccessMask, dstAccessMask = (VkAccessFlags)pMemoryBarriers[i].DstAccessMask, }; } pMemBarriers = tempMem; } uint bufBarrierCount = 0; VkBufferMemoryBarrier* pBufBarriers = null; if (pBufferMemoryBarriers != null) { bufBarrierCount = (uint)pBufferMemoryBarriers.Length; var tempBuf = stackalloc VkBufferMemoryBarrier[pBufferMemoryBarriers.Length]; for (var i = 0; i < bufBarrierCount; ++i) { var current = pBufferMemoryBarriers[i]; var bBuffer = (VkBuffer) current.Buffer; Debug.Assert(bBuffer != null); tempBuf[i] = new VkBufferMemoryBarrier { sType = VkStructureType.StructureTypeBufferMemoryBarrier, pNext = IntPtr.Zero, dstAccessMask = (VkAccessFlags)current.DstAccessMask, srcAccessMask = (VkAccessFlags)current.SrcAccessMask, srcQueueFamilyIndex = current.SrcQueueFamilyIndex, dstQueueFamilyIndex = current.DstQueueFamilyIndex, buffer = bBuffer.Handle, offset = current.Offset, size = current.Size, }; } pBufBarriers = tempBuf; } uint imgBarriersCount = 0; VkImageMemoryBarrier* pImgBarriers = null; if (pImageMemoryBarriers != null) { imgBarriersCount = (uint)pImageMemoryBarriers.Length; var tempImg = stackalloc VkImageMemoryBarrier[pImageMemoryBarriers.Length]; for (var i = 0; i < bufBarrierCount; ++i) { var current = pImageMemoryBarriers[i]; var bImage = (VkImage) current.Image; Debug.Assert(bImage != null); tempImg[i] = new VkImageMemoryBarrier { sType = VkStructureType.StructureTypeImageMemoryBarrier, pNext = IntPtr.Zero, dstAccessMask = (VkAccessFlags)current.DstAccessMask, srcAccessMask = (VkAccessFlags)current.SrcAccessMask, oldLayout = (Magnesium.Vulkan.VkImageLayout)current.OldLayout, newLayout = (Magnesium.Vulkan.VkImageLayout)current.NewLayout, srcQueueFamilyIndex = current.SrcQueueFamilyIndex, dstQueueFamilyIndex = current.DstQueueFamilyIndex, image = bImage.Handle, subresourceRange = new VkImageSubresourceRange { aspectMask = (Magnesium.Vulkan.VkImageAspectFlags)current.SubresourceRange.AspectMask, baseArrayLayer = current.SubresourceRange.BaseArrayLayer, baseMipLevel = current.SubresourceRange.BaseMipLevel, layerCount = current.SubresourceRange.LayerCount, levelCount = current.SubresourceRange.LevelCount, } }; } pImgBarriers = tempImg; } Interops.vkCmdWaitEvents( this.Handle, eventCount, eventHandles, (VkPipelineStageFlags)srcStageMask, (VkPipelineStageFlags)dstStageMask, memBarrierCount, pMemBarriers, bufBarrierCount, pBufBarriers, imgBarriersCount, pImgBarriers); } } public void CmdPipelineBarrier(MgPipelineStageFlagBits srcStageMask, MgPipelineStageFlagBits dstStageMask, MgDependencyFlagBits dependencyFlags, MgMemoryBarrier[] pMemoryBarriers, MgBufferMemoryBarrier[] pBufferMemoryBarriers, MgImageMemoryBarrier[] pImageMemoryBarriers) { unsafe { var memBarrierCount = pMemoryBarriers != null ? (uint)pMemoryBarriers.Length : 0U; var pMemBarriers = stackalloc VkMemoryBarrier[(int)memBarrierCount]; for (var i = 0; i < memBarrierCount; ++i) { pMemBarriers[i] = new VkMemoryBarrier { sType = VkStructureType.StructureTypeMemoryBarrier, pNext = IntPtr.Zero, srcAccessMask = (VkAccessFlags)pMemoryBarriers[i].SrcAccessMask, dstAccessMask = (VkAccessFlags)pMemoryBarriers[i].DstAccessMask, }; } uint bufBarrierCount = pBufferMemoryBarriers != null ? (uint)pBufferMemoryBarriers.Length : 0U; var pBufBarriers = stackalloc VkBufferMemoryBarrier[(int) bufBarrierCount]; for (var j = 0; j < bufBarrierCount; ++j) { var current = pBufferMemoryBarriers[j]; var bBuffer = (VkBuffer) current.Buffer; Debug.Assert(bBuffer != null); pBufBarriers[j] = new VkBufferMemoryBarrier { sType = VkStructureType.StructureTypeBufferMemoryBarrier, pNext = IntPtr.Zero, dstAccessMask = (VkAccessFlags)current.DstAccessMask, srcAccessMask = (VkAccessFlags)current.SrcAccessMask, srcQueueFamilyIndex = current.SrcQueueFamilyIndex, dstQueueFamilyIndex = current.DstQueueFamilyIndex, buffer = bBuffer.Handle, offset = current.Offset, size = current.Size, }; } uint imgBarriersCount = pImageMemoryBarriers != null ? (uint)pImageMemoryBarriers.Length : 0U; var pImgBarriers = stackalloc VkImageMemoryBarrier[(int) imgBarriersCount]; for (var k = 0; k < imgBarriersCount; ++k) { var current = pImageMemoryBarriers[k]; var bImage = (VkImage) current.Image; Debug.Assert(bImage != null); pImgBarriers[k] = new VkImageMemoryBarrier { sType = VkStructureType.StructureTypeImageMemoryBarrier, pNext = IntPtr.Zero, dstAccessMask = (VkAccessFlags)current.DstAccessMask, srcAccessMask = (VkAccessFlags)current.SrcAccessMask, oldLayout = (VkImageLayout)current.OldLayout, newLayout = (VkImageLayout)current.NewLayout, srcQueueFamilyIndex = current.SrcQueueFamilyIndex, dstQueueFamilyIndex = current.DstQueueFamilyIndex, image = bImage.Handle, subresourceRange = new VkImageSubresourceRange { aspectMask = (VkImageAspectFlags)current.SubresourceRange.AspectMask, baseArrayLayer = current.SubresourceRange.BaseArrayLayer, baseMipLevel = current.SubresourceRange.BaseMipLevel, layerCount = current.SubresourceRange.LayerCount, levelCount = current.SubresourceRange.LevelCount, } }; } VkMemoryBarrier* mems = memBarrierCount > 0 ? pMemBarriers : null; VkBufferMemoryBarrier* bufs = bufBarrierCount > 0 ? pBufBarriers : null; VkImageMemoryBarrier* images = imgBarriersCount > 0 ? pImgBarriers : null; Interops.vkCmdPipelineBarrier(Handle, (VkPipelineStageFlags)srcStageMask, (VkPipelineStageFlags)dstStageMask, (VkDependencyFlags)dependencyFlags, memBarrierCount, mems, bufBarrierCount, bufs, imgBarriersCount, images); } } public void CmdBeginQuery(IMgQueryPool queryPool, UInt32 query, MgQueryControlFlagBits flags) { var bQueryPool = (VkQueryPool) queryPool; Debug.Assert(bQueryPool != null); Interops.vkCmdBeginQuery(this.Handle, bQueryPool.Handle, query, (Magnesium.Vulkan.VkQueryControlFlags)flags); } public void CmdEndQuery(IMgQueryPool queryPool, UInt32 query) { var bQueryPool = (VkQueryPool) queryPool; Debug.Assert(bQueryPool != null); Interops.vkCmdEndQuery(this.Handle, bQueryPool.Handle, query); } public void CmdResetQueryPool(IMgQueryPool queryPool, UInt32 firstQuery, UInt32 queryCount) { var bQueryPool = (VkQueryPool) queryPool; Debug.Assert(bQueryPool != null); Interops.vkCmdResetQueryPool(this.Handle, bQueryPool.Handle, firstQuery, queryCount); } public void CmdWriteTimestamp(MgPipelineStageFlagBits pipelineStage, IMgQueryPool queryPool, UInt32 query) { var bQueryPool = (VkQueryPool) queryPool; Debug.Assert(bQueryPool != null); Interops.vkCmdWriteTimestamp(this.Handle, (VkPipelineStageFlags)pipelineStage, bQueryPool.Handle, query); } public void CmdCopyQueryPoolResults(IMgQueryPool queryPool, UInt32 firstQuery, UInt32 queryCount, IMgBuffer dstBuffer, UInt64 dstOffset, UInt64 stride, MgQueryResultFlagBits flags) { var bQueryPool =(VkQueryPool) queryPool; Debug.Assert(bQueryPool != null); var bDstBuffer = (VkBuffer) dstBuffer; Debug.Assert(bDstBuffer != null); Interops.vkCmdCopyQueryPoolResults(this.Handle, bQueryPool.Handle, firstQuery, queryCount, bDstBuffer.Handle, dstOffset, stride, (Magnesium.Vulkan.VkQueryResultFlags)flags); } public void CmdPushConstants(IMgPipelineLayout layout, MgShaderStageFlagBits stageFlags, UInt32 offset, UInt32 size, IntPtr pValues) { var bLayout = (VkPipelineLayout) layout; Debug.Assert(bLayout != null); Interops.vkCmdPushConstants(this.Handle, bLayout.Handle, (Magnesium.Vulkan.VkShaderStageFlags)stageFlags, offset, size, pValues); } public void CmdBeginRenderPass(MgRenderPassBeginInfo pRenderPassBegin, MgSubpassContents contents) { if (pRenderPassBegin == null) { throw new ArgumentNullException(nameof(pRenderPassBegin)); } var bRenderPass = (VkRenderPass) pRenderPassBegin.RenderPass; Debug.Assert(bRenderPass != null); var bFrameBuffer = (VkFramebuffer) pRenderPassBegin.Framebuffer; Debug.Assert(bFrameBuffer != null); var clearValueCount = pRenderPassBegin.ClearValues != null ? (UInt32) pRenderPassBegin.ClearValues.Length : 0U; var clearValues = IntPtr.Zero; try { if (clearValueCount > 0) { var stride = Marshal.SizeOf(typeof(MgClearValue)); clearValues = Marshal.AllocHGlobal((int)(stride * clearValueCount)); for (uint i = 0; i < clearValueCount; ++i) { IntPtr dest = IntPtr.Add(clearValues, (int)(i * stride)); Marshal.StructureToPtr(pRenderPassBegin.ClearValues[i], dest, false); } } var beginInfo = new VkRenderPassBeginInfo { sType = VkStructureType.StructureTypeRenderPassBeginInfo, pNext = IntPtr.Zero, renderPass = bRenderPass.Handle, framebuffer = bFrameBuffer.Handle, renderArea = pRenderPassBegin.RenderArea, clearValueCount = clearValueCount, pClearValues = clearValues, }; Interops.vkCmdBeginRenderPass(this.Handle, ref beginInfo, (Magnesium.Vulkan.VkSubpassContents)contents); } finally { if (clearValues != IntPtr.Zero) { Marshal.FreeHGlobal(clearValues); } } } public void CmdNextSubpass(MgSubpassContents contents) { Interops.vkCmdNextSubpass(this.Handle, (VkSubpassContents)contents); } public void CmdEndRenderPass() { Interops.vkCmdEndRenderPass(this.Handle); } public void CmdExecuteCommands(IMgCommandBuffer[] pCommandBuffers) { var handles = new IntPtr[pCommandBuffers.Length]; var bufferCount = (uint)pCommandBuffers.Length; for (uint i = 0; i < bufferCount; ++i) { var bBuffer = (VkCommandBuffer) pCommandBuffers[i]; Debug.Assert(bBuffer != null); handles[i] = bBuffer.Handle; } Interops.vkCmdExecuteCommands(this.Handle, bufferCount, handles); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public partial class CommonSecurityDescriptor_Constructor { public static IEnumerable<object[]> CommonSecurityDescriptor_Constructor_TestData() { yield return new object[] { false, false, 20 , "S-1-5-0", "S-1-5-32-544", "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { false, true , 20 , "S-1-5-0", "S-1-5-32-544", "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , false, 20 , "S-1-5-0", "S-1-5-32-544", "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , "S-1-5-0", "S-1-5-32-544", "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 1 , "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , -1 , "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 0 , "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 65536, "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 65535, "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 32768, "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , "BA" , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , "BA" , "BG" , "64:2:1:BA:false:0", null }; yield return new object[] { true , true , 20 , "BA" , "BG" , null , "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , "BA" , "BG" , null , null }; yield return new object[] { true , true , 20 , "BA" , null , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , "BA" , null , "64:2:1:BA:false:0", null }; yield return new object[] { true , true , 20 , "BA" , null , null , "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , "BA" , null , null , null }; yield return new object[] { true , true , 20 , null , "BG" , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , null , "BG" , "64:2:1:BA:false:0", null }; yield return new object[] { true , true , 20 , null , "BG" , null , "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , null , "BG" , null , null }; yield return new object[] { true , true , 20 , null , null , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , null , null , "64:2:1:BA:false:0", null }; yield return new object[] { true , true , 20 , null , null , null , "0:1:1:BO:false:0" }; yield return new object[] { true , true , 20 , null , null , null , null }; yield return new object[] { true , true , 1 , null , null , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 16 , "BA" , "BG" , null , "0:1:1:BO:false:0" }; yield return new object[] { true , true , 4 , "BA" , "BG" , "64:2:1:BA:false:0", null }; yield return new object[] { true , true , 1 , "S-1-5-0", "S-1-5-32-544", null , null }; yield return new object[] { true , true , 16 , null , null , null , null }; yield return new object[] { true , true , 16 , null , null , "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 16 , "S-1-5-0", "S-1-5-32-544", "64:2:1:BA:false:0", "0:1:1:BO:false:0" }; yield return new object[] { true , true , 16 , "S-1-5-0", "S-1-5-32-544", "64:2:1:BA:false:0", null }; } [Fact] public static void AdditionalTestCases() { //test cases include the exceptions from the constructor SystemAcl sacl = null; DiscretionaryAcl dacl = null; CommonSecurityDescriptor sd = null; // test case 1: SACL is not null, SACL.IsContainer is true, but isContainer parameter is false sacl = new SystemAcl(true, true, 10); AssertExtensions.Throws<ArgumentException>("systemAcl", () => { sd = new CommonSecurityDescriptor(false, true, ControlFlags.SystemAclPresent, null, null, sacl, null); }); // test case 2: SACL is not null, SACL.IsContainer is false, but isContainer parameter is true sacl = new SystemAcl(false, true, 10); AssertExtensions.Throws<ArgumentException>("systemAcl", () => { sd = new CommonSecurityDescriptor(true, true, ControlFlags.SystemAclPresent, null, null, sacl, null); }); // test case 3: DACL is not null, DACL.IsContainer is true, but isContainer parameter is false dacl = new DiscretionaryAcl(true, true, 10); AssertExtensions.Throws<ArgumentException>("discretionaryAcl", () => { sd = new CommonSecurityDescriptor(false, true, ControlFlags.DiscretionaryAclPresent, null, null, null, dacl); }); // test case 4: DACL is not null, DACL.IsContainer is false, but isContainer parameter is true dacl = new DiscretionaryAcl(false, true, 10); AssertExtensions.Throws<ArgumentException>("discretionaryAcl", () => { sd = new CommonSecurityDescriptor(true, true, ControlFlags.DiscretionaryAclPresent, null, null, null, dacl); }); // test case 5: SACL is not null, SACL.IsDS is true, but isDS parameter is false sacl = new SystemAcl(true, true, 10); AssertExtensions.Throws<ArgumentException>("systemAcl", () => { sd = new CommonSecurityDescriptor(true, false, ControlFlags.SystemAclPresent, null, null, sacl, null); }); // test case 6: SACL is not null, SACL.IsDS is false, but isDS parameter is true sacl = new SystemAcl(true, false, 10); AssertExtensions.Throws<ArgumentException>("systemAcl", () => { sd = new CommonSecurityDescriptor(true, true, ControlFlags.SystemAclPresent, null, null, sacl, null); }); // test case 7: DACL is not null, DACL.IsDS is true, but isDS parameter is false dacl = new DiscretionaryAcl(true, true, 10); AssertExtensions.Throws<ArgumentException>("discretionaryAcl", () => { sd = new CommonSecurityDescriptor(true, false, ControlFlags.DiscretionaryAclPresent, null, null, null, dacl); }); // test case 8: DACL is not null, DACL.IsDS is false, but isDS parameter is true dacl = new DiscretionaryAcl(true, false, 10); AssertExtensions.Throws<ArgumentException>("discretionaryAcl", () => { sd = new CommonSecurityDescriptor(true, true, ControlFlags.DiscretionaryAclPresent, null, null, null, dacl); }); } [Theory] [MemberData(nameof(CommonSecurityDescriptor_Constructor_TestData))] public static void TestConstructor(bool isContainer, bool isDS, int flags, string ownerStr, string groupStr, string saclStr, string daclStr) { ControlFlags controlFlags = ControlFlags.OwnerDefaulted; SecurityIdentifier owner = null; SecurityIdentifier group = null; RawAcl rawAcl = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; controlFlags = (ControlFlags)flags; owner = (ownerStr != null) ? new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(ownerStr)) : null; group = (groupStr != null) ? new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(groupStr)) : null; rawAcl = (saclStr != null) ? Utils.CreateRawAclFromString(saclStr) : null; if (rawAcl == null) sacl = null; else sacl = new SystemAcl(isContainer, isDS, rawAcl); rawAcl = (daclStr != null) ? Utils.CreateRawAclFromString(daclStr) : null; if (rawAcl == null) dacl = null; else dacl = new DiscretionaryAcl(isContainer, isDS, rawAcl); Assert.True(VerifyResult(isContainer, isDS, controlFlags, owner, group, sacl, dacl)); } private static bool VerifyResult(bool isContainer, bool isDS, ControlFlags controlFlags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl sacl, DiscretionaryAcl dacl) { CommonSecurityDescriptor commonSecurityDescriptor = null; bool result = false; try { commonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, controlFlags, owner, group, sacl, dacl); // verify the result if ((isContainer == commonSecurityDescriptor.IsContainer) && (isDS == commonSecurityDescriptor.IsDS) && ((((sacl != null) ? (controlFlags | ControlFlags.SystemAclPresent) : (controlFlags & (~ControlFlags.SystemAclPresent))) | ControlFlags.SelfRelative | ControlFlags.DiscretionaryAclPresent) == commonSecurityDescriptor.ControlFlags) && (owner == commonSecurityDescriptor.Owner) && (group == commonSecurityDescriptor.Group) && (sacl == commonSecurityDescriptor.SystemAcl) && (Utils.ComputeBinaryLength(commonSecurityDescriptor, dacl != null) == commonSecurityDescriptor.BinaryLength)) { if (dacl == null) { //check the contructor created an empty Dacl with correct IsContainer and isDS info if (isContainer == commonSecurityDescriptor.DiscretionaryAcl.IsContainer && isDS == commonSecurityDescriptor.DiscretionaryAcl.IsDS && commonSecurityDescriptor.DiscretionaryAcl.Count == 1 && Utils.VerifyDaclWithCraftedAce(isContainer, isDS, commonSecurityDescriptor.DiscretionaryAcl)) { result = true; } else { result = false; } } else if (dacl == commonSecurityDescriptor.DiscretionaryAcl) { result = true; } else { result = false; } } else { result = false; } } catch (ArgumentException) { if ((sacl != null && sacl.IsContainer != isContainer) || (sacl != null && sacl.IsDS != isDS) || (dacl != null && dacl.IsContainer != isContainer) || (dacl != null && dacl.IsDS != isDS)) result = true; else { // unexpected exception result = false; } } return result; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Dynamic; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; class MetaPythonFunction : MetaPythonObject, IPythonInvokable, IPythonOperable, IPythonConvertible, IInferableInvokable, IConvertibleMetaObject, IPythonGetable { public MetaPythonFunction(Expression/*!*/ expression, BindingRestrictions/*!*/ restrictions, PythonFunction/*!*/ value) : base(expression, BindingRestrictions.Empty, value) { Assert.NotNull(value); } #region IPythonInvokable Members public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) { return new FunctionBinderHelper(pythonInvoke, this, codeContext, args).MakeMetaObject(); } #endregion #region IPythonGetable Members public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) { return BindGetMemberWorker(member, member.Name, codeContext); } #endregion #region MetaObject Overrides public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { ParameterExpression tmp = Expression.Parameter(typeof(object)); // first get the default binder value DynamicMetaObject fallback = action.FallbackInvokeMember(this, args); // then fallback w/ an error suggestion that does a late bound lookup. return action.FallbackInvokeMember( this, args, new DynamicMetaObject( Ast.Block( new[] { tmp }, Ast.Condition( Ast.NotEqual( Ast.Assign( tmp, Ast.Call( typeof(PythonOps).GetMethod("PythonFunctionGetMember"), AstUtils.Convert( Expression, typeof(PythonFunction) ), Expression.Constant(action.Name) ) ), Ast.Constant(OperationFailed.Value) ), action.FallbackInvoke( new DynamicMetaObject(tmp, BindingRestrictions.Empty), args, null ).Expression, AstUtils.Convert(fallback.Expression, typeof(object)) ) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions) ) ); } public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ call, params DynamicMetaObject/*!*/[]/*!*/ args) { return new FunctionBinderHelper(call, this, null, args).MakeMetaObject(); } public override DynamicMetaObject BindConvert(ConvertBinder/*!*/ conversion) { return ConvertWorker(conversion, conversion.Type, conversion.Explicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast); } public DynamicMetaObject BindConvert(PythonConversionBinder binder) { return ConvertWorker(binder, binder.Type, binder.ResultKind); } public DynamicMetaObject ConvertWorker(DynamicMetaObjectBinder binder, Type type, ConversionResultKind kind) { if (type.IsSubclassOf(typeof(Delegate))) { return MakeDelegateTarget(binder, type, Restrict(typeof(PythonFunction))); } return FallbackConvert(binder); } public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() { foreach (object o in Value.__dict__.Keys) { if (o is string) { yield return (string)o; } } } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return BindGetMemberWorker(binder, binder.Name, PythonContext.GetCodeContextMO(binder)); } private DynamicMetaObject BindGetMemberWorker(DynamicMetaObjectBinder binder, string name, DynamicMetaObject codeContext) { ParameterExpression tmp = Expression.Parameter(typeof(object)); // first get the default binder value DynamicMetaObject fallback = FallbackGetMember(binder, this, codeContext); // then fallback w/ an error suggestion that does a late bound lookup. return FallbackGetMember( binder, this, codeContext, new DynamicMetaObject( Ast.Block( new[] { tmp }, Ast.Condition( Ast.NotEqual( Ast.Assign( tmp, Ast.Call( typeof(PythonOps).GetMethod("PythonFunctionGetMember"), AstUtils.Convert( Expression, typeof(PythonFunction) ), Expression.Constant(name) ) ), Ast.Constant(OperationFailed.Value) ), tmp, AstUtils.Convert(fallback.Expression, typeof(object)) ) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions) ) ); } private static DynamicMetaObject FallbackGetMember(DynamicMetaObjectBinder binder, DynamicMetaObject self, DynamicMetaObject codeContext) { return FallbackGetMember(binder, self, codeContext, null); } private static DynamicMetaObject FallbackGetMember(DynamicMetaObjectBinder binder, DynamicMetaObject self, DynamicMetaObject codeContext, DynamicMetaObject errorSuggestion) { PythonGetMemberBinder pyGetMem = binder as PythonGetMemberBinder; if (pyGetMem != null) { return pyGetMem.Fallback(self, codeContext, errorSuggestion); } return ((GetMemberBinder)binder).FallbackGetMember(self, errorSuggestion); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { // fallback w/ an error suggestion that does a late bound set return binder.FallbackSetMember( this, value, new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("PythonFunctionSetMember"), AstUtils.Convert( Expression, typeof(PythonFunction) ), Expression.Constant(binder.Name), AstUtils.Convert( value.Expression, typeof(object) ) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)) ) ); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { switch (binder.Name) { case "func_dict": case "__dict__": return new DynamicMetaObject( Expression.Call( typeof(PythonOps).GetMethod("PythonFunctionDeleteDict") ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)) ); case "__doc__": case "func_doc": return new DynamicMetaObject( Expression.Call( typeof(PythonOps).GetMethod("PythonFunctionDeleteDoc"), Expression.Convert(Expression, typeof(PythonFunction)) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)) ); case "func_defaults": return new DynamicMetaObject( Expression.Call( typeof(PythonOps).GetMethod("PythonFunctionDeleteDefaults"), Expression.Convert(Expression, typeof(PythonFunction)) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)) ); } // first get the default binder value DynamicMetaObject fallback = binder.FallbackDeleteMember(this); // then fallback w/ an error suggestion that does a late bound delete return binder.FallbackDeleteMember( this, new DynamicMetaObject( Expression.Condition( Ast.Call( typeof(PythonOps).GetMethod("PythonFunctionDeleteMember"), AstUtils.Convert( Expression, typeof(PythonFunction) ), Expression.Constant(binder.Name) ), Expression.Default(typeof(void)), // we deleted the member AstUtils.Convert( fallback.Expression, // report language specific error, typeof(void) ) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions) ) ); } #endregion #region Calls /// <summary> /// Performs the actual work of binding to the function. /// /// Overall this works by going through the arguments and attempting to bind all the outstanding known /// arguments - position arguments and named arguments which map to parameters are easy and handled /// in the 1st pass for GetArgumentsForRule. We also pick up any extra named or position arguments which /// will need to be passed off to a kw argument or a params array. /// /// After all the normal args have been assigned to do a 2nd pass in FinishArguments. Here we assign /// a value to either a value from the params list, kw-dict, or defaults. If there is ambiguity between /// this (e.g. we have a splatted params list, kw-dict, and defaults) we call a helper which extracts them /// in the proper order (first try the list, then the dict, then the defaults). /// </summary> class FunctionBinderHelper { private readonly MetaPythonFunction/*!*/ _func; // the meta object for the function we're calling private readonly DynamicMetaObject/*!*/[]/*!*/ _args; // the arguments for the function private readonly DynamicMetaObject/*!*/[]/*!*/ _originalArgs; // the original arguments for the function private readonly DynamicMetaObjectBinder/*!*/ _call; // the signature for the method call private readonly Expression _codeContext; // the code context expression if one is available. private List<ParameterExpression>/*!*/ _temps; // temporary variables allocated to create the rule private ParameterExpression _dict, _params, _paramsLen; // splatted dictionary & params + the initial length of the params array, null if not provided. private List<Expression> _init; // a set of initialization code (e.g. creating a list for the params array) private Expression _error; // a custom error expression if the default needs to be overridden. private bool _extractedParams; // true if we needed to extract a parameter from the parameter list. private bool _extractedDefault; // true if we needed to extract a parameter from the kw list. private bool _needCodeTest; // true if we need to test the code object private Expression _deferTest; // non-null if we have a test which could fail at runtime and we need to fallback to deferal private Expression _userProvidedParams; // expression the user provided that should be expanded for params. private Expression _paramlessCheck; // tests when we have no parameters public FunctionBinderHelper(DynamicMetaObjectBinder/*!*/ call, MetaPythonFunction/*!*/ function, Expression codeContext, DynamicMetaObject/*!*/[]/*!*/ args) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "PythonFunction Invoke " + function.Value.FunctionCompatibility + " w/ " + args.Length + " args"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "PythonFunction"); _call = call; _func = function; _args = args; _originalArgs = args; _temps = new List<ParameterExpression>(); _codeContext = codeContext; // Remove the passed in instance argument if present int instanceIndex = Signature.IndexOf(ArgumentType.Instance); if (instanceIndex > -1) { _args = ArrayUtils.RemoveAt(_args, instanceIndex); } } public DynamicMetaObject/*!*/ MakeMetaObject() { Expression[] invokeArgs = GetArgumentsForRule(); BindingRestrictions restrict = _func.Restrictions.Merge(GetRestrictions().Merge(BindingRestrictions.Combine(_args))); DynamicMetaObject res; if (invokeArgs != null) { // successful call Expression target = AddInitialization(MakeFunctionInvoke(invokeArgs)); if (_temps.Count > 0) { target = Ast.Block( _temps, target ); } res = new DynamicMetaObject( target, restrict ); } else if (_error != null) { // custom error generated while figuring out the call res = new DynamicMetaObject(_error, restrict); } else { // generic error res = new DynamicMetaObject( _call.Throw( Ast.Call( typeof(PythonOps).GetMethod(Signature.HasKeywordArgument() ? "BadKeywordArgumentError" : "FunctionBadArgumentError"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Constant(Signature.GetProvidedPositionalArgumentCount()) ), typeof(object) ), restrict ); } DynamicMetaObject[] deferArgs = ArrayUtils.Insert(_func, _originalArgs); if (_codeContext != null) { deferArgs = ArrayUtils.Insert(new DynamicMetaObject(_codeContext, BindingRestrictions.Empty), deferArgs); } return BindingHelpers.AddDynamicTestAndDefer( _call, res, deferArgs, new ValidationInfo(_deferTest), res.Expression.Type // force defer to our return type, our restrictions guarantee this to be true (only defaults can change, and we restrict to the delegate type) ); } private CallSignature Signature { get { return BindingHelpers.GetCallSignature(_call); } } /// <summary> /// Makes the test for our rule. /// </summary> private BindingRestrictions/*!*/ GetRestrictions() { if (!Signature.HasKeywordArgument()) { return GetSimpleRestriction(); } return GetComplexRestriction(); } /// <summary> /// Makes the test when we just have simple positional arguments. /// </summary> private BindingRestrictions/*!*/ GetSimpleRestriction() { _deferTest = Ast.Equal( Ast.Call( typeof(PythonOps).GetMethod("FunctionGetCompatibility"), Ast.Convert(_func.Expression, typeof(PythonFunction)) ), AstUtils.Constant(_func.Value.FunctionCompatibility) ); return BindingRestrictionsHelpers.GetRuntimeTypeRestriction( _func.Expression, typeof(PythonFunction) ); } /// <summary> /// Makes the test when we have a keyword argument call or splatting. /// </summary> /// <returns></returns> private BindingRestrictions/*!*/ GetComplexRestriction() { if (_extractedDefault) { return BindingRestrictions.GetInstanceRestriction(_func.Expression, _func.Value); } else if (_needCodeTest) { return GetSimpleRestriction().Merge( BindingRestrictions.GetInstanceRestriction( Expression.Property( GetFunctionParam(), "__code__" ), _func.Value.__code__ ) ); } return GetSimpleRestriction(); } /// <summary> /// Gets the array of expressions which correspond to each argument for the function. These /// correspond with the function as it's defined in Python and must be transformed for our /// delegate type before being used. /// </summary> private Expression/*!*/[]/*!*/ GetArgumentsForRule() { Expression[] exprArgs = new Expression[_func.Value.NormalArgumentCount + _func.Value.ExtraArguments]; List<Expression> extraArgs = null; Dictionary<string, Expression> namedArgs = null; int instanceIndex = Signature.IndexOf(ArgumentType.Instance); // walk all the provided args and find out where they go... for (int i = 0; i < _args.Length; i++) { int parameterIndex = (instanceIndex == -1 || i < instanceIndex) ? i : i + 1; switch (Signature.GetArgumentKind(i)) { case ArgumentType.Dictionary: _args[parameterIndex] = MakeDictionaryCopy(_args[parameterIndex]); continue; case ArgumentType.List: _userProvidedParams = _args[parameterIndex].Expression; continue; case ArgumentType.Named: _needCodeTest = true; bool foundName = false; for (int j = 0; j < _func.Value.NormalArgumentCount; j++) { if (_func.Value.ArgNames[j] == Signature.GetArgumentName(i)) { if (exprArgs[j] != null) { // kw-argument provided for already provided normal argument. if (_error == null) { _error = _call.Throw( Expression.Call( typeof(PythonOps).GetMethod("MultipleKeywordArgumentError"), GetFunctionParam(), Expression.Constant(_func.Value.ArgNames[j]) ), typeof(object) ); } return null; } exprArgs[j] = _args[parameterIndex].Expression; foundName = true; break; } } if (!foundName) { if (namedArgs == null) { namedArgs = new Dictionary<string, Expression>(); } namedArgs[Signature.GetArgumentName(i)] = _args[parameterIndex].Expression; } continue; } if (i < _func.Value.NormalArgumentCount) { exprArgs[i] = _args[parameterIndex].Expression; } else { if (extraArgs == null) { extraArgs = new List<Expression>(); } extraArgs.Add(_args[parameterIndex].Expression); } } if (!FinishArguments(exprArgs, extraArgs, namedArgs)) { if (namedArgs != null && _func.Value.ExpandDictPosition == -1) { MakeUnexpectedKeywordError(namedArgs); } return null; } return GetArgumentsForTargetType(exprArgs); } /// <summary> /// Binds any missing arguments to values from params array, kw dictionary, or default values. /// </summary> private bool FinishArguments(Expression[] exprArgs, List<Expression> paramsArgs, Dictionary<string, Expression> namedArgs) { int noDefaults = _func.Value.NormalArgumentCount - _func.Value.Defaults.Length; // number of args w/o defaults for (int i = 0; i < _func.Value.NormalArgumentCount; i++) { if (exprArgs[i] != null) { if (_userProvidedParams != null && i >= Signature.GetProvidedPositionalArgumentCount()) { exprArgs[i] = ValidateNotDuplicate(exprArgs[i], _func.Value.ArgNames[i], i); } continue; } if (i < noDefaults) { exprArgs[i] = ExtractNonDefaultValue(_func.Value.ArgNames[i]); if (exprArgs[i] == null) { // can't get a value, this is an invalid call. return false; } } else { exprArgs[i] = ExtractDefaultValue(i, i - noDefaults); } } if (!TryFinishList(exprArgs, paramsArgs) || !TryFinishDictionary(exprArgs, namedArgs)) return false; // add check for extra parameters. AddCheckForNoExtraParameters(exprArgs); return true; } /// <summary> /// Creates the argument for the list expansion parameter. /// </summary> private bool TryFinishList(Expression[] exprArgs, List<Expression> paramsArgs) { if (_func.Value.ExpandListPosition != -1) { if (_userProvidedParams != null) { if (_params == null && paramsArgs == null) { // we didn't extract any params, we can re-use a Tuple or // make a single copy. exprArgs[_func.Value.ExpandListPosition] = Ast.Call( typeof(PythonOps).GetMethod("GetOrCopyParamsTuple"), GetFunctionParam(), AstUtils.Convert(_userProvidedParams, typeof(object)) ); } else { // user provided a sequence to be expanded, and we may have used it, // or we have extra args. EnsureParams(); exprArgs[_func.Value.ExpandListPosition] = Ast.Call( typeof(PythonOps).GetMethod("MakeTupleFromSequence"), AstUtils.Convert(_params, typeof(object)) ); if (paramsArgs != null) { MakeParamsAddition(paramsArgs); } } } else { exprArgs[_func.Value.ExpandListPosition] = MakeParamsTuple(paramsArgs); } } else if (paramsArgs != null) { // extra position args which are unused and no where to put them. return false; } return true; } /// <summary> /// Adds extra positional arguments to the start of the expanded list. /// </summary> private void MakeParamsAddition(List<Expression> paramsArgs) { _extractedParams = true; List<Expression> args = new List<Expression>(paramsArgs.Count + 1); args.Add(_params); args.AddRange(paramsArgs); EnsureInit(); _init.Add( AstUtils.ComplexCallHelper( typeof(PythonOps).GetMethod("AddParamsArguments"), args.ToArray() ) ); } /// <summary> /// Creates the argument for the dictionary expansion parameter. /// </summary> private bool TryFinishDictionary(Expression[] exprArgs, Dictionary<string, Expression> namedArgs) { if (_func.Value.ExpandDictPosition != -1) { if (_dict != null) { // used provided a dictionary to be expanded exprArgs[_func.Value.ExpandDictPosition] = _dict; if (namedArgs != null) { foreach (KeyValuePair<string, Expression> kvp in namedArgs) { MakeDictionaryAddition(kvp); } } } else { exprArgs[_func.Value.ExpandDictPosition] = MakeDictionary(namedArgs); } } else if (namedArgs != null) { // extra named args which are unused and no where to put them. return false; } return true; } /// <summary> /// Adds an unbound keyword argument into the dictionary. /// </summary> /// <param name="kvp"></param> private void MakeDictionaryAddition(KeyValuePair<string, Expression> kvp) { _init.Add( Ast.Call( typeof(PythonOps).GetMethod("AddDictionaryArgument"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Constant(kvp.Key), AstUtils.Convert(kvp.Value, typeof(object)), AstUtils.Convert(_dict, typeof(PythonDictionary)) ) ); } /// <summary> /// Adds a check to the last parameter (so it's evaluated after we've extracted /// all the parameters) to ensure that we don't have any extra params or kw-params /// when we don't have a params array or params dict to expand them into. /// </summary> private void AddCheckForNoExtraParameters(Expression[] exprArgs) { List<Expression> tests = new List<Expression>(3); // test we've used all of the extra parameters if (_func.Value.ExpandListPosition == -1) { if (_params != null) { // we used some params, they should have gone down to zero... tests.Add( Ast.Call( typeof(PythonOps).GetMethod("CheckParamsZero"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), _params ) ); } else if (_userProvidedParams != null) { // the user provided params, we didn't need any, and they should be zero tests.Add( Ast.Call( typeof(PythonOps).GetMethod("CheckUserParamsZero"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Convert(_userProvidedParams, typeof(object)) ) ); } } // test that we've used all the extra named arguments if (_func.Value.ExpandDictPosition == -1 && _dict != null) { tests.Add( Ast.Call( typeof(PythonOps).GetMethod("CheckDictionaryZero"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Convert(_dict, typeof(IDictionary)) ) ); } if (tests.Count != 0) { if (exprArgs.Length != 0) { // if we have arguments run the tests after the last arg is evaluated. Expression last = exprArgs[exprArgs.Length - 1]; ParameterExpression temp; _temps.Add(temp = Ast.Variable(last.Type, "$temp")); tests.Insert(0, Ast.Assign(temp, last)); tests.Add(temp); exprArgs[exprArgs.Length - 1] = Ast.Block(tests.ToArray()); } else { // otherwise run them right before the method call _paramlessCheck = Ast.Block(tests.ToArray()); } } } /// <summary> /// Helper function to validate that a named arg isn't duplicated with by /// a params list or the dictionary (or both). /// </summary> private Expression ValidateNotDuplicate(Expression value, string name, int position) { EnsureParams(); return Ast.Block( Ast.Call( typeof(PythonOps).GetMethod("VerifyUnduplicatedByPosition"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function AstUtils.Constant(name, typeof(string)), // name AstUtils.Constant(position), // position _paramsLen // params list length ), value ); } /// <summary> /// Helper function to get a value (which has no default) from either the /// params list or the dictionary (or both). /// </summary> private Expression ExtractNonDefaultValue(string name) { if (_userProvidedParams != null) { // expanded params if (_dict != null) { // expanded params & dict return ExtractFromListOrDictionary(name); } else { return ExtractNextParamsArg(); } } else if (_dict != null) { // expanded dict return ExtractDictionaryArgument(name); } // missing argument, no default, no expanded params or dict. return null; } /// <summary> /// Helper function to get the specified variable from the dictionary. /// </summary> private Expression ExtractDictionaryArgument(string name) { _needCodeTest = true; return Ast.Call( typeof(PythonOps).GetMethod("ExtractDictionaryArgument"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function AstUtils.Constant(name, typeof(string)), // name AstUtils.Constant(Signature.ArgumentCount), // arg count AstUtils.Convert(_dict, typeof(PythonDictionary)) // dictionary ); } /// <summary> /// Helper function to extract the variable from defaults, or to call a helper /// to check params / kw-dict / defaults to see which one contains the actual value. /// </summary> private Expression ExtractDefaultValue(int index, int dfltIndex) { if (_dict == null && _userProvidedParams == null) { // we can pull the default directly return Ast.Call( typeof(PythonOps).GetMethod("FunctionGetDefaultValue"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Constant(dfltIndex) ); } else { // we might have a conflict, check the default last. if (_userProvidedParams != null) { EnsureParams(); } _extractedDefault = true; return Ast.Call( typeof(PythonOps).GetMethod("GetFunctionParameterValue"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Constant(dfltIndex), AstUtils.Constant(_func.Value.ArgNames[index], typeof(string)), VariableOrNull(_params, typeof(List)), VariableOrNull(_dict, typeof(PythonDictionary)) ); } } /// <summary> /// Helper function to extract from the params list or dictionary depending upon /// which one has an available value. /// </summary> private Expression ExtractFromListOrDictionary(string name) { EnsureParams(); _needCodeTest = true; return Ast.Call( typeof(PythonOps).GetMethod("ExtractAnyArgument"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function AstUtils.Constant(name, typeof(string)), // name _paramsLen, // arg count _params, // params list AstUtils.Convert(_dict, typeof(IDictionary)) // dictionary ); } private void EnsureParams() { if (!_extractedParams) { Debug.Assert(_userProvidedParams != null); MakeParamsCopy(_userProvidedParams); _extractedParams = true; } } /// <summary> /// Helper function to extract the next argument from the params list. /// </summary> private Expression ExtractNextParamsArg() { if (!_extractedParams) { MakeParamsCopy(_userProvidedParams); _extractedParams = true; } return Ast.Call( typeof(PythonOps).GetMethod("ExtractParamsArgument"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function AstUtils.Constant(Signature.ArgumentCount), // arg count _params // list ); } private static Expression VariableOrNull(ParameterExpression var, Type type) { if (var != null) { return AstUtils.Convert( var, type ); } return AstUtils.Constant(null, type); } /// <summary> /// Fixes up the argument list for the appropriate target delegate type. /// </summary> private Expression/*!*/[]/*!*/ GetArgumentsForTargetType(Expression[] exprArgs) { Type target = _func.Value.func_code.Target.GetType(); if (target == typeof(Func<PythonFunction, object[], object>)) { exprArgs = new Expression[] { AstUtils.NewArrayHelper(typeof(object), exprArgs) }; } return exprArgs; } /// <summary> /// Helper function to get the function argument strongly typed. /// </summary> private UnaryExpression/*!*/ GetFunctionParam() { return Ast.Convert(_func.Expression, typeof(PythonFunction)); } /// <summary> /// Called when the user is expanding a dictionary - we copy the user /// dictionary and verify that it contains only valid string names. /// </summary> private DynamicMetaObject/*!*/ MakeDictionaryCopy(DynamicMetaObject/*!*/ userDict) { Debug.Assert(_dict == null); userDict = userDict.Restrict(userDict.GetLimitType()); _temps.Add(_dict = Ast.Variable(typeof(PythonDictionary), "$dict")); EnsureInit(); string methodName; if (typeof(PythonDictionary).IsAssignableFrom(userDict.GetLimitType())) { methodName = "CopyAndVerifyPythonDictionary"; } else if (typeof(IDictionary).IsAssignableFrom(userDict.GetLimitType())) { methodName = "CopyAndVerifyDictionary"; } else { methodName = "CopyAndVerifyUserMapping"; } _init.Add( Ast.Assign( _dict, Ast.Call( typeof(PythonOps).GetMethod(methodName), GetFunctionParam(), AstUtils.Convert(userDict.Expression, userDict.GetLimitType()) ) ) ); return userDict; } /// <summary> /// Called when the user is expanding a params argument /// </summary> private void MakeParamsCopy(Expression/*!*/ userList) { Debug.Assert(_params == null); _temps.Add(_params = Ast.Variable(typeof(List), "$list")); _temps.Add(_paramsLen = Ast.Variable(typeof(int), "$paramsLen")); EnsureInit(); _init.Add( Ast.Assign( _params, Ast.Call( typeof(PythonOps).GetMethod("CopyAndVerifyParamsList"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Convert(userList, typeof(object)) ) ) ); _init.Add( Ast.Assign(_paramsLen, Ast.Add( Ast.Call(_params, typeof(List).GetMethod("__len__")), AstUtils.Constant(Signature.GetProvidedPositionalArgumentCount()) ) ) ); } /// <summary> /// Called when the user hasn't supplied a dictionary to be expanded but the /// function takes a dictionary to be expanded. /// </summary> private Expression MakeDictionary(Dictionary<string, Expression/*!*/> namedArgs) { Debug.Assert(_dict == null); _temps.Add(_dict = Ast.Variable(typeof(PythonDictionary), "$dict")); Expression dictCreator; if (namedArgs != null) { Debug.Assert(namedArgs.Count > 0); Expression[] items = new Expression[namedArgs.Count * 2]; int itemIndex = 0; foreach (KeyValuePair<string, Expression> kvp in namedArgs) { items[itemIndex++] = AstUtils.Convert(kvp.Value, typeof(object)); items[itemIndex++] = AstUtils.Constant(kvp.Key, typeof(object)); } dictCreator = Ast.Assign( _dict, Ast.Call( typeof(PythonOps).GetMethod("MakeHomogeneousDictFromItems"), Ast.NewArrayInit(typeof(object), items) ) ); } else { dictCreator = Ast.Assign( _dict, Ast.Call( typeof(PythonOps).GetMethod("MakeDict"), AstUtils.Constant(0) ) ); } return dictCreator; } /// <summary> /// Helper function to create the expression for creating the actual tuple passed through. /// </summary> private static Expression/*!*/ MakeParamsTuple(List<Expression> extraArgs) { if (extraArgs != null) { return AstUtils.ComplexCallHelper( typeof(PythonOps).GetMethod("MakeTuple"), extraArgs.ToArray() ); } return Ast.Call( typeof(PythonOps).GetMethod("MakeTuple"), Ast.NewArrayInit(typeof(object[])) ); } /// <summary> /// Creates the code to invoke the target delegate function w/ the specified arguments. /// </summary> private Expression/*!*/ MakeFunctionInvoke(Expression[] invokeArgs) { Type targetType = _func.Value.func_code.Target.GetType(); MethodInfo method = targetType.GetMethod("Invoke"); // If calling generator, create the instance of PythonGenerator first // and add it into the list of arguments invokeArgs = ArrayUtils.Insert(GetFunctionParam(), invokeArgs); Expression invoke = AstUtils.SimpleCallHelper( Ast.Convert( Ast.Call( _call.SupportsLightThrow() ? typeof(PythonOps).GetMethod("FunctionGetLightThrowTarget") : typeof(PythonOps).GetMethod("FunctionGetTarget"), GetFunctionParam() ), targetType ), method, invokeArgs ); if (_paramlessCheck != null) { invoke = Expression.Block(_paramlessCheck, invoke); } return invoke; } /// <summary> /// Appends the initialization code for the call to the function if any exists. /// </summary> private Expression/*!*/ AddInitialization(Expression body) { if (_init == null) return body; List<Expression> res = new List<Expression>(_init); res.Add(body); return Ast.Block(res); } private void MakeUnexpectedKeywordError(Dictionary<string, Expression> namedArgs) { string name = null; foreach (string id in namedArgs.Keys) { name = id; break; } _error = _call.Throw( Ast.Call( typeof(PythonOps).GetMethod("UnexpectedKeywordArgumentError"), AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), AstUtils.Constant(name, typeof(string)) ), typeof(PythonOps) ); } private void EnsureInit() { if (_init == null) _init = new List<Expression>(); } } #endregion #region Operations private static DynamicMetaObject/*!*/ MakeCallSignatureRule(DynamicMetaObject self) { return new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("GetFunctionSignature"), AstUtils.Convert( self.Expression, typeof(PythonFunction) ) ), BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(PythonFunction)) ); } private static DynamicMetaObject MakeIsCallableRule(DynamicMetaObject/*!*/ self) { return new DynamicMetaObject( AstUtils.Constant(true), BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(PythonFunction)) ); } #endregion #region Helpers public new PythonFunction/*!*/ Value { get { return (PythonFunction)base.Value; } } #endregion #region IPythonOperable Members DynamicMetaObject IPythonOperable.BindOperation(PythonOperationBinder action, DynamicMetaObject[] args) { switch (action.Operation) { case PythonOperationKind.CallSignatures: return MakeCallSignatureRule(this); case PythonOperationKind.IsCallable: return MakeIsCallableRule(this); } return null; } #endregion #region IInvokableInferable Members InferenceResult IInferableInvokable.GetInferredType(Type delegateType, Type parameterType) { if (!delegateType.IsSubclassOf(typeof(Delegate))) { throw new InvalidOperationException(); } MethodInfo invoke = delegateType.GetMethod("Invoke"); ParameterInfo[] pis = invoke.GetParameters(); if (pis.Length == Value.NormalArgumentCount) { // our signatures are compatible return new InferenceResult( typeof(object), Restrictions.Merge( BindingRestrictions.GetTypeRestriction( Expression, typeof(PythonFunction) ).Merge( BindingRestrictions.GetExpressionRestriction( Expression.Equal( Expression.Call( typeof(PythonOps).GetMethod("FunctionGetCompatibility"), Expression.Convert(Expression, typeof(PythonFunction)) ), Expression.Constant(Value.FunctionCompatibility) ) ) ) ) ); } return null; } #endregion #region IConvertibleMetaObject Members bool IConvertibleMetaObject.CanConvertTo(Type/*!*/ type, bool @explicit) { return type.IsSubclassOf(typeof(Delegate)); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; //--- using System.IO; using System.Text.RegularExpressions; namespace FSWatch { public enum DEFAULT:int { MAX_FOLDER_HISTORY = 32 } public partial class MainForm: Form { private Regex regexProductVersion = new Regex(@"(\d+\.\d+.\d+).*", RegexOptions.Compiled); private string m_sAppTitle = ""; public MainForm() { InitializeComponent(); m_sAppTitle = Application.ProductName + " v" + regexProductVersion.Replace(Application.ProductVersion, "$1"); } private void MainForm_Load(object sender, EventArgs e) { UpdateFormTitle(""); Page_AddNew(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref4/html/M_System_Configuration_ApplicationSettingsBase_Save.htm global::FSWatch.Properties.Settings.Default.Save(); } #region UI Events private void MainForm_KeyDown(object sender, KeyEventArgs e) { // My favorite feature implementation if (e.KeyCode == Keys.F11) { e.Handled = true; if (this.Opacity < 0.11d) { return; } this.Opacity -= 0.1d; } else if (e.KeyCode == Keys.F12) { e.Handled = true; this.Opacity += 0.1d; } // exit else if (e.KeyCode == Keys.Escape) { e.Handled = true; #if DEBUG Application.Exit(); #endif } // about else if (e.KeyCode == Keys.F1) { e.Handled = true; string link = "http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx"; DialogResult dlgResult = MessageBox.Show( "More information available online at: \""+ link +"\"\nDo you want to Proceed?" , Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dlgResult == DialogResult.Yes) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = link; proc.StartInfo.UseShellExecute = true; proc.Start(); } } else if (e.KeyCode == Keys.F5) { TabPage tab = tabSet.SelectedTab; if (null != tab && null != tab.Tag) { UC_Page page = tab.Tag as UC_Page; if (null != page) { page.btnLaunchSwitch_Click(sender, e); } } e.Handled = true; } else if (e.Control && e.KeyCode == Keys.T) { e.Handled = true; Page_AddNew(); } else if (e.Control && e.KeyCode == Keys.W) { e.Handled = true; Page_Remove(tabSet.SelectedTab); } } private void MainForm_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Page_AddNew(); } } void tabSet_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Middle) { TabPage tab = GetTabPageAtLocation(tabSet, e.Location); if (null != tab) { Page_Remove(tab); } } } #endregion UI Events #region UI Compound private TabPage GetTabPageAtLocation(TabControl _tabControl, Point _point) { for (int c = 0; c < _tabControl.TabPages.Count; c++) { if (_tabControl.GetTabRect(c).Contains(_point)) { return _tabControl.TabPages[c]; } } return null; } public void UpdateFormTitle(string _sTargetFolder) { this.Text = _sTargetFolder +" - "+ m_sAppTitle; } private void Page_AddNew() { TabPage tab = new TabPage("(*)"); UC_Page page = new UC_Page(); page.OnFolderChanged += new UC_Page.OnFolderChangedDelegate(page_OnFolderChanged); page.Dock = DockStyle.Fill; tab.Controls.Add(page); tab.Tag = page; // associate `tab.Tag` with hosted Page class, note that `page.Parent == tab` tabSet.Controls.Add(tab); tabSet.SelectedTab = tab; UpdateFormTitle(tab.Text); } void tab_MouseHover(object sender, EventArgs e) { DEBUG.TRACE("- MouseHover - {{{0}}}", sender.ToString()); } void page_OnFolderChanged(TabPage _tabPage, string _sCurrentFolder) { _tabPage.Text = _sCurrentFolder; this.UpdateFormTitle(_sCurrentFolder); } private void Page_Selected(object sender, TabControlEventArgs e) { this.UpdateFormTitle(e.TabPage.Text); } private void Page_Remove(TabPage _tab) { if (tabSet.TabPages.Count > 1) { UC_Page page = _tab.Tag as UC_Page; page.Stop(); // page.Finallyze(); page = null; int iCurPos = tabSet.TabPages.IndexOf(_tab); int iLastPos = tabSet.TabPages.Count - 1; if (iCurPos == iLastPos) { tabSet.SelectTab(iCurPos - 1); tabSet.TabPages.RemoveAt(iCurPos); } else if (iCurPos < iLastPos) { tabSet.TabPages.RemoveAt(iCurPos); tabSet.SelectTab(iCurPos); } UpdateFormTitle(tabSet.SelectedTab.Text); } } #endregion UI Compound }; }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using MyWebApi.Areas.HelpPage.ModelDescriptions; using MyWebApi.Areas.HelpPage.Models; namespace MyWebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) 2012 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.MiniJSON { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { // interpret all numbers as if they are english US formatted numbers private static NumberFormatInfo numberFormat = (new CultureInfo("en-US")).NumberFormat; /// <summary> /// Parses the string json into a value. /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false.</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string. /// </summary> /// <param name="obj">A Dictionary&lt;string, object&gt; / List&lt;object&gt;.</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable.</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } private sealed class Parser : IDisposable { private const string WhiteSpace = " \t\n\r"; private const string WordBreak = " \t\n\r{}[],:\""; private StringReader json; private Parser(string jsonString) { this.json = new StringReader(jsonString); } private enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL } private char PeekChar { get { return Convert.ToChar(this.json.Peek()); } } private char NextChar { get { return Convert.ToChar(this.json.Read()); } } private string NextWord { get { StringBuilder word = new StringBuilder(); while (WordBreak.IndexOf(this.PeekChar) == -1) { word.Append(this.NextChar); if (this.json.Peek() == -1) { break; } } return word.ToString(); } } private TOKEN NextToken { get { this.EatWhitespace(); if (this.json.Peek() == -1) { return TOKEN.NONE; } char c = this.PeekChar; switch (c) { case '{': return TOKEN.CURLY_OPEN; case '}': this.json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': this.json.Read(); return TOKEN.SQUARED_CLOSE; case ',': this.json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } string word = this.NextWord; switch (word) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { this.json.Dispose(); this.json = null; } private Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace this.json.Read(); // { while (true) { switch (this.NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = this.ParseString(); if (name == null) { return null; } // : if (this.NextToken != TOKEN.COLON) { return null; } // ditch the colon this.json.Read(); // value table[name] = this.ParseValue(); break; } } } private List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket this.json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = this.NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = this.ParseByToken(nextToken); array.Add(value); break; } } return array; } private object ParseValue() { TOKEN nextToken = this.NextToken; return this.ParseByToken(nextToken); } private object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return this.ParseString(); case TOKEN.NUMBER: return this.ParseNumber(); case TOKEN.CURLY_OPEN: return this.ParseObject(); case TOKEN.SQUARED_OPEN: return this.ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } private string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote this.json.Read(); bool parsing = true; while (parsing) { if (this.json.Peek() == -1) { parsing = false; break; } c = this.NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (this.json.Peek() == -1) { parsing = false; break; } c = this.NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new StringBuilder(); for (int i = 0; i < 4; i++) { hex.Append(this.NextChar); } s.Append((char)Convert.ToInt32(hex.ToString(), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } private object ParseNumber() { string number = this.NextWord; if (number.IndexOf('.') == -1) { return long.Parse(number, numberFormat); } return double.Parse(number, numberFormat); } private void EatWhitespace() { while (WhiteSpace.IndexOf(this.PeekChar) != -1) { this.json.Read(); if (this.json.Peek() == -1) { break; } } } } private sealed class Serializer { private StringBuilder builder; private Serializer() { this.builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } private void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { this.builder.Append("null"); } else if ((asStr = value as string) != null) { this.SerializeString(asStr); } else if (value is bool) { this.builder.Append(value.ToString().ToLower()); } else if ((asList = value as IList) != null) { this.SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { this.SerializeObject(asDict); } else if (value is char) { this.SerializeString(value.ToString()); } else { this.SerializeOther(value); } } private void SerializeObject(IDictionary obj) { bool first = true; this.builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { this.builder.Append(','); } this.SerializeString(e.ToString()); this.builder.Append(':'); this.SerializeValue(obj[e]); first = false; } this.builder.Append('}'); } private void SerializeArray(IList array) { this.builder.Append('['); bool first = true; foreach (object obj in array) { if (!first) { this.builder.Append(','); } this.SerializeValue(obj); first = false; } this.builder.Append(']'); } private void SerializeString(string str) { this.builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': this.builder.Append("\\\""); break; case '\\': this.builder.Append("\\\\"); break; case '\b': this.builder.Append("\\b"); break; case '\f': this.builder.Append("\\f"); break; case '\n': this.builder.Append("\\n"); break; case '\r': this.builder.Append("\\r"); break; case '\t': this.builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { this.builder.Append(c); } else { this.builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } break; } } this.builder.Append('\"'); } private void SerializeOther(object value) { if (value is float || value is int || value is uint || value is long || value is double || value is sbyte || value is byte || value is short || value is ushort || value is ulong || value is decimal) { this.builder.Append(value.ToString()); } else { this.SerializeString(value.ToString()); } } } } }
using System; using System.Threading; using System.Threading.Tasks; using Content.Server.CPUJob.JobQueues; using Content.Server.CPUJob.JobQueues.Queues; using NUnit.Framework; using Robust.Shared.Timing; using Robust.UnitTesting; namespace Content.Tests.Server.Jobs { [TestFixture] [TestOf(typeof(Job<>))] [TestOf(typeof(JobQueue))] public sealed class JobQueueTest : RobustUnitTest { /// <summary> /// Test a job that immediately exits with a value. /// </summary> [Test] public void TestImmediateJob() { // Pass debug stopwatch so time doesn't advance. var sw = new DebugStopwatch(); var queue = new JobQueue(sw); var job = new ImmediateJob(); queue.EnqueueJob(job); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Finished)); Assert.That(job.Result, Is.EqualTo("honk!")); } [Test] public void TestLongJob() { var swA = new DebugStopwatch(); var swB = new DebugStopwatch(); var queue = new LongJobQueue(swB); var job = new LongJob(swA, swB); queue.EnqueueJob(job); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Paused)); Assert.That((float)job.DebugTime, new ApproxEqualityConstraint(1f)); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Paused)); Assert.That((float)job.DebugTime, new ApproxEqualityConstraint(2f)); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Finished)); Assert.That(job.Result, Is.EqualTo("foo!")); Assert.That((float)job.DebugTime, new ApproxEqualityConstraint(2.4f)); } [Test] public void TestLongJobCancel() { var swA = new DebugStopwatch(); var swB = new DebugStopwatch(); var queue = new LongJobQueue(swB); var cts = new CancellationTokenSource(); var job = new LongJob(swA, swB, cts.Token); queue.EnqueueJob(job); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Paused)); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Paused)); cts.Cancel(); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Finished)); Assert.That((float)job.DebugTime, new ApproxEqualityConstraint(2.0f)); Assert.That(job.Result, Is.Null); } [Test] public void TestWaitingJob() { var sw = new DebugStopwatch(); var queue = new LongJobQueue(sw); var tcs = new TaskCompletionSource<object>(); var job = new WaitingJob(tcs.Task); queue.EnqueueJob(job); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Waiting)); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Waiting)); tcs.SetResult(1); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Finished)); Assert.That(job.Result, Is.EqualTo("oof!")); } [Test] public void TestWaitingJobCancel() { var sw = new DebugStopwatch(); var queue = new LongJobQueue(sw); var tcs = new TaskCompletionSource<object>(); var job = new WaitingJob(tcs.Task); queue.EnqueueJob(job); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Waiting)); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Waiting)); tcs.SetCanceled(); queue.Process(); Assert.That(job.Status, Is.EqualTo(JobStatus.Finished)); Assert.That(job.Result, Is.Null); } private sealed class DebugStopwatch : IStopwatch { public TimeSpan Elapsed { get; set; } public void Restart() { Elapsed = TimeSpan.Zero; } public void Start() { Elapsed = TimeSpan.Zero; } } private sealed class ImmediateJob : Job<string> { public ImmediateJob() : base(0) { } protected override Task<string> Process() { return Task.FromResult("honk!"); } } private sealed class LongJob : Job<string> { private readonly DebugStopwatch _stopwatch; private readonly DebugStopwatch _stopwatchB; public LongJob(DebugStopwatch stopwatchA, DebugStopwatch stopwatchB, CancellationToken cancel = default) : base(0.95, stopwatchA, cancel) { _stopwatch = stopwatchA; _stopwatchB = stopwatchB; } protected override async Task<string> Process() { for (var i = 0; i < 12; i++) { // Increment time by 0.2 seconds. IncrementTime(); await SuspendIfOutOfTime(); } return "foo!"; } private void IncrementTime() { var diff = TimeSpan.FromSeconds(0.2); _stopwatch.Elapsed += diff; _stopwatchB.Elapsed += diff; } } private sealed class LongJobQueue : JobQueue { public LongJobQueue(IStopwatch swB) : base(swB) { } public override double MaxTime => 0.9; } private sealed class WaitingJob : Job<string> { private readonly Task _t; public WaitingJob(Task t) : base(0) { _t = t; } protected override async Task<string> Process() { await WaitAsyncTask(_t); return "oof!"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Routing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc { // Tests Controller for the unit testability with which users can simply instantiate controllers for unit tests public class ControllerUnitTestabilityTests { [Theory] [MemberData(nameof(TestabilityViewTestData))] public void ControllerView_InvokedInUnitTests(object model, string viewName) { // Arrange var controller = new TestabilityController(); // Act var result = controller.View_Action(viewName, model); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewResult>(result); Assert.Equal(viewName, viewResult.ViewName); Assert.NotNull(viewResult.ViewData); Assert.Same(model, viewResult.Model); Assert.Same(model, viewResult.ViewData.Model); Assert.Same(controller.ViewData, viewResult.ViewData); Assert.Same(controller.TempData, viewResult.TempData); } [Theory] [MemberData(nameof(TestabilityViewTestData))] public void ControllerPartialView_InvokedInUnitTests(object model, string viewName) { // Arrange var controller = new TestabilityController(); // Act var result = controller.PartialView_Action(viewName, model); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<PartialViewResult>(result); Assert.Equal(viewName, viewResult.ViewName); Assert.NotNull(viewResult.ViewData); Assert.Same(model, viewResult.Model); Assert.Same(model, viewResult.ViewData.Model); Assert.Same(controller.ViewData, viewResult.ViewData); Assert.Same(controller.TempData, viewResult.TempData); } [Fact] public void ControllerContent_InvokedInUnitTests() { // Arrange var content = "Content_1"; var contentType = "text/asp"; var encoding = Encoding.ASCII; var controller = new TestabilityController(); // Act var result = controller.Content_Action(content, contentType, encoding); // Assert Assert.NotNull(result); var contentResult = Assert.IsType<ContentResult>(result); Assert.Equal(content, contentResult.Content); Assert.Equal("text/asp; charset=us-ascii", contentResult.ContentType.ToString()); Assert.Equal(encoding, MediaType.GetEncoding(contentResult.ContentType)); } [Theory] [InlineData("/Created_1", "<html>CreatedBody</html>")] [InlineData("/Created_2", null)] public void ControllerCreated_InvokedInUnitTests(string uri, string content) { // Arrange var controller = new TestabilityController(); // Act var result = controller.Created_Action(uri, content); // Assert Assert.NotNull(result); var createdResult = Assert.IsType<CreatedResult>(result); Assert.Equal(uri, createdResult.Location); Assert.Equal(content, createdResult.Value); Assert.Equal(StatusCodes.Status201Created, createdResult.StatusCode); } [Theory] [InlineData("/Accepted_1", "<html>AcceptedBody</html>")] [InlineData("/Accepted_2", null)] public void ControllerAccepted_InvokedInUnitTests(string uri, string content) { // Arrange var controller = new TestabilityController(); // Act var result = controller.Accepted_Action(uri, content); // Assert Assert.NotNull(result); var acceptedResult = Assert.IsType<AcceptedResult>(result); Assert.Equal(uri, acceptedResult.Location); Assert.Equal(content, acceptedResult.Value); Assert.Equal(StatusCodes.Status202Accepted, acceptedResult.StatusCode); } [Fact] public void ControllerFileContent_InvokedInUnitTests() { // Arrange var content = "<html>CreatedBody</html>"; var contentType = "text/html"; var fileName = "Created.html"; var controller = new TestabilityController(); // Act var result = controller.FileContent_Action(content, contentType, fileName); // Assert Assert.NotNull(result); var fileContentResult = Assert.IsType<FileContentResult>(result); Assert.Equal(contentType, fileContentResult.ContentType.ToString()); Assert.Equal(fileName ?? string.Empty, fileContentResult.FileDownloadName); if (content == null) { Assert.Null(fileContentResult.FileContents); } else { Assert.Equal(content, Encoding.UTF8.GetString(fileContentResult.FileContents)); } } [Fact] public void ControllerFileStream_InvokedInUnitTests() { // Arrange var content = "<html>CreatedBody</html>"; var contentType = "text/html"; var fileName = "Created.html"; var mockHttpContext = new Mock<HttpContext>(); mockHttpContext.Setup(x => x.Response.RegisterForDispose(It.IsAny<IDisposable>())); var controller = new TestabilityController(); controller.ControllerContext.HttpContext = mockHttpContext.Object; // Act var result = controller.FileStream_Action(content, contentType, fileName); // Assert Assert.NotNull(result); var fileStreamResult = Assert.IsType<FileStreamResult>(result); Assert.Equal(contentType, fileStreamResult.ContentType.ToString()); Assert.Equal(fileName ?? string.Empty, fileStreamResult.FileDownloadName); if (content == null) { Assert.Null(fileStreamResult.FileStream); } else { using (var stream = new StreamReader(fileStreamResult.FileStream, Encoding.UTF8)) { Assert.Equal(content, stream.ReadToEnd()); } } } [Fact] public void ControllerJson_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var model = new MyModel() { Property1 = "Property_1" }; // Act var result = controller.Json_Action(model); // Assert Assert.NotNull(result); var jsonResult = Assert.IsType<JsonResult>(result); Assert.NotNull(jsonResult.Value); Assert.Same(model, jsonResult.Value); Assert.IsType<MyModel>(jsonResult.Value); // Arrange controller = new TestabilityController(); // Act result = controller.Json_Action(null); // Assert Assert.NotNull(result); jsonResult = Assert.IsType<JsonResult>(result); Assert.Null(jsonResult.Value); } [Fact] public void ControllerJsonWithSerializerSettings_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var model = new MyModel() { Property1 = "Property_1" }; var serializerSettings = new object(); // Act var result = controller.JsonWithSerializerSettings_Action(model, serializerSettings); // Assert Assert.NotNull(result); var jsonResult = Assert.IsType<JsonResult>(result); Assert.NotNull(jsonResult.Value); Assert.Same(model, jsonResult.Value); Assert.IsType<MyModel>(jsonResult.Value); } [Fact] public void ControllerHttpNotFound_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); // Act var result = controller.HttpNotFound_Action(); // Assert Assert.NotNull(result); var httpNotFoundResult = Assert.IsType<NotFoundResult>(result); Assert.Equal(StatusCodes.Status404NotFound, httpNotFoundResult.StatusCode); } [Fact] public void ControllerHttpNotFoundObject_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); // Act var result = controller.HttpNotFoundObject_Action("Test Content"); // Assert Assert.NotNull(result); var httpNotFoundObjectResult = Assert.IsType<NotFoundObjectResult>(result); Assert.Equal(StatusCodes.Status404NotFound, httpNotFoundObjectResult.StatusCode); Assert.Equal("Test Content", httpNotFoundObjectResult.Value); } [Fact] public void ControllerHttpBadRequest_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); // Act var result = controller.HttpBadRequest_Action(); // Assert Assert.NotNull(result); var httpBadRequest = Assert.IsType<BadRequestResult>(result); Assert.Equal(StatusCodes.Status400BadRequest, httpBadRequest.StatusCode); } [Fact] public void ControllerHttpBadRequestObject_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var error = new { Error = "Error Message" }; // Act var result = controller.HttpBadRequestObject_Action(error); // Assert Assert.NotNull(result); var httpBadRequest = Assert.IsType<BadRequestObjectResult>(result); Assert.Equal(StatusCodes.Status400BadRequest, httpBadRequest.StatusCode); Assert.Same(error, httpBadRequest.Value); // Arrange controller = new TestabilityController(); // Act result = controller.HttpBadRequestObject_Action(null); // Assert Assert.NotNull(result); httpBadRequest = Assert.IsType<BadRequestObjectResult>(result); Assert.Equal(StatusCodes.Status400BadRequest, httpBadRequest.StatusCode); Assert.Null(httpBadRequest.Value); } [Fact] public void ControllerCreatedAtRoute_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var routeName = "RouteName_1"; var routeValues = new Dictionary<string, object>() { { "route", "sample" } }; var value = new { Value = "Value_1" }; // Act var result = controller.CreatedAtRoute_Action(routeName, routeValues, value); // Assert Assert.NotNull(result); var createdAtRouteResult = Assert.IsType<CreatedAtRouteResult>(result); Assert.Equal(routeName, createdAtRouteResult.RouteName); Assert.Single(createdAtRouteResult.RouteValues); Assert.Equal("sample", createdAtRouteResult.RouteValues["route"]); Assert.Same(value, createdAtRouteResult.Value); // Arrange controller = new TestabilityController(); // Act result = controller.CreatedAtRoute_Action(null, null, null); // Assert Assert.NotNull(result); createdAtRouteResult = Assert.IsType<CreatedAtRouteResult>(result); Assert.Null(createdAtRouteResult.RouteName); Assert.Null(createdAtRouteResult.RouteValues); Assert.Null(createdAtRouteResult.Value); } [Fact] public void ControllerAcceptedAtRoute_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var routeName = "RouteName_1"; var routeValues = new Dictionary<string, object>() { { "route", "sample" } }; var value = new { Value = "Value_1" }; // Act var result = controller.AcceptedAtRoute_Action(routeName, routeValues, value); // Assert Assert.NotNull(result); var acceptedAtRouteResult = Assert.IsType<AcceptedAtRouteResult>(result); Assert.Equal(routeName, acceptedAtRouteResult.RouteName); Assert.Single(acceptedAtRouteResult.RouteValues); Assert.Equal("sample", acceptedAtRouteResult.RouteValues["route"]); Assert.Same(value, acceptedAtRouteResult.Value); // Arrange controller = new TestabilityController(); // Act result = controller.AcceptedAtRoute_Action(null, null, null); // Assert Assert.NotNull(result); acceptedAtRouteResult = Assert.IsType<AcceptedAtRouteResult>(result); Assert.Null(acceptedAtRouteResult.RouteName); Assert.Null(acceptedAtRouteResult.RouteValues); Assert.Null(acceptedAtRouteResult.Value); } [Fact] public void ControllerCreatedAtAction_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var actionName = "ActionName_1"; var controllerName = "ControllerName_1"; var routeValues = new Dictionary<string, object>() { { "route", "sample" } }; var value = new { Value = "Value_1" }; // Act var result = controller.CreatedAtAction_Action(actionName, controllerName, routeValues, value); // Assert Assert.NotNull(result); var createdAtActionResult = Assert.IsType<CreatedAtActionResult>(result); Assert.Equal(actionName, createdAtActionResult.ActionName); Assert.Equal(controllerName, createdAtActionResult.ControllerName); Assert.Single(createdAtActionResult.RouteValues); Assert.Equal("sample", createdAtActionResult.RouteValues["route"]); Assert.Same(value, createdAtActionResult.Value); // Arrange controller = new TestabilityController(); // Act result = controller.CreatedAtAction_Action(null, null, null, null); // Assert Assert.NotNull(result); createdAtActionResult = Assert.IsType<CreatedAtActionResult>(result); Assert.Null(createdAtActionResult.ActionName); Assert.Null(createdAtActionResult.ControllerName); Assert.Null(createdAtActionResult.Value); Assert.Null(createdAtActionResult.RouteValues); } [Fact] public void ControllerAcceptedAtAction_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var actionName = "ActionName_1"; var controllerName = "ControllerName_1"; var routeValues = new Dictionary<string, object>() { { "route", "sample" } }; var value = new { Value = "Value_1" }; // Act var result = controller.AcceptedAtAction_Action(actionName, controllerName, routeValues, value); // Assert Assert.NotNull(result); var acceptedAtActionResult = Assert.IsType<AcceptedAtActionResult>(result); Assert.Equal(actionName, acceptedAtActionResult.ActionName); Assert.Equal(controllerName, acceptedAtActionResult.ControllerName); Assert.Single(acceptedAtActionResult.RouteValues); Assert.Equal("sample", acceptedAtActionResult.RouteValues["route"]); Assert.Same(value, acceptedAtActionResult.Value); // Arrange controller = new TestabilityController(); // Act result = controller.AcceptedAtAction_Action(null, null, null, null); // Assert Assert.NotNull(result); acceptedAtActionResult = Assert.IsType<AcceptedAtActionResult>(result); Assert.Null(acceptedAtActionResult.ActionName); Assert.Null(acceptedAtActionResult.ControllerName); Assert.Null(acceptedAtActionResult.Value); Assert.Null(acceptedAtActionResult.RouteValues); } [Fact] public void ControllerRedirectToRoute_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var routeName = "RouteName_1"; var routeValues = new Dictionary<string, object>() { { "route", "sample" } }; // Act var result = controller.RedirectToRoute_Action(routeName, routeValues); // Assert Assert.NotNull(result); var redirectToRouteResult = Assert.IsType<RedirectToRouteResult>(result); Assert.Equal(routeName, redirectToRouteResult.RouteName); Assert.Single(redirectToRouteResult.RouteValues); Assert.Equal("sample", redirectToRouteResult.RouteValues["route"]); // Arrange controller = new TestabilityController(); // Act result = controller.RedirectToRoute_Action(null, null); // Assert Assert.NotNull(result); redirectToRouteResult = Assert.IsType<RedirectToRouteResult>(result); Assert.Null(redirectToRouteResult.RouteName); Assert.Null(redirectToRouteResult.RouteValues); } [Fact] public void ControllerRedirectToAction_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var controllerName = "ControllerName_1"; var actionName = "ActionName_1"; var routeValues = new Dictionary<string, object>() { { "route", "sample" } }; // Act var result = controller.RedirectToAction_Action(actionName, controllerName, routeValues); // Assert Assert.NotNull(result); var redirectToActionResult = Assert.IsType<RedirectToActionResult>(result); Assert.Equal(actionName, redirectToActionResult.ActionName); Assert.Equal(controllerName, redirectToActionResult.ControllerName); Assert.Single(redirectToActionResult.RouteValues); Assert.Equal("sample", redirectToActionResult.RouteValues["route"]); // Arrange controller = new TestabilityController(); // Act result = controller.RedirectToAction_Action(null, null, null); // Assert Assert.NotNull(result); redirectToActionResult = Assert.IsType<RedirectToActionResult>(result); Assert.Null(redirectToActionResult.ControllerName); Assert.Null(redirectToActionResult.ActionName); Assert.Null(redirectToActionResult.RouteValues); } [Fact] public void ControllerRedirect_InvokedInUnitTests() { // Arrange var controller = new TestabilityController(); var url = "http://contoso.com"; // Act var result = controller.Redirect_Action(url); // Assert Assert.NotNull(result); var redirectResult = Assert.IsType<RedirectResult>(result); Assert.Equal(url, redirectResult.Url); // Arrange controller = new TestabilityController(); // Act && Assert Assert.Throws<ArgumentException>(() => controller.Redirect_Action(null)); } [Fact] public void ControllerActionContext_ReturnsNotNull() { // Arrange && Act var controller = new TestabilityController(); // Assert Assert.NotNull(controller.ControllerContext); Assert.NotNull(controller.ControllerContext.ModelState); Assert.Null(controller.ControllerContext.ActionDescriptor); Assert.Null(controller.ControllerContext.HttpContext); Assert.Null(controller.ControllerContext.RouteData); } [Fact] public void ContextDefaultConstructor_CanBeUsedForControllerContext() { // Arrange var controllerContext = new ControllerContext(); var controller = new TestabilityController(); // Act controller.ControllerContext = controllerContext; // Assert Assert.Equal(controllerContext.HttpContext, controller.HttpContext); Assert.Equal(controllerContext.RouteData, controller.RouteData); Assert.Equal(controllerContext.ModelState, controller.ModelState); } [Fact] public void ControllerContextSetter_CanBeUsedWithControllerActionContext() { // Arrange var actionDescriptor = new ControllerActionDescriptor(); var httpContext = new DefaultHttpContext(); var routeData = new RouteData(); var controllerContext = new ControllerContext() { ActionDescriptor = actionDescriptor, HttpContext = httpContext, RouteData = routeData, }; var controller = new TestabilityController(); // Act controller.ControllerContext = controllerContext; // Assert Assert.Same(httpContext, controller.HttpContext); Assert.Same(routeData, controller.RouteData); Assert.Equal(controllerContext.ModelState, controller.ModelState); Assert.Same(actionDescriptor, controllerContext.ActionDescriptor); } [Fact] public void ContextModelState_ShouldBeSameAsViewDataAndControllerModelState() { // Arrange var controller1 = new TestabilityController(); var controller2 = new TestabilityController(); // Act controller2.ControllerContext = new ControllerContext(); // Assert Assert.Equal(controller1.ModelState, controller1.ControllerContext.ModelState); Assert.Equal(controller1.ModelState, controller1.ViewData.ModelState); Assert.Equal(controller1.ControllerContext.ModelState, controller2.ModelState); Assert.Equal(controller1.ControllerContext.ModelState, controller2.ControllerContext.ModelState); Assert.Equal(controller1.ControllerContext.ModelState, controller2.ViewData.ModelState); } [Fact] public void ViewComponent_WithName() { // Arrange var controller = new TestabilityController(); // Act var result = controller.ViewComponent("TagCloud"); // Assert Assert.NotNull(result); Assert.Equal("TagCloud", result.ViewComponentName); } [Fact] public void ViewComponent_WithType() { // Arrange var controller = new TestabilityController(); // Act var result = controller.ViewComponent(typeof(TagCloudViewComponent)); // Assert Assert.NotNull(result); Assert.Equal(typeof(TagCloudViewComponent), result.ViewComponentType); } [Fact] public void ViewComponent_WithArguments() { // Arrange var controller = new TestabilityController(); // Act var result = controller.ViewComponent(typeof(TagCloudViewComponent), new { Arg1 = "Hi", Arg2 = "There" }); // Assert Assert.NotNull(result); Assert.Equal(typeof(TagCloudViewComponent), result.ViewComponentType); Assert.Equal(new { Arg1 = "Hi", Arg2 = "There" }, result.Arguments); } [Fact] public void Problem_Works() { // Arrange var detail = "Some random error"; var controller = new TestabilityController(); // Act var result = controller.Problem(detail); // Assert var badRequest = Assert.IsType<ObjectResult>(result); var problemDetails = Assert.IsType<ProblemDetails>(badRequest.Value); Assert.Equal(detail, problemDetails.Detail); } [Fact] public void ValidationProblem_Works() { // Arrange var detail = "Some random error"; var controller = new TestabilityController(); // Act controller.ModelState.AddModelError("some-key", "some-error"); var result = controller.ValidationProblem(detail); // Assert var badRequest = Assert.IsType<ObjectResult>(result); var validationProblemDetails = Assert.IsType<ValidationProblemDetails>(badRequest.Value); Assert.Equal(detail, validationProblemDetails.Detail); var error = Assert.Single(validationProblemDetails.Errors); Assert.Equal("some-key", error.Key); Assert.Equal(new[] { "some-error" }, error.Value); } public static IEnumerable<object[]> TestabilityViewTestData { get { yield return new object[] { null, null }; yield return new object[] { new MyModel { Property1 = "Property_1", Property2 = "Property_2" }, "ViewName_1" }; } } private class TestabilityController : Controller { public IActionResult View_Action(string viewName, object data) { return View(viewName, data); } public IActionResult PartialView_Action(string viewName, object data) { return PartialView(viewName, data); } public IActionResult Content_Action(string content, string contentType, Encoding encoding) { return Content(content, contentType, encoding); } public IActionResult Created_Action(string uri, object data) { return Created(uri, data); } public IActionResult Accepted_Action(string uri, object data) { return Accepted(uri, data); } public IActionResult FileContent_Action(string content, string contentType, string fileName) { var contentArray = Encoding.UTF8.GetBytes(content); return File(contentArray, contentType, fileName); } public IActionResult FileStream_Action(string content, string contentType, string fileName) { var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content)); return File(memoryStream, contentType, fileName); } public IActionResult Json_Action(object data) { return Json(data); } public IActionResult JsonWithSerializerSettings_Action(object data, object serializerSettings) { return Json(data, serializerSettings); } public IActionResult Redirect_Action(string url) { return Redirect(url); } public IActionResult RedirectToAction_Action(string actionName, string controllerName, object routeValues) { return RedirectToAction(actionName, controllerName, routeValues); } public IActionResult RedirectToRoute_Action(string routeName, object routeValues) { return RedirectToRoute(routeName, routeValues); } public IActionResult CreatedAtAction_Action(string actionName, string controllerName, object routeValues, object value) { return CreatedAtAction(actionName, controllerName, routeValues, value); } public IActionResult CreatedAtRoute_Action(string routeName, object routeValues, object value) { return CreatedAtRoute(routeName, routeValues, value); } public IActionResult AcceptedAtAction_Action(string actionName, string controllerName, object routeValues, object value) { return AcceptedAtAction(actionName, controllerName, routeValues, value); } public IActionResult AcceptedAtRoute_Action(string routeName, object routeValues, object value) { return AcceptedAtRoute(routeName, routeValues, value); } public IActionResult HttpBadRequest_Action() { return BadRequest(); } public IActionResult HttpBadRequestObject_Action(object error) { return BadRequest(error); } public IActionResult HttpNotFound_Action() { return NotFound(); } public IActionResult HttpNotFoundObject_Action(object value) { return NotFound(value); } } private class MyModel { public string Property1 { get; set; } public string Property2 { get; set; } } private class TagCloudViewComponent { } } }
// This file is provided under The MIT License as part of Steamworks.NET. // Copyright (c) 2013-2017 Riley Labrecque // Please see the included LICENSE.txt for additional information. // Uncomment this out or add it to your custom platform defines to disable checking the plugin platform settings. //#define DISABLEPLATFORMSETTINGS using UnityEngine; using UnityEditor; using System.IO; // This copys various files into their required locations when Unity is launched to make installation a breeze. [InitializeOnLoad] public class RedistInstall { static RedistInstall() { CopyFile("Assets/Plugins/Steamworks.NET/redist", "steam_appid.txt", false); // We only need to copy the dll into the project root on <= Unity 5.0 #if UNITY_EDITOR_WIN && (UNITY_4_7 || UNITY_5_0) #if UNITY_EDITOR_64 CopyFile("Assets/Plugins/x86_64", "steam_api64.dll", true); #else CopyFile("Assets/Plugins/x86", "steam_api.dll", true); #endif #endif #if UNITY_5 || UNITY_2017 #if !DISABLEPLATFORMSETTINGS SetPlatformSettings(); #endif #endif } static void CopyFile(string path, string filename, bool bCheckDifference) { string strCWD = Directory.GetCurrentDirectory(); string strSource = Path.Combine(Path.Combine(strCWD, path), filename); string strDest = Path.Combine(strCWD, filename); if (!File.Exists(strSource)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. {0} could not be found in '{1}'. Place {0} from the Steamworks SDK in the project root manually.", filename, Path.Combine(strCWD, path))); return; } if (File.Exists(strDest)) { if (!bCheckDifference) return; if (File.GetLastWriteTime(strSource) == File.GetLastWriteTime(strDest)) { FileInfo fInfo = new FileInfo(strSource); FileInfo fInfo2 = new FileInfo(strDest); if (fInfo.Length == fInfo2.Length) { return; } } Debug.Log(string.Format("[Steamworks.NET] {0} in the project root differs from the Steamworks.NET redistributable. Updating.... Please relaunch Unity.", filename)); } else { Debug.Log(string.Format("[Steamworks.NET] {0} is not present in the project root. Copying...", filename)); } File.Copy(strSource, strDest, true); File.SetAttributes(strDest, File.GetAttributes(strDest) & ~FileAttributes.ReadOnly); if (File.Exists(strDest)) { Debug.Log(string.Format("[Steamworks.NET] Successfully copied {0} into the project root. Please relaunch Unity.", filename)); } else { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. File.Copy() Failed. Please copy {0} into the project root manually.", Path.Combine(path, filename))); } } #if UNITY_5 || UNITY_2017 static void SetPlatformSettings() { foreach(var plugin in PluginImporter.GetAllImporters()) { // Skip any null plugins, why is this a thing?! if(plugin == null) { continue; } // Skip any absolute paths, as they are only builtin plugins. if(Path.IsPathRooted(plugin.assetPath)) { continue; } bool didUpdate = false; string filename = Path.GetFileName(plugin.assetPath); switch(filename) { case "CSteamworks.bundle": didUpdate |= ResetPluginSettings(plugin, "AnyCPU", "OSX"); didUpdate |= SetCompatibleWithOSX(plugin); break; case "libCSteamworks.so": case "libsteam_api.so": if(plugin.assetPath.Contains("x86_64")) { didUpdate |= ResetPluginSettings(plugin, "x86_64", "Linux"); didUpdate |= SetCompatibleWithLinux(plugin, BuildTarget.StandaloneLinux64); } else { didUpdate |= ResetPluginSettings(plugin, "x86", "Linux"); didUpdate |= SetCompatibleWithLinux(plugin, BuildTarget.StandaloneLinux); } break; case "CSteamworks.dll": if (plugin.assetPath.Contains("x86_64")) { didUpdate |= ResetPluginSettings(plugin, "x86_64", "Windows"); didUpdate |= SetCompatibleWithWindows(plugin, BuildTarget.StandaloneWindows64); } else { didUpdate |= ResetPluginSettings(plugin, "x86", "Windows"); didUpdate |= SetCompatibleWithWindows(plugin, BuildTarget.StandaloneWindows); } break; case "steam_api.dll": case "steam_api64.dll": if (plugin.assetPath.Contains("x86_64")) { didUpdate |= ResetPluginSettings(plugin, "x86_64", "Windows"); #if UNITY_5_3_OR_NEWER didUpdate |= SetCompatibleWithWindows(plugin, BuildTarget.StandaloneWindows64); #endif } else { didUpdate |= ResetPluginSettings(plugin, "x86", "Windows"); #if UNITY_5_3_OR_NEWER didUpdate |= SetCompatibleWithWindows(plugin, BuildTarget.StandaloneWindows); #endif } #if !UNITY_5_3_OR_NEWER // We do this because Unity had a bug where dependent dll's didn't get loaded from the Plugins // folder in actual builds. But they do in the editor now! So close... Unity bug number: 728945 // So ultimately we must keep using RedistCopy to copy steam_api[64].dll next to the .exe on builds, and // we don't want a useless duplicate version of the dll ending up in the Plugins folder. // This was fixed in Unity 5.3! didUpdate |= SetCompatibleWithEditor(plugin); #endif break; } if (didUpdate) { plugin.SaveAndReimport(); } } } static bool ResetPluginSettings(PluginImporter plugin, string CPU, string OS) { bool didUpdate = false; if (plugin.GetCompatibleWithAnyPlatform() != false) { plugin.SetCompatibleWithAnyPlatform(false); didUpdate = true; } if (plugin.GetCompatibleWithEditor() != true) { plugin.SetCompatibleWithEditor(true); didUpdate = true; } if (plugin.GetEditorData("CPU") != CPU) { plugin.SetEditorData("CPU", CPU); didUpdate = true; } if (plugin.GetEditorData("OS") != OS) { plugin.SetEditorData("OS", OS); didUpdate = true; } return didUpdate; } static bool SetCompatibleWithOSX(PluginImporter plugin) { bool didUpdate = false; didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneOSX, true); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux64, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinuxUniversal, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows64, false); return didUpdate; } static bool SetCompatibleWithLinux(PluginImporter plugin, BuildTarget platform) { bool didUpdate = false; if (platform == BuildTarget.StandaloneLinux) { didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux, true); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux64, false); } else { didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux64, true); } didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinuxUniversal, true); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneOSX, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows64, false); return didUpdate; } static bool SetCompatibleWithWindows(PluginImporter plugin, BuildTarget platform) { bool didUpdate = false; if (platform == BuildTarget.StandaloneWindows) { didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows, true); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows64, false); } else { didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows64, true); } didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux64, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinuxUniversal, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneOSX, false); return didUpdate; } static bool SetCompatibleWithEditor(PluginImporter plugin) { bool didUpdate = false; didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux64, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinux, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneLinuxUniversal, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneOSX, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows, false); didUpdate |= SetCompatibleWithPlatform(plugin, BuildTarget.StandaloneWindows64, false); return didUpdate; } static bool SetCompatibleWithPlatform(PluginImporter plugin, BuildTarget platform, bool enable) { if (plugin.GetCompatibleWithPlatform(platform) == enable) { return false; } plugin.SetCompatibleWithPlatform(platform, enable); return true; } #endif // UNITY_5 }
using System; using System.Collections; using Raksha.Asn1; using Raksha.Asn1.Cms; using Raksha.Asn1.Kisa; using Raksha.Asn1.Nist; using Raksha.Asn1.Ntt; using Raksha.Asn1.Pkcs; using Raksha.Asn1.X509; using Raksha.Asn1.X9; using Raksha.Crypto; using Raksha.Crypto.Parameters; using Raksha.Security; using Raksha.Utilities; using Raksha.X509; namespace Raksha.Cms { /** * General class for generating a CMS enveloped-data message. * * A simple example of usage. * * <pre> * CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator(); * * fact.addKeyTransRecipient(cert); * * CMSEnvelopedData data = fact.generate(content, algorithm, "BC"); * </pre> */ public class CmsEnvelopedGenerator { // Note: These tables are complementary: If rc2Table[i]==j, then rc2Ekb[j]==i internal static readonly short[] rc2Table = { 0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0, 0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a, 0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36, 0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c, 0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60, 0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa, 0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e, 0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf, 0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6, 0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3, 0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c, 0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2, 0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5, 0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5, 0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f, 0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab }; // internal static readonly short[] rc2Ekb = // { // 0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5, // 0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5, // 0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef, // 0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d, // 0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb, // 0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d, // 0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3, // 0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61, // 0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1, // 0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21, // 0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42, // 0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f, // 0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7, // 0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15, // 0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7, // 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd // }; // TODO Create named constants for all of these public static readonly string DesEde3Cbc = PkcsObjectIdentifiers.DesEde3Cbc.Id; public static readonly string RC2Cbc = PkcsObjectIdentifiers.RC2Cbc.Id; public const string IdeaCbc = "1.3.6.1.4.1.188.7.1.1.2"; public const string Cast5Cbc = "1.2.840.113533.7.66.10"; public static readonly string Aes128Cbc = NistObjectIdentifiers.IdAes128Cbc.Id; public static readonly string Aes192Cbc = NistObjectIdentifiers.IdAes192Cbc.Id; public static readonly string Aes256Cbc = NistObjectIdentifiers.IdAes256Cbc.Id; public static readonly string Camellia128Cbc = NttObjectIdentifiers.IdCamellia128Cbc.Id; public static readonly string Camellia192Cbc = NttObjectIdentifiers.IdCamellia192Cbc.Id; public static readonly string Camellia256Cbc = NttObjectIdentifiers.IdCamellia256Cbc.Id; public static readonly string SeedCbc = KisaObjectIdentifiers.IdSeedCbc.Id; public static readonly string DesEde3Wrap = PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id; public static readonly string Aes128Wrap = NistObjectIdentifiers.IdAes128Wrap.Id; public static readonly string Aes192Wrap = NistObjectIdentifiers.IdAes192Wrap.Id; public static readonly string Aes256Wrap = NistObjectIdentifiers.IdAes256Wrap.Id; public static readonly string Camellia128Wrap = NttObjectIdentifiers.IdCamellia128Wrap.Id; public static readonly string Camellia192Wrap = NttObjectIdentifiers.IdCamellia192Wrap.Id; public static readonly string Camellia256Wrap = NttObjectIdentifiers.IdCamellia256Wrap.Id; public static readonly string SeedWrap = KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap.Id; public static readonly string ECDHSha1Kdf = X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme.Id; public static readonly string ECMqvSha1Kdf = X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme.Id; internal readonly IList recipientInfoGenerators = Platform.CreateArrayList(); internal readonly SecureRandom rand; internal CmsAttributeTableGenerator unprotectedAttributeGenerator = null; public CmsEnvelopedGenerator() : this(new SecureRandom()) { } /// <summary>Constructor allowing specific source of randomness</summary> /// <param name="rand">Instance of <c>SecureRandom</c> to use.</param> public CmsEnvelopedGenerator( SecureRandom rand) { this.rand = rand; } public CmsAttributeTableGenerator UnprotectedAttributeGenerator { get { return this.unprotectedAttributeGenerator; } set { this.unprotectedAttributeGenerator = value; } } /** * add a recipient. * * @param cert recipient's public key certificate * @exception ArgumentException if there is a problem with the certificate */ public void AddKeyTransRecipient( X509Certificate cert) { KeyTransRecipientInfoGenerator ktrig = new KeyTransRecipientInfoGenerator(); ktrig.RecipientCert = cert; recipientInfoGenerators.Add(ktrig); } /** * add a recipient * * @param key the public key used by the recipient * @param subKeyId the identifier for the recipient's public key * @exception ArgumentException if there is a problem with the key */ public void AddKeyTransRecipient( AsymmetricKeyParameter pubKey, byte[] subKeyId) { KeyTransRecipientInfoGenerator ktrig = new KeyTransRecipientInfoGenerator(); ktrig.RecipientPublicKey = pubKey; ktrig.SubjectKeyIdentifier = new DerOctetString(subKeyId); recipientInfoGenerators.Add(ktrig); } /** * add a KEK recipient. * @param key the secret key to use for wrapping * @param keyIdentifier the byte string that identifies the key */ public void AddKekRecipient( string keyAlgorithm, // TODO Remove need for this parameter KeyParameter key, byte[] keyIdentifier) { AddKekRecipient(keyAlgorithm, key, new KekIdentifier(keyIdentifier, null, null)); } /** * add a KEK recipient. * @param key the secret key to use for wrapping * @param keyIdentifier the byte string that identifies the key */ public void AddKekRecipient( string keyAlgorithm, // TODO Remove need for this parameter KeyParameter key, KekIdentifier kekIdentifier) { KekRecipientInfoGenerator kekrig = new KekRecipientInfoGenerator(); kekrig.KekIdentifier = kekIdentifier; kekrig.KeyEncryptionKeyOID = keyAlgorithm; kekrig.KeyEncryptionKey = key; recipientInfoGenerators.Add(kekrig); } public void AddPasswordRecipient( CmsPbeKey pbeKey, string kekAlgorithmOid) { Pbkdf2Params p = new Pbkdf2Params(pbeKey.Salt, pbeKey.IterationCount); PasswordRecipientInfoGenerator prig = new PasswordRecipientInfoGenerator(); prig.KeyDerivationAlgorithm = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbkdf2, p); prig.KeyEncryptionKeyOID = kekAlgorithmOid; prig.KeyEncryptionKey = pbeKey.GetEncoded(kekAlgorithmOid); recipientInfoGenerators.Add(prig); } /** * Add a key agreement based recipient. * * @param agreementAlgorithm key agreement algorithm to use. * @param senderPrivateKey private key to initialise sender side of agreement with. * @param senderPublicKey sender public key to include with message. * @param recipientCert recipient's public key certificate. * @param cekWrapAlgorithm OID for key wrapping algorithm to use. * @exception SecurityUtilityException if the algorithm requested cannot be found * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified */ public void AddKeyAgreementRecipient( string agreementAlgorithm, AsymmetricKeyParameter senderPrivateKey, AsymmetricKeyParameter senderPublicKey, X509Certificate recipientCert, string cekWrapAlgorithm) { IList recipientCerts = Platform.CreateArrayList(1); recipientCerts.Add(recipientCert); AddKeyAgreementRecipients(agreementAlgorithm, senderPrivateKey, senderPublicKey, recipientCerts, cekWrapAlgorithm); } /** * Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure). * * @param agreementAlgorithm key agreement algorithm to use. * @param senderPrivateKey private key to initialise sender side of agreement with. * @param senderPublicKey sender public key to include with message. * @param recipientCerts recipients' public key certificates. * @param cekWrapAlgorithm OID for key wrapping algorithm to use. * @exception SecurityUtilityException if the algorithm requested cannot be found * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified */ public void AddKeyAgreementRecipients( string agreementAlgorithm, AsymmetricKeyParameter senderPrivateKey, AsymmetricKeyParameter senderPublicKey, ICollection recipientCerts, string cekWrapAlgorithm) { if (!senderPrivateKey.IsPrivate) throw new ArgumentException("Expected private key", "senderPrivateKey"); if (senderPublicKey.IsPrivate) throw new ArgumentException("Expected public key", "senderPublicKey"); /* TODO * "a recipient X.509 version 3 certificate that contains a key usage extension MUST * assert the keyAgreement bit." */ KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator(); karig.KeyAgreementOID = new DerObjectIdentifier(agreementAlgorithm); karig.KeyEncryptionOID = new DerObjectIdentifier(cekWrapAlgorithm); karig.RecipientCerts = recipientCerts; karig.SenderKeyPair = new AsymmetricCipherKeyPair(senderPublicKey, senderPrivateKey); recipientInfoGenerators.Add(karig); } protected internal virtual AlgorithmIdentifier GetAlgorithmIdentifier( string encryptionOid, KeyParameter encKey, Asn1Encodable asn1Params, out ICipherParameters cipherParameters) { Asn1Object asn1Object; if (asn1Params != null) { asn1Object = asn1Params.ToAsn1Object(); cipherParameters = ParameterUtilities.GetCipherParameters( encryptionOid, encKey, asn1Object); } else { asn1Object = DerNull.Instance; cipherParameters = encKey; } return new AlgorithmIdentifier( new DerObjectIdentifier(encryptionOid), asn1Object); } protected internal virtual Asn1Encodable GenerateAsn1Parameters( string encryptionOid, byte[] encKeyBytes) { Asn1Encodable asn1Params = null; try { if (encryptionOid.Equals(RC2Cbc)) { byte[] iv = new byte[8]; rand.NextBytes(iv); // TODO Is this detailed repeat of Java version really necessary? int effKeyBits = encKeyBytes.Length * 8; int parameterVersion; if (effKeyBits < 256) { parameterVersion = rc2Table[effKeyBits]; } else { parameterVersion = effKeyBits; } asn1Params = new RC2CbcParameter(parameterVersion, iv); } else { asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand); } } catch (SecurityUtilityException) { // No problem... no parameters generated } return asn1Params; } } }
// 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>CustomerConversionGoal</c> resource.</summary> public sealed partial class CustomerConversionGoalName : gax::IResourceName, sys::IEquatable<CustomerConversionGoalName> { /// <summary>The possible contents of <see cref="CustomerConversionGoalName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>. /// </summary> CustomerCategorySource = 1, } private static gax::PathTemplate s_customerCategorySource = new gax::PathTemplate("customers/{customer_id}/customerConversionGoals/{category_source}"); /// <summary>Creates a <see cref="CustomerConversionGoalName"/> 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="CustomerConversionGoalName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerConversionGoalName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerConversionGoalName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerConversionGoalName"/> with the pattern /// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="CustomerConversionGoalName"/> constructed from the provided ids. /// </returns> public static CustomerConversionGoalName FromCustomerCategorySource(string customerId, string categoryId, string sourceId) => new CustomerConversionGoalName(ResourceNameType.CustomerCategorySource, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), categoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>. /// </returns> public static string Format(string customerId, string categoryId, string sourceId) => FormatCustomerCategorySource(customerId, categoryId, sourceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>. /// </returns> public static string FormatCustomerCategorySource(string customerId, string categoryId, string sourceId) => s_customerCategorySource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerConversionGoalName"/> 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}/customerConversionGoals/{category}~{source}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customerConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerConversionGoalName"/> if successful.</returns> public static CustomerConversionGoalName Parse(string customerConversionGoalName) => Parse(customerConversionGoalName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerConversionGoalName"/> 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}/customerConversionGoals/{category}~{source}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerConversionGoalName">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="CustomerConversionGoalName"/> if successful.</returns> public static CustomerConversionGoalName Parse(string customerConversionGoalName, bool allowUnparsed) => TryParse(customerConversionGoalName, allowUnparsed, out CustomerConversionGoalName 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="CustomerConversionGoalName"/> 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}/customerConversionGoals/{category}~{source}</c></description> /// </item> /// </list> /// </remarks> /// <param name="customerConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerConversionGoalName"/>, 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 customerConversionGoalName, out CustomerConversionGoalName result) => TryParse(customerConversionGoalName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerConversionGoalName"/> 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}/customerConversionGoals/{category}~{source}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerConversionGoalName">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="CustomerConversionGoalName"/>, 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 customerConversionGoalName, bool allowUnparsed, out CustomerConversionGoalName result) { gax::GaxPreconditions.CheckNotNull(customerConversionGoalName, nameof(customerConversionGoalName)); gax::TemplatedResourceName resourceName; if (s_customerCategorySource.TryParseName(customerConversionGoalName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCategorySource(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerConversionGoalName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CustomerConversionGoalName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string categoryId = null, string customerId = null, string sourceId = null) { Type = type; UnparsedResource = unparsedResourceName; CategoryId = categoryId; CustomerId = customerId; SourceId = sourceId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerConversionGoalName"/> class from the component parts of /// pattern <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> public CustomerConversionGoalName(string customerId, string categoryId, string sourceId) : this(ResourceNameType.CustomerCategorySource, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), categoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId))) { } /// <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>Category</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CategoryId { 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>Source</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string SourceId { 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.CustomerCategorySource: return s_customerCategorySource.Expand(CustomerId, $"{CategoryId}~{SourceId}"); 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 CustomerConversionGoalName); /// <inheritdoc/> public bool Equals(CustomerConversionGoalName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerConversionGoalName a, CustomerConversionGoalName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerConversionGoalName a, CustomerConversionGoalName b) => !(a == b); } public partial class CustomerConversionGoal { /// <summary> /// <see cref="CustomerConversionGoalName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CustomerConversionGoalName ResourceNameAsCustomerConversionGoalName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerConversionGoalName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using Cvv.WebUtility.Mvc.Provider; namespace Cvv.WebUtility.Core.Json { class JSONDeserializer : IDeserializerProvider { public object Parse(string stringValue, Type targetType) { if (targetType.Name.EndsWith("&")) throw new JSONException("Not support this type: " + targetType.Name); return ParseValue(stringValue, targetType); } private static Dictionary<Type, TokenId> _baseType = new Dictionary<Type, TokenId>(); static JSONDeserializer() { _baseType.Add(typeof(Boolean), TokenId.Boolean); _baseType.Add(typeof(Byte), TokenId.Byte); _baseType.Add(typeof(SByte), TokenId.SByte); _baseType.Add(typeof(Char), TokenId.Char); _baseType.Add(typeof(Decimal), TokenId.Decimal); _baseType.Add(typeof(Double), TokenId.Double); _baseType.Add(typeof(Single), TokenId.Single); _baseType.Add(typeof(Int32), TokenId.Int32); _baseType.Add(typeof(UInt32), TokenId.UInt32); _baseType.Add(typeof(Int64), TokenId.Int64); _baseType.Add(typeof(UInt64), TokenId.UInt64); _baseType.Add(typeof(Object), TokenId.Object); _baseType.Add(typeof(Int16), TokenId.Int16); _baseType.Add(typeof(UInt16), TokenId.UInt16); _baseType.Add(typeof(String), TokenId.String); _baseType.Add(typeof(DateTime), TokenId.DateTime); _baseType.Add(typeof(Guid), TokenId.Guid); _baseType.Add(typeof(Boolean[]), TokenId.ArrayBoolean); _baseType.Add(typeof(Byte[]), TokenId.ArrayByte); _baseType.Add(typeof(SByte[]), TokenId.ArraySByte); _baseType.Add(typeof(Char[]), TokenId.ArrayChar); _baseType.Add(typeof(Decimal[]), TokenId.ArrayDecimal); _baseType.Add(typeof(Double[]), TokenId.ArrayDouble); _baseType.Add(typeof(Single[]), TokenId.ArraySingle); _baseType.Add(typeof(Int32[]), TokenId.ArrayInt32); _baseType.Add(typeof(UInt32[]), TokenId.ArrayUInt32); _baseType.Add(typeof(Int64[]), TokenId.ArrayInt64); _baseType.Add(typeof(UInt64[]), TokenId.ArrayUInt64); _baseType.Add(typeof(Object[]), TokenId.ArrayObject); _baseType.Add(typeof(Int16[]), TokenId.ArrayInt16); _baseType.Add(typeof(UInt16[]), TokenId.ArrayUInt16); _baseType.Add(typeof(String[]), TokenId.ArrayString); _baseType.Add(typeof(DateTime[]), TokenId.ArrayDateTime); _baseType.Add(typeof(Guid[]), TokenId.ArrayGuid); _baseType.Add(typeof(IList<Boolean>), TokenId.ArrayBoolean); _baseType.Add(typeof(IList<Byte>), TokenId.ArrayByte); _baseType.Add(typeof(IList<SByte>), TokenId.ArraySByte); _baseType.Add(typeof(IList<Char>), TokenId.ArrayChar); _baseType.Add(typeof(IList<Decimal>), TokenId.ArrayDecimal); _baseType.Add(typeof(IList<Double>), TokenId.ArrayDouble); _baseType.Add(typeof(IList<Single>), TokenId.ArraySingle); _baseType.Add(typeof(IList<Int32>), TokenId.ArrayInt32); _baseType.Add(typeof(IList<UInt32>), TokenId.ArrayUInt32); _baseType.Add(typeof(IList<Int64>), TokenId.ArrayInt64); _baseType.Add(typeof(IList<UInt64>), TokenId.ArrayUInt64); _baseType.Add(typeof(IList<Object>), TokenId.ArrayObject); _baseType.Add(typeof(IList<Int16>), TokenId.ArrayInt16); _baseType.Add(typeof(IList<UInt16>), TokenId.ArrayUInt16); _baseType.Add(typeof(IList<String>), TokenId.ArrayString); _baseType.Add(typeof(IList<DateTime>), TokenId.ArrayDateTime); _baseType.Add(typeof(IList<Guid>), TokenId.ArrayGuid); } public static object ParseValue(string stringValue, Type targetType) { if (stringValue == null) stringValue = string.Empty; TokenId tokenId; if (_baseType.TryGetValue(targetType, out tokenId)) { switch (tokenId) { case TokenId.Boolean: return CreateBoolean(stringValue); case TokenId.Byte: return CreateByte(stringValue); case TokenId.SByte: return CreateSByte(stringValue); case TokenId.Char: return CreateChar(stringValue); case TokenId.Decimal: return CreateDecimal(stringValue); case TokenId.Double: return CreateDouble(stringValue); case TokenId.Single: return CreateSingle(stringValue); case TokenId.Int32: return CreateInt32(stringValue); case TokenId.UInt32: return CreateUInt32(stringValue); case TokenId.Int64: return CreateInt64(stringValue); case TokenId.UInt64: return CreateUInt64(stringValue); case TokenId.Object: return CreateObject(stringValue); case TokenId.Int16: return CreateInt16(stringValue); case TokenId.UInt16: return CreateUInt16(stringValue); case TokenId.String: return CreateString(stringValue); case TokenId.DateTime: return CreateDateTime(stringValue); case TokenId.Guid: return CreateGuid(stringValue); case TokenId.ArrayBoolean: return CreateArrayBoolean(stringValue); case TokenId.ArrayByte: return CreateArrayByte(stringValue); case TokenId.ArraySByte: return CreateArraySByte(stringValue); case TokenId.ArrayChar: return CreateArrayChar(stringValue); case TokenId.ArrayDecimal: return CreateArrayDecimal(stringValue); case TokenId.ArrayDouble: return CreateArrayDouble(stringValue); case TokenId.ArraySingle: return CreateArraySingle(stringValue); case TokenId.ArrayInt32: return CreateArrayInt32(stringValue); case TokenId.ArrayUInt32: return CreateArrayUInt32(stringValue); case TokenId.ArrayInt64: return CreateArrayInt64(stringValue); case TokenId.ArrayUInt64: return CreateArrayUInt64(stringValue); case TokenId.ArrayObject: return CreateArrayObject(stringValue); case TokenId.ArrayInt16: return CreateArrayInt16(stringValue); case TokenId.ArrayUInt16: return CreateArrayUInt16(stringValue); case TokenId.ArrayString: return CreateArrayString(stringValue); case TokenId.ArrayDateTime: return CreateArrayDateTime(stringValue); case TokenId.ArrayGuid: return CreateArrayGuid(stringValue); default: return CreateObject(stringValue); } } else if (targetType.IsInterface) { if (targetType.IsGenericType) { int index = 0; char[] json = stringValue.ToCharArray(); if (json.Length > 0) { Advance(json, ref index, Token.LBracket); } return ParseList(json, ref index, targetType); } throw new JSONException("MiniJSON not supported this interface '" + targetType.Name + "'"); } else if (typeof(Array).IsAssignableFrom(targetType)) { int index = 0; char[] json = stringValue.ToCharArray(); if (json.Length > 0) { Advance(json, ref index, Token.LBracket); } return ParseArray(json, ref index, targetType); } else { int index = 0; char[] json = stringValue.ToCharArray(); if (json.Length > 0) { Advance(json, ref index, Token.LCurly); } return ParseObject(json, ref index, targetType); } } private static object ParseValue(char[] json, ref int index, Type targetType) { switch (Advance(json, ref index)) { case Token.Number: { string value = ParseNumber(json, ref index); return ParseValue(value, targetType); } case Token.String: { string value = ParseString(json, ref index); return ParseValue(value, targetType); } case Token.LCurly: return ParseObject(json, ref index, targetType); case Token.LBracket: return ParseList(json, ref index, targetType); case Token.True: return true; case Token.False: return false; case Token.Null: return null; } throw new JSONException("Unrecognized token at index " + index); } private static object ParseObject(char[] json, ref int index, Type targetType) { ConstructorInfo[] constructors = targetType.GetConstructors(); if (constructors.Length != 2) { throw new JSONException("Model must be 2 constructors, first with zero parameters, another with full parameters as properties"); } if (json.Length == 0) { return Activator.CreateInstance(targetType); } ConstructorInfo ctr = constructors[1]; ParameterInfo[] parameters = ctr.GetParameters(); Dictionary<string, Type> argsType = new Dictionary<string, Type>(StringComparer.InvariantCulture); foreach (ParameterInfo parameter in parameters) { argsType.Add(parameter.Name, parameter.ParameterType); } Dictionary<string, object> table = new Dictionary<string, object>(); while (true) { switch (Advance(json, ref index)) { case Token.Comma: break; case Token.RCurly: { object[] args = new object[parameters.Length]; for (int i = 0; i < args.Length; i++) { object val; string propertyName = parameters[i].Name; if (table.TryGetValue(propertyName, out val)) args[i] = val; } return Activator.CreateInstance(targetType, args); } default: { string name = CamelCase(ParseString(json, ref index)); Advance(json, ref index, Token.Colon); Type outType; if (argsType.TryGetValue(name, out outType)) { object value = ParseValue(json, ref index, outType); table[name] = value; } else { object value = ParseValue(json, ref index, typeof(object)); table[name] = value; } } break; } } } private static Array ParseArray(char[] json, ref int index, Type targetType) { Type elementType = targetType.GetElementType(); ArrayList array = new ArrayList(); if (json.Length == 0) { return array.ToArray(elementType); } while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: { Advance(json, ref index); return array.ToArray(elementType); } default: array.Add(ParseValue(json, ref index, elementType)); break; } } } private static IList ParseList(char[] json, ref int index, Type targetType) { Type[] typeArguments = targetType.GetGenericArguments(); if (typeArguments.Length != 1 || !typeof(IList<>).MakeGenericType(typeArguments).IsAssignableFrom(targetType)) { throw new JSONException("MiniJSON not implemented this interface '" + targetType.Name + "'"); } IList array = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(typeArguments)); if (json.Length == 0) { return array; } while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array; default: array.Add(ParseValue(json, ref index, typeArguments[0])); break; } } } private static Boolean CreateBoolean(string stringValue) { Boolean val; Boolean.TryParse(stringValue, out val); return val; } private static Byte CreateByte(string stringValue) { Byte val; if (stringValue.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) { Byte.TryParse(stringValue.Substring(2), NumberStyles.HexNumber, null, out val); } else { Byte.TryParse(stringValue, out val); } return val; } private static SByte CreateSByte(string stringValue) { SByte val; if (stringValue.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) { SByte.TryParse(stringValue.Substring(2), NumberStyles.HexNumber, null, out val); } else { SByte.TryParse(stringValue, out val); } return val; } private static Char CreateChar(string stringValue) { Char val; Char.TryParse(stringValue, out val); return val; } private static Decimal CreateDecimal(string stringValue) { Decimal val; Decimal.TryParse(stringValue, out val); return val; } private static Double CreateDouble(string stringValue) { Double val; Double.TryParse(stringValue, out val); return val; } private static Single CreateSingle(string stringValue) { Single val; Single.TryParse(stringValue, out val); return val; } private static Int32 CreateInt32(string stringValue) { Int32 val; if (stringValue.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) { Int32.TryParse(stringValue.Substring(2), NumberStyles.HexNumber, null, out val); } else { Int32.TryParse(stringValue, out val); } return val; } private static UInt32 CreateUInt32(string stringValue) { UInt32 val; if (stringValue.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) { UInt32.TryParse(stringValue.Substring(2), NumberStyles.HexNumber, null, out val); } else { UInt32.TryParse(stringValue, out val); } return val; } private static Int64 CreateInt64(string stringValue) { Int64 val; if (stringValue.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) { Int64.TryParse(stringValue.Substring(2), NumberStyles.HexNumber, null, out val); } else { Int64.TryParse(stringValue, out val); } return val; } private static UInt64 CreateUInt64(string stringValue) { UInt64 val; if (stringValue.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) { UInt64.TryParse(stringValue.Substring(2), NumberStyles.HexNumber, null, out val); } else { UInt64.TryParse(stringValue, out val); } return val; } private static Object CreateObject(string stringValue) { return stringValue; } private static Int16 CreateInt16(string stringValue) { Int16 val; Int16.TryParse(stringValue, out val); return val; } private static UInt16 CreateUInt16(string stringValue) { UInt16 val; UInt16.TryParse(stringValue, out val); return val; } private static String CreateString(string stringValue) { return stringValue; } private static DateTime CreateDateTime(string stringValue) { DateTime val; DateTime.TryParse(stringValue, out val); return val; } private static Guid CreateGuid(string stringValue) { Guid val; try { val = new Guid(stringValue); } catch (Exception) { val = Guid.Empty; } return val; } private static Boolean[] CreateArrayBoolean(string stringValue) { Boolean[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayBoolean(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Boolean[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateBoolean(array[i]); } } return rval; } private static Byte[] CreateArrayByte(string stringValue) { Byte[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayByte(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Byte[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateByte(array[i]); } } return rval; } private static SByte[] CreateArraySByte(string stringValue) { SByte[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArraySByte(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new SByte[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateSByte(array[i]); } } return rval; } private static Char[] CreateArrayChar(string stringValue) { Char[] rval; if (stringValue.TrimStart().StartsWith("\"")) { int index = 0; string s = ParseString(stringValue.ToCharArray(), ref index); rval = s.ToCharArray(); } else { rval = stringValue.ToCharArray(); } return rval; } private static Decimal[] CreateArrayDecimal(string stringValue) { Decimal[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayDecimal(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Decimal[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateDecimal(array[i]); } } return rval; } private static Double[] CreateArrayDouble(string stringValue) { Double[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayDouble(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Double[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateDouble(array[i]); } } return rval; } private static Single[] CreateArraySingle(string stringValue) { Single[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArraySingle(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Single[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateSingle(array[i]); } } return rval; } private static Int32[] CreateArrayInt32(string stringValue) { Int32[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayInt32(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Int32[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateInt32(array[i]); } } return rval; } private static UInt32[] CreateArrayUInt32(string stringValue) { UInt32[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayUInt32(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new UInt32[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateUInt32(array[i]); } } return rval; } private static Int64[] CreateArrayInt64(string stringValue) { Int64[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayInt64(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Int64[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateInt64(array[i]); } } return rval; } private static UInt64[] CreateArrayUInt64(string stringValue) { UInt64[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayUInt64(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new UInt64[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateUInt64(array[i]); } } return rval; } private static Object[] CreateArrayObject(string stringValue) { throw new NotImplementedException(); } private static Int16[] CreateArrayInt16(string stringValue) { Int16[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayInt16(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new Int16[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateInt16(array[i]); } } return rval; } private static UInt16[] CreateArrayUInt16(string stringValue) { UInt16[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayUInt16(stringValue.ToCharArray(), ref index); } else { string[] array = StringToArray(stringValue); rval = new UInt16[array.Length]; for (int i = 0; i < array.Length; i++) { rval[i] = CreateUInt16(array[i]); } } return rval; } private static String[] CreateArrayString(string stringValue) { string[] rval; if (stringValue.TrimStart().StartsWith("[")) { int index = 0; rval = ParseArrayString(stringValue.ToCharArray(), ref index); } else { rval = StringToArray(stringValue); } return rval; } private static DateTime[] CreateArrayDateTime(string stringValue) { throw new NotImplementedException(); } private static Guid[] CreateArrayGuid(string stringValue) { throw new NotImplementedException(); } private static string[] StringToArray(string stringValue) { if (string.IsNullOrEmpty(stringValue)) { return new string[0]; } else { return stringValue.Split(','); } } private static Boolean[] ParseArrayBoolean(char[] json, ref int index) { List<Boolean> array = new List<Boolean>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseBoolean(json, ref index)); break; } } } private static Boolean ParseBoolean(char[] json, ref int index) { Token token = Advance(json, ref index); Boolean rval; if (token == Token.True) { rval = true; } else if (token == Token.False) { rval = false; } else if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateBoolean(stringValue); } else { rval = false; } return rval; } private static Byte[] ParseArrayByte(char[] json, ref int index) { List<Byte> array = new List<Byte>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseByte(json, ref index)); break; } } } private static Byte ParseByte(char[] json, ref int index) { Token token = Advance(json, ref index); Byte rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateByte(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateByte(stringValue); } return rval; } private static SByte[] ParseArraySByte(char[] json, ref int index) { List<SByte> array = new List<SByte>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseSByte(json, ref index)); break; } } } private static SByte ParseSByte(char[] json, ref int index) { Token token = Advance(json, ref index); SByte rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateSByte(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateSByte(stringValue); } return rval; } private static Decimal[] ParseArrayDecimal(char[] json, ref int index) { List<Decimal> array = new List<Decimal>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseDecimal(json, ref index)); break; } } } private static Decimal ParseDecimal(char[] json, ref int index) { Token token = Advance(json, ref index); Decimal rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateDecimal(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateDecimal(stringValue); } return rval; } private static Double[] ParseArrayDouble(char[] json, ref int index) { List<Double> array = new List<Double>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseDouble(json, ref index)); break; } } } private static Double ParseDouble(char[] json, ref int index) { Token token = Advance(json, ref index); Double rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateDouble(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateDouble(stringValue); } return rval; } private static Single[] ParseArraySingle(char[] json, ref int index) { List<Single> array = new List<Single>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseSingle(json, ref index)); break; } } } private static Single ParseSingle(char[] json, ref int index) { Token token = Advance(json, ref index); Single rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateSingle(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateSingle(stringValue); } return rval; } private static Int32[] ParseArrayInt32(char[] json, ref int index) { List<Int32> array = new List<Int32>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseInt32(json, ref index)); break; } } } private static Int32 ParseInt32(char[] json, ref int index) { Token token = Advance(json, ref index); Int32 rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateInt32(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateInt32(stringValue); } return rval; } private static UInt32[] ParseArrayUInt32(char[] json, ref int index) { List<UInt32> array = new List<UInt32>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseUInt32(json, ref index)); break; } } } private static UInt32 ParseUInt32(char[] json, ref int index) { Token token = Advance(json, ref index); UInt32 rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateUInt32(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateUInt32(stringValue); } return rval; } private static Int64[] ParseArrayInt64(char[] json, ref int index) { List<Int64> array = new List<Int64>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseInt64(json, ref index)); break; } } } private static Int64 ParseInt64(char[] json, ref int index) { Token token = Advance(json, ref index); Int64 rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateInt64(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateInt64(stringValue); } return rval; } private static UInt64[] ParseArrayUInt64(char[] json, ref int index) { List<UInt64> array = new List<UInt64>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseUInt64(json, ref index)); break; } } } private static UInt64 ParseUInt64(char[] json, ref int index) { Token token = Advance(json, ref index); UInt64 rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateUInt64(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateUInt64(stringValue); } return rval; } private static Int16[] ParseArrayInt16(char[] json, ref int index) { List<Int16> array = new List<Int16>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseInt16(json, ref index)); break; } } } private static Int16 ParseInt16(char[] json, ref int index) { Token token = Advance(json, ref index); Int16 rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateInt16(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateInt16(stringValue); } return rval; } private static UInt16[] ParseArrayUInt16(char[] json, ref int index) { List<UInt16> array = new List<UInt16>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, index)) { case Token.Comma: Advance(json, ref index); break; case Token.RBracket: Advance(json, ref index); return array.ToArray(); default: array.Add(ParseUInt16(json, ref index)); break; } } } private static UInt16 ParseUInt16(char[] json, ref int index) { Token token = Advance(json, ref index); UInt16 rval; if (token == Token.String) { string stringValue = ParseString(json, ref index); rval = CreateUInt16(stringValue); } else { string stringValue = ParseNumber(json, ref index); rval = CreateUInt16(stringValue); } return rval; } private static string[] ParseArrayString(char[] json, ref int index) { List<string> array = new List<string>(); Advance(json, ref index, Token.LBracket); while (true) { switch (Advance(json, ref index)) { case Token.Comma: break; case Token.RBracket: return array.ToArray(); default: array.Add(ParseString(json, ref index)); break; } } } private static string ParseString(char[] json, ref int index) { StringBuilder s = new StringBuilder(); int runIndex = -1; while (index < json.Length) { char c = json[index++]; if (c == '"') { if (runIndex != -1) { if (s.Length == 0) return new string(json, runIndex, index - runIndex - 1); s.Append(json, runIndex, index - runIndex - 1); } return s.ToString(); } if (c != '\\') { if (runIndex == -1) runIndex = index - 1; continue; } if (index == json.Length) break; if (runIndex != -1) { s.Append(json, runIndex, index - runIndex - 1); runIndex = -1; } switch (json[index++]) { case '"': s.Append('"'); break; case '\\': s.Append('\\'); break; case '/': s.Append('/'); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': { int remainingLength = json.Length - index; if (remainingLength < 4) break; uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]); s.Append((char)codePoint); index += 4; } break; } } throw new JSONException("Unexpectedly reached end of string"); } private static string ParseNumber(char[] json, ref int index) { var startIndex = index - 1; do { if (index == json.Length) break; char c = json[index]; if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E' || c == 'x' || c == 'X') { if (++index == json.Length) break; continue; } break; } while (true); return new string(json, startIndex, index - startIndex); } private static uint ParseSingleChar(char c1, uint multipliyer) { uint p1 = 0; if (c1 >= '0' && c1 <= '9') p1 = (uint)(c1 - '0') * multipliyer; else if (c1 >= 'A' && c1 <= 'F') p1 = (uint)((c1 - 'A') + 10) * multipliyer; else if (c1 >= 'a' && c1 <= 'f') p1 = (uint)((c1 - 'a') + 10) * multipliyer; return p1; } private static uint ParseUnicode(char c1, char c2, char c3, char c4) { uint p1 = ParseSingleChar(c1, 0x1000); uint p2 = ParseSingleChar(c2, 0x100); uint p3 = ParseSingleChar(c3, 0x10); uint p4 = ParseSingleChar(c4, 1); return p1 + p2 + p3 + p4; } private static void Advance(char[] json, ref int index, Token expecToken) { Token curtok = Advance(json, ref index); if (curtok != expecToken) throw new JSONException(string.Format("Expect token: {0}, but got token: {1}", expecToken, curtok)); } private static Token Advance(char[] json, int index) { return Advance(json, ref index); } private static Token Advance(char[] json, ref int index) { char c; while (index < json.Length) { c = json[index]; if (c > ' ') break; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; index++; } if (index == json.Length) { return Token.Eof; } c = json[index]; index++; switch (c) { case '{': return Token.LCurly; case '}': return Token.RCurly; case '[': return Token.LBracket; case ']': return Token.RBracket; case ',': return Token.Comma; case '"': return Token.String; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': case '+': case '.': return Token.Number; case ':': return Token.Colon; case 'f': if (json.Length - index >= 4 && json[index + 0] == 'a' && json[index + 1] == 'l' && json[index + 2] == 's' && json[index + 3] == 'e') { index += 4; return Token.False; } break; case 't': if (json.Length - index >= 3 && json[index + 0] == 'r' && json[index + 1] == 'u' && json[index + 2] == 'e') { index += 3; return Token.True; } break; case 'n': if (json.Length - index >= 3 && json[index + 0] == 'u' && json[index + 1] == 'l' && json[index + 2] == 'l') { index += 3; return Token.Null; } break; } throw new JSONException("Could not find token at index " + --index); } public static string CamelCase(string name) { if (string.IsNullOrEmpty(name)) return string.Empty; if (name.Length < 2) return name.ToLower(); return char.ToLower(name[0]) + name.Substring(1); } public static string PascalCase(string name) { if (string.IsNullOrEmpty(name)) return string.Empty; if (name.Length < 2) return name.ToUpper(); return char.ToUpper(name[0]) + name.Substring(1); } enum Token { Eof = -1, LCurly, RCurly, LBracket, RBracket, Colon, Comma, String, Number, True, False, Null, } enum TokenId { Boolean, Byte, SByte, Char, Decimal, Double, Single, Int32, UInt32, Int64, UInt64, Object, Int16, UInt16, String, DateTime, Guid, ArrayBoolean, ArrayByte, ArraySByte, ArrayChar, ArrayDecimal, ArrayDouble, ArraySingle, ArrayInt32, ArrayUInt32, ArrayInt64, ArrayUInt64, ArrayObject, ArrayInt16, ArrayUInt16, ArrayString, ArrayDateTime, ArrayGuid, } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdGroupExtensionSettingServiceClient"/> instances.</summary> public sealed partial class AdGroupExtensionSettingServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupExtensionSettingServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupExtensionSettingServiceSettings"/>.</returns> public static AdGroupExtensionSettingServiceSettings GetDefault() => new AdGroupExtensionSettingServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupExtensionSettingServiceSettings"/> object with default settings. /// </summary> public AdGroupExtensionSettingServiceSettings() { } private AdGroupExtensionSettingServiceSettings(AdGroupExtensionSettingServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdGroupExtensionSettingSettings = existing.GetAdGroupExtensionSettingSettings; MutateAdGroupExtensionSettingsSettings = existing.MutateAdGroupExtensionSettingsSettings; OnCopy(existing); } partial void OnCopy(AdGroupExtensionSettingServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupExtensionSettingServiceClient.GetAdGroupExtensionSetting</c> and /// <c>AdGroupExtensionSettingServiceClient.GetAdGroupExtensionSettingAsync</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 GetAdGroupExtensionSettingSettings { 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> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupExtensionSettingServiceClient.MutateAdGroupExtensionSettings</c> and /// <c>AdGroupExtensionSettingServiceClient.MutateAdGroupExtensionSettingsAsync</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 MutateAdGroupExtensionSettingsSettings { 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="AdGroupExtensionSettingServiceSettings"/> object.</returns> public AdGroupExtensionSettingServiceSettings Clone() => new AdGroupExtensionSettingServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupExtensionSettingServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class AdGroupExtensionSettingServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupExtensionSettingServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupExtensionSettingServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupExtensionSettingServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupExtensionSettingServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupExtensionSettingServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupExtensionSettingServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupExtensionSettingServiceClient Build() { AdGroupExtensionSettingServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupExtensionSettingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupExtensionSettingServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupExtensionSettingServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupExtensionSettingServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupExtensionSettingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupExtensionSettingServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupExtensionSettingServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupExtensionSettingServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupExtensionSettingServiceClient.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>AdGroupExtensionSettingService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group extension settings. /// </remarks> public abstract partial class AdGroupExtensionSettingServiceClient { /// <summary> /// The default endpoint for the AdGroupExtensionSettingService 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 AdGroupExtensionSettingService scopes.</summary> /// <remarks> /// The default AdGroupExtensionSettingService 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="AdGroupExtensionSettingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupExtensionSettingServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupExtensionSettingServiceClient"/>.</returns> public static stt::Task<AdGroupExtensionSettingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupExtensionSettingServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupExtensionSettingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupExtensionSettingServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupExtensionSettingServiceClient"/>.</returns> public static AdGroupExtensionSettingServiceClient Create() => new AdGroupExtensionSettingServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupExtensionSettingServiceClient"/> 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="AdGroupExtensionSettingServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupExtensionSettingServiceClient"/>.</returns> internal static AdGroupExtensionSettingServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupExtensionSettingServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient grpcClient = new AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient(callInvoker); return new AdGroupExtensionSettingServiceClientImpl(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 AdGroupExtensionSettingService client</summary> public virtual AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupExtensionSetting GetAdGroupExtensionSetting(GetAdGroupExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(GetAdGroupExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(GetAdGroupExtensionSettingRequest request, st::CancellationToken cancellationToken) => GetAdGroupExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group extension setting to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupExtensionSetting GetAdGroupExtensionSetting(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupExtensionSetting(new GetAdGroupExtensionSettingRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group extension setting to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupExtensionSettingAsync(new GetAdGroupExtensionSettingRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group extension setting to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdGroupExtensionSettingAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group extension setting to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupExtensionSetting GetAdGroupExtensionSetting(gagvr::AdGroupExtensionSettingName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupExtensionSetting(new GetAdGroupExtensionSettingRequest { ResourceNameAsAdGroupExtensionSettingName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group extension setting to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(gagvr::AdGroupExtensionSettingName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupExtensionSettingAsync(new GetAdGroupExtensionSettingRequest { ResourceNameAsAdGroupExtensionSettingName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group extension setting to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(gagvr::AdGroupExtensionSettingName resourceName, st::CancellationToken cancellationToken) => GetAdGroupExtensionSettingAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupExtensionSettingsResponse MutateAdGroupExtensionSettings(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(MutateAdGroupExtensionSettingsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group extension settings are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group extension /// settings. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupExtensionSettingsResponse MutateAdGroupExtensionSettings(string customerId, scg::IEnumerable<AdGroupExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupExtensionSettings(new MutateAdGroupExtensionSettingsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group extension settings are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group extension /// settings. /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(string customerId, scg::IEnumerable<AdGroupExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupExtensionSettingsAsync(new MutateAdGroupExtensionSettingsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group extension settings are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group extension /// settings. /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(string customerId, scg::IEnumerable<AdGroupExtensionSettingOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupExtensionSettingsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupExtensionSettingService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group extension settings. /// </remarks> public sealed partial class AdGroupExtensionSettingServiceClientImpl : AdGroupExtensionSettingServiceClient { private readonly gaxgrpc::ApiCall<GetAdGroupExtensionSettingRequest, gagvr::AdGroupExtensionSetting> _callGetAdGroupExtensionSetting; private readonly gaxgrpc::ApiCall<MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse> _callMutateAdGroupExtensionSettings; /// <summary> /// Constructs a client wrapper for the AdGroupExtensionSettingService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupExtensionSettingServiceSettings"/> used within this client. /// </param> public AdGroupExtensionSettingServiceClientImpl(AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient grpcClient, AdGroupExtensionSettingServiceSettings settings) { GrpcClient = grpcClient; AdGroupExtensionSettingServiceSettings effectiveSettings = settings ?? AdGroupExtensionSettingServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdGroupExtensionSetting = clientHelper.BuildApiCall<GetAdGroupExtensionSettingRequest, gagvr::AdGroupExtensionSetting>(grpcClient.GetAdGroupExtensionSettingAsync, grpcClient.GetAdGroupExtensionSetting, effectiveSettings.GetAdGroupExtensionSettingSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdGroupExtensionSetting); Modify_GetAdGroupExtensionSettingApiCall(ref _callGetAdGroupExtensionSetting); _callMutateAdGroupExtensionSettings = clientHelper.BuildApiCall<MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse>(grpcClient.MutateAdGroupExtensionSettingsAsync, grpcClient.MutateAdGroupExtensionSettings, effectiveSettings.MutateAdGroupExtensionSettingsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupExtensionSettings); Modify_MutateAdGroupExtensionSettingsApiCall(ref _callMutateAdGroupExtensionSettings); 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_GetAdGroupExtensionSettingApiCall(ref gaxgrpc::ApiCall<GetAdGroupExtensionSettingRequest, gagvr::AdGroupExtensionSetting> call); partial void Modify_MutateAdGroupExtensionSettingsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse> call); partial void OnConstruction(AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient grpcClient, AdGroupExtensionSettingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupExtensionSettingService client</summary> public override AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient GrpcClient { get; } partial void Modify_GetAdGroupExtensionSettingRequest(ref GetAdGroupExtensionSettingRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAdGroupExtensionSettingsRequest(ref MutateAdGroupExtensionSettingsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdGroupExtensionSetting GetAdGroupExtensionSetting(GetAdGroupExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupExtensionSettingRequest(ref request, ref callSettings); return _callGetAdGroupExtensionSetting.Sync(request, callSettings); } /// <summary> /// Returns the requested ad group extension setting in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdGroupExtensionSetting> GetAdGroupExtensionSettingAsync(GetAdGroupExtensionSettingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupExtensionSettingRequest(ref request, ref callSettings); return _callGetAdGroupExtensionSetting.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupExtensionSettingsResponse MutateAdGroupExtensionSettings(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupExtensionSettingsRequest(ref request, ref callSettings); return _callMutateAdGroupExtensionSettings.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupExtensionSettingsRequest(ref request, ref callSettings); return _callMutateAdGroupExtensionSettings.Async(request, callSettings); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using Grpc.Core; #if USE_GRPC_NET_CLIENT using Grpc.Net.Client; #endif using UnityEngine; namespace MagicOnion.Unity { public static class GrpcChannelProviderExtensions { /// <summary> /// Create a channel to the target and register the channel under the management of the provider. /// </summary> public static GrpcChannelx CreateChannel(this IGrpcChannelProvider provider, GrpcChannelTarget target) => provider.CreateChannel(new CreateGrpcChannelContext(provider, target)); #if USE_GRPC_NET_CLIENT /// <summary> /// Create a channel to the target and register the channel under the management of the provider. /// </summary> public static GrpcChannelx CreateChannel(this IGrpcChannelProvider provider, GrpcChannelTarget target, GrpcChannelOptions channelOptions) => provider.CreateChannel(new CreateGrpcChannelContext(provider, target, channelOptions)); #endif #if !USE_GRPC_NET_CLIENT_ONLY /// <summary> /// Create a channel to the target and register the channel under the management of the provider. /// </summary> public static GrpcChannelx CreateChannel(this IGrpcChannelProvider provider, GrpcChannelTarget target, ChannelCredentials channelCredentials, IReadOnlyList<ChannelOption> channelOptions) => provider.CreateChannel(new CreateGrpcChannelContext(provider, target, new GrpcCCoreChannelOptions(channelOptions, channelCredentials))); #endif } /// <summary> /// Provide and manage gRPC channels for MagicOnion. /// </summary> public static class GrpcChannelProvider { private static IGrpcChannelProvider _defaultProvider; /// <summary> /// Gets a default channel provider. the provider will be initialized by <see cref="GrpcChannelProviderHost"/>. /// </summary> public static IGrpcChannelProvider Default => _defaultProvider ?? throw new InvalidOperationException("The default GrpcChannelProvider is not configured yet. Setup GrpcChannelProviderHost or initialize manually. "); public static void SetDefaultProvider(IGrpcChannelProvider provider) { _defaultProvider = provider; } } /// <summary> /// Provides logging for the channel provider. /// </summary> public sealed class LoggingGrpcChannelProvider : IGrpcChannelProvider { private readonly IGrpcChannelProvider _baseProvider; public LoggingGrpcChannelProvider(IGrpcChannelProvider baseProvider) { _baseProvider = baseProvider ?? throw new ArgumentNullException(nameof(baseProvider)); } public GrpcChannelx CreateChannel(CreateGrpcChannelContext context) { var channel = _baseProvider.CreateChannel(context); Debug.Log($"Channel Created: {context.Target.Host}:{context.Target.Port} ({(context.Target.IsInsecure ? "Insecure" : "Secure")}) [{channel.Id}]"); return channel; } public IReadOnlyCollection<GrpcChannelx> GetAllChannels() { return _baseProvider.GetAllChannels(); } public void UnregisterChannel(GrpcChannelx channel) { _baseProvider.UnregisterChannel(channel); Debug.Log($"Channel Unregistered: {channel.TargetUri.Host}:{channel.TargetUri.Port} [{channel.Id}]"); } public void ShutdownAllChannels() { _baseProvider.ShutdownAllChannels(); } } /// <summary> /// Provide and manage gRPC channels for MagicOnion. /// </summary> public abstract class GrpcChannelProviderBase : IGrpcChannelProvider { private readonly List<GrpcChannelx> _channels = new List<GrpcChannelx>(); private int _seq; protected abstract GrpcChannelx CreateChannelCore(int id, CreateGrpcChannelContext context); /// <summary> /// Create a channel to the target and register the channel under the management of the provider. /// </summary> public GrpcChannelx CreateChannel(CreateGrpcChannelContext context) { var channelHolder = CreateChannelCore(Interlocked.Increment(ref _seq), context); RegisterChannel(channelHolder); return channelHolder; } private void RegisterChannel(GrpcChannelx channel) { lock (_channels) { _channels.Add(channel); } } public void UnregisterChannel(GrpcChannelx channel) { lock (_channels) { _channels.Remove(channel); } } /// <summary> /// Returns all channels under the management of the provider. /// </summary> /// <returns></returns> public IReadOnlyCollection<GrpcChannelx> GetAllChannels() { lock (_channels) { return _channels.ToArray(); } } /// <summary> /// Shutdown all channels under the management of the provider. /// </summary> public void ShutdownAllChannels() { lock (_channels) { foreach (var channel in _channels.ToArray() /* snapshot */) { try { channel.Dispose(); } catch (Exception e) { Debug.LogException(e); } } } } } /// <summary> /// Provide and manage gRPC channels for MagicOnion. /// </summary> #if USE_GRPC_NET_CLIENT && USE_GRPC_NET_CLIENT_ONLY public class DefaultGrpcChannelProvider : GrpcNetClientGrpcChannelProvider { public DefaultGrpcChannelProvider() : base() {} public DefaultGrpcChannelProvider(GrpcChannelOptions channelOptions) : base(channelOptions) {} } #else public class DefaultGrpcChannelProvider : GrpcCCoreGrpcChannelProvider { public DefaultGrpcChannelProvider() : base() { } public DefaultGrpcChannelProvider(IReadOnlyList<ChannelOption> channelOptions) : base(channelOptions) { } public DefaultGrpcChannelProvider(GrpcCCoreChannelOptions channelOptions) : base(channelOptions) { } } #endif #if USE_GRPC_NET_CLIENT /// <summary> /// Provide and manage gRPC channels using Grpc.Net.Client for MagicOnion. /// </summary> public class GrpcNetClientGrpcChannelProvider : GrpcChannelProviderBase { private readonly GrpcChannelOptions _defaultChannelOptions; public GrpcNetClientGrpcChannelProvider() : this(new GrpcChannelOptions()) { } public GrpcNetClientGrpcChannelProvider(GrpcChannelOptions options) { _defaultChannelOptions = options ?? throw new ArgumentNullException(nameof(options)); } /// <summary> /// Create a channel to the target and register the channel under the management of the provider. /// </summary> protected override GrpcChannelx CreateChannelCore(int id, CreateGrpcChannelContext context) { var address = new Uri((context.Target.IsInsecure ? "http" : "https") + $"://{context.Target.Host}:{context.Target.Port}"); var channelOptions = context.ChannelOptions.Get<GrpcChannelOptions>() ?? _defaultChannelOptions; var channel = GrpcChannel.ForAddress(address, channelOptions); var channelHolder = new GrpcChannelx( id, context.Provider.UnregisterChannel /* Root provider may be wrapped outside this provider class. */, channel, address, new GrpcChannelOptionsBag(channelOptions) ); return channelHolder; } } #endif #if !USE_GRPC_NET_CLIENT_ONLY /// <summary> /// Provide and manage gRPC channels using gRPC C-core for MagicOnion. /// </summary> public class GrpcCCoreGrpcChannelProvider : GrpcChannelProviderBase { private readonly GrpcCCoreChannelOptions _defaultChannelOptions; public GrpcCCoreGrpcChannelProvider() : this(new GrpcCCoreChannelOptions()) { } public GrpcCCoreGrpcChannelProvider(IReadOnlyList<ChannelOption> channelOptions) : this(new GrpcCCoreChannelOptions(channelOptions)) { } public GrpcCCoreGrpcChannelProvider(GrpcCCoreChannelOptions channelOptions) { _defaultChannelOptions = channelOptions ?? throw new ArgumentNullException(nameof(channelOptions)); } /// <summary> /// Create a channel to the target and register the channel under the management of the provider. /// </summary> protected override GrpcChannelx CreateChannelCore(int id, CreateGrpcChannelContext context) { var channelOptions = context.ChannelOptions.Get<GrpcCCoreChannelOptions>() ?? _defaultChannelOptions; var channel = new Channel(context.Target.Host, context.Target.Port, context.Target.IsInsecure ? ChannelCredentials.Insecure : channelOptions.ChannelCredentials, channelOptions.ChannelOptions); var channelHolder = new GrpcChannelx( id, context.Provider.UnregisterChannel /* Root provider may be wrapped outside this provider class. */, channel, new Uri((context.Target.IsInsecure ? "http" : "https") + $"://{context.Target.Host}:{context.Target.Port}"), new GrpcChannelOptionsBag(channelOptions) ); return channelHolder; } } public sealed class GrpcCCoreChannelOptions { public IReadOnlyList<ChannelOption> ChannelOptions { get; set; } public ChannelCredentials ChannelCredentials { get; set; } public GrpcCCoreChannelOptions(IReadOnlyList<ChannelOption> channelOptions = null, ChannelCredentials channelCredentials = null) { ChannelOptions = channelOptions ?? Array.Empty<ChannelOption>(); ChannelCredentials = channelCredentials ?? new SslCredentials(); } } #endif }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G08_Region (editable child object).<br/> /// This is a generated base class of <see cref="G08_Region"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G09_CityObjects"/> of type <see cref="G09_CityColl"/> (1:M relation to <see cref="G10_City"/>)<br/> /// This class is an item of <see cref="G07_RegionColl"/> collection. /// </remarks> [Serializable] public partial class G08_Region : BusinessBase<G08_Region> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Regions ID"); /// <summary> /// Gets the Regions ID. /// </summary> /// <value>The Regions ID.</value> public int Region_ID { get { return GetProperty(Region_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Region_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Regions Name"); /// <summary> /// Gets or sets the Regions Name. /// </summary> /// <value>The Regions Name.</value> public string Region_Name { get { return GetProperty(Region_NameProperty); } set { SetProperty(Region_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G09_Region_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G09_Region_Child> G09_Region_SingleObjectProperty = RegisterProperty<G09_Region_Child>(p => p.G09_Region_SingleObject, "G09 Region Single Object", RelationshipTypes.Child); /// <summary> /// Gets the G09 Region Single Object ("self load" child property). /// </summary> /// <value>The G09 Region Single Object.</value> public G09_Region_Child G09_Region_SingleObject { get { return GetProperty(G09_Region_SingleObjectProperty); } private set { LoadProperty(G09_Region_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G09_Region_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G09_Region_ReChild> G09_Region_ASingleObjectProperty = RegisterProperty<G09_Region_ReChild>(p => p.G09_Region_ASingleObject, "G09 Region ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the G09 Region ASingle Object ("self load" child property). /// </summary> /// <value>The G09 Region ASingle Object.</value> public G09_Region_ReChild G09_Region_ASingleObject { get { return GetProperty(G09_Region_ASingleObjectProperty); } private set { LoadProperty(G09_Region_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G09_CityObjects"/> property. /// </summary> public static readonly PropertyInfo<G09_CityColl> G09_CityObjectsProperty = RegisterProperty<G09_CityColl>(p => p.G09_CityObjects, "G09 City Objects", RelationshipTypes.Child); /// <summary> /// Gets the G09 City Objects ("self load" child property). /// </summary> /// <value>The G09 City Objects.</value> public G09_CityColl G09_CityObjects { get { return GetProperty(G09_CityObjectsProperty); } private set { LoadProperty(G09_CityObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G08_Region"/> object. /// </summary> /// <returns>A reference to the created <see cref="G08_Region"/> object.</returns> internal static G08_Region NewG08_Region() { return DataPortal.CreateChild<G08_Region>(); } /// <summary> /// Factory method. Loads a <see cref="G08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="G08_Region"/> object.</returns> internal static G08_Region GetG08_Region(SafeDataReader dr) { G08_Region obj = new G08_Region(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G08_Region"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G08_Region() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G08_Region"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(G09_Region_SingleObjectProperty, DataPortal.CreateChild<G09_Region_Child>()); LoadProperty(G09_Region_ASingleObjectProperty, DataPortal.CreateChild<G09_Region_ReChild>()); LoadProperty(G09_CityObjectsProperty, DataPortal.CreateChild<G09_CityColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Region_IDProperty, dr.GetInt32("Region_ID")); LoadProperty(Region_NameProperty, dr.GetString("Region_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(G09_Region_SingleObjectProperty, G09_Region_Child.GetG09_Region_Child(Region_ID)); LoadProperty(G09_Region_ASingleObjectProperty, G09_Region_ReChild.GetG09_Region_ReChild(Region_ID)); LoadProperty(G09_CityObjectsProperty, G09_CityColl.GetG09_CityColl(Region_ID)); } /// <summary> /// Inserts a new <see cref="G08_Region"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G06_Country parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IG08_RegionDal>(); using (BypassPropertyChecks) { int region_ID = -1; dal.Insert( parent.Country_ID, out region_ID, Region_Name ); LoadProperty(Region_IDProperty, region_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="G08_Region"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IG08_RegionDal>(); using (BypassPropertyChecks) { dal.Update( Region_ID, Region_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="G08_Region"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IG08_RegionDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Region_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// 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.Threading; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System { // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset // is stored as an Int16 internally to save space, but presented as a TimeSpan. // // The range is constrained so that both the represented clock time and the represented // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime // for actual UTC times, and a slightly constrained range on one end when an offset is // present. // // This class should be substitutable for date time in most cases; so most operations // effectively work on the clock time. However, the underlying UTC time is what counts // for the purposes of identity, sorting and subtracting two instances. // // // There are theoretically two date times stored, the UTC and the relative local representation // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this // out and for internal readability. [StructLayout(LayoutKind.Auto)] public struct DateTimeOffset : IComparable, IFormattable, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset> { // Constants internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; internal const Int64 MinOffset = -MaxOffset; private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000 private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 // Static Fields public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero); // Instance Fields private DateTime _dateTime; private Int16 _offsetMinutes; // Constructors // Constructs a DateTimeOffset from a tick count and offset public DateTimeOffset(long ticks, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); // Let the DateTime constructor do the range checks DateTime dateTime = new DateTime(ticks); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. For UTC and Unspecified kinds, creates a // UTC instance with a zero offset. For local, extracts the local offset. public DateTimeOffset(DateTime dateTime) { TimeSpan offset; if (dateTime.Kind != DateTimeKind.Utc) { // Local and Unspecified are both treated as Local offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { offset = new TimeSpan(0); } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that // the offset corresponds to the local. public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(SR.Argument_OffsetLocalMismatch, nameof(offset)); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (offset != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_OffsetUtcMismatch, nameof(offset)); } } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond and offset public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); } // Returns a DateTimeOffset representing the current date and time. The // resolution of the returned value depends on the system timer. For // Windows NT 3.5 and later the timer resolution is approximately 10ms, // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98 // it is approximately 55ms. // public static DateTimeOffset Now { get { return new DateTimeOffset(DateTime.Now); } } public static DateTimeOffset UtcNow { get { return new DateTimeOffset(DateTime.UtcNow); } } public DateTime DateTime { get { return ClockDateTime; } } public DateTime UtcDateTime { get { return DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc); } } public DateTime LocalDateTime { get { return UtcDateTime.ToLocalTime(); } } // Adjust to a given offset with the same UTC time. Can throw ArgumentException // public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((_dateTime + offset).Ticks, offset); } // Instance Properties // The clock or visible time represented. This is just a wrapper around the internal date because this is // the chosen storage mechanism. Going through this helper is good for readability and maintainability. // This should be used for display but not identity. private DateTime ClockDateTime { get { return new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified); } } // Returns the date part of this DateTimeOffset. The resulting value // corresponds to this DateTimeOffset with the time-of-day part set to // zero (midnight). // public DateTime Date { get { return ClockDateTime.Date; } } // Returns the day-of-month part of this DateTimeOffset. The returned // value is an integer between 1 and 31. // public int Day { get { return ClockDateTime.Day; } } // Returns the day-of-week part of this DateTimeOffset. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek DayOfWeek { get { return ClockDateTime.DayOfWeek; } } // Returns the day-of-year part of this DateTimeOffset. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { return ClockDateTime.DayOfYear; } } // Returns the hour part of this DateTimeOffset. The returned value is an // integer between 0 and 23. // public int Hour { get { return ClockDateTime.Hour; } } // Returns the millisecond part of this DateTimeOffset. The returned value // is an integer between 0 and 999. // public int Millisecond { get { return ClockDateTime.Millisecond; } } // Returns the minute part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Minute { get { return ClockDateTime.Minute; } } // Returns the month part of this DateTimeOffset. The returned value is an // integer between 1 and 12. // public int Month { get { return ClockDateTime.Month; } } public TimeSpan Offset { get { return new TimeSpan(0, _offsetMinutes, 0); } } // Returns the second part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Second { get { return ClockDateTime.Second; } } // Returns the tick count for this DateTimeOffset. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return ClockDateTime.Ticks; } } public long UtcTicks { get { return UtcDateTime.Ticks; } } // Returns the time-of-day part of this DateTimeOffset. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return ClockDateTime.TimeOfDay; } } // Returns the year part of this DateTimeOffset. The returned value is an // integer between 1 and 9999. // public int Year { get { return ClockDateTime.Year; } } // Returns the DateTimeOffset resulting from adding the given // TimeSpan to this DateTimeOffset. // public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // days to this DateTimeOffset. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // hours to this DateTimeOffset. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } // Returns the DateTimeOffset resulting from the given number of // milliseconds to this DateTimeOffset. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTimeOffset. The value // argument is permitted to be negative. // public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // minutes to this DateTimeOffset. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // seconds to this DateTimeOffset. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // 100-nanosecond ticks to this DateTimeOffset. The value argument // is permitted to be negative. // public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // years to this DateTimeOffset. The result is computed by incrementing // (or decrementing) the year part of this DateTimeOffset by value // years. If the month and day of this DateTimeOffset is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTimeOffset. // public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } // Compares two DateTimeOffset values, returning an integer that indicates // their relationship. // public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } // Compares this DateTimeOffset to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // int IComparable.CompareTo(Object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); } DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime; DateTime utc = UtcDateTime; if (utc > objUtc) return 1; if (utc < objUtc) return -1; return 0; } public int CompareTo(DateTimeOffset other) { DateTime otherUtc = other.UtcDateTime; DateTime utc = UtcDateTime; if (utc > otherUtc) return 1; if (utc < otherUtc) return -1; return 0; } // Checks if this DateTimeOffset is equal to a given object. Returns // true if the given object is a boxed DateTimeOffset and its value // is equal to the value of this DateTimeOffset. Returns false // otherwise. // public override bool Equals(Object obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { // // returns true when the ClockDateTime, Kind, and Offset match // // currently the Kind should always be Unspecified, but there is always the possibility that a future version // of DateTimeOffset overloads the Kind field // return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind); } // Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is // a long representing the date and time as the number of // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. // public static DateTimeOffset FromFileTime(long fileTime) { return new DateTimeOffset(DateTime.FromFileTime(fileTime)); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { const long MinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; const long MaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; if (seconds < MinSeconds || seconds > MaxSeconds) { throw new ArgumentOutOfRangeException(nameof(seconds), string.Format(SR.ArgumentOutOfRange_Range, MinSeconds, MaxSeconds)); } long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) { throw new ArgumentOutOfRangeException(nameof(milliseconds), string.Format(SR.ArgumentOutOfRange_Range, MinMilliseconds, MaxMilliseconds)); } long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } // Returns the hash code for this DateTimeOffset. // public override int GetHashCode() { return UtcDateTime.GetHashCode(); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input) { TimeSpan offset; DateTime dateResult = FormatProvider.ParseDateTime(input, null, DateTimeStyles.None, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) { return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = FormatProvider.ParseDateTime(input, formatProvider, styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) { return ParseExact(input, format, formatProvider, DateTimeStyles.None); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = FormatProvider.ParseDateTimeExact(input, format, formatProvider, styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult = FormatProvider.ParseDateTimeExactMultiple(input, formats, formatProvider, styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { // Truncate sub-second precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times. // // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 // ticks = 621355967990010000 // ticksFromEpoch = ticks - UnixEpochTicks = -9990000 // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 // // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, // whereas we actually always want to round *down* when converting to Unix time. This happens // automatically for positive Unix time values. Now the example becomes: // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 // secondsFromEpoch = seconds - UnixEpochSeconds = -1 // // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, // rather than toward the Unix Epoch (1/1/1970 00:00:00). long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond; return seconds - UnixEpochSeconds; } public long ToUnixTimeMilliseconds() { // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond; return milliseconds - UnixEpochMilliseconds; } public DateTimeOffset ToLocalTime() { return new DateTimeOffset(UtcDateTime.ToLocalTime()); } public override String ToString() { return FormatProvider.FormatDateTime(ClockDateTime, null, null, Offset); } public String ToString(String format) { return FormatProvider.FormatDateTime(ClockDateTime, format, null, Offset); } public String ToString(IFormatProvider formatProvider) { return FormatProvider.FormatDateTime(ClockDateTime, null, formatProvider, Offset); } public String ToString(String format, IFormatProvider formatProvider) { return FormatProvider.FormatDateTime(ClockDateTime, format, formatProvider, Offset); } public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static Boolean TryParse(String input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; Boolean parsed = FormatProvider.TryParseDateTime(input, null, DateTimeStyles.None, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = FormatProvider.TryParseDateTime(input, formatProvider, styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = FormatProvider.TryParseDateTimeExact(input, format, formatProvider, styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); TimeSpan offset; DateTime dateResult; Boolean parsed = FormatProvider.TryParseDateTimeExactMultiple(input, formats, formatProvider, styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // Ensures the TimeSpan is valid to go in a DateTimeOffset. private static Int16 ValidateOffset(TimeSpan offset) { Int64 ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); } if (ticks < MinOffset || ticks > MaxOffset) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. Int64 utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); } // make sure the Kind is set to Unspecified // return new DateTime(utcTicks, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName); } if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName); } // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatability with DateTime style &= ~DateTimeStyles.RoundtripKind; // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse style &= ~DateTimeStyles.AssumeLocal; return style; } // Operators public static implicit operator DateTimeOffset(DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Avalonia.Platform; namespace Avalonia.Shared.PlatformSupport { /// <summary> /// Loads assets compiled into the application binary. /// </summary> public class AssetLoader : IAssetLoader { private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache = new Dictionary<string, AssemblyDescriptor>(); private AssemblyDescriptor _defaultAssembly; public AssetLoader(Assembly assembly = null) { if (assembly == null) assembly = Assembly.GetEntryAssembly(); if (assembly != null) _defaultAssembly = new AssemblyDescriptor(assembly); } public void SetDefaultAssembly(Assembly assembly) { _defaultAssembly = new AssemblyDescriptor(assembly); } /// <summary> /// Checks if an asset with the specified URI exists. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns>True if the asset could be found; otherwise false.</returns> public bool Exists(Uri uri, Uri baseUri = null) { return GetAsset(uri, baseUri) != null; } /// <summary> /// Opens the resource with the requested URI. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns>A stream containing the resource contents.</returns> /// <exception cref="FileNotFoundException"> /// The resource was not found. /// </exception> public Stream Open(Uri uri, Uri baseUri = null) { var asset = GetAsset(uri, baseUri); if (asset == null) { throw new FileNotFoundException($"The resource {uri} could not be found."); } return asset.GetStream(); } private IAssetDescriptor GetAsset(Uri uri, Uri baseUri) { if (!uri.IsAbsoluteUri || uri.Scheme == "resm") { var uriQueryParams = ParseQueryString(uri); var baseUriQueryParams = uri != null ? ParseQueryString(uri) : null; var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultAssembly; if (asm == null && _defaultAssembly == null) { throw new ArgumentException( "No default assembly, entry assembly or explicit assembly specified; " + "don't know where to look up for the resource, try specifiyng assembly explicitly."); } IAssetDescriptor rv; var resourceKey = uri.AbsolutePath; #if __IOS__ // TODO: HACK: to get iOS up and running. Using Shared projects for resources // is flawed as this alters the reource key locations across platforms // I think we need to use Portable libraries from now on to avoid that. if(asm.Name.Contains("iOS")) { resourceKey = resourceKey.Replace("TestApplication", "Avalonia.iOSTestApplication"); } #endif asm.Resources.TryGetValue(resourceKey, out rv); return rv; } throw new ArgumentException($"Invalid uri, see https://github.com/AvaloniaUI/Avalonia/issues/282#issuecomment-166982104", nameof(uri)); } private AssemblyDescriptor GetAssembly(Uri uri) { if (uri != null) { var qs = ParseQueryString(uri); string assemblyName; if (qs.TryGetValue("assembly", out assemblyName)) { return GetAssembly(assemblyName); } } return null; } private AssemblyDescriptor GetAssembly(string name) { if (name == null) { return _defaultAssembly; } AssemblyDescriptor rv; if (!AssemblyNameCache.TryGetValue(name, out rv)) { var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name); if (match != null) { AssemblyNameCache[name] = rv = new AssemblyDescriptor(match); } else { // iOS does not support loading assemblies dynamically! // #if !__IOS__ AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name)); #endif } } return rv; } private Dictionary<string, string> ParseQueryString(Uri uri) { return uri.Query.TrimStart('?') .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Split('=')) .ToDictionary(p => p[0], p => p[1]); } private interface IAssetDescriptor { Stream GetStream(); } private class AssemblyResourceDescriptor : IAssetDescriptor { private readonly Assembly _asm; private readonly string _name; public AssemblyResourceDescriptor(Assembly asm, string name) { _asm = asm; _name = name; } public Stream GetStream() { return _asm.GetManifestResourceStream(_name); } } private class AssemblyDescriptor { public AssemblyDescriptor(Assembly assembly) { Assembly = assembly; if (assembly != null) { Resources = assembly.GetManifestResourceNames() .ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n)); Name = assembly.GetName().Name; } } public Assembly Assembly { get; } public Dictionary<string, IAssetDescriptor> Resources { get; } public string Name { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers.Text; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Globalization { internal static class TimeSpanFormat { internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false); internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true); /// <summary>Main method called from TimeSpan.ToString.</summary> internal static string Format(TimeSpan value, string? format, IFormatProvider? formatProvider) { if (string.IsNullOrEmpty(format)) { return FormatC(value); // formatProvider ignored, as "c" is invariant } if (format.Length == 1) { char c = format[0]; if (c == 'c' || (c | 0x20) == 't') // special-case to optimize the default TimeSpan format { return FormatC(value); // formatProvider ignored, as "c" is invariant } if ((c | 0x20) == 'g') // special-case to optimize the remaining 'g'/'G' standard formats { return FormatG(value, DateTimeFormatInfo.GetInstance(formatProvider), c == 'G' ? StandardFormat.G : StandardFormat.g); } throw new FormatException(SR.Format_InvalidString); } return StringBuilderCache.GetStringAndRelease(FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null)); } /// <summary>Main method called from TimeSpan.TryFormat.</summary> internal static bool TryFormat(TimeSpan value, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? formatProvider) { if (format.Length == 0) { return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten); } if (format.Length == 1) { char c = format[0]; if (c == 'c' || ((c | 0x20) == 't')) { return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten); } else { StandardFormat sf = c == 'g' ? StandardFormat.g : c == 'G' ? StandardFormat.G : throw new FormatException(SR.Format_InvalidString); return TryFormatStandard(value, sf, DateTimeFormatInfo.GetInstance(formatProvider).DecimalSeparator, destination, out charsWritten); } } StringBuilder sb = FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null); if (sb.Length <= destination.Length) { sb.CopyTo(0, destination, sb.Length); charsWritten = sb.Length; StringBuilderCache.Release(sb); return true; } charsWritten = 0; StringBuilderCache.Release(sb); return false; } internal static string FormatC(TimeSpan value) { Span<char> destination = stackalloc char[26]; // large enough for any "c" TimeSpan TryFormatStandard(value, StandardFormat.C, null, destination, out int charsWritten); return new string(destination.Slice(0, charsWritten)); } private static string FormatG(TimeSpan value, DateTimeFormatInfo dtfi, StandardFormat format) { string decimalSeparator = dtfi.DecimalSeparator; int maxLength = 25 + decimalSeparator.Length; // large enough for any "g"/"G" TimeSpan Span<char> destination = maxLength < 128 ? stackalloc char[maxLength] : new char[maxLength]; // the chances of needing this case are almost 0, as DecimalSeparator.Length will basically always == 1 TryFormatStandard(value, format, decimalSeparator, destination, out int charsWritten); return new string(destination.Slice(0, charsWritten)); } private enum StandardFormat { C, G, g } private static bool TryFormatStandard(TimeSpan value, StandardFormat format, string? decimalSeparator, Span<char> destination, out int charsWritten) { Debug.Assert(format == StandardFormat.C || format == StandardFormat.G || format == StandardFormat.g); // First, calculate how large an output buffer is needed to hold the entire output. int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary uint fraction; ulong totalSecondsRemaining; { // Turn this into a non-negative TimeSpan if possible. long ticks = value.Ticks; if (ticks < 0) { requiredOutputLength = 9; // requiredOutputLength + 1 for the leading '-' sign ticks = -ticks; if (ticks < 0) { Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */); // We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue. fraction = 4775808; totalSecondsRemaining = 922337203685; goto AfterComputeFraction; } } totalSecondsRemaining = Math.DivRem((ulong)ticks, TimeSpan.TicksPerSecond, out ulong fraction64); fraction = (uint)fraction64; } AfterComputeFraction: // Only write out the fraction if it's non-zero, and in that // case write out the entire fraction (all digits). Debug.Assert(fraction < 10_000_000); int fractionDigits = 0; switch (format) { case StandardFormat.C: // "c": Write out a fraction only if it's non-zero, and write out all 7 digits of it. if (fraction != 0) { fractionDigits = DateTimeFormat.MaxSecondsFractionDigits; requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator } break; case StandardFormat.G: // "G": Write out a fraction regardless of whether it's 0, and write out all 7 digits of it. fractionDigits = DateTimeFormat.MaxSecondsFractionDigits; requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator break; default: // "g": Write out a fraction only if it's non-zero, and write out only the most significant digits. Debug.Assert(format == StandardFormat.g); if (fraction != 0) { fractionDigits = DateTimeFormat.MaxSecondsFractionDigits - FormattingHelpers.CountDecimalTrailingZeros(fraction, out fraction); requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator } break; } ulong totalMinutesRemaining = 0, seconds = 0; if (totalSecondsRemaining > 0) { // Only compute minutes if the TimeSpan has an absolute value of >= 1 minute. totalMinutesRemaining = Math.DivRem(totalSecondsRemaining, 60 /* seconds per minute */, out seconds); Debug.Assert(seconds < 60); } ulong totalHoursRemaining = 0, minutes = 0; if (totalMinutesRemaining > 0) { // Only compute hours if the TimeSpan has an absolute value of >= 1 hour. totalHoursRemaining = Math.DivRem(totalMinutesRemaining, 60 /* minutes per hour */, out minutes); Debug.Assert(minutes < 60); } // At this point, we can switch over to 32-bit DivRem since the data has shrunk far enough. Debug.Assert(totalHoursRemaining <= uint.MaxValue); uint days = 0, hours = 0; if (totalHoursRemaining > 0) { // Only compute days if the TimeSpan has an absolute value of >= 1 day. days = Math.DivRem((uint)totalHoursRemaining, 24 /* hours per day */, out hours); Debug.Assert(hours < 24); } int hourDigits = 2; if (format == StandardFormat.g && hours < 10) { // "g": Only writing a one-digit hour, rather than expected two-digit hour hourDigits = 1; requiredOutputLength--; } int dayDigits = 0; if (days > 0) { dayDigits = FormattingHelpers.CountDigits(days); Debug.Assert(dayDigits <= 8); requiredOutputLength += dayDigits + 1; // for the leading "d." } else if (format == StandardFormat.G) { // "G": has a leading "0:" if days is 0 requiredOutputLength += 2; dayDigits = 1; } if (destination.Length < requiredOutputLength) { charsWritten = 0; return false; } // Write leading '-' if necessary int idx = 0; if (value.Ticks < 0) { destination[idx++] = '-'; } // Write day and separator, if necessary if (dayDigits != 0) { WriteDigits(days, destination.Slice(idx, dayDigits)); idx += dayDigits; destination[idx++] = format == StandardFormat.C ? '.' : ':'; } // Write "[h]h:mm:ss Debug.Assert(hourDigits == 1 || hourDigits == 2); if (hourDigits == 2) { WriteTwoDigits(hours, destination.Slice(idx)); idx += 2; } else { destination[idx++] = (char)('0' + hours); } destination[idx++] = ':'; WriteTwoDigits((uint)minutes, destination.Slice(idx)); idx += 2; destination[idx++] = ':'; WriteTwoDigits((uint)seconds, destination.Slice(idx)); idx += 2; // Write fraction and separator, if necessary if (fractionDigits != 0) { Debug.Assert(format == StandardFormat.C || decimalSeparator != null); if (format == StandardFormat.C) { destination[idx++] = '.'; } else if (decimalSeparator!.Length == 1) { destination[idx++] = decimalSeparator[0]; } else { decimalSeparator.AsSpan().CopyTo(destination); idx += decimalSeparator.Length; } WriteDigits(fraction, destination.Slice(idx, fractionDigits)); idx += fractionDigits; } Debug.Assert(idx == requiredOutputLength); charsWritten = requiredOutputLength; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTwoDigits(uint value, Span<char> buffer) { Debug.Assert(buffer.Length >= 2); uint temp = '0' + value; value /= 10; buffer[1] = (char)(temp - (value * 10)); buffer[0] = (char)('0' + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteDigits(uint value, Span<char> buffer) { Debug.Assert(buffer.Length > 0); for (int i = buffer.Length - 1; i >= 1; i--) { uint temp = '0' + value; value /= 10; buffer[i] = (char)(temp - (value * 10)); } Debug.Assert(value < 10); buffer[0] = (char)('0' + value); } /// <summary>Format the TimeSpan instance using the specified format.</summary> private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, StringBuilder? result = null) { Debug.Assert(dtfi != null); bool resultBuilderIsPooled = false; if (result == null) { result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); resultBuilderIsPooled = true; } int day = (int)(value.Ticks / TimeSpan.TicksPerDay); long time = value.Ticks % TimeSpan.TicksPerDay; if (value.Ticks < 0) { day = -day; time = -time; } int hours = (int)(time / TimeSpan.TicksPerHour % 24); int minutes = (int)(time / TimeSpan.TicksPerMinute % 60); int seconds = (int)(time / TimeSpan.TicksPerSecond % 60); int fraction = (int)(time % TimeSpan.TicksPerSecond); long tmp = 0; int i = 0; int tokenLen; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'h': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, hours, tokenLen); break; case 'm': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, minutes, tokenLen); break; case 's': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, seconds, tokenLen); break; case 'f': // // The fraction of a second in single-digit precision. The remaining digits are truncated. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits) { goto default; // to release the builder and throw } tmp = fraction; tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen); result.AppendSpanFormattable(tmp, DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture); break; case 'F': // // Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits) { goto default; // to release the builder and throw } tmp = fraction; tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen); int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (tmp % 10 == 0) { tmp /= 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.AppendSpanFormattable(tmp, DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture); } break; case 'd': // // tokenLen == 1 : Day as digits with no leading zero. // tokenLen == 2+: Day as digits with leading zero for single-digit days. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 8) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, day, tokenLen, true); break; case '\'': case '\"': tokenLen = DateTimeFormat.ParseQuoteString(format, i, result); break; case '%': // Optional format character. // For example, format string "%d" will print day // Most of the cases, "%" can be ignored. nextChar = DateTimeFormat.ParseNextChar(format, i); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if (nextChar >= 0 && nextChar != (int)'%') { char nextCharChar = (char)nextChar; StringBuilder origStringBuilder = FormatCustomized(value, MemoryMarshal.CreateReadOnlySpan<char>(ref nextCharChar, 1), dtfi, result); Debug.Assert(ReferenceEquals(origStringBuilder, result)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // goto default; // to release the builder and throw } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For example, "\d" will insert the character 'd' into the string. // nextChar = DateTimeFormat.ParseNextChar(format, i); if (nextChar >= 0) { result.Append((char)nextChar); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // goto default; // to release the builder and throw } break; default: // Invalid format string if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } i += tokenLen; } return result; } internal struct FormatLiterals { internal string AppCompatLiteral; internal int dd; internal int hh; internal int mm; internal int ss; internal int ff; private string[] _literals; internal string Start => _literals[0]; internal string DayHourSep => _literals[1]; internal string HourMinuteSep => _literals[2]; internal string MinuteSecondSep => _literals[3]; internal string SecondFractionSep => _literals[4]; internal string End => _literals[5]; /* factory method for static invariant FormatLiterals */ internal static FormatLiterals InitInvariant(bool isNegative) { FormatLiterals x = new FormatLiterals(); x._literals = new string[6]; x._literals[0] = isNegative ? "-" : string.Empty; x._literals[1] = "."; x._literals[2] = ":"; x._literals[3] = ":"; x._literals[4] = "."; x._literals[5] = string.Empty; x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep; x.dd = 2; x.hh = 2; x.mm = 2; x.ss = 2; x.ff = DateTimeFormat.MaxSecondsFractionDigits; return x; } // For the "v1" TimeSpan localized patterns, the data is simply literal field separators with // the constants guaranteed to include DHMSF ordered greatest to least significant. // Once the data becomes more complex than this we will need to write a proper tokenizer for // parsing and formatting internal void Init(ReadOnlySpan<char> format, bool useInvariantFieldLengths) { dd = hh = mm = ss = ff = 0; _literals = new string[6]; for (int i = 0; i < _literals.Length; i++) { _literals[i] = string.Empty; } StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); bool inQuote = false; char quote = '\''; int field = 0; for (int i = 0; i < format.Length; i++) { switch (format[i]) { case '\'': case '\"': if (inQuote && (quote == format[i])) { /* we were in a quote and found a matching exit quote, so we are outside a quote now */ if (field >= 0 && field <= 5) { _literals[field] = sb.ToString(); sb.Length = 0; inQuote = false; } else { Debug.Fail($"Unexpected field value: {field}"); return; // how did we get here? } } else if (!inQuote) { /* we are at the start of a new quote block */ quote = format[i]; inQuote = true; } else { /* we were in a quote and saw the other type of quote character, so we are still in a quote */ } break; case '%': Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); goto default; case '\\': if (!inQuote) { i++; /* skip next character that is escaped by this backslash or percent sign */ break; } goto default; case 'd': if (!inQuote) { Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 1; // DayHourSep dd++; } break; case 'h': if (!inQuote) { Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 2; // HourMinuteSep hh++; } break; case 'm': if (!inQuote) { Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 3; // MinuteSecondSep mm++; } break; case 's': if (!inQuote) { Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 4; // SecondFractionSep ss++; } break; case 'f': case 'F': if (!inQuote) { Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 5; // End ff++; } break; default: sb.Append(format[i]); break; } } Debug.Assert(field == 5); AppCompatLiteral = MinuteSecondSep + SecondFractionSep; Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); if (useInvariantFieldLengths) { dd = 2; hh = 2; mm = 2; ss = 2; ff = DateTimeFormat.MaxSecondsFractionDigits; } else { if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation. if (hh < 1 || hh > 2) hh = 2; if (mm < 1 || mm > 2) mm = 2; if (ss < 1 || ss > 2) ss = 2; if (ff < 1 || ff > 7) ff = 7; } StringBuilderCache.Release(sb); } } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using ESRI.ArcLogistics.Data; using ESRI.ArcLogistics.DomainObjects; using ESRI.ArcLogistics.Routing.Json; using ESRI.ArcLogistics.Services; using ESRI.ArcLogistics.Utility.CoreEx; namespace ESRI.ArcLogistics.Routing { /// <summary> /// Solve statistics keeper class. /// </summary> internal class SolveStatistics { /// <summary> /// Request time. /// </summary> public TimeSpan RequestTime { get; internal set; } } /// <summary> /// VRP result keeper class. /// </summary> internal class VrpResult { /// <summary> /// Gets a reference to the collection of job messages received from /// VRP service. /// </summary> public JobMessage[] Messages { get; internal set; } /// <summary> /// Gets a reference to the route solve response. /// </summary> public BatchRouteSolveResponse RouteResponse { get; internal set; } /// <summary> /// Gets a reference to the VRP results. Could be null if there are no /// results for some reason (e.g. all submitted orders have violations). /// </summary> public GPRouteResult ResultObjects { get; internal set; } /// <summary> /// Gets a solve operation HResult from server. /// </summary> public int SolveHR { get; internal set; } } /// <summary> /// Base VRP operation implementation class. /// </summary> internal abstract class VrpOperation : ISolveOperation<SubmitVrpJobRequest> { #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Create a new instance of the <c>VrpOperation</c> class. /// </summary> /// <param name="context">Solver context.</param> /// <param name="schedule">Current schedule.</param> /// <param name="options">Solve options.</param> public VrpOperation(SolverContext context, Schedule schedule, SolveOptions options) { _context = context; _schedule = schedule; _options = options; } #endregion constructors #region ISolveOperation<TSolveRequest> Members /// <summary> /// Related schedule. /// </summary> public Schedule Schedule { get { return _schedule; } } /// <summary> /// Solve operation type. /// </summary> public abstract SolveOperationType OperationType { get; } /// <summary> /// Input parameters. /// </summary> public abstract Object InputParams { get; } /// <summary> /// Checks - can get result without solve. /// </summary> public virtual bool CanGetResultWithoutSolve { get { return false; } } /// <summary> /// Creates result without solve. /// </summary> /// <returns>Always NULL.</returns> public virtual SolveResult CreateResultWithoutSolve() { return null; } /// <summary> /// Creates request. /// </summary> /// <returns>Created VRP request.</returns> public SubmitVrpJobRequest CreateRequest() { // check number of allowed routes _CheckLicensePermissions(); // get orders and routes to solve SolveRequestData reqData = this.RequestData; // validate request data _ValidateReqData(reqData); // build request SubmitVrpJobRequest req = BuildRequest(reqData); // set operation info for logging req.OperationType = this.OperationType; req.OperationDate = (DateTime)_schedule.PlannedDate; if (req.PointBarriers != null) _pointBarriers = req.PointBarriers.Features; if (req.LineBarriers != null) _polylineBarriers = req.LineBarriers.Features; if (req.PolygonBarriers != null) _polygonBarriers = req.PolygonBarriers.Features; return req; } /// <summary> /// Does solve. /// </summary> /// <param name="jobRequest">VRP request.</param> /// <param name="cancelTracker">Cancel tracker (Can be NULL).</param> /// <returns>Function returning VRP solve operation result.</returns> public Func<SolveOperationResult<SubmitVrpJobRequest>> Solve( SubmitVrpJobRequest jobRequest, ICancelTracker cancelTracker) { Debug.Assert(null != jobRequest); var result = default(VrpResult); var resultProvider = Functional.MakeLambda(() => { var operationResult = new SolveOperationResult<SubmitVrpJobRequest>(); operationResult.SolveResult = _ProcessSolveResult(result, jobRequest); operationResult.NextStepOperation = _nextStep; return operationResult; }); if (jobRequest.Orders.Features.Length == 0) { result = new VrpResult() { SolveHR = 0, }; return resultProvider; } var factory = _context.VrpServiceFactory; using (var client = factory.CreateService(VrpRequestBuilder.JsonTypes)) { var requestTime = new Stopwatch(); requestTime.Start(); // send request var response = _SendRequest( client, jobRequest, cancelTracker); // create VRP result result = new VrpResult() { Messages = response.Messages, SolveHR = response.SolveHR, ResultObjects = response.RouteResult, }; if (CanProcessResult(result.SolveHR)) { _ValidateVrpResults(response); // calc. statistics requestTime.Stop(); var stat = new SolveStatistics() { RequestTime = requestTime.Elapsed }; _LogJobStatistics(response.JobID, stat); } if (!_options.GenerateDirections && result.ResultObjects != null) { result.ResultObjects.Directions = null; } return resultProvider; } } #endregion #region protected properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Solver context. /// </summary> protected SolverContext SolverContext { get { return _context; } } /// <summary> /// Solve options. /// </summary> protected SolveOptions Options { get { return _options; } } #endregion protected properties #region protected abstract properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Request data. /// </summary> protected abstract SolveRequestData RequestData { get; } #endregion protected abstract properties #region protected abstract methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Creates operation. /// </summary> /// <param name="reqData">Solve request data.</param> /// <param name="violations">List of violations.</param> /// <returns>Created VRP opeartion.</returns> protected abstract VrpOperation CreateOperation(SolveRequestData reqData, List<Violation> violations); #endregion protected abstract methods #region protected overridable properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Request builder. /// </summary> protected virtual VrpRequestBuilder RequestBuilder { get { return new VrpRequestBuilder(_context); } } /// <summary> /// Request options. /// </summary> protected virtual SolveRequestOptions RequestOptions { get { var opt = new SolveRequestOptions(); // TODO: configure proper parameter in model opt.PopulateRouteLines = _options.GenerateDirections; opt.ConvertUnassignedOrders = true; return opt; } } #endregion protected overridable properties #region protected overridable methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Builds request. /// </summary> /// <param name="reqData">Solve request data.</param> /// <returns>Submit VRP job request.</returns> protected virtual SubmitVrpJobRequest BuildRequest(SolveRequestData reqData) { return this.RequestBuilder.BuildRequest( _schedule, reqData, this.RequestOptions, this.Options); } /// <summary> /// Checks - can process result. /// </summary> /// <param name="solveHR">Solve operation HResult from server.</param> /// <returns>TRUE if can process result.</returns> protected virtual bool CanProcessResult(int solveHR) { return ComHelper.IsHRSucceeded(solveHR) || solveHR == (int)NAError.E_NA_VRP_SOLVER_EMPTY_INFEASIBLE_ROUTES || solveHR == (int)NAError.E_NA_VRP_SOLVER_PREASSIGNED_INFEASIBLE_ROUTES || solveHR == (int)NAError.E_NA_VRP_SOLVER_NO_SOLUTION || solveHR == (int)NAError.E_NA_VRP_SOLVER_INVALID_INPUT; } /// <summary> /// Checks - can convert result. /// </summary> /// <param name="solveHR">Solve operation HResult from server.</param> /// <returns>TRUE if HResult is succeeded.</returns> protected virtual bool CanConvertResult(int solveHR) { return ComHelper.IsHRSucceeded(solveHR); } /// <summary> /// Checks - is solve succeeded. /// </summary> /// <param name="solveHR">Solve operation HResult from server.</param> /// <returns>TRUE if solve operation succeeded on server.</returns> protected virtual bool IsSolveSucceeded(int solveHR) { return CanConvertResult(solveHR); } /// <summary> /// Processes result. /// </summary> /// <param name="vrpResult">VRP solve operation result.</param> /// <param name="request">Request used for obtaining the response.</param> /// <returns>Founded violations.</returns> protected virtual List<Violation> ProcessResult( VrpResult vrpResult, SubmitVrpJobRequest request) { Debug.Assert(vrpResult != null); Debug.Assert(request != null); // get violations List<Violation> violations = GetViolations(vrpResult); VrpOperation nextStep = null; if (CanConvertResult(vrpResult.SolveHR)) { if (vrpResult.ResultObjects != null) { // convert VRP result IList<RouteResult> routeResults = ConvertResult(vrpResult, request); // check if we need next step nextStep = GetNextStepOperation(routeResults, violations); if (nextStep == null) SetRouteResults(routeResults); // final step, set results to schedule } } else if (!_options.FailOnInvalidOrderGeoLocation) { if (!_HasRestrictedDepots(violations)) { List<Order> restrictedOrders = _GetRestrictedOrders(violations); if (restrictedOrders.Count > 0) nextStep = _GetRestrictedOrdersOperation(restrictedOrders, violations); } } _nextStep = nextStep; return violations; } /// <summary> /// Gets next step operation. /// </summary> /// <param name="routeResults">Route's result.</param> /// <param name="violations">Violations.</param> /// <returns>Next step operation otr NULL if not supported.</returns> protected virtual VrpOperation GetNextStepOperation( IList<RouteResult> routeResults, List<Violation> violations) { return null; } /// <summary> /// Gets violations. /// </summary> /// <param name="vrpResult">VRP solve operation result.</param> /// <returns>Founded violations.</returns> protected virtual List<Violation> GetViolations(VrpResult vrpResult) { Debug.Assert(null != vrpResult); var list = new List<Violation>(); var conv = new VrpResultConverter(_context.Project, _schedule, _context.SolverSettings); var results = vrpResult.ResultObjects; int hr = vrpResult.SolveHR; if (ComHelper.IsHRSucceeded(hr) && vrpResult.ResultObjects != null) list.AddRange(conv.GetOrderViolations(results.ViolatedStops, hr)); else if (hr == (int)NAError.E_NA_VRP_SOLVER_EMPTY_INFEASIBLE_ROUTES) list.AddRange(conv.GetRouteViolations(results.Routes, hr)); else if (hr == (int)NAError.E_NA_VRP_SOLVER_NO_SOLUTION) list.AddRange(conv.GetOrderViolations(results.ViolatedStops, hr)); else if (hr == (int)NAError.E_NA_VRP_SOLVER_PREASSIGNED_INFEASIBLE_ROUTES) { list.AddRange(conv.GetRouteViolations(results.Routes, hr)); list.AddRange(conv.GetOrderViolations(results.ViolatedStops, hr)); } else if (hr == (int)NAError.E_NA_VRP_SOLVER_INVALID_INPUT) { list.AddRange(conv.GetDepotViolations(results.ViolatedStops)); list.AddRange(conv.GetRestrictedOrderViolations(results.ViolatedStops)); } return list; } /// <summary> /// Converts VRP operation result to route's result. /// </summary> /// <param name="vrpResult">VRP solve operation result.</param> /// <param name="request">Request used for obtaining the response.</param> /// <returns>Route results.</returns> protected virtual IList<RouteResult> ConvertResult( VrpResult vrpResult, SubmitVrpJobRequest request) { Debug.Assert(vrpResult != null); Debug.Assert(request != null); var conv = new VrpResultConverter(_context.Project, _schedule, _context.SolverSettings); return conv.Convert(vrpResult.ResultObjects, vrpResult.RouteResponse, request); } /// <summary> /// Sets route's results. /// </summary> /// <param name="routeResults">Route's results</param> protected virtual void SetRouteResults(IList<RouteResult> routeResults) { // get locked orders var lockedOrders = new List<Order>(); foreach (Route route in _schedule.Routes) { foreach (Stop stop in route.Stops) { if (stop.StopType == StopType.Order && stop.IsLocked) lockedOrders.Add(stop.AssociatedObject as Order); } } // set locked status to new stops foreach (RouteResult rr in routeResults) { foreach (StopData stop in rr.Stops) { if (stop.StopType == StopType.Order && lockedOrders.Contains(stop.AssociatedObject as Order)) { stop.IsLocked = true; } } } // set route results to schedule _context.Project.Schedules.SetRouteResults(_schedule, routeResults); } #endregion protected overridable methods #region private methods /// <summary> /// Processes (converts) solve operation result. /// </summary> /// <param name="vrpResult">VRP solve operation result.</param> /// <param name="request">Request used for obtaining the response.</param> /// <returns>Solve operation result.</returns> private SolveResult _ProcessSolveResult(VrpResult vrpResult, SubmitVrpJobRequest request) { Debug.Assert(vrpResult != null); Debug.Assert(request != null); List<Violation> violations = null; if (CanProcessResult(vrpResult.SolveHR)) violations = ProcessResult(vrpResult, request); return _CreateSolveResult(vrpResult, violations); } /// <summary> /// Converts job submitting response into the result of synchronous /// job execution. /// </summary> /// <param name="response">The reference to the response object to /// be converted.</param> /// <param name="client">The reference to the REST service client object /// to retrieve job results with.</param> /// <param name="cancelTracker">The reference to the cancellation tracker /// object.</param> /// <returns><see cref="T:ESRI.ArcLogistics.Routing.Json.VrpResultsResponse"/> /// object corresponding to the specified job submitting response.</returns> private VrpResultsResponse _ConvertToSyncReponse( GetVrpJobResultResponse response, IVrpRestService client, ICancelTracker cancelTracker) { var syncResponse = new VrpResultsResponse() { SolveSucceeded = false, JobID = response.JobId, }; syncResponse.SolveSucceeded = false; syncResponse.Messages = response.Messages; syncResponse.SolveHR = HResult.E_FAIL; if (response.JobStatus != NAJobStatus.esriJobSucceeded) { return syncResponse; } var solveSucceeded = _GetGPObject<GPBoolParam>( client, response.JobId, response.Outputs.SolveSucceeded.ParamUrl); syncResponse.SolveSucceeded = solveSucceeded.Value; syncResponse.SolveHR = _GetSolveHR(syncResponse); if (CanProcessResult(syncResponse.SolveHR)) { _ValidateResponse(response); // get route results syncResponse.RouteResult = _LoadResultData( client, response, cancelTracker); } return syncResponse; } /// <summary> /// Sends request to the VRP REST service using either syncronous or /// asynchronous service depending on the request. /// </summary> /// <param name="client">The reference to the REST service client object /// to send requests with.</param> /// <param name="request">The request to be sent to the VRP service.</param> /// <param name="tracker">The reference to the cancellation tracker /// object.</param> /// <returns>Result of the request processing by the VRP REST service.</returns> private VrpResultsResponse _SendRequest( IVrpRestService client, SubmitVrpJobRequest request, ICancelTracker tracker) { if (_context.VrpRequestAnalyzer.CanExecuteSyncronously(request)) { var response = client.ExecuteJob(request); return _GetVrpResults(response); } var asyncResponse = _SendAsyncRequest(client, request, tracker); return _ConvertToSyncReponse(asyncResponse, client, tracker); } /// <summary> /// Sends async. request to the VRP REST service using either asynchronous service /// depending on the request. /// </summary> /// <param name="context">The reference to the VRP REST service context.</param> /// <param name="request">The request to be sent to the VRP service.</param> /// <param name="tracker">The reference to the cancellation tracker object.</param> /// <returns>Result of the request processing by the VRP REST service.</returns> private GetVrpJobResultResponse _SendAsyncRequest( IVrpRestService context, SubmitVrpJobRequest request, ICancelTracker tracker) { Debug.Assert(context != null); Debug.Assert(request != null); // check cancellation state _CheckCancelState(tracker); GetVrpJobResultResponse resp = null; try { // submit job resp = _SubmitJob(context, request); // poll job status bool jobCompleted = false; do { // check cancellation state _CheckCancelState(tracker); // check job status if (resp.JobStatus == NAJobStatus.esriJobFailed || resp.JobStatus == NAJobStatus.esriJobSucceeded || resp.JobStatus == NAJobStatus.esriJobCancelled) { // job completed jobCompleted = true; _LogResponse(resp); } else { // TODO: limit number of retries or total request time // job is still executing, make timeout Thread.Sleep(RETRY_DELAY); // check cancellation state _CheckCancelState(tracker); string jobId = resp.JobId; try { // try to get job result resp = _GetJobResult(context, jobId); } catch (Exception e) { _LogJobError(jobId, e); if (!ServiceHelper.IsCommunicationError(e)) throw; } } } while (!jobCompleted); } catch (UserBreakException) { if (resp != null) _CancelJob(context, resp.JobId); // cancel job on server throw; } return resp; } /// <summary> /// Loads result data from response from the VRP REST service. /// </summary> /// <param name="client">The reference to the REST service client object /// to send requests with.</param> /// <param name="resp">The response from the VRP service.</param> /// <param name="tracker">The reference to the cancellation tracker /// object.</param> /// <returns>Result of the response GP route.</returns> private GPRouteResult _LoadResultData( IVrpRestService client, GetVrpJobResultResponse resp, ICancelTracker tracker) { Debug.Assert(client != null); Debug.Assert(resp != null); // get output routes _CheckCancelState(tracker); var routesParam = _GetGPObject<GPFeatureRecordSetLayerParam>( client, resp.JobId, resp.Outputs.Routes.ParamUrl); // get output stops _CheckCancelState(tracker); var stopsParam = _GetGPObject<GPRecordSetParam>( client, resp.JobId, resp.Outputs.Stops.ParamUrl); // get unassigned orders _CheckCancelState(tracker); var violatedStopsParam = _GetGPObject<GPRecordSetParam>( client, resp.JobId, resp.Outputs.ViolatedStops.ParamUrl); // Get directions. _CheckCancelState(tracker); var directionsParam = _GetGPObject<GPFeatureRecordSetLayerParam>( client, resp.JobId, resp.Outputs.Directions.ParamUrl); GPRouteResult result = new GPRouteResult(); result.Routes = routesParam.Value; result.Stops = stopsParam.Value; result.ViolatedStops = violatedStopsParam.Value; result.Directions = directionsParam.Value; return result; } private GetVrpJobResultResponse _SubmitJob( IVrpRestService client, SubmitVrpJobRequest request) { Debug.Assert(client != null); Debug.Assert(request != null); GetVrpJobResultResponse response = null; try { response = client.SubmitJob(request); } catch (RestException e) { _LogServiceError(e); throw SolveHelper.ConvertServiceException( Properties.Messages.Error_SubmitJobFailed, e); } return response; } private GetVrpJobResultResponse _GetJobResult( IVrpRestService client, string jobId) { Debug.Assert(client != null); Debug.Assert(jobId != null); GetVrpJobResultResponse response = null; try { response = client.GetJobResult(jobId); } catch (RestException e) { _LogServiceError(e); throw SolveHelper.ConvertServiceException( String.Format(Properties.Messages.Erorr_GetJobResult, jobId), e); } return response; } private T _GetGPObject<T>( IVrpRestService client, string jobId, string objectUrl) where T : IFaultInfo { Debug.Assert(client != null); Debug.Assert(jobId != null); Debug.Assert(objectUrl != null); var result = default(T); try { result = client.GetGPObject<T>(jobId, objectUrl); } catch (RestException e) { _LogServiceError(e); throw SolveHelper.ConvertServiceException( String.Format(Properties.Messages.Error_GetJobParameter, jobId), e); } return result; } private void _CheckLicensePermissions() { // check if license activated if (Licenser.ActivatedLicense == null) { throw new LicenseException(LicenseError.LicenseNotActivated, Properties.Messages.Error_LicenseNotActivated); } // check license permissions if (Licenser.ActivatedLicense.IsRestricted) { // routes permission (max routes per schedule) _CheckRoutesLicPermission(); // orders permission (max number of orders planned on schedule's date) _CheckOrdersLicPermission(); } } private void _CheckRoutesLicPermission() { int routesCount = _schedule.Routes.Count; int? maxRoutesCount = Licenser.ActivatedLicense.PermittedRouteNumber; if (maxRoutesCount != null && routesCount > maxRoutesCount) { throw new LicenseException(LicenseError.MaxRoutesPermission, String.Format(Properties.Messages.Error_MaxRoutesPermission, maxRoutesCount, routesCount)); } } private void _CheckOrdersLicPermission() { int dayOrders = _context.Project.Orders.GetCount( (DateTime)_schedule.PlannedDate); int? maxOrdersCount = Licenser.ActivatedLicense.PermittedOrderNumber; if (maxOrdersCount != null && dayOrders > maxOrdersCount) { throw new LicenseException(LicenseError.MaxOrdersPermission, String.Format(Properties.Messages.Error_MaxOrdersPermission, maxOrdersCount, dayOrders)); } } private void _CancelJob(IVrpRestService client, string jobId) { Debug.Assert(client != null); Debug.Assert(jobId != null); try { client.CancelJob(jobId); } catch (Exception e) { Logger.Error(String.Format(LOG_JOB_CANCEL_ERROR, jobId, e.Message)); Logger.Error(e); } } private static int _GetSolveHR(VrpResultsResponse resp) { Debug.Assert(resp != null); // check "succeeded" flag int hr = HResult.E_FAIL; if (!resp.SolveSucceeded) { // solve is not succeeded, try to determine exact HRESULT code // by response messages JobMessage[] messages = resp.Messages; if (messages != null) { // process messages if (!SolveErrorParser.ParseErrorCode(messages, out hr)) { // cannot determine HRESULT hr = HResult.E_FAIL; Logger.Warning(LOG_UNDETERMINED_SOLVE_HR); } } } else { // solve is succeeded, HRESULT = SO_OK hr = HResult.S_OK; } return hr; } private void _ValidateReqData(SolveRequestData reqData) { Debug.Assert(reqData != null); // check routes count if (reqData.Routes.Count < 1) throw new RouteException(Properties.Messages.Error_InvalidRoutesNum); // validate objects var invalidObjects = new List<DataObject>(); invalidObjects.AddRange(_ValidateObjects<Order>(reqData.Orders)); invalidObjects.AddRange(_ValidateObjects<Route>(reqData.Routes)); if (invalidObjects.Count > 0) { throw new RouteException(Properties.Messages.Error_InvalidScheduleData, invalidObjects.ToArray()); } } private SolveResult _CreateSolveResult(VrpResult vrpResult, List<Violation> violations) { Debug.Assert(vrpResult != null); // convert job messages var msgList = new List<ServerMessage>(); if (vrpResult.Messages != null) { foreach (JobMessage msg in vrpResult.Messages) msgList.Add(_ConvertJobMessage(msg)); } // violations List<Violation> vltList = violations; if (vltList == null) vltList = new List<Violation>(); // status bool isSucceeded = IsSolveSucceeded(vrpResult.SolveHR); return new SolveResult(msgList.ToArray(), vltList.ToArray(), !isSucceeded); } private VrpOperation _GetRestrictedOrdersOperation( List<Order> restrictedOrders, List<Violation> violations) { Debug.Assert(restrictedOrders != null); SolveRequestData reqData = this.RequestData; var newOrders = new List<Order>(); foreach (Order order in reqData.Orders) { if (!restrictedOrders.Contains(order)) newOrders.Add(order); } VrpOperation operation = null; if (newOrders.Count > 0) { reqData.Orders = newOrders; operation = CreateOperation(reqData, violations); } return operation; } private List<Order> _GetRestrictedOrders(List<Violation> violations) { Debug.Assert(violations != null); ICollection<Order> curOrders = this.RequestData.Orders; var list = new List<Order>(); foreach (Violation violation in violations) { if (violation.ViolationType == ViolationType.TooFarFromRoad || violation.ViolationType == ViolationType.RestrictedStreet) { if (violation.AssociatedObject != null && violation.AssociatedObject is Order) { Order restrictedOrder = violation.AssociatedObject as Order; if (curOrders.Contains(restrictedOrder)) list.Add(restrictedOrder); } } } return list; } private static bool _HasRestrictedDepots(List<Violation> violations) { Debug.Assert(violations != null); bool res = false; foreach (Violation violation in violations) { if (violation.ViolationType == ViolationType.TooFarFromRoad || violation.ViolationType == ViolationType.RestrictedStreet) { if (violation.AssociatedObject != null && violation.AssociatedObject is Location) { res = true; break; } } } return res; } private static void _ValidateResponse(GetVrpJobResultResponse resp) { Debug.Assert(resp != null); if (resp.Outputs == null || resp.Outputs.Routes == null || resp.Outputs.Stops == null) { throw new RouteException(Properties.Messages.Error_InvalidResultJobResponse); } } private static VrpResultsResponse _GetVrpResults( SyncVrpResponse response) { Debug.Assert(response != null); var vrpResponse = new VrpResultsResponse() { RouteResult = new GPRouteResult(), JobID = SYNC_JOB_ID, }; var results = vrpResponse.RouteResult; var layer = default(GPFeatureRecordSetLayer); _GetVrpObject<GPFeatureRecordSetLayer>( response, SyncVrpResponse.ParamRoutes, out layer); results.Routes = layer; var recordSet = default(GPRecordSet); _GetVrpObject<GPRecordSet>(response, SyncVrpResponse.ParamStops, out recordSet); results.Stops = recordSet; _GetVrpObject<GPRecordSet>( response, SyncVrpResponse.ParamUnassignedOrders, out recordSet); results.ViolatedStops = recordSet; _GetVrpObject<GPFeatureRecordSetLayer>( response, SyncVrpResponse.ParamDirections, out layer); results.Directions = layer; // solve result flag bool solveRes = false; if (_GetVrpObject<bool>(response, SyncVrpResponse.ParamSucceeded, out solveRes)) vrpResponse.SolveSucceeded = solveRes; else vrpResponse.SolveSucceeded = false; // messages vrpResponse.Messages = response.Messages; vrpResponse.SolveHR = _GetSolveHR(vrpResponse); return vrpResponse; } private static bool _GetVrpObject<T>(SyncVrpResponse response, string paramName, out T obj) { Debug.Assert(response != null); Debug.Assert(paramName != null); obj = default(T); bool res = false; if (response.Objects != null) { foreach (GPParamObject gpParam in response.Objects) { if (!String.IsNullOrEmpty(gpParam.paramName) && gpParam.paramName.Equals(paramName, StringComparison.OrdinalIgnoreCase)) { obj = (T)gpParam.value; res = true; break; } } } return res; } private static void _ValidateVrpResults(VrpResultsResponse resp) { Debug.Assert(resp != null); var results = resp.RouteResult; var invalidResults = results == null || results.Routes == null || results.Stops == null; if (invalidResults) { throw new RouteException(Properties.Messages.Error_InvalidResultJobResponse); } } private static ServerMessage _ConvertJobMessage(JobMessage msg) { Debug.Assert(msg != null); var type = ServerMessageType.Info; if (msg.Type == NAJobMessageType.esriJobMessageTypeError) type = ServerMessageType.Error; else if (msg.Type == NAJobMessageType.esriJobMessageTypeWarning) type = ServerMessageType.Warning; return new ServerMessage(type, msg.Description); } private static List<DataObject> _ValidateObjects<T>(ICollection<T> objects) where T : DataObject { var invalidObjects = new List<DataObject>(); foreach (T obj in objects) { if (!String.IsNullOrEmpty(obj.PrimaryError)) invalidObjects.Add(obj); } return invalidObjects; } private static void _CheckCancelState(ICancelTracker tracker) { if (tracker != null && tracker.IsCancelled) throw new UserBreakException(); } private static void _LogServiceError(RestException ex) { var error = new GPError(); error.Message = ex.Message; error.Code = ex.ErrorCode; error.Details = ex.Details; Logger.Error(_BuildFaultResponseLog(error)); } private static void _LogResponse(GetJobResultResponse resp) { try { string log = null; if (Logger.IsSeverityEnabled(TraceEventType.Information)) { if (resp.IsFault) { GPError error = resp.FaultInfo; if (error != null) log = _BuildFaultResponseLog(error); } else log = _BuildResponseLog(resp); if (log != null) Logger.Info(log); } } catch { } } private static string _BuildResponseLog(GetJobResultResponse resp) { var sb = new StringBuilder(); sb.Append(Environment.NewLine); sb.Append("jobId: "); sb.AppendLine(resp.JobId); sb.Append("jobStatus: "); sb.AppendLine(resp.JobStatus); sb.Append(Environment.NewLine); if (resp.Messages != null) { foreach (JobMessage msg in resp.Messages) { sb.Append(msg.Type); sb.AppendLine(": "); sb.AppendLine(msg.Description); sb.AppendLine(""); } } return sb.ToString(); } private static string _BuildFaultResponseLog(GPError error) { var sb = new StringBuilder(); sb.Append(Environment.NewLine); sb.Append("code: "); sb.AppendLine(error.Code.ToString()); sb.Append("message: "); sb.AppendLine(error.Message); sb.AppendLine("details:"); if (error.Details != null) { foreach (string msg in error.Details) sb.AppendLine(msg); } return sb.ToString(); } private static void _LogJobError(string jobId, Exception e) { Logger.Error(String.Format(LOG_JOB_ERROR, jobId, e.Message)); Logger.Error(e); } private void _LogJobStatistics(string jobId, SolveStatistics statistics) { Logger.Info(String.Format(LOG_JOB_STATISTICS, this.OperationType, jobId, statistics.RequestTime.TotalSeconds)); } #endregion private methods #region private constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // retry delay (milliseconds) private const int RETRY_DELAY = 3000; // log messages private const string LOG_JOB_ERROR = "Failed to send request for job id={0}: {1}"; private const string LOG_JOB_STATISTICS = "Statistics for {0} (job id={1}):\nSolve and data transfer time: {2} seconds"; private const string LOG_JOB_CANCEL_ERROR = "Failed to cancel job id={0}: {1}"; private const string LOG_UNDETERMINED_SOLVE_HR = "Cannot determine solve HRESULT code by response messages."; /// <summary> /// The string to be used as job ID for the synchronous requests. /// </summary> private const string SYNC_JOB_ID = "sync-service"; #endregion #region private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private SolverContext _context; private Schedule _schedule; private SolveOptions _options; private VrpOperation _nextStep; private GPFeature[] _pointBarriers; private GPFeature[] _polygonBarriers; private GPFeature[] _polylineBarriers; #endregion private fields } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.ComponentModel; using Microsoft.WindowsAPICodePack.DirectX.Direct2D1; namespace D2DShapes { internal class GeometryShape : DrawingShape { private Geometry geometry; internal PathGeometry geometryOutlined; internal PathGeometry geometrySimplified; internal PathGeometry geometryWidened; internal Matrix3x2F? worldTransform; public GeometryShape(RenderTarget initialRenderTarget, Random random, D2DFactory d2DFactory, D2DBitmap bitmap) : base(initialRenderTarget, random, d2DFactory, bitmap) { coolStrokes = CoinFlip; double which = Random.NextDouble(); if (which < 0.67 || coolStrokes) PenBrush = RandomBrush(); if (!coolStrokes && which > 0.33) FillBrush = RandomBrush(); if (coolStrokes || CoinFlip) StrokeStyle = RandomStrokeStyle(); if (CoinFlip) worldTransform = RandomMatrix3x2(); StrokeWidth = RandomStrokeWidth(); geometry = RandomGeometry(); if (coolStrokes || Random.NextDouble() < 0.3) ModifyGeometry(); if (coolStrokes && CoinFlip) { ModifyGeometry(); } } [TypeConverter(typeof(ExpandableObjectConverter))] public Geometry Geometry { get { return geometry; } set { geometry = value; } } private void ModifyGeometry() { GeometrySink geometrySink; double which = Random.NextDouble(); if (which < 0.33) { geometryOutlined = d2DFactory.CreatePathGeometry(); geometrySink = geometryOutlined.Open(); geometry.Outline(geometrySink, FlatteningTolerance); geometrySink.Close(); geometrySink.Dispose(); geometry.Dispose(); geometry = geometryOutlined; } else if (which < 0.67) { geometrySimplified = d2DFactory.CreatePathGeometry(); geometrySink = geometrySimplified.Open(); geometry.Simplify( CoinFlip ? GeometrySimplificationOption.Lines : GeometrySimplificationOption.CubicsAndLines, geometrySink, FlatteningTolerance ); geometrySink.Close(); geometrySink.Dispose(); geometry.Dispose(); geometry = geometrySimplified; } else { geometryWidened = d2DFactory.CreatePathGeometry(); geometrySink = geometryWidened.Open(); geometry.Widen( RandomStrokeWidth(), //75 RandomStrokeStyle(), geometrySink, FlatteningTolerance); geometrySink.Close(); geometrySink.Dispose(); geometry.Dispose(); geometry = geometryWidened; } } //this could be called recursively public Geometry RandomGeometry() { return RandomGeometry(0); } public Geometry RandomGeometry(int level) { Geometry g = null; while (g == null) { double which = Random.NextDouble(); if (which < 0.20) g = RandomEllipseGeometry(); else if (which < 0.40) g = RandomRoundRectGeometry(); else if (which < 0.60) g = RandomRectangleGeometry(); else if (which < 0.80) g = RandomPathGeometry(); else if (level < 3) g = RandomGeometryGroup(level + 1); } if (worldTransform.HasValue) g = d2DFactory.CreateTransformedGeometry(g, worldTransform.Value); return g; } private Geometry RandomTransformedGeometry() { Geometry start, ret; start = RandomGeometry(); ret = d2DFactory.CreateTransformedGeometry( start, RandomMatrix3x2()); start.Dispose(); return ret; } private Geometry RandomGeometryGroup(int level) { var geometries = new List<Geometry>(); int count = Random.Next(1, 5); for (int i = 0; i < count; i++) geometries.Add(RandomGeometry(level)); GeometryGroup ret = d2DFactory.CreateGeometryGroup( Random.NextDouble() < .5 ? FillMode.Winding : FillMode.Alternate, geometries); foreach (var g in geometries) { g.Dispose(); } return ret; } private PathGeometry RandomPathGeometry() { PathGeometry g = d2DFactory.CreatePathGeometry(); int totalSegmentCount = 0; int figureCount = Random.Next(1, 2); using (GeometrySink sink = g.Open()) { for (int f = 0; f < figureCount; f++) { int segmentCount = Random.Next(2, 20); AddRandomFigure(sink, segmentCount); totalSegmentCount += segmentCount; } sink.Close(); } System.Diagnostics.Debug.Assert(g.SegmentCount == totalSegmentCount); System.Diagnostics.Debug.Assert(g.FigureCount == figureCount); return g; } private void AddRandomFigure(IGeometrySink sink, int segmentCount) { previousPoint = null; sink.BeginFigure( RandomNearPoint(), CoinFlip ? FigureBegin.Filled : FigureBegin.Hollow); FigureEnd end = CoinFlip ? FigureEnd.Closed : FigureEnd.Closed; if (end == FigureEnd.Closed) segmentCount--; if (CoinFlip) for (int i = 0; i < segmentCount; i++) AddRandomSegment(sink); else { double which = Random.NextDouble(); if (which < 0.33) sink.AddLines(RandomLines(segmentCount)); else if (which < 0.67) sink.AddQuadraticBeziers(RandomQuadraticBeziers(segmentCount)); else sink.AddBeziers(RandomBeziers(segmentCount)); } sink.EndFigure(end); } private IEnumerable<Point2F> RandomLines(int segmentCount) { var lines = new List<Point2F>(); for (int i = 0; i < segmentCount; i++) lines.Add(RandomNearPoint()); return lines; } private IEnumerable<QuadraticBezierSegment> RandomQuadraticBeziers(int segmentCount) { var beziers = new List<QuadraticBezierSegment>(); for (int i = 0; i < segmentCount; i++) beziers.Add(new QuadraticBezierSegment( RandomNearPoint(), RandomNearPoint())); return beziers; } private IEnumerable<BezierSegment> RandomBeziers(int segmentCount) { var beziers = new List<BezierSegment>(); for (int i = 0; i < segmentCount; i++) beziers.Add(new BezierSegment( RandomNearPoint(), RandomNearPoint(), RandomNearPoint())); return beziers; } private void AddRandomSegment(IGeometrySink sink) { double which = Random.NextDouble(); if (which < 0.25) sink.AddLine(RandomNearPoint()); else if (which < 0.5) sink.AddArc(RandomArc()); else if (which < 0.75) sink.AddBezier(RandomBezier()); else if (which < 1.0) sink.AddQuadraticBezier(RandomQuadraticBezier()); } private QuadraticBezierSegment RandomQuadraticBezier() { return new QuadraticBezierSegment( RandomNearPoint(), RandomNearPoint()); } private BezierSegment RandomBezier() { return new BezierSegment( RandomNearPoint(), RandomNearPoint(), RandomNearPoint()); } private ArcSegment RandomArc() { return new ArcSegment( RandomNearPoint(), RandomSize(), (float)Random.NextDouble() * 360, CoinFlip ? SweepDirection.Clockwise : SweepDirection.Counterclockwise, CoinFlip ? ArcSize.Large : ArcSize.Small ); } private SizeF RandomSize() { return new SizeF( (float)Random.NextDouble() * CanvasWidth, (float)Random.NextDouble() * CanvasHeight); } private RoundedRectangleGeometry RandomRoundRectGeometry() { return d2DFactory.CreateRoundedRectangleGeometry( RandomRoundedRect()); } private RectangleGeometry RandomRectangleGeometry() { return d2DFactory.CreateRectangleGeometry( RandomRect(CanvasWidth, CanvasHeight)); } private EllipseGeometry RandomEllipseGeometry() { return d2DFactory.CreateEllipseGeometry( RandomEllipse()); } protected internal override void ChangeRenderTarget(RenderTarget newRenderTarget) { PenBrush = CopyBrushToRenderTarget(PenBrush, newRenderTarget); FillBrush = CopyBrushToRenderTarget(FillBrush, newRenderTarget); } protected internal override void Draw(RenderTarget renderTarget) { Geometry g = geometry; if (FillBrush != null) { renderTarget.FillGeometry(g, FillBrush, null); } if (PenBrush != null) { if (StrokeStyle != null) { renderTarget.DrawGeometry(g, PenBrush, StrokeWidth, StrokeStyle); } else { renderTarget.DrawGeometry(g, PenBrush, StrokeWidth); } } } public override bool HitTest(Point2F point) { return geometry.FillContainsPoint(point, FlatteningTolerance); } public override void Dispose() { if (geometry != null) geometry.Dispose(); geometry = null; base.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; #if !LINUX using System.Windows.Forms; #endif using EndlessClient.Audio; using EndlessClient.Dialogs; using EndlessClient.GameExecution; using EndlessClient.Rendering; using EOLib.Graphics; using EOLib.Localization; using EOLib.Net.API; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XNAControls.Old; namespace EndlessClient.Old { public partial class EOGame : Game { private static EOGame inst; /// <summary> /// Singleton Instance: used/disposed from main in Program.cs /// </summary> public static EOGame Instance => inst ?? (inst = new EOGame()); public SpriteFont DBGFont { get; private set; } private const int WIDTH = 640; private const int HEIGHT = 480; public GameStates State { get; private set; } public PacketAPI API => null; public INativeGraphicsManager GFXManager { get; private set; } #if DEBUG //don't do FPS render on release builds private TimeSpan? lastFPSRender; private int localFPS; #endif public void ShowLostConnectionDialog() { if (_backButtonPressed) return; EOMessageBox.Show(State == GameStates.PlayingTheGame ? DialogResourceID.CONNECTION_LOST_IN_GAME : DialogResourceID.CONNECTION_LOST_CONNECTION); } public void ResetWorldElements() { OldWorld.Instance.ResetGameElements(); } public void DisconnectFromGameServer() { if (OldWorld.Instance.Client.ConnectedAndInitialized) OldWorld.Instance.Client.Disconnect(); } public void SetInitialGameState() { doStateChange(GameStates.Initial); } public void DoShowLostConnectionDialogAndReturnToMainMenu() { ShowLostConnectionDialog(); ResetWorldElements(); DisconnectFromGameServer(); SetInitialGameState(); } private void doStateChange(GameStates newState) { GameStates prevState = State; State = newState; if(prevState == GameStates.PlayingTheGame && State != GameStates.PlayingTheGame) { Components.OfType<IDisposable>() .ToList() .ForEach(x => x.Dispose()); Components.Clear(); foreach (var dlg in XNAControl.Dialogs) { dlg.Visible = true; Components.Add(dlg); } } List<DrawableGameComponent> toRemove = new List<DrawableGameComponent>(); foreach (var component in Components.OfType<DrawableGameComponent>()) { //don't hide dialogs if (component is XNAControl && (XNAControl.Dialogs.Contains(component as XNAControl) || XNAControl.Dialogs.Contains((component as XNAControl).TopParent))) continue; if (prevState == GameStates.PlayingTheGame && State != GameStates.PlayingTheGame) { toRemove.Add(component); } else { if (component is OldCharacterRenderer) toRemove.Add(component as OldCharacterRenderer); //this needs to be done separately because it's a foreach loop if (component is XNATextBox) { (component as XNATextBox).Text = ""; (component as XNATextBox).Selected = false; } if (component != null) component.Visible = false; } } foreach (DrawableGameComponent comp in toRemove) { if (comp is XNAControl) (comp as XNAControl).Close(); else comp.Dispose(); if (Components.Contains(comp)) Components.Remove(comp); } toRemove.Clear(); if (prevState == GameStates.PlayingTheGame && State != GameStates.PlayingTheGame) InitializeControls(true); //reinitialize to defaults switch (State) { case GameStates.PlayingTheGame: FieldInfo[] fi = GetType().GetFields(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic); for (int i = Components.Count - 1; i >= 0; --i) { IGameComponent comp = Components[i]; if (comp != _backButton && (comp as DrawableGameComponent) != null && fi.Count(_fi => _fi.GetValue(this) == comp) == 1) { (comp as DrawableGameComponent).Dispose(); Components.Remove(comp); } } _backButton.Visible = true; //note: HUD construction moved to successful welcome message in GameLoadingDialog close event handler break; } } //----------------------------- //***** DEFAULT XNA STUFF ***** //----------------------------- private EOGame() { _graphicsDeviceManager = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = WIDTH, PreferredBackBufferHeight = HEIGHT }; Content.RootDirectory = "Content"; } protected override void Initialize() { IsMouseVisible = true; if (!InitializeSoundManager()) return; base.Initialize(); } protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); InitializeControls(); } protected override void Draw(GameTime gameTime) { #if DEBUG if (State != GameStates.TestMode) { if (lastFPSRender == null) lastFPSRender = gameTime.TotalGameTime; localFPS++; if (gameTime.TotalGameTime.TotalMilliseconds - lastFPSRender.Value.TotalMilliseconds > 1000) { OldWorld.FPS = localFPS; localFPS = 0; lastFPSRender = gameTime.TotalGameTime; } } #endif base.Draw(gameTime); } private bool InitializeSoundManager() { try { SoundManager = new SoundManager(); } catch (Exception ex) { #if !LINUX MessageBox.Show( string.Format("There was an error (type: {2}) initializing the sound manager: {0}\n\nCall Stack:\n {1}", ex.Message, ex.StackTrace, ex.GetType()), "Sound Manager Error"); #endif Exit(); return false; } if (OldWorld.Instance.MusicEnabled) SoundManager.PlayBackgroundMusic(1); //mfx001 == main menu theme return true; } //------------------- //***** CLEANUP ***** //------------------- protected override void Dispose(bool disposing) { if (!OldWorld.Initialized) return; if (OldWorld.Instance.Client.ConnectedAndInitialized) OldWorld.Instance.Client.Disconnect(); if(_backButton != null) _backButton.Close(); if(_spriteBatch != null) _spriteBatch.Dispose(); ((IDisposable)_graphicsDeviceManager).Dispose(); GFXManager.Dispose(); Dispatcher.Dispose(); OldWorld.Instance.Dispose(); base.Dispose(disposing); } } }
namespace Webcrawler { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.btnSearch = new System.Windows.Forms.Button(); this.dgvInternalUrl = new System.Windows.Forms.DataGridView(); this.grpBxInternalUrl = new System.Windows.Forms.GroupBox(); this.grpBxExternalUrl = new System.Windows.Forms.GroupBox(); this.dgvExternalUrl = new System.Windows.Forms.DataGridView(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label2 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgvInternalUrl)).BeginInit(); this.grpBxInternalUrl.SuspendLayout(); this.grpBxExternalUrl.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgvExternalUrl)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(4, 0); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(52, 15); this.label1.TabIndex = 0; this.label1.Text = "Address:"; // // textBox1 // this.tableLayoutPanel1.SetColumnSpan(this.textBox1, 2); this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox1.Location = new System.Drawing.Point(119, 3); this.textBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(453, 23); this.textBox1.TabIndex = 1; // // btnSearch // this.btnSearch.Location = new System.Drawing.Point(234, 38); this.btnSearch.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.btnSearch.Name = "btnSearch"; this.btnSearch.Size = new System.Drawing.Size(91, 23); this.btnSearch.TabIndex = 2; this.btnSearch.Text = "Search"; this.btnSearch.UseVisualStyleBackColor = true; this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click); // // dgvInternalUrl // this.dgvInternalUrl.AllowUserToAddRows = false; this.dgvInternalUrl.AllowUserToDeleteRows = false; this.dgvInternalUrl.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.dgvInternalUrl.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvInternalUrl.ColumnHeadersVisible = false; this.dgvInternalUrl.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvInternalUrl.Location = new System.Drawing.Point(4, 19); this.dgvInternalUrl.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.dgvInternalUrl.Name = "dgvInternalUrl"; this.dgvInternalUrl.ReadOnly = true; this.dgvInternalUrl.RowHeadersVisible = false; this.dgvInternalUrl.Size = new System.Drawing.Size(560, 139); this.dgvInternalUrl.TabIndex = 3; // // grpBxInternalUrl // this.tableLayoutPanel1.SetColumnSpan(this.grpBxInternalUrl, 3); this.grpBxInternalUrl.Controls.Add(this.dgvInternalUrl); this.grpBxInternalUrl.Dock = System.Windows.Forms.DockStyle.Fill; this.grpBxInternalUrl.Location = new System.Drawing.Point(4, 73); this.grpBxInternalUrl.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.grpBxInternalUrl.Name = "grpBxInternalUrl"; this.grpBxInternalUrl.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); this.grpBxInternalUrl.Size = new System.Drawing.Size(568, 161); this.grpBxInternalUrl.TabIndex = 4; this.grpBxInternalUrl.TabStop = false; this.grpBxInternalUrl.Text = "Internal Url\'s"; // // grpBxExternalUrl // this.tableLayoutPanel1.SetColumnSpan(this.grpBxExternalUrl, 3); this.grpBxExternalUrl.Controls.Add(this.dgvExternalUrl); this.grpBxExternalUrl.Dock = System.Windows.Forms.DockStyle.Fill; this.grpBxExternalUrl.Location = new System.Drawing.Point(4, 240); this.grpBxExternalUrl.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.grpBxExternalUrl.Name = "grpBxExternalUrl"; this.grpBxExternalUrl.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); this.grpBxExternalUrl.Size = new System.Drawing.Size(568, 162); this.grpBxExternalUrl.TabIndex = 5; this.grpBxExternalUrl.TabStop = false; this.grpBxExternalUrl.Text = "External Url\'s"; // // dgvExternalUrl // this.dgvExternalUrl.AllowUserToAddRows = false; this.dgvExternalUrl.AllowUserToDeleteRows = false; this.dgvExternalUrl.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.dgvExternalUrl.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvExternalUrl.ColumnHeadersVisible = false; this.dgvExternalUrl.Dock = System.Windows.Forms.DockStyle.Fill; this.dgvExternalUrl.Location = new System.Drawing.Point(4, 19); this.dgvExternalUrl.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.dgvExternalUrl.Name = "dgvExternalUrl"; this.dgvExternalUrl.ReadOnly = true; this.dgvExternalUrl.RowHeadersVisible = false; this.dgvExternalUrl.Size = new System.Drawing.Size(560, 140); this.dgvExternalUrl.TabIndex = 3; // // comboBox1 // this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Top; this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "1", "2", "3"}); this.comboBox1.Location = new System.Drawing.Point(119, 38); this.comboBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(107, 23); this.comboBox1.TabIndex = 6; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 3; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 60F)); this.tableLayoutPanel1.Controls.Add(this.grpBxExternalUrl, 0, 3); this.tableLayoutPanel1.Controls.Add(this.grpBxInternalUrl, 0, 2); this.tableLayoutPanel1.Controls.Add(this.textBox1, 1, 0); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.btnSearch, 2, 1); this.tableLayoutPanel1.Controls.Add(this.comboBox1, 1, 1); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 4; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 35F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 35F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(576, 405); this.tableLayoutPanel1.TabIndex = 7; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(4, 35); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(42, 15); this.label2.TabIndex = 7; this.label2.Text = "Loops:"; // // Form1 // this.AcceptButton = this.btnSearch; this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(576, 405); this.Controls.Add(this.tableLayoutPanel1); this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.MinimumSize = new System.Drawing.Size(583, 430); this.Name = "Form1"; this.Text = "WebCrawler"; ((System.ComponentModel.ISupportInitialize)(this.dgvInternalUrl)).EndInit(); this.grpBxInternalUrl.ResumeLayout(false); this.grpBxExternalUrl.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgvExternalUrl)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button btnSearch; private System.Windows.Forms.DataGridView dgvInternalUrl; private System.Windows.Forms.GroupBox grpBxInternalUrl; private System.Windows.Forms.GroupBox grpBxExternalUrl; private System.Windows.Forms.DataGridView dgvExternalUrl; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label2; } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ using System; using System.Collections; namespace Alachisoft.NosDB.Common.DataStructures { ///<summary> /// The RedBlackEnumerator class returns the keys or data objects of the treap in /// sorted order. ///</summary> public class RedBlackEnumerator : IDictionaryEnumerator { // the treap uses the stack to order the nodes private Stack stack; // return the keys //private bool keys; // return in ascending order (true) or descending (false) private bool ascending; // key private object ordKey; // the data or value associated with the key private object objValue; private ITreeNode _sentinelNode; #region / --- IDictionary Enumerator --- / ///<summary> ///Key ///</summary> /*public IComparable*/ object IDictionaryEnumerator.Key { get { return ordKey; } //set //{ // ordKey = value; //} } //public T Key //{ // get // { // return ordKey; // } //} ///<summary> ///Data ///</summary> /*public*/ object IDictionaryEnumerator.Value { get { return objValue; } //set //{ // objValue = value; //} } //public object Value //{ // get { return objValue; } //} DictionaryEntry IDictionaryEnumerator.Entry { get { return new DictionaryEntry(); } } object IEnumerator.Current { get { return null; } } void IEnumerator.Reset() { } #endregion public RedBlackEnumerator() { } ///<summary> /// Determine order, walk the tree and push the nodes onto the stack ///</summary> public RedBlackEnumerator(ITreeNode tnode, bool ascending, ITreeNode sentinelNode) { stack = new Stack(); this.ascending = ascending; _sentinelNode = sentinelNode; // use depth-first traversal to push nodes into stack // the lowest node will be at the top of the stack if(ascending) { // find the lowest node while(tnode != _sentinelNode) { stack.Push(tnode); tnode = tnode.Left; } } else { // the highest node will be at top of stack while(tnode != _sentinelNode) { stack.Push(tnode); tnode = tnode.Right; } } } ///<summary> /// HasMoreElements ///</summary> public bool HasMoreElements() { bool result = stack != null && stack.Count > 0; return result; } ///<summary> /// NextElement ///</summary> public object NextElement() { if(stack.Count == 0) throw(new RedBlackException("Element not found")); // the top of stack will always have the next item // get top of stack but don't remove it as the next nodes in sequence // may be pushed onto the top // the stack will be popped after all the nodes have been returned ITreeNode node = (ITreeNode) stack.Peek(); //next node in sequence if(ascending) { if(node.Right == _sentinelNode) { // yes, top node is lowest node in subtree - pop node off stack ITreeNode tn = (ITreeNode) stack.Pop(); // peek at right node's parent // get rid of it if it has already been used while(HasMoreElements()&& ((ITreeNode) stack.Peek()).Right == tn) tn = (ITreeNode) stack.Pop(); } else { // find the next items in the sequence // traverse to left; find lowest and push onto stack ITreeNode tn = node.Right; while(tn != _sentinelNode) { stack.Push(tn); tn = tn.Left; } } } else // descending, same comments as above apply { if(node.Left == _sentinelNode) { // walk the tree ITreeNode tn = (ITreeNode) stack.Pop(); while(HasMoreElements() && ((ITreeNode)stack.Peek()).Left == tn) tn = (ITreeNode) stack.Pop(); } else { // determine next node in sequence // traverse to left subtree and find greatest node - push onto stack ITreeNode tn = node.Left; while(tn != _sentinelNode) { stack.Push(tn); tn = tn.Right; } } } // the following is for .NET compatibility (see MoveNext()) ordKey = node.Key; objValue = node.Value; // ******** testing only ******** // try // { // parentKey = node.Parent.Key; // testing only // // } // catch(Exception e) // { // Trace.error("RedBlackEnumerator.NextElement()", e.StackTrace); // object o = e; // stop compiler from complaining // parentKey = 0; // } // if(node.Color == 0) // testing only // Color = "Red"; // else // Color = "Black"; // ******** testing only ******** //return keys == true ? node.Key : node.Data; return node.Key; } ///<summary> /// MoveNext /// For .NET compatibility ///</summary> public bool MoveNext() { if(HasMoreElements()) { NextElement(); return true; } return false; } } }
//--------------------------------------------------------------------------- // // File: HtmlXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Html - Xaml conversion // //--------------------------------------------------------------------------- namespace DocumentSerialization { using System; using System.Xml; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Windows; // DependencyProperty using System.Windows.Documents; // TextElement internal static class HtmlCssParser { // ................................................................. // // Processing CSS Attributes // // ................................................................. internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext) { string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext); string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style"); // Combine styles from stylesheet and from inline attribute. // The order is important - the latter styles will override the former. string style = styleFromStylesheet != null ? styleFromStylesheet : null; if (styleInline != null) { style = style == null ? styleInline : (style + ";" + styleInline); } // Apply local style to current formatting properties if (style != null) { string[] styleValues = style.Split(';'); for (int i = 0; i < styleValues.Length; i++) { string[] styleNameValue; styleNameValue = styleValues[i].Split(':'); if (styleNameValue.Length == 2) { string styleName = styleNameValue[0].Trim().ToLower(); string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower(); int nextIndex = 0; switch (styleName) { case "font": ParseCssFont(styleValue, localProperties); break; case "font-family": ParseCssFontFamily(styleValue, ref nextIndex, localProperties); break; case "font-size": ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); break; case "font-style": ParseCssFontStyle(styleValue, ref nextIndex, localProperties); break; case "font-weight": ParseCssFontWeight(styleValue, ref nextIndex, localProperties); break; case "font-variant": ParseCssFontVariant(styleValue, ref nextIndex, localProperties); break; case "line-height": ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); break; case "word-spacing": // TODO: Implement word-spacing conversion break; case "letter-spacing": // TODO: Implement letter-spacing conversion break; case "color": ParseCssColor(styleValue, ref nextIndex, localProperties, "color"); break; case "text-decoration": ParseCssTextDecoration(styleValue, ref nextIndex, localProperties); break; case "text-transform": ParseCssTextTransform(styleValue, ref nextIndex, localProperties); break; case "background-color": ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color"); break; case "background": // TODO: need to parse composite background property ParseCssBackground(styleValue, ref nextIndex, localProperties); break; case "text-align": ParseCssTextAlign(styleValue, ref nextIndex, localProperties); break; case "vertical-align": ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties); break; case "text-indent": ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false); break; case "width": case "height": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "margin": // top/right/bottom/left ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "margin-top": case "margin-right": case "margin-bottom": case "margin-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "padding": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "padding-top": case "padding-right": case "padding-bottom": case "padding-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "border": ParseCssBorder(styleValue, ref nextIndex, localProperties); break; case "border-style": case "border-width": case "border-color": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "border-top": case "border-right": case "border-left": case "border-bottom": // TODO: Parse css border style break; // NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right) // In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method case "border-top-style": case "border-right-style": case "border-left-style": case "border-bottom-style": case "border-top-color": case "border-right-color": case "border-left-color": case "border-bottom-color": case "border-top-width": case "border-right-width": case "border-left-width": case "border-bottom-width": // TODO: Parse css border style break; case "display": // TODO: Implement display style conversion break; case "float": ParseCssFloat(styleValue, ref nextIndex, localProperties); break; case "clear": ParseCssClear(styleValue, ref nextIndex, localProperties); break; default: break; } } } } } // ................................................................. // // Pasring CSS - Lexical Helpers // // ................................................................. // Skips whitespaces in style values private static void ParseWhiteSpace(string styleValue, ref int nextIndex) { while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex])) { nextIndex++; } } // Checks if the following character matches to a given word and advances nextIndex // by the word's length in case of success. // Otherwise leaves nextIndex in place (except for possible whitespaces). // Returns true or false depending on success or failure of matching. private static bool ParseWord(string word, string styleValue, ref int nextIndex) { ParseWhiteSpace(styleValue, ref nextIndex); for (int i = 0; i < word.Length; i++) { if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i])) { return false; } } if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length])) { return false; } nextIndex += word.Length; return true; } // CHecks whether the following character sequence matches to one of the given words, // and advances the nextIndex to matched word length. // Returns null in case if there is no match or the word matched. private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex) { for (int i = 0; i < words.Length; i++) { if (ParseWord(words[i], styleValue, ref nextIndex)) { return words[i]; } } return null; } private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName) { string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex); if (attributeValue != null) { localProperties[attributeName] = attributeValue; } } private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative) { ParseWhiteSpace(styleValue, ref nextIndex); int startIndex = nextIndex; // Parse optional munis sign if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-') { nextIndex++; } if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex])) { while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.')) { nextIndex++; } string number = styleValue.Substring(startIndex, nextIndex - startIndex); string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex); if (unit == null) { unit = "px"; // Assuming pixels by default } if (mustBeNonNegative && styleValue[startIndex] == '-') { return "0"; } else { return number + unit; } } return null; } private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative) { string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative); if (length != null) { localValues[propertyName] = length; } } private static readonly string[] _colors = new string[] { "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen", }; private static readonly string[] _systemColors = new string[] { "activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext", }; private static string ParseCssColor(string styleValue, ref int nextIndex) { // TODO: Implement color parsing // rgb(100%,53.5%,10%) // rgb(255,91,26) // #FF5B1A // black | silver | gray | ... | aqua // transparent - for background-color ParseWhiteSpace(styleValue, ref nextIndex); string color = null; if (nextIndex < styleValue.Length) { int startIndex = nextIndex; char character = styleValue[nextIndex]; if (character == '#') { nextIndex++; while (nextIndex < styleValue.Length) { character = Char.ToUpper(styleValue[nextIndex]); if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F')) { break; } nextIndex++; } if (nextIndex > startIndex + 1) { color = styleValue.Substring(startIndex, nextIndex - startIndex); } } else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg") { // TODO: Implement real rgb() color parsing while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')') { nextIndex++; } if (nextIndex < styleValue.Length) { nextIndex++; // to skip ')' } color = "gray"; // return bogus color } else if (Char.IsLetter(character)) { color = ParseWordEnumeration(_colors, styleValue, ref nextIndex); if (color == null) { color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex); if (color != null) { // TODO: Implement smarter system color converions into real colors color = "black"; } } } } return color; } private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName) { string color = ParseCssColor(styleValue, ref nextIndex); if (color != null) { localValues[propertyName] = color; } } // ................................................................. // // Pasring CSS font Property // // ................................................................. // CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size. // An aggregated "font" property lets you specify in one action all the five in combination // with additional line-height property. // // font-family: [<family-name>,]* [<family-name> | <generic-family>] // generic-family: serif | sans-serif | monospace | cursive | fantasy // The list of families sets priorities to choose fonts; // Quotes not allowed around generic-family names // font-style: normal | italic | oblique // font-variant: normal | small-caps // font-weight: normal | bold | bolder | lighter | 100 ... 900 | // Default is "normal", normal==400 // font-size: <absolute-size> | <relative-size> | <length> | <percentage> // absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large // relative-size: larger | smaller // length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches> // Default: medium // font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family> private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" }; private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" }; private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" }; private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" }; private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" }; private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" }; // Parses CSS string fontStyle representing a value for css font attribute private static void ParseCssFont(string styleValue, Hashtable localProperties) { int nextIndex = 0; ParseCssFontStyle(styleValue, ref nextIndex, localProperties); ParseCssFontVariant(styleValue, ref nextIndex, localProperties); ParseCssFontWeight(styleValue, ref nextIndex, localProperties); ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/') { nextIndex++; ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); } ParseCssFontFamily(styleValue, ref nextIndex, localProperties); } private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style"); } private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant"); } private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight"); } private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties) { string fontFamilyList = null; while (nextIndex < styleValue.Length) { // Try generic-family string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex); if (fontFamily == null) { // Try quoted font family name if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\'')) { char quote = styleValue[nextIndex]; nextIndex++; int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote) { nextIndex++; } fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"'; } if (fontFamily == null) { // Try unquoted font family name int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';') { nextIndex++; } if (nextIndex > startIndex) { fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim(); if (fontFamily.Length == 0) { fontFamily = null; } } } } ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',') { nextIndex++; } if (fontFamily != null) { // TODO: css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names // fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily; if (fontFamilyList == null && fontFamily.Length > 0) { if (fontFamily[0] == '"' || fontFamily[0] == '\'') { // Unquote the font family name fontFamily = fontFamily.Substring(1, fontFamily.Length - 2); } else { // Convert generic css family name } fontFamilyList = fontFamily; } } else { break; } } if (fontFamilyList != null) { localProperties["font-family"] = fontFamilyList; } } // ................................................................. // // Pasring CSS list-style Property // // ................................................................. // list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ] private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" }; private static readonly string[] _listStylePositions = new string[] { "inside", "outside" }; private static void ParseCssListStyle(string styleValue, Hashtable localProperties) { int nextIndex = 0; while (nextIndex < styleValue.Length) { string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex); if (listStyleType != null) { localProperties["list-style-type"] = listStyleType; } else { string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex); if (listStylePosition != null) { localProperties["list-style-position"] = listStylePosition; } else { string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex); if (listStyleImage != null) { localProperties["list-style-image"] = listStyleImage; } else { // TODO: Process unrecognized list style value break; } } } } } private static string ParseCssListStyleType(string styleValue, ref int nextIndex) => ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex); private static string ParseCssListStylePosition(string styleValue, ref int nextIndex) => ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex); private static string ParseCssListStyleImage(string styleValue, ref int nextIndex) => null; // ................................................................. // // Pasring CSS text-decorations Property // // ................................................................. private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" }; private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties) { // Set default text-decorations:none; for (int i = 1; i < _textDecorations.Length; i++) { localProperties["text-decoration-" + _textDecorations[i]] = "false"; } // Parse list of decorations values while (nextIndex < styleValue.Length) { string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex); if (decoration == null || decoration == "none") { break; } localProperties["text-decoration-" + decoration] = "true"; } } // ................................................................. // // Pasring CSS text-transform Property // // ................................................................. private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" }; private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform"); } // ................................................................. // // Pasring CSS text-align Property // // ................................................................. private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" }; private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align"); } // ................................................................. // // Pasring CSS vertical-align Property // // ................................................................. private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" }; private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { // TODO: Parse percentage value for vertical-align style ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align"); } // ................................................................. // // Pasring CSS float Property // // ................................................................. private static readonly string[] _floats = new string[] { "left", "right", "none" }; private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float"); } // ................................................................. // // Pasring CSS clear Property // // ................................................................. private static readonly string[] _clears = new string[] { "none", "left", "right", "both" }; private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear"); } // ................................................................. // // Pasring CSS margin and padding Properties // // ................................................................. // Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName) { // CSS Spec: // If only one value is set, then the value applies to all four sides; // If two or three values are set, then missinng value(s) are taken fromm the opposite side(s). // The order they are applied is: top/right/bottom/left Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color"); string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-top"] = value; localProperties[propertyName + "-bottom"] = value; localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-bottom"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-left"] = value; } } } return true; } return false; } // ................................................................. // // Pasring CSS border Properties // // ................................................................. // border: [ <border-width> || <border-style> || <border-color> ] private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties) { while ( ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color")) { } } // ................................................................. // // Pasring CSS border-style Propertie // // ................................................................. private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" }; private static string ParseCssBorderStyle(string styleValue, ref int nextIndex) => ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex); // ................................................................. // // TODO: What are these definitions doing here: // // ................................................................. private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" }; // ................................................................. // // Pasring CSS Background Properties // // ................................................................. private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues) { // TODO: Implement parsing background attribute } } internal class CssStylesheet { // Constructor public CssStylesheet(XmlElement htmlElement) { if (htmlElement != null) { this.DiscoverStyleDefinitions(htmlElement); } } // Recursively traverses an html tree, discovers STYLE elements and creates a style definition table // for further cascading style application public void DiscoverStyleDefinitions(XmlElement htmlElement) { if (htmlElement.LocalName.ToLower() == "link") { return; // TODO: Add LINK elements processing for included stylesheets // <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet> } if (htmlElement.LocalName.ToLower() != "style") { // This is not a STYLE element. Recurse into it for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement) { this.DiscoverStyleDefinitions((XmlElement)htmlChildNode); } } return; } // Add style definitions from this style. // Collect all text from this style definition StringBuilder stylesheetBuffer = new StringBuilder(); for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlText || htmlChildNode is XmlComment) { stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value)); } } // CssStylesheet has the following syntactical structure: // @import declaration; // selector { definition } // where "selector" is one of: ".classname", "tagname" // It can contain comments in the following form: /*...*/ int nextCharacterIndex = 0; while (nextCharacterIndex < stylesheetBuffer.Length) { // Extract selector int selectorStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{') { // Skip declaration directive starting from @ if (stylesheetBuffer[nextCharacterIndex] == '@') { while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';') { nextCharacterIndex++; } selectorStart = nextCharacterIndex + 1; } nextCharacterIndex++; } if (nextCharacterIndex < stylesheetBuffer.Length) { // Extract definition int definitionStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}') { nextCharacterIndex++; } // Define a style if (nextCharacterIndex - definitionStart > 2) { this.AddStyleDefinition( stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart), stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2)); } // Skip closing brace if (nextCharacterIndex < stylesheetBuffer.Length) { Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}'); nextCharacterIndex++; } } } } // Returns a string with all c-style comments replaced by spaces private string RemoveComments(string text) { int commentStart = text.IndexOf("/*"); if (commentStart < 0) { return text; } int commentEnd = text.IndexOf("*/", commentStart + 2); if (commentEnd < 0) { return text.Substring(0, commentStart); } return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2)); } public void AddStyleDefinition(string selector, string definition) { // Notrmalize parameter values selector = selector.Trim().ToLower(); definition = definition.Trim().ToLower(); if (selector.Length == 0 || definition.Length == 0) { return; } if (_styleDefinitions == null) { _styleDefinitions = new List<StyleDefinition>(); } string[] simpleSelectors = selector.Split(','); for (int i = 0; i < simpleSelectors.Length; i++) { string simpleSelector = simpleSelectors[i].Trim(); if (simpleSelector.Length > 0) { _styleDefinitions.Add(new StyleDefinition(simpleSelector, definition)); } } } public string GetStyle(string elementName, List<XmlElement> sourceContext) { Debug.Assert(sourceContext.Count > 0); Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName); // TODO: Add id processing for style selectors if (_styleDefinitions != null) { for (int i = _styleDefinitions.Count - 1; i >= 0; i--) { string selector = _styleDefinitions[i].Selector; string[] selectorLevels = selector.Split(' '); int indexInSelector = selectorLevels.Length - 1; int indexInContext = sourceContext.Count - 1; string selectorLevel = selectorLevels[indexInSelector].Trim(); if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1])) { return _styleDefinitions[i].Definition; } } } return null; } private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement) { if (selectorLevel.Length == 0) { return false; } int indexOfDot = selectorLevel.IndexOf('.'); int indexOfPound = selectorLevel.IndexOf('#'); string selectorClass = null; string selectorId = null; string selectorTag = null; if (indexOfDot >= 0) { if (indexOfDot > 0) { selectorTag = selectorLevel.Substring(0, indexOfDot); } selectorClass = selectorLevel.Substring(indexOfDot + 1); } else if (indexOfPound >= 0) { if (indexOfPound > 0) { selectorTag = selectorLevel.Substring(0, indexOfPound); } selectorId = selectorLevel.Substring(indexOfPound + 1); } else { selectorTag = selectorLevel; } if (selectorTag != null && selectorTag != xmlElement.LocalName) { return false; } if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId) { return false; } if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass) { return false; } return true; } private class StyleDefinition { public StyleDefinition(string selector, string definition) { this.Selector = selector; this.Definition = definition; } public string Selector; public string Definition; } private List<StyleDefinition> _styleDefinitions; } }
using System; using System.IO; using System.Text; namespace xcite.logging.streams { /// <summary> /// Inherits <see cref="AbstractStream"/> and writes into a specified file. Note, the file stream remains /// as long open as the file stream instance exists. /// </summary> public class FileStream : AbstractStream, FileStream._Bender { private AbstractStreamWriter _streamWriter; /// <inheritdoc /> protected override void OnDispose(bool disposing) { ReleaseUnmanagedResources(); _streamWriter?.Dispose(); _streamWriter = null; } /// <summary> Name of the file the stream writes to. </summary> public string FileName { get; set; } /// <summary> /// Flag to determine whether the file should be appended or overwritten. /// Default is TRUE. /// </summary> public bool Append { get; set; } = true; /// <summary> File locking model. Default is <see cref="ELockingModel.Exclusive"/>. </summary> public ELockingModel LockingModel { get; set; } = ELockingModel.None; /// <summary> Flag to determine to create one log file per day. </summary> public bool DailyRolling { get; set; } /// <inheritdoc /> protected override void Write(string value) { if (string.IsNullOrEmpty(FileName) || string.IsNullOrEmpty(value)) return; AbstractStreamWriter streamWriter = GetStreamWriter(); if (streamWriter == null) return; byte[] data = Encoding.UTF8.GetBytes(value); streamWriter.LockStream(data.Length); try { streamWriter.WriteToStream(data); } finally { streamWriter.UnlockStream(data.Length); } } /// <summary> /// Returns a stream writer to write to. /// The instance is either newly created or an already existing /// one is returned. /// </summary> protected virtual AbstractStreamWriter GetStreamWriter() { if (DailyRolling) { _streamWriter = UpdateFileStream(_streamWriter); } if (_streamWriter != null) return _streamWriter; if (LockingModel == ELockingModel.Exclusive) _streamWriter = new ExclusiveLockingStreamWriter(); else if (LockingModel == ELockingModel.Minimal) _streamWriter = new MinimalLockingStreamWriter(); else _streamWriter = new NonLockingStreamWriter(); string fqFilePath = Path.GetFullPath(FileName); string fqFolderPath = Path.GetDirectoryName(fqFilePath); if (!string.IsNullOrEmpty(fqFolderPath) && !Directory.Exists(fqFolderPath)) Directory.CreateDirectory(fqFolderPath); _streamWriter.InitStream(FileName, Append); return _streamWriter; } /// <summary> /// Returns an updated file stream when last write date of the <paramref name="currentStream"/> /// has another day than today. In this case, the <paramref name="currentStream"/> is closed /// and its file is renamed. Finally, NULL is returned. /// When the <paramref name="currentStream"/> does not require an update, it is returned /// unmodified. /// </summary> protected virtual AbstractStreamWriter UpdateFileStream(AbstractStreamWriter currentStream) { // No stream, nothing to check if (currentStream == null) return null; // When nothing has been written to the stream yet, there is nothing to check if (currentStream.lastWrite == default) return currentStream; // When the day hasn't changed yet, there is nothing to do if (currentStream.lastWrite.Day == DateTime.Today.Day) return currentStream; // Close stream DateTime lastWriteDay = currentStream.lastWrite; currentStream.Dispose(); // Calculate new file name string year = lastWriteDay.Year.ToString(); string month = lastWriteDay.Month.ToString("00"); string day = lastWriteDay.Day.ToString("00"); int extIdx = FileName.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase); string fnm = FileName.Substring(0, extIdx); string ext = FileName.Substring(extIdx); string mvFn = $"{fnm}-{year}-{month}-{day}{ext}"; // Renamed existing file File.Move(FileName, mvFn); // Drop existing file stream return null; } /// <summary> /// Is invoked when the instance is being disposed. Clients may added some /// addition disposing steps here. /// </summary> protected virtual void ReleaseUnmanagedResources() { // Clients may override } /// <inheritdoc /> void _Bender.SetLastWrite(DateTime value) { if (_streamWriter == null) return; _streamWriter.lastWrite = value; } /// <summary> Defines a locking model aware file stream writer. /// </summary> protected abstract class AbstractStreamWriter : IDisposable { private System.IO.FileStream _fileStream; public DateTime lastWrite; /// <summary> /// Initializes a file stream with the specified <paramref name="fileName"/>. /// If <paramref name="append"/> is FALSE, a new file is always created and an /// existing file is overridden.. Otherwise an existing file is extended. If /// no file exists, a new one is always created. /// </summary> public virtual void InitStream(string fileName, bool append) { FileMode fileMode = append ? FileMode.OpenOrCreate : FileMode.Create; _fileStream = OnInitStream(fileName, fileMode); _fileStream.Seek(0, SeekOrigin.End); } /// <summary> /// Notifies the instance to lock the file stream so that no other /// process can access the file. /// </summary> public virtual void LockStream(int size) => OnLockStream(_fileStream, size); /// <summary> Writes the given <paramref name="data"/> to the underlying stream. </summary> public virtual void WriteToStream(byte[] data) { _fileStream.Write(data, 0, data.Length); _fileStream.Flush(); lastWrite = DateTime.Today; } /// <summary> /// Notifies the instance to unlock the file stream so that other /// processes may access the file. /// </summary> public virtual void UnlockStream(int size) => OnUnlockStream(_fileStream, size); /// <inheritdoc /> public virtual void Dispose() { _fileStream?.Dispose(); _fileStream = null; } /// <summary> /// Is invoked when <see cref="InitStream"/> is called. Sub-classes /// can add custom behavior to the stream. /// </summary> /// <returns></returns> protected abstract System.IO.FileStream OnInitStream(string fileName, FileMode fileMode); /// <summary> /// Is invoked when <see cref="LockStream"/> is called. Sub-classes /// can add custom behavior to the stream. /// </summary> protected abstract void OnLockStream(System.IO.FileStream fileStream, int size); /// <summary> /// Is invoked when <see cref="UnlockStream"/> is called. Sub-classes /// can add custom behavior to the stream. /// </summary> protected abstract void OnUnlockStream(System.IO.FileStream fileStream, int size); } /// <summary> /// Implementation of <see cref="AbstractStreamWriter"/> that does not acquire /// a lock for the log file. Other processes can always read the file. /// </summary> private class NonLockingStreamWriter : AbstractStreamWriter { /// <inheritdoc /> protected override System.IO.FileStream OnInitStream(string fileName, FileMode fileMode) { return new System.IO.FileStream(fileName, fileMode, FileAccess.Write, FileShare.ReadWrite); } /// <inheritdoc /> protected override void OnLockStream(System.IO.FileStream fileStream, int size) { // No lock } /// <inheritdoc /> protected override void OnUnlockStream(System.IO.FileStream fileStream, int size) { // No unlock } } /// <summary> /// Implementation of <see cref="AbstractStreamWriter"/> that only acquires /// a lock for the log file in the moment of writing. Other processes can /// mostly read the log file. /// </summary> class MinimalLockingStreamWriter : AbstractStreamWriter { /// <inheritdoc /> protected override System.IO.FileStream OnInitStream(string fileName, FileMode fileMode) { return new System.IO.FileStream(fileName, fileMode, FileAccess.Write, FileShare.Read); } /// <inheritdoc /> protected override void OnLockStream(System.IO.FileStream fileStream, int size) { // No additional lock required } /// <inheritdoc /> protected override void OnUnlockStream(System.IO.FileStream fileStream, int size) { // No additional lock required } } /// <summary> /// Implementation of <see cref="AbstractStreamWriter"/> that acquires /// an exclusive lock for the log file. No other process can read or /// write to that file. /// </summary> class ExclusiveLockingStreamWriter : AbstractStreamWriter { /// <inheritdoc /> protected override System.IO.FileStream OnInitStream(string fileName, FileMode fileMode) { return new System.IO.FileStream(fileName, fileMode, FileAccess.Write, FileShare.None); } /// <inheritdoc /> protected override void OnLockStream(System.IO.FileStream fileStream, int size) { // No additional lock required } /// <inheritdoc /> protected override void OnUnlockStream(System.IO.FileStream fileStream, int size) { // No additional unlock required } } /// <summary> Interface for internal usage </summary> // ReSharper disable once InconsistentNaming public interface _Bender { /// <summary> Sets the last write instant to the given <paramref name="value"/>. </summary> void SetLastWrite(DateTime value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal sealed class OpenSslX509ChainProcessor : IChainPal { // Constructed (0x20) | Sequence (0x10) => 0x30. private const uint ConstructedSequenceTagId = 0x30; public void Dispose() { } public bool? Verify(X509VerificationFlags flags, out Exception exception) { exception = null; bool isEndEntity = true; foreach (X509ChainElement element in ChainElements) { if (HasUnsuppressedError(flags, element, isEndEntity)) { return false; } isEndEntity = false; } return true; } private static bool HasUnsuppressedError(X509VerificationFlags flags, X509ChainElement element, bool isEndEntity) { foreach (X509ChainStatus status in element.ChainElementStatus) { if (status.Status == X509ChainStatusFlags.NoError) { return false; } Debug.Assert( (status.Status & (status.Status - 1)) == 0, "Only one bit is set in status.Status"); // The Windows certificate store API only checks the time error for a "peer trust" certificate, // but we don't have a concept for that in Unix. If we did, we'd need to do that logic that here. // Note also that that logic is skipped if CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG is set. X509VerificationFlags? suppressionFlag; if (status.Status == X509ChainStatusFlags.RevocationStatusUnknown) { if (isEndEntity) { suppressionFlag = X509VerificationFlags.IgnoreEndRevocationUnknown; } else if (IsSelfSigned(element.Certificate)) { suppressionFlag = X509VerificationFlags.IgnoreRootRevocationUnknown; } else { suppressionFlag = X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown; } } else { suppressionFlag = GetSuppressionFlag(status.Status); } // If an error was found, and we do NOT have the suppression flag for it enabled, // we have an unsuppressed error, so return true. (If there's no suppression for a given code, // we (by definition) don't have that flag set. if (!suppressionFlag.HasValue || (flags & suppressionFlag) == 0) { return true; } } return false; } public X509ChainElement[] ChainElements { get; private set; } public X509ChainStatus[] ChainStatus { get; private set; } public SafeX509ChainHandle SafeHandle { get { return null; } } public static IChainPal BuildChain( X509Certificate2 leaf, HashSet<X509Certificate2> candidates, HashSet<X509Certificate2> downloaded, HashSet<X509Certificate2> systemTrusted, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, ref TimeSpan remainingDownloadTime) { X509ChainElement[] elements; List<X509ChainStatus> overallStatus = new List<X509ChainStatus>(); WorkingChain workingChain = new WorkingChain(); Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback; // An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to // Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes. // // (If you need to think of it as an X509Store, it's a volatile memory store) using (SafeX509StoreHandle store = Interop.Crypto.X509StoreCreate()) using (SafeX509StoreCtxHandle storeCtx = Interop.Crypto.X509StoreCtxCreate()) { Interop.Crypto.CheckValidOpenSslHandle(store); Interop.Crypto.CheckValidOpenSslHandle(storeCtx); bool lookupCrl = revocationMode != X509RevocationMode.NoCheck; foreach (X509Certificate2 cert in candidates) { OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal; if (!Interop.Crypto.X509StoreAddCert(store, pal.SafeHandle)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } if (lookupCrl) { CrlCache.AddCrlForCertificate( cert, store, revocationMode, verificationTime, ref remainingDownloadTime); // If we only wanted the end-entity certificate CRL then don't look up // any more of them. lookupCrl = revocationFlag != X509RevocationFlag.EndCertificateOnly; } } if (revocationMode != X509RevocationMode.NoCheck) { if (!Interop.Crypto.X509StoreSetRevocationFlag(store, revocationFlag)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle; if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } Interop.Crypto.X509StoreCtxSetVerifyCallback(storeCtx, workingCallback); Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime); int verify = Interop.Crypto.X509VerifyCert(storeCtx); if (verify < 0) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the // chain is just fine (unless it returned a negative code for an exception) Debug.Assert(verify == 1, "verify == 1"); using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(storeCtx)) { int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack); elements = new X509ChainElement[chainSize]; int maybeRootDepth = chainSize - 1; // The leaf cert is 0, up to (maybe) the root at chainSize - 1 for (int i = 0; i < chainSize; i++) { List<X509ChainStatus> status = new List<X509ChainStatus>(); List<Interop.Crypto.X509VerifyStatusCode> elementErrors = i < workingChain.Errors.Count ? workingChain.Errors[i] : null; if (elementErrors != null) { AddElementStatus(elementErrors, status, overallStatus); } IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i); if (elementCertPtr == IntPtr.Zero) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Duplicate the certificate handle X509Certificate2 elementCert = new X509Certificate2(elementCertPtr); // If the last cert is self signed then it's the root cert, do any extra checks. if (i == maybeRootDepth && IsSelfSigned(elementCert)) { // If the root certificate was downloaded or the system // doesn't trust it, it's untrusted. if (downloaded.Contains(elementCert) || !systemTrusted.Contains(elementCert)) { AddElementStatus( Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED, status, overallStatus); } } elements[i] = new X509ChainElement(elementCert, status.ToArray(), ""); } } } GC.KeepAlive(workingCallback); if ((certificatePolicy != null && certificatePolicy.Count > 0) || (applicationPolicy != null && applicationPolicy.Count > 0)) { List<X509Certificate2> certsToRead = new List<X509Certificate2>(); foreach (X509ChainElement element in elements) { certsToRead.Add(element.Certificate); } CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead); bool failsPolicyChecks = false; if (certificatePolicy != null) { if (!policyChain.MatchesCertificatePolicies(certificatePolicy)) { failsPolicyChecks = true; } } if (applicationPolicy != null) { if (!policyChain.MatchesApplicationPolicies(applicationPolicy)) { failsPolicyChecks = true; } } if (failsPolicyChecks) { X509ChainElement leafElement = elements[0]; X509ChainStatus chainStatus = new X509ChainStatus { Status = X509ChainStatusFlags.InvalidPolicyConstraints, StatusInformation = SR.Chain_NoPolicyMatch, }; var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1); elementStatus.AddRange(leafElement.ChainElementStatus); AddUniqueStatus(elementStatus, ref chainStatus); AddUniqueStatus(overallStatus, ref chainStatus); elements[0] = new X509ChainElement( leafElement.Certificate, elementStatus.ToArray(), leafElement.Information); } } return new OpenSslX509ChainProcessor { ChainStatus = overallStatus.ToArray(), ChainElements = elements, }; } private static void AddElementStatus( List<Interop.Crypto.X509VerifyStatusCode> errorCodes, List<X509ChainStatus> elementStatus, List<X509ChainStatus> overallStatus) { foreach (var errorCode in errorCodes) { AddElementStatus(errorCode, elementStatus, overallStatus); } } private static void AddElementStatus( Interop.Crypto.X509VerifyStatusCode errorCode, List<X509ChainStatus> elementStatus, List<X509ChainStatus> overallStatus) { X509ChainStatusFlags statusFlag = MapVerifyErrorToChainStatus(errorCode); Debug.Assert( (statusFlag & (statusFlag - 1)) == 0, "Status flag has more than one bit set", "More than one bit is set in status '{0}' for error code '{1}'", statusFlag, errorCode); foreach (X509ChainStatus currentStatus in elementStatus) { if ((currentStatus.Status & statusFlag) != 0) { return; } } X509ChainStatus chainStatus = new X509ChainStatus { Status = statusFlag, StatusInformation = Interop.Crypto.GetX509VerifyCertErrorString(errorCode), }; elementStatus.Add(chainStatus); AddUniqueStatus(overallStatus, ref chainStatus); } private static void AddUniqueStatus(IList<X509ChainStatus> list, ref X509ChainStatus status) { X509ChainStatusFlags statusCode = status.Status; for (int i = 0; i < list.Count; i++) { if (list[i].Status == statusCode) { return; } } list.Add(status); } private static X509VerificationFlags? GetSuppressionFlag(X509ChainStatusFlags status) { switch (status) { case X509ChainStatusFlags.UntrustedRoot: case X509ChainStatusFlags.PartialChain: return X509VerificationFlags.AllowUnknownCertificateAuthority; case X509ChainStatusFlags.NotValidForUsage: case X509ChainStatusFlags.CtlNotValidForUsage: return X509VerificationFlags.IgnoreWrongUsage; case X509ChainStatusFlags.NotTimeValid: return X509VerificationFlags.IgnoreNotTimeValid; case X509ChainStatusFlags.CtlNotTimeValid: return X509VerificationFlags.IgnoreCtlNotTimeValid; case X509ChainStatusFlags.InvalidNameConstraints: case X509ChainStatusFlags.HasNotSupportedNameConstraint: case X509ChainStatusFlags.HasNotDefinedNameConstraint: case X509ChainStatusFlags.HasNotPermittedNameConstraint: case X509ChainStatusFlags.HasExcludedNameConstraint: return X509VerificationFlags.IgnoreInvalidName; case X509ChainStatusFlags.InvalidPolicyConstraints: case X509ChainStatusFlags.NoIssuanceChainPolicy: return X509VerificationFlags.IgnoreInvalidPolicy; case X509ChainStatusFlags.InvalidBasicConstraints: return X509VerificationFlags.IgnoreInvalidBasicConstraints; case X509ChainStatusFlags.HasNotSupportedCriticalExtension: // This field would be mapped in by AllFlags, but we don't have a name for it currently. return (X509VerificationFlags)0x00002000; case X509ChainStatusFlags.NotTimeNested: return X509VerificationFlags.IgnoreNotTimeNested; } return null; } private static X509ChainStatusFlags MapVerifyErrorToChainStatus(Interop.Crypto.X509VerifyStatusCode code) { switch (code) { case Interop.Crypto.X509VerifyStatusCode.X509_V_OK: return X509ChainStatusFlags.NoError; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_NOT_YET_VALID: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_HAS_EXPIRED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: return X509ChainStatusFlags.NotTimeValid; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED: return X509ChainStatusFlags.Revoked; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE: return X509ChainStatusFlags.NotSignatureValid; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: return X509ChainStatusFlags.UntrustedRoot; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_HAS_EXPIRED: return X509ChainStatusFlags.OfflineRevocation; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_SIGNATURE_FAILURE: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: return X509ChainStatusFlags.RevocationStatusUnknown; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_EXTENSION: return X509ChainStatusFlags.InvalidExtension; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: return X509ChainStatusFlags.PartialChain; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_PURPOSE: return X509ChainStatusFlags.NotValidForUsage; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_CA: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_NON_CA: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_PATH_LENGTH_EXCEEDED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CERTSIGN: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: return X509ChainStatusFlags.InvalidBasicConstraints; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_POLICY_EXTENSION: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_NO_EXPLICIT_POLICY: return X509ChainStatusFlags.InvalidPolicyConstraints; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REJECTED: return X509ChainStatusFlags.ExplicitDistrust; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: return X509ChainStatusFlags.HasNotSupportedCriticalExtension; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_CHAIN_TOO_LONG: throw new CryptographicException(); case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_OUT_OF_MEM: throw new OutOfMemoryException(); default: Debug.Fail("Unrecognized X509VerifyStatusCode:" + code); throw new CryptographicException(); } } internal static HashSet<X509Certificate2> FindCandidates( X509Certificate2 leaf, X509Certificate2Collection extraStore, HashSet<X509Certificate2> downloaded, HashSet<X509Certificate2> systemTrusted, ref TimeSpan remainingDownloadTime) { var candidates = new HashSet<X509Certificate2>(); var toProcess = new Queue<X509Certificate2>(); toProcess.Enqueue(leaf); using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine)) using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser)) using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser)) { systemRootStore.Open(OpenFlags.ReadOnly); systemIntermediateStore.Open(OpenFlags.ReadOnly); userRootStore.Open(OpenFlags.ReadOnly); userIntermediateStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection systemRootCerts = systemRootStore.Certificates; X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates; X509Certificate2Collection userRootCerts = userRootStore.Certificates; X509Certificate2Collection userIntermediateCerts = userIntermediateStore.Certificates; // fill the system trusted collection foreach (X509Certificate2 systemRootCert in systemRootCerts) { systemTrusted.Add(systemRootCert); } foreach (X509Certificate2 userRootCert in userRootCerts) { systemTrusted.Add(userRootCert); } X509Certificate2Collection[] storesToCheck = { extraStore, userIntermediateCerts, systemIntermediateCerts, userRootCerts, systemRootCerts, }; while (toProcess.Count > 0) { X509Certificate2 current = toProcess.Dequeue(); candidates.Add(current); HashSet<X509Certificate2> results = FindIssuer( current, storesToCheck, downloaded, ref remainingDownloadTime); if (results != null) { foreach (X509Certificate2 result in results) { if (!candidates.Contains(result)) { toProcess.Enqueue(result); } } } } } return candidates; } private static HashSet<X509Certificate2> FindIssuer( X509Certificate2 cert, X509Certificate2Collection[] stores, HashSet<X509Certificate2> downloadedCerts, ref TimeSpan remainingDownloadTime) { if (IsSelfSigned(cert)) { // It's a root cert, we won't make any progress. return null; } SafeX509Handle certHandle = ((OpenSslX509CertificateReader)cert.Pal).SafeHandle; foreach (X509Certificate2Collection store in stores) { HashSet<X509Certificate2> fromStore = null; foreach (X509Certificate2 candidate in store) { SafeX509Handle candidateHandle = ((OpenSslX509CertificateReader)candidate.Pal).SafeHandle; int issuerError = Interop.Crypto.X509CheckIssued(candidateHandle, certHandle); if (issuerError == 0) { if (fromStore == null) { fromStore = new HashSet<X509Certificate2>(); } fromStore.Add(candidate); } } if (fromStore != null) { return fromStore; } } byte[] authorityInformationAccess = null; foreach (X509Extension extension in cert.Extensions) { if (StringComparer.Ordinal.Equals(extension.Oid.Value, Oids.AuthorityInformationAccess)) { // If there's an Authority Information Access extension, it might be used for // looking up additional certificates for the chain. authorityInformationAccess = extension.RawData; break; } } if (authorityInformationAccess != null) { X509Certificate2 downloaded = DownloadCertificate( authorityInformationAccess, ref remainingDownloadTime); if (downloaded != null) { downloadedCerts.Add(downloaded); return new HashSet<X509Certificate2>() { downloaded }; } } return null; } private static bool IsSelfSigned(X509Certificate2 cert) { return StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer); } private static X509Certificate2 DownloadCertificate( byte[] authorityInformationAccess, ref TimeSpan remainingDownloadTime) { // Don't do any work if we're over limit. if (remainingDownloadTime <= TimeSpan.Zero) { return null; } string uri = FindHttpAiaRecord(authorityInformationAccess, Oids.CertificateAuthorityIssuers); if (uri == null) { return null; } return CertificateAssetDownloader.DownloadCertificate(uri, ref remainingDownloadTime); } internal static string FindHttpAiaRecord(byte[] authorityInformationAccess, string recordTypeOid) { DerSequenceReader reader = new DerSequenceReader(authorityInformationAccess); while (reader.HasData) { DerSequenceReader innerReader = reader.ReadSequence(); // If the sequence's first element is a sequence, unwrap it. if (innerReader.PeekTag() == ConstructedSequenceTagId) { innerReader = innerReader.ReadSequence(); } Oid oid = innerReader.ReadOid(); if (StringComparer.Ordinal.Equals(oid.Value, recordTypeOid)) { string uri = innerReader.ReadIA5String(); Uri parsedUri; if (!Uri.TryCreate(uri, UriKind.Absolute, out parsedUri)) { continue; } if (!StringComparer.Ordinal.Equals(parsedUri.Scheme, "http")) { continue; } return uri; } } return null; } private class WorkingChain { internal readonly List<List<Interop.Crypto.X509VerifyStatusCode>> Errors = new List<List<Interop.Crypto.X509VerifyStatusCode>>(); internal int VerifyCallback(int ok, IntPtr ctx) { if (ok < 0) { return ok; } try { using (var storeCtx = new SafeX509StoreCtxHandle(ctx, ownsHandle: false)) { Interop.Crypto.X509VerifyStatusCode errorCode = Interop.Crypto.X509StoreCtxGetError(storeCtx); int errorDepth = Interop.Crypto.X509StoreCtxGetErrorDepth(storeCtx); if (errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_OK) { while (Errors.Count <= errorDepth) { Errors.Add(null); } if (Errors[errorDepth] == null) { Errors[errorDepth] = new List<Interop.Crypto.X509VerifyStatusCode>(); } Errors[errorDepth].Add(errorCode); } } return 1; } catch { return -1; } } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXCRPC { using System; using System.Threading; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario contains test cases that refer to methods on AsyncEMSMDB interface /// </summary> [TestClass] public class S02_AsynchronousCall : TestSuiteBase { #region Variable /// <summary> /// Indicates whether events are pending for the client on the Session Context on the server. /// </summary> private bool isNotificationPending; /// <summary> /// A Boolean indicates whether the server disable asynchronous RPC notification. /// </summary> private bool isDisableAsyncRPCNotification = false; /// <summary> /// Declares a delegate for a method that returns a uint. /// </summary> /// <returns>Returns a delegate object.</returns> private delegate uint MethodCaller(); #endregion #region Test Class Initialization and Cleanup /// <summary> /// Initializes the test class before running the test cases in the class. /// </summary> /// <param name="context">Context of test class</param> [ClassInitialize] public static void ClassInitialize(TestContext context) { TestClassBase.Initialize(context); } /// <summary> /// Clean up the test class after running the test cases in the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion /// <summary> /// This case tests methods on the AsyncEMSMDB interface without pending events. /// </summary> [TestCategory("MSOXCRPC"), TestMethod()] public void MSOXCRPC_S02_TC01_TestWithoutPendingEvent() { this.CheckTransport(); #region Client connects with Server this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed, and send Session Context Handle (CXH) to EcDoAsyncConnectEx for testing EcDoAsyncWaitEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Call EcDoAsyncConnectEx this.returnValue = this.oxcrpcAdapter.EcDoAsyncConnectEx(this.pcxh, ref this.pacxh); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R713, the returned value of method EcDoAsyncConnectEx is {0}.", this.returnValue); // Verify MS-OXCRPC requirement: MS-OXCRPC_R713 Site.CaptureRequirementIfAreEqual<uint>( 0, this.returnValue, 713, @"[In EcDoAsyncConnectEx Method (opnum 14)] Return Values: If the method succeeds, the return value is 0."); #endregion #region Call EcDoAsyncWaitEx DateTime startTime = DateTime.Now; this.returnValue = this.oxcrpcAdapter.EcDoAsyncWaitEx(this.pacxh, out this.isNotificationPending); DateTime endTime = DateTime.Now; TimeSpan interval = endTime.Subtract(startTime); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R704, the returned value of method EcDoAsyncWaitEx is {0}.", this.returnValue); // Verify MS-OXCRPC requirement: MS-OXCRPC_R704 // Method EcDoAsyncWaitEx succeed indicates that method EcDoAsyncConnectEx binds a session context handle can be used in calls to EcDoAsyncWaitEx. Site.CaptureRequirementIfAreEqual<uint>( 0, this.returnValue, 704, @"[In EcDoAsyncConnectEx Method (opnum 14)] The EcDoAsyncConnectEx method binds a session context handle returned from the EcDoConnectEx method, as specified in section 3.1.4.1, to a new asynchronous context handle that can be used in calls to the EcDoAsyncWaitEx method in the AsyncEMSMDB interface, as specified in section 3.3.4.1."); if (Common.IsRequirementEnabled(1930, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1930, there are {0} pending events for the client on the Session Context on the server.The EcDoAsyncWaitEx execute time is {1}", this.isNotificationPending ? string.Empty : "not", interval.TotalMinutes); // Because above step not trigger any event, so if isNotificationPending is false and the execute time of EcDoAsyncWaitEx larger than 5 minutes.R1930 will be verified. bool isR1930Verified = this.isNotificationPending == false && interval.TotalSeconds >= 290; // Verify MS-OXCRPC requirement: MS-OXCRPC_R1930 Site.CaptureRequirementIfIsTrue( isR1930Verified, 1930, @"[In Appendix B: Product Behavior] Implementation does return the call and will not set the NotificationPending flag in the pulFlagsOut field, If no events are available within five minutes of the time that the client last accessed the server through a call to EcDoRpcExt2. (Microsoft Exchange Server 2010 and above follow this behavior.)"); } if (Common.IsRequirementEnabled(1907, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1907, there are {0} pending events for the client on the Session Context on the server. The EcDoAsyncWaitEx execute time is {1}", this.isNotificationPending ? string.Empty : "not", interval.TotalMinutes); bool isR1907Verified = interval.TotalSeconds >= 290 && interval.TotalSeconds < 360; // Verify MS-OXCRPC requirement: MS-OXCRPC_R1907 Site.CaptureRequirementIfIsTrue( isR1907Verified, 1907, @"[In Appendix B: Product Behavior] Implementation does complete the call every 5 minutes regardless of the client's last activity time. [In Appendix B: Product Behavior] <37> Section 3.3.4.1: Exchange 2007 completes the call every 5 minutes regardless of the client's last activity time."); } // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1338"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1338 Site.CaptureRequirementIfAreEqual<uint>( 0, this.returnValue, 1338, @"[In EcDoAsyncWaitEx Method (opnum 0)] Return Values: If the method succeeds, the return value is 0."); if (Common.IsRequirementEnabled(1922, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1922"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1922 // If this method is invoked successfully, it means EcDoAsyncWaitEx method is supported. The return value 0 means success. Site.CaptureRequirementIfAreEqual<uint>( 0, this.returnValue, 1922, @"[In Appendix B: Product Behavior] <36> Section 3.3.4: Implementation does support AsyncEMSMDB method EcDoAsyncWaitEx. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } #endregion #region Client disconnects with Server this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); #endregion } /// <summary> /// This case tests methods on the AsyncEMSMDB interface with pending events. /// </summary> [TestCategory("MSOXCRPC"), TestMethod()] public void MSOXCRPC_S02_TC02_TestWithPendingEvent() { this.CheckTransport(); #region Initializes Server and Client this.returnStatus = this.oxcrpcAdapter.InitializeRPC(this.authenticationLevel, this.authenticationService, this.userName, this.password); Site.Assert.IsTrue(this.returnStatus, "The returned status is {0}. TRUE means that initializing the server and client to call EcDoAsyncWaitEx successfully, and FALSE means that initializing the server and client to call EcDoAsyncWaitEx failed.", this.returnStatus); #endregion #region Client connects with Server this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed and send Session Context Handle (CXH) to EcDoRpcExt2 for testing EcDoAsyncWaitEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Call EcDoRpcExt2 method with RopLogon as rgbIn // Parameter inObjHandle is no use for RopLogon command, so set it to unUsedInfo. this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopLogon, this.unusedInfo, this.userPrivilege); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoRpcExt2 should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); RopLogonResponse logonResponse = (RopLogonResponse)this.response; Site.Assert.AreEqual<uint>(0, logonResponse.ReturnValue, "RopLogon should succeed and 0 is expected to be returned. The returned value is {0}.", logonResponse.ReturnValue); this.objHandle = this.responseSOHTable[TestSuiteBase.FIRST][logonResponse.OutputHandleIndex]; #endregion #region Call EcDoAsyncConnectEx this.returnValue = this.oxcrpcAdapter.EcDoAsyncConnectEx(this.pcxh, ref this.pacxh); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoAsyncConnectEx should succeed and sends ACXH to EcDoAsyncWaitEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Register events on server this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopRegisterNotification, this.objHandle, logonResponse.FolderIds[(int)FolderIds.InterpersonalMessage]); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoRpcExt2 should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); RopRegisterNotificationResponse registerNotificationResponse = (RopRegisterNotificationResponse)this.response; Site.Assert.AreEqual<uint>(0, registerNotificationResponse.ReturnValue, "RopRegisterNotification should succeed and 0 is expected to be returned. The returned value is {0}.", registerNotificationResponse.ReturnValue); #endregion #region Call EcDoAsyncWaitEx // Trigger the event bool isCreateMailSuccess = this.oxcrpcControlAdapter.CreateMailItem(); Site.Assert.IsTrue(isCreateMailSuccess, "CreateMailItem method should execute successfully."); this.returnValue = this.oxcrpcAdapter.EcDoAsyncWaitEx(this.pacxh, out this.isNotificationPending); Site.Assert.AreEqual<uint>(0, this.returnValue, @"EcDoAsyncWaitEx should succeed to check whether the NotificationPending flag is set in the pulFlagsOut field, on AsyncEMSMDB method if an event is pending. '0' is expected to be returned. The returned value is {0}.", this.returnValue); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1231, there are {0} pending events for the client on the Session Context on the server.", this.isNotificationPending ? string.Empty : "not"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1231 Site.CaptureRequirementIfIsTrue( this.isNotificationPending, 1231, @"[In EcDoAsyncWaitEx Method (opnum 0)] If an event is pending, the server completes the call immediately and returns the NotificationPending flag in the pulFlagsOut parameter."); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R19"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R19 // Because client can use the asynchronous context handle to call EcDoAsyncWaitEx method successful. // So R19 will be verified. this.Site.CaptureRequirementIfAreEqual<uint>( 0, this.returnValue, 19, @"[In ACXH Data Type] The AXCH data type is an asynchronous context handle to be used with an AsyncEMSMDB interface, as specified in section 3.3 and section 3.4."); #endregion #region Call EcDoRpcExt2 with no ROP in rgbIn to get the notify information // Parameter inObjHandle and auxInfo are no use for null ROP command, so set them to unUsedInfo. this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.WithoutRops, this.unusedInfo, this.unusedInfo); this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.pcbOut = ConstValues.ValidpcbOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); Site.Assert.AreEqual<uint>(0, this.returnValue, @"EcDoRpcExt2 should succeed to get the RopNotifyResponse. '0' is expected to be returned. The returned value is {0}.", this.returnValue); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1243, the ROP response is {0}", (RopNotifyResponse)this.response); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1243 // According to the Open Specification MS-OXCNOTIF, the event details are in the RopNotifyResponse. If the rgbOut can be converted (parsed) to RopNotifyResponse, this requirement will be verified. Site.CaptureRequirementIfIsNotNull( (RopNotifyResponse)this.response, 1243, @"[In EcDoAsyncWaitEx Method (opnum 0)] [pulFlagsOut] [Flag NotificationPending] The server will return the event details in the ROP response buffer."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1229, the ROP response is {0}", (RopNotifyResponse)this.response); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1229 // If the response of method EcDoRpcExt2 is not null, it indicates that method EcDoAsyncWaitEx have been completed because server will return the event details in the ROP response buffer. Site.CaptureRequirementIfIsNotNull( (RopNotifyResponse)this.response, 1229, @"[In EcDoAsyncWaitEx Method (opnum 0)] The EcDoAsyncWaitEx method is an asynchronous call that the server does not complete until events are pending on the Session Context, up to a 5-minute duration of no client activity."); #endregion #region Client disconnects with Server this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoDisconnect should succeed and CXH used for testing EcDoAsyncWaitEx should be released. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion } /// <summary> /// This case tests calling EcDoAsyncWaitEx when asynchronous context handle becomes invalid. /// </summary> [TestCategory("MSOXCRPC"), TestMethod()] public void MSOXCRPC_S02_TC03_TestInvalidAsynchronousContextHandle() { this.CheckTransport(); #region Client connects with Server this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed, and send Session Context Handle (CXH) to EcDoAsyncConnectEx for testing EcDoAsyncWaitEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Call EcDoRpcExt2 method with RopLogon as rgbIn // Parameter inObjHandle is no use for RopLogon command, so set it to unUsedInfo. this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopLogon, this.unusedInfo, this.userPrivilege); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); Site.Assert.AreEqual<uint>(0, this.returnValue, "RopLogon should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); RopLogonResponse logonResponse = (RopLogonResponse)this.response; Site.Assert.AreEqual<uint>(0, logonResponse.ReturnValue, "RopLogon should succeed and 0 is expected to be returned. The returned value is {0}.", logonResponse.ReturnValue); this.objHandle = this.responseSOHTable[TestSuiteBase.FIRST][logonResponse.OutputHandleIndex]; #endregion #region Call EcDoAsyncConnectEx this.returnValue = this.oxcrpcAdapter.EcDoAsyncConnectEx(this.pcxh, ref this.pacxh); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoAsyncConnectEx should succeed and sends ACXH to EcDoAsyncWaitEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Register events on server this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopRegisterNotification, this.objHandle, logonResponse.FolderIds[(int)FolderIds.InterpersonalMessage]); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoRpcExt2 should succeed and '0' is expected to be returned. The returned value is {0}.", this.returnValue); RopRegisterNotificationResponse registerNotificationResponse = (RopRegisterNotificationResponse)this.response; Site.Assert.AreEqual<uint>(0, registerNotificationResponse.ReturnValue, "RopRegisterNotification should succeed and '0' is expected to be returned. The returned value is {0}.", registerNotificationResponse.ReturnValue); #endregion #region Client disconnects with Server this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoDisconnect should succeed and CXH used for testing EcDoAsyncWaitEx should be released. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Call EcDoAsyncWaitEx uint returnValueForEcDoAsyncWaitEx = this.oxcrpcAdapter.EcDoAsyncWaitEx(this.pacxh, out this.isNotificationPending); #endregion #region Call EcDoRpcExt2 with no ROP in rgbIn to get the notify information // Parameter inObjHandle and auxInfo are no use for null ROP command, so set them to unUsedInfo. this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.WithoutRops, this.unusedInfo, this.unusedInfo); this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.pcbOut = ConstValues.ValidpcbOut; uint returnValueForEcDoRpcExt2 = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); #region Capture code. // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1213, server returns {0} when call EcDoAsyncWaitEx, server returns {1} when call EcDoRpcExt2.", returnValueForEcDoAsyncWaitEx, returnValueForEcDoRpcExt2); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1213 bool isVerifiedR1213 = returnValueForEcDoAsyncWaitEx != 0 || returnValueForEcDoRpcExt2 != 0; this.Site.CaptureRequirementIfIsTrue( isVerifiedR1213, 1213, @"[In Abstract Data Model] When the session context is destroyed, the asynchronous context handle becomes invalid and will be rejected if used."); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1269,server returns {0} when call EcDoAsyncWaitEx, server returns {1} when call EcDoRpcExt2.", returnValueForEcDoAsyncWaitEx, returnValueForEcDoRpcExt2); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1269 bool isVerifiedR1269 = returnValueForEcDoAsyncWaitEx != 0 || returnValueForEcDoRpcExt2 != 0; this.Site.CaptureRequirementIfIsTrue( isVerifiedR1269, 1269, @"[In Abstract Data Model] When the client connection is lost, the asynchronous context handle becomes invalid and will be rejected if used."); #endregion #endregion } /// <summary> /// This case tests calling EcDoAsyncWaitEx unsuccessfully. /// </summary> [TestCategory("MSOXCRPC"), TestMethod()] public void MSOXCRPC_S02_TC04_TestEcDoAsyncWaitExFail() { this.CheckTransport(); #region Client connects with Server this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed, and send Session Context Handle (CXH) to EcDoAsyncConnectEx for testing EcDoAsyncWaitEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Call EcDoAsyncConnectEx this.returnValue = this.oxcrpcAdapter.EcDoAsyncConnectEx(this.pcxh, ref this.pacxh); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R713, the returned value of method EcDoAsyncConnectEx is {0}.", this.returnValue); // Verify MS-OXCRPC requirement: MS-OXCRPC_R713 Site.CaptureRequirementIfAreEqual<uint>( 0, this.returnValue, 713, @"[In EcDoAsyncConnectEx Method (opnum 14)] Return Values: If the method succeeds, the return value is 0."); #endregion #region Call EcDoAsyncWaitEx when pacxh is invalid this.pcxhInvalid = (IntPtr)ConstValues.InvalidPcxh; this.returnValueForInvalidCXH = this.oxcrpcAdapter.EcDoAsyncWaitEx(this.pcxhInvalid, out this.isNotificationPending); Site.Assert.AreNotEqual<uint>(0, this.returnValueForInvalidCXH, "EcDoAsyncWaitEx should not succeed if the CXH is invalid. '0' isn't expected to be returned. The returned value is {0}.", this.returnValueForInvalidCXH); #endregion #region Capture code. // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1228, the return value of EcDoAsyncWaitEx with ACXH valid is {0}, the return value of EcDoAsyncWaitEx with ACXH invalid is {1}.", this.returnValue, this.returnValueForInvalidCXH); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1228 // When the ACXH is returned from EcDoAsyncWaitEx method, the call is successful. While the ACXH is not returned from the EcDoAsyncWaitEx method, the call is failed. // If the code can reach here, this requirement is verified. bool isVerifyR1228 = (this.returnValue == ResultSuccess) && (this.returnValueForInvalidCXH != ResultSuccess); Site.CaptureRequirementIfIsTrue( isVerifyR1228, 1228, @"[In Message Processing Events and Sequencing Rules] Method EcDoAsyncWaitEx: The method requires an active asynchronous context handle returned from the EcDoAsyncConnectEx method on the EMSMDB interface."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1232, the return value of EcDoAsyncWaitEx with ACXH valid is {0}, the return value of EcDoAsyncWaitEx with ACXH invalid is {1}.", this.returnValue, this.returnValueForInvalidCXH); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1232 // Since the context of R1232 is similar with R1228, if the R1228 is verified, it means R1232 is verified. bool isVerifyR1232 = isVerifyR1228; Site.CaptureRequirementIfIsTrue( isVerifyR1232, 1232, @"[In EcDoAsyncWaitEx Method (opnum 0)] This call [EcDoAsyncWaitEx] requires an active asynchronous context handle to be returned from the EcDoAsyncConnectEx method on the EMSMDB interface, as specified in section 3.1.4.1."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R310, the return value of EcDoAsyncWaitEx with ACXH valid is {0}, the return value of EcDoAsyncWaitEx with ACXH invalid is {1}.", this.returnValue, this.returnValueForInvalidCXH); // Verify MS-OXCRPC requirement: MS-OXCRPC_R310 // Since the context of R310 is similar with R1228, if the R1228 is verified, it means R310 is verified. bool isVerifyR310 = isVerifyR1228; Site.CaptureRequirementIfIsTrue( isVerifyR310, 310, @"[In Protocol Details] All method calls that require a valid asynchronous context handle [EcDoAsyncWaitEx] are listed in the following table."); if (Common.IsRequirementEnabled(1908, this.Site)) { // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1908"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1908 this.Site.CaptureRequirementIfAreNotEqual<uint>( TestSuiteBase.ResultSuccess, this.returnValueForInvalidCXH, 1908, @"[In Appendix B: Product Behavior] Implementation does reject the request if the asynchronous context handle is invalid. (<38> Section 3.3.4.1: Exchange 2007 and Exchange 2010 follow this behavior.)"); } #endregion #region Call EcDoAsyncWaitEx with an EcDoAsyncWaitEx call outstanding on this ACXH uint returnValueOfFirstCall = 0; uint returnValueOfSecondCall = 0; MethodCaller asyncThread = new MethodCaller( () => { return this.oxcrpcAdapter.EcDoAsyncWaitEx(this.pacxh, out this.isNotificationPending); }); IAsyncResult result = asyncThread.BeginInvoke(null, null); returnValueOfSecondCall = this.oxcrpcAdapter.EcDoAsyncWaitEx(this.pacxh, out this.isNotificationPending); returnValueOfFirstCall = asyncThread.EndInvoke(result); Site.Log.Add(LogEntryKind.Debug, string.Format("The return value of the first EcDoAsyncWaitEx method is {0}", returnValueOfFirstCall)); Site.Log.Add(LogEntryKind.Debug, string.Format("The return value of the second EcDoAsyncWaitEx method is {0}", returnValueOfSecondCall)); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1343"); bool isR1343Verified = returnValueOfSecondCall == 0x000007EE || returnValueOfFirstCall == 0x000007EE; // Verify MS-OXCRPC requirement: MS-OXCRPC_R1343 Site.CaptureRequirementIfIsTrue( isR1343Verified, 1343, @"[In EcDoAsyncWaitEx Method (opnum 0)] [Return Values] [Rejected (0x000007EE)] An EcDoAsyncWaitEx method call is already outstanding on this asynchronous context handle.<38>"); #endregion #region Client disconnects with Server this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); #endregion } /// <summary> /// This case tests calling EcDoAsyncConnectEx when server has disabled the asynchronous RPC notifications. /// </summary> [TestCategory("MSOXCRPC"), TestMethod()] public void MSOXCRPC_S02_TC05_TestEcDoAsyncConnectExWithDisableAsynchronous() { this.CheckTransport(); #region Call DisableAsyncRPCNotification method to disable asynchronous RPC notifications. // Disable the asynchronous RPC notification on server this.oxcrpcControlAdapter.DisableAsyncRPCNotification(); // On Exchange 2013, when test case restart the service, // the service is not ready immediately for communicate with server over RPC. // So test case need call EcDoConnectEx and EcDoRpcExt2 to check the service whether is ready for communicate with server over RPC. bool isRestartSuccess = this.CheckServiceStartSuccess(); Site.Assert.IsTrue(isRestartSuccess, "The service should start success."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Asynchronous RPC notification is disabled on server through SUT control Adapter."); this.isDisableAsyncRPCNotification = true; #endregion #region Initializes Server and Client this.returnStatus = this.oxcrpcAdapter.InitializeRPC(this.authenticationLevel, this.authenticationService, this.userName, this.password); Site.Assert.IsTrue(this.returnStatus, "The returned status is {0}. TRUE means that initializing the server and client in order to call the following EcDoAsyncConncet successfully, and FALSE means that initializing the server and client in order to call the following EcDoAsyncConncet failed.", this.returnStatus); #endregion #region Client connects with Server this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoConnectEx should succeed, and send Session Context Handle (CXH) to EcDoAsyncConnectEx. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Bind a CXH to an ACXH this.returnValue = this.oxcrpcAdapter.EcDoAsyncConnectEx(this.pcxh, ref this.pacxh); if (Common.IsRequirementEnabled(1812, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1812"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1812 Site.CaptureRequirementIfAreEqual<uint>( 0x000007EE, this.returnValue, 1812, @"[In Appendix B: Product Behavior] Implementation does return the ecRejected error code, when the Server has asynchronous RPC notifications disabled. (Microsoft Exchange Server 2007 follows this behavior.)"); } if (Common.IsRequirementEnabled(1942, this.Site)) { // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1942"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1942 this.Site.CaptureRequirementIfAreEqual<uint>( 0x000007EE, this.returnValue, 1942, @"[In Appendix B: Product Behavior] Implementation does return ecRejected (0x000007EE) when client either polls for notifications or calls EcRRegisterPushNotifications. (Microsoft Exchange Server 2007 follows this behavior.)"); } if (Common.IsRequirementEnabled(1941, this.Site)) { // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1941"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1941 this.Site.CaptureRequirementIfAreNotEqual<uint>( 0x000007EE, this.returnValue, 1941, @"[In Appendix B: Product Behavior] Implementation does not return [ecRejected (0x000007EE)] when Client either polls for notifications or calls EcRRegisterPushNotifications. [In Appendix B: Product Behavior] <26> Section 3.1.4.4: Exchange 2010, Exchange 2013, and Exchange 2016 do not return the ecRejected error code."); } if (Common.IsRequirementEnabled(1757, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCRPC_R1757"); // Verify MS-OXCRPC requirement: MS-OXCRPC_R1757 Site.CaptureRequirementIfAreNotEqual<uint>( 0x000007EE, this.returnValue, 1757, @"[In Appendix B: Product Behavior] Implementation does not return the ecRejected error code, when the Server has asynchronous RPC notifications disabled. (<26> Section 3.1.4.4: Exchange 2010, Exchange 2013, and Exchange 2016 do not return the ecRejected error code.)"); } #endregion #region Client disconnects with Server this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); Site.Assert.AreEqual<uint>(0, this.returnValue, "EcDoDisconnect with the server should succeed and CXH for testing EcDoAsyncConnectEx should be released. '0' is expected to be returned. The returned value is {0}.", this.returnValue); #endregion #region Call EnableAsyncRPCNotification method to enable asynchronous RPC notifications. // Enable the asynchronous RPC notification on server this.oxcrpcControlAdapter.EnableAsyncRPCNotification(); // On Exchange 2013, when test case restart the service, // the service is not ready immediately for connect server over RPC. // So test case need call EcDoConnectEx to check the service whether is ready for connect server over RPC. isRestartSuccess = this.CheckServiceStartSuccess(); Site.Assert.IsTrue(isRestartSuccess, "The service should start success."); this.isDisableAsyncRPCNotification = false; #endregion } /// <summary> /// Clean up the test case after running it /// </summary> protected override void TestCleanup() { #region Call EnableAsyncRPCNotification method to enable asynchronous RPC notifications. if (this.isDisableAsyncRPCNotification == true) { // Enable the asynchronous RPC notification on server this.oxcrpcControlAdapter.EnableAsyncRPCNotification(); this.isDisableAsyncRPCNotification = false; } #endregion base.TestCleanup(); } /// <summary> /// Check whether the service started successfully. /// </summary> /// <returns>A Boolean value indicates whether service started successfully.</returns> private bool CheckServiceStartSuccess() { int tryToConnectCount = 0; int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", Site)); int retryCount = int.Parse(Common.GetConfigurationPropertyValue("ConnectRetryCount", Site)); #region Initializes Server and Client this.returnStatus = this.oxcrpcAdapter.InitializeRPC(this.authenticationLevel, this.authenticationService, this.userName, this.password); Site.Assert.IsTrue(this.returnStatus, "The returned status is {0}. TRUE means that initializing the server and client in order to call the following EcDoAsyncConncet successfully, and FALSE means that initializing the server and client in order to call the following EcDoAsyncConncet failed.", this.returnStatus); #endregion #region Call EcDoConnectEx to try to connect with Server while (tryToConnectCount < retryCount) { this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoConnectEx( ref this.pcxh, TestSuiteBase.UlIcxrLinkForNoSessionLink, ref this.pulTimeStamp, null, this.userDN, ref this.pcbAuxOut, this.rgwClientVersion, out this.rgwBestVersion, out this.picxr); if (this.returnValue == 0) { this.rgbIn = AdapterHelper.ComposeRgbIn(ROPCommandType.RopLogon, this.unusedInfo, this.userPrivilege); this.pcbOut = ConstValues.ValidpcbOut; this.pcbAuxOut = ConstValues.ValidpcbAuxOut; this.returnValue = this.oxcrpcAdapter.EcDoRpcExt2( ref this.pcxh, PulFlags.NoCompression | PulFlags.NoXorMagic, this.rgbIn, ref this.pcbOut, null, ref this.pcbAuxOut, out this.response, ref this.responseSOHTable); if (this.returnValue == 0) { this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); return true; } else { this.returnValue = this.oxcrpcAdapter.EcDoDisconnect(ref this.pcxh); } } tryToConnectCount++; Thread.Sleep(waitTime*3); } return false; #endregion } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudhsm-2014-05-30.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.CloudHSM { /// <summary> /// Constants used for properties of type ClientVersion. /// </summary> public class ClientVersion : ConstantClass { /// <summary> /// Constant v5_1 for ClientVersion /// </summary> public static readonly ClientVersion v5_1 = new ClientVersion("5.1"); /// <summary> /// Constant v5_3 for ClientVersion /// </summary> public static readonly ClientVersion v5_3 = new ClientVersion("5.3"); /// <summary> /// Default Constructor /// </summary> public ClientVersion(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ClientVersion FindValue(string value) { return FindValue<ClientVersion>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ClientVersion(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type CloudHsmObjectState. /// </summary> public class CloudHsmObjectState : ConstantClass { /// <summary> /// Constant DEGRADED for CloudHsmObjectState /// </summary> public static readonly CloudHsmObjectState DEGRADED = new CloudHsmObjectState("DEGRADED"); /// <summary> /// Constant READY for CloudHsmObjectState /// </summary> public static readonly CloudHsmObjectState READY = new CloudHsmObjectState("READY"); /// <summary> /// Constant UPDATING for CloudHsmObjectState /// </summary> public static readonly CloudHsmObjectState UPDATING = new CloudHsmObjectState("UPDATING"); /// <summary> /// Default Constructor /// </summary> public CloudHsmObjectState(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static CloudHsmObjectState FindValue(string value) { return FindValue<CloudHsmObjectState>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator CloudHsmObjectState(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type HsmStatus. /// </summary> public class HsmStatus : ConstantClass { /// <summary> /// Constant DEGRADED for HsmStatus /// </summary> public static readonly HsmStatus DEGRADED = new HsmStatus("DEGRADED"); /// <summary> /// Constant PENDING for HsmStatus /// </summary> public static readonly HsmStatus PENDING = new HsmStatus("PENDING"); /// <summary> /// Constant RUNNING for HsmStatus /// </summary> public static readonly HsmStatus RUNNING = new HsmStatus("RUNNING"); /// <summary> /// Constant SUSPENDED for HsmStatus /// </summary> public static readonly HsmStatus SUSPENDED = new HsmStatus("SUSPENDED"); /// <summary> /// Constant TERMINATED for HsmStatus /// </summary> public static readonly HsmStatus TERMINATED = new HsmStatus("TERMINATED"); /// <summary> /// Constant TERMINATING for HsmStatus /// </summary> public static readonly HsmStatus TERMINATING = new HsmStatus("TERMINATING"); /// <summary> /// Constant UPDATING for HsmStatus /// </summary> public static readonly HsmStatus UPDATING = new HsmStatus("UPDATING"); /// <summary> /// Default Constructor /// </summary> public HsmStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static HsmStatus FindValue(string value) { return FindValue<HsmStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator HsmStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type SubscriptionType. /// </summary> public class SubscriptionType : ConstantClass { /// <summary> /// Constant PRODUCTION for SubscriptionType /// </summary> public static readonly SubscriptionType PRODUCTION = new SubscriptionType("PRODUCTION"); /// <summary> /// Default Constructor /// </summary> public SubscriptionType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static SubscriptionType FindValue(string value) { return FindValue<SubscriptionType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator SubscriptionType(string value) { return FindValue(value); } } }