context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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 Xunit; namespace Microsoft.AspNetCore.Razor.Language { public class StringSegmentTest { [Fact] public void StringSegment_Empty() { // Arrange & Act var segment = StringSegment.Empty; // Assert Assert.True(segment.HasValue); Assert.Same(string.Empty, segment.Value); Assert.Equal(0, segment.Offset); Assert.Equal(0, segment.Length); } [Fact] public void StringSegment_ImplicitConvertFromString() { StringSegment segment = "Hello"; Assert.True(segment.HasValue); Assert.Equal(0, segment.Offset); Assert.Equal(5, segment.Length); Assert.Equal("Hello", segment.Value); } [Fact] public void StringSegment_StringCtor_AllowsNullBuffers() { // Arrange & Act var segment = new StringSegment(null); // Assert Assert.False(segment.HasValue); Assert.Equal(0, segment.Offset); Assert.Equal(0, segment.Length); } [Theory] [InlineData("", 0, 0)] [InlineData("abc", 2, 0)] public void StringSegmentConstructor_AllowsEmptyBuffers(string text, int offset, int length) { // Arrange & Act var segment = new StringSegment(text, offset, length); // Assert Assert.True(segment.HasValue); Assert.Equal(offset, segment.Offset); Assert.Equal(length, segment.Length); } [Fact] public void StringSegment_StringCtor_InitializesValuesCorrectly() { // Arrange var buffer = "Hello world!"; // Act var segment = new StringSegment(buffer); // Assert Assert.True(segment.HasValue); Assert.Equal(0, segment.Offset); Assert.Equal(buffer.Length, segment.Length); } [Fact] public void StringSegment_Value_Valid() { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var value = segment.Value; // Assert Assert.Equal("ello", value); } [Fact] public void StringSegment_Value_Invalid() { // Arrange var segment = new StringSegment(); // Act var value = segment.Value; // Assert Assert.Null(value); } [Fact] public void StringSegment_HasValue_Valid() { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var hasValue = segment.HasValue; // Assert Assert.True(hasValue); } [Fact] public void StringSegment_HasValue_Invalid() { // Arrange var segment = new StringSegment(); // Act var hasValue = segment.HasValue; // Assert Assert.False(hasValue); } [Theory] [InlineData("a", 0, 1, 0, 'a')] [InlineData("abc", 1, 1, 0, 'b')] [InlineData("abcdef", 1, 4, 0, 'b')] [InlineData("abcdef", 1, 4, 1, 'c')] [InlineData("abcdef", 1, 4, 2, 'd')] [InlineData("abcdef", 1, 4, 3, 'e')] public void StringSegment_Indexer_InRange(string value, int offset, int length, int index, char expected) { var segment = new StringSegment(value, offset, length); var result = segment[index]; Assert.Equal(expected, result); } [Theory] [InlineData("", 0, 0, 0)] [InlineData("a", 0, 1, -1)] [InlineData("a", 0, 1, 1)] public void StringSegment_Indexer_OutOfRangeThrows(string value, int offset, int length, int index) { var segment = new StringSegment(value, offset, length); Assert.Throws<IndexOutOfRangeException>(() => segment[index]); } public static TheoryData<string, StringComparison, bool> EndsWithData { get { // candidate / comparer / expected result return new TheoryData<string, StringComparison, bool>() { { "Hello", StringComparison.Ordinal, false }, { "ello ", StringComparison.Ordinal, false }, { "ll", StringComparison.Ordinal, false }, { "ello", StringComparison.Ordinal, true }, { "llo", StringComparison.Ordinal, true }, { "lo", StringComparison.Ordinal, true }, { "o", StringComparison.Ordinal, true }, { string.Empty, StringComparison.Ordinal, true }, { "eLLo", StringComparison.Ordinal, false }, { "eLLo", StringComparison.OrdinalIgnoreCase, true }, }; } } public static TheoryData<string, StringComparison, bool> StartsWithData { get { // candidate / comparer / expected result return new TheoryData<string, StringComparison, bool>() { { "Hello", StringComparison.Ordinal, false }, { "ello ", StringComparison.Ordinal, false }, { "ll", StringComparison.Ordinal, false }, { "ello", StringComparison.Ordinal, true }, { "ell", StringComparison.Ordinal, true }, { "el", StringComparison.Ordinal, true }, { "e", StringComparison.Ordinal, true }, { string.Empty, StringComparison.Ordinal, true }, { "eLLo", StringComparison.Ordinal, false }, { "eLLo", StringComparison.OrdinalIgnoreCase, true }, }; } } [Theory] [MemberData(nameof(StartsWithData))] public void StringSegment_StartsWith_Valid(string candidate, StringComparison comparison, bool expectedResult) { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var result = segment.StartsWith(candidate, comparison); // Assert Assert.Equal(expectedResult, result); } [Fact] public void StringSegment_StartsWith_Invalid() { // Arrange var segment = new StringSegment(); // Act var result = segment.StartsWith(string.Empty, StringComparison.Ordinal); // Assert Assert.False(result); } public static TheoryData<string, StringComparison, bool> EqualsStringData { get { // candidate / comparer / expected result return new TheoryData<string, StringComparison, bool>() { { "eLLo", StringComparison.OrdinalIgnoreCase, true }, { "eLLo", StringComparison.Ordinal, false }, }; } } [Theory] [MemberData(nameof(EqualsStringData))] public void StringSegment_Equals_String_Valid(string candidate, StringComparison comparison, bool expectedResult) { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var result = segment.Equals(candidate, comparison); // Assert Assert.Equal(expectedResult, result); } [Fact] public void StringSegment_StaticEquals_Valid() { var segment1 = new StringSegment("My Car Is Cool", 3, 3); var segment2 = new StringSegment("Your Carport is blue", 5, 3); Assert.True(StringSegment.Equals(segment1, segment2)); } [Fact] public void StringSegment_StaticEquals_Invalid() { var segment1 = new StringSegment("My Car Is Cool", 3, 4); var segment2 = new StringSegment("Your Carport is blue", 5, 4); Assert.False(StringSegment.Equals(segment1, segment2)); } [Fact] public void StringSegment_IsNullOrEmpty_Valid() { Assert.True(StringSegment.IsNullOrEmpty(null)); Assert.True(StringSegment.IsNullOrEmpty(string.Empty)); Assert.True(StringSegment.IsNullOrEmpty(new StringSegment(null))); Assert.True(StringSegment.IsNullOrEmpty(new StringSegment(string.Empty))); Assert.True(StringSegment.IsNullOrEmpty(StringSegment.Empty)); Assert.True(StringSegment.IsNullOrEmpty(new StringSegment(string.Empty, 0, 0))); Assert.True(StringSegment.IsNullOrEmpty(new StringSegment("Hello", 0, 0))); Assert.True(StringSegment.IsNullOrEmpty(new StringSegment("Hello", 3, 0))); } [Fact] public void StringSegment_IsNullOrEmpty_Invalid() { Assert.False(StringSegment.IsNullOrEmpty("A")); Assert.False(StringSegment.IsNullOrEmpty("ABCDefg")); Assert.False(StringSegment.IsNullOrEmpty(new StringSegment("A", 0, 1))); Assert.False(StringSegment.IsNullOrEmpty(new StringSegment("ABCDefg", 3, 2))); } public static TheoryData GetHashCode_ReturnsSameValueForEqualSubstringsData { get { return new TheoryData<StringSegment, StringSegment> { { default(StringSegment), default(StringSegment) }, { default(StringSegment), new StringSegment() }, { new StringSegment("Test123", 0, 0), new StringSegment(string.Empty) }, { new StringSegment("C`est si bon", 2, 3), new StringSegment("Yesterday", 1, 3) }, { new StringSegment("Hello", 1, 4), new StringSegment("Hello world", 1, 4) }, { new StringSegment("Hello"), new StringSegment("Hello", 0, 5) }, }; } } [Theory] [MemberData(nameof(GetHashCode_ReturnsSameValueForEqualSubstringsData))] public void GetHashCode_ReturnsSameValueForEqualSubstrings(object segment1, object segment2) { // Act var hashCode1 = ((StringSegment)segment1).GetHashCode(); var hashCode2 = ((StringSegment)segment2).GetHashCode(); // Assert Assert.Equal(hashCode1, hashCode2); } public static TheoryData GetHashCode_ReturnsDifferentValuesForInequalSubstringsData { get { var testString = "Test123"; return new TheoryData<StringSegment, StringSegment> { { new StringSegment(testString, 0, 1), new StringSegment(string.Empty) }, { new StringSegment(testString, 0, 1), new StringSegment(testString, 1, 1) }, { new StringSegment(testString, 1, 2), new StringSegment(testString, 1, 3) }, { new StringSegment(testString, 0, 4), new StringSegment("TEST123", 0, 4) }, }; } } [Theory] [MemberData(nameof(GetHashCode_ReturnsDifferentValuesForInequalSubstringsData))] public void GetHashCode_ReturnsDifferentValuesForInequalSubstrings( object segment1, object segment2) { // Act var hashCode1 = segment1.GetHashCode(); var hashCode2 = segment2.GetHashCode(); // Assert Assert.NotEqual(hashCode1, hashCode2); } [Fact] public void StringSegment_EqualsString_Invalid() { // Arrange var segment = new StringSegment(); // Act var result = segment.Equals(string.Empty, StringComparison.Ordinal); // Assert Assert.False(result); } public static TheoryData<object> DefaultStringSegmentEqualsStringSegmentData { get { // candidate return new TheoryData<object>() { { default(StringSegment) }, { new StringSegment() }, }; } } [Theory] [MemberData(nameof(DefaultStringSegmentEqualsStringSegmentData))] public void DefaultStringSegment_EqualsStringSegment(object candidate) { // Arrange var segment = default(StringSegment); // Act var result = segment.Equals((StringSegment)candidate, StringComparison.Ordinal); // Assert Assert.True(result); } public static TheoryData<object> DefaultStringSegmentDoesNotEqualStringSegmentData { get { // candidate return new TheoryData<object>() { { new StringSegment("Hello, World!", 1, 4) }, { new StringSegment("Hello", 1, 0) }, { new StringSegment(string.Empty) }, }; } } [Theory] [MemberData(nameof(DefaultStringSegmentDoesNotEqualStringSegmentData))] public void DefaultStringSegment_DoesNotEqualStringSegment(object candidate) { // Arrange var segment = default(StringSegment); // Act var result = segment.Equals((StringSegment)candidate, StringComparison.Ordinal); // Assert Assert.False(result); } public static TheoryData<string> DefaultStringSegmentDoesNotEqualStringData { get { // candidate return new TheoryData<string>() { { string.Empty }, { "Hello, World!" }, }; } } [Theory] [MemberData(nameof(DefaultStringSegmentDoesNotEqualStringData))] public void DefaultStringSegment_DoesNotEqualString(string candidate) { // Arrange var segment = default(StringSegment); // Act var result = segment.Equals(candidate, StringComparison.Ordinal); // Assert Assert.False(result); } public static TheoryData<object, object, bool> EqualsStringSegmentData { get { // candidate / comparer / expected result return new TheoryData<object, object, bool>() { { new StringSegment("Hello, World!", 1, 4), StringComparison.Ordinal, true }, { new StringSegment("HELlo, World!", 1, 4), StringComparison.Ordinal, false }, { new StringSegment("HELlo, World!", 1, 4), StringComparison.OrdinalIgnoreCase, true }, { new StringSegment("ello, World!", 0, 4), StringComparison.Ordinal, true }, { new StringSegment("ello, World!", 0, 3), StringComparison.Ordinal, false }, { new StringSegment("ello, World!", 1, 3), StringComparison.Ordinal, false }, }; } } [Theory] [MemberData(nameof(EqualsStringSegmentData))] public void StringSegment_Equals_StringSegment_Valid(object candidate, StringComparison comparison, bool expectedResult) { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var result = segment.Equals((StringSegment)candidate, comparison); // Assert Assert.Equal(expectedResult, result); } [Fact] public void StringSegment_EqualsStringSegment_Invalid() { // Arrange var segment = new StringSegment(); var candidate = new StringSegment("Hello, World!", 3, 2); // Act var result = segment.Equals(candidate, StringComparison.Ordinal); // Assert Assert.False(result); } [Fact] public void StringSegment_SubsegmentOffset_Valid() { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var result = segment.Subsegment(offset: 1); // Assert Assert.Equal(new StringSegment("Hello, World!", 2, 3), result); Assert.Equal("llo", result.Value); } [Fact] public void StringSegment_Subsegment_Valid() { // Arrange var segment = new StringSegment("Hello, World!", 1, 4); // Act var result = segment.Subsegment(offset: 1, length: 2); // Assert Assert.Equal(new StringSegment("Hello, World!", 2, 2), result); Assert.Equal("ll", result.Value); } [Fact] public void IndexOf_ComputesIndex_RelativeToTheCurrentSegment() { // Arrange var segment = new StringSegment("Hello, World!", 1, 10); // Act var result = segment.IndexOf(','); // Assert Assert.Equal(4, result); } [Fact] public void IndexOf_ReturnsMinusOne_IfElementNotInSegment() { // Arrange var segment = new StringSegment("Hello, World!", 1, 3); // Act var result = segment.IndexOf(','); // Assert Assert.Equal(-1, result); } [Fact] public void IndexOf_SkipsANumberOfCaracters_IfStartIsProvided() { // Arrange const string buffer = "Hello, World!, Hello people!"; var segment = new StringSegment(buffer, 3, buffer.Length - 3); // Act var result = segment.IndexOf('!', 15); // Assert Assert.Equal(buffer.Length - 4, result); } [Fact] public void IndexOf_SearchOnlyInsideTheRange_IfStartAndCountAreProvided() { // Arrange const string buffer = "Hello, World!, Hello people!"; var segment = new StringSegment(buffer, 3, buffer.Length - 3); // Act var result = segment.IndexOf('!', 15, 5); // Assert Assert.Equal(-1, result); } [Fact] public void IndexOfAny_ComputesIndex_RelativeToTheCurrentSegment() { // Arrange var segment = new StringSegment("Hello, World!", 1, 10); // Act var result = segment.IndexOfAny(new[] { ',' }); // Assert Assert.Equal(4, result); } [Fact] public void IndexOfAny_ReturnsMinusOne_IfElementNotInSegment() { // Arrange var segment = new StringSegment("Hello, World!", 1, 3); // Act var result = segment.IndexOfAny(new[] { ',' }); // Assert Assert.Equal(-1, result); } [Fact] public void IndexOfAny_SkipsANumberOfCaracters_IfStartIsProvided() { // Arrange const string buffer = "Hello, World!, Hello people!"; var segment = new StringSegment(buffer, 3, buffer.Length - 3); // Act var result = segment.IndexOfAny(new[] { '!' }, 15); // Assert Assert.Equal(buffer.Length - 4, result); } [Fact] public void IndexOfAny_SearchOnlyInsideTheRange_IfStartAndCountAreProvided() { // Arrange const string buffer = "Hello, World!, Hello people!"; var segment = new StringSegment(buffer, 3, buffer.Length - 3); // Act var result = segment.IndexOfAny(new[] { '!' }, 15, 5); // Assert Assert.Equal(-1, result); } [Fact] public void Value_DoesNotAllocateANewString_IfTheSegmentContainsTheWholeBuffer() { // Arrange const string buffer = "Hello, World!"; var segment = new StringSegment(buffer); // Act var result = segment.Value; // Assert Assert.Same(buffer, result); } [Fact] public void StringSegment_CreateEmptySegment() { // Arrange var segment = new StringSegment("//", 1, 0); // Assert Assert.True(segment.HasValue); } } }
// // Authors: // Alan McGovern alan.mcgovern@gmail.com // Ben Motmans <ben.motmans@gmail.com> // // Copyright (C) 2006 Alan McGovern // Copyright (C) 2007 Ben Motmans // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Xml; using System.Text; using System.Diagnostics; namespace Mono.Nat.Upnp { public sealed class UpnpNatDevice : AbstractNatDevice, IEquatable<UpnpNatDevice> { private EndPoint hostEndPoint; private IPAddress localAddress; private string serviceDescriptionUrl; private string controlUrl; private string serviceType; /// <summary> /// The callback to invoke when we are finished setting up the device /// </summary> private NatDeviceCallback callback; internal UpnpNatDevice (IPAddress localAddress, string deviceDetails, string serviceType) { this.LastSeen = DateTime.Now; this.localAddress = localAddress; // Split the string at the "location" section so i can extract the ipaddress and service description url var locationDetails = deviceDetails.Substring(deviceDetails.IndexOf("Location", StringComparison.InvariantCultureIgnoreCase) + 9).Split('\r')[0]; this.serviceType = serviceType; // Make sure we have no excess whitespace locationDetails = locationDetails.Trim(); // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address // Are we going to get addresses with the "http://" attached? if (locationDetails.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { NatUtility.Log("Found device at: {0}", locationDetails); // This bit strings out the "http://" from the string locationDetails = locationDetails.Substring(7); // We then split off the end of the string to get something like: 192.168.0.3:241 in our string var hostAddressAndPort = locationDetails.Remove(locationDetails.IndexOf('/')); // From this we parse out the IP address and Port if (hostAddressAndPort.IndexOf(':') > 0) { this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort.Remove(hostAddressAndPort.IndexOf(':'))), Convert.ToUInt16(hostAddressAndPort.Substring(hostAddressAndPort.IndexOf(':') + 1), System.Globalization.CultureInfo.InvariantCulture)); } else { // there is no port specified, use default port (80) this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort), 80); } NatUtility.Log("Parsed device as: {0}", this.hostEndPoint.ToString()); // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip // and port information this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/')); } else { Trace.WriteLine("Couldn't decode address. Please send following string to the developer: "); Trace.WriteLine(deviceDetails); } } /// <summary> /// The EndPoint that the device is at /// </summary> internal EndPoint HostEndPoint { get { return this.hostEndPoint; } } /// <summary> /// The relative url of the xml file that describes the list of services is at /// </summary> internal string ServiceDescriptionUrl { get { return this.serviceDescriptionUrl; } } /// <summary> /// The relative url that we can use to control the port forwarding /// </summary> internal string ControlUrl { get { return this.controlUrl; } } /// <summary> /// The service type we're using on the device /// </summary> internal string ServiceType { get { return this.serviceType; } } /// <summary> /// Begins an async call to get the external ip address of the router /// </summary> public override IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState) { // Create the port map message var message = new GetExternalIPAddressMessage(this); return BeginMessageInternal(message, callback, asyncState, EndGetExternalIPInternal); } /// <summary> /// Maps the specified port to this computer /// </summary> public override IAsyncResult BeginCreatePortMap(Mapping mapping, AsyncCallback callback, object asyncState) { var message = new CreatePortMappingMessage(mapping, localAddress, this); return BeginMessageInternal(message, callback, mapping, EndCreatePortMapInternal); } /// <summary> /// Removes a port mapping from this computer /// </summary> public override IAsyncResult BeginDeletePortMap(Mapping mapping, AsyncCallback callback, object asyncState) { var message = new DeletePortMappingMessage(mapping, this); return BeginMessageInternal(message, callback, asyncState, EndDeletePortMapInternal); } public override IAsyncResult BeginGetAllMappings(AsyncCallback callback, object asyncState) { var message = new GetGenericPortMappingEntry(0, this); return BeginMessageInternal(message, callback, asyncState, EndGetAllMappingsInternal); } public override IAsyncResult BeginGetSpecificMapping (Protocol protocol, int port, AsyncCallback callback, object asyncState) { var message = new GetSpecificPortMappingEntryMessage(protocol, port, this); return this.BeginMessageInternal(message, callback, asyncState, new AsyncCallback(this.EndGetSpecificMappingInternal)); } /// <summary> /// /// </summary> /// <param name="result"></param> public override void EndCreatePortMap(IAsyncResult result) { if (result == null) throw new ArgumentNullException("result"); var mappingResult = result as PortMapAsyncResult; if (mappingResult == null) throw new ArgumentException("Invalid AsyncResult", "result"); // Check if we need to wait for the operation to finish if (!result.IsCompleted) result.AsyncWaitHandle.WaitOne(); // If we have a saved exception, it means something went wrong during the mapping // so we just rethrow the exception and let the user figure out what they should do. if (mappingResult.SavedMessage is ErrorMessage) { var msg = mappingResult.SavedMessage as ErrorMessage; throw new MappingException(msg.ErrorCode, msg.Description); } //return result.AsyncState as Mapping; } /// <summary> /// /// </summary> /// <param name="result"></param> public override void EndDeletePortMap(IAsyncResult result) { if (result == null) throw new ArgumentNullException("result"); var mappingResult = result as PortMapAsyncResult; if (mappingResult == null) throw new ArgumentException("Invalid AsyncResult", "result"); // Check if we need to wait for the operation to finish if (!mappingResult.IsCompleted) mappingResult.AsyncWaitHandle.WaitOne(); // If we have a saved exception, it means something went wrong during the mapping // so we just rethrow the exception and let the user figure out what they should do. if (mappingResult.SavedMessage is ErrorMessage) { var msg = mappingResult.SavedMessage as ErrorMessage; throw new MappingException(msg.ErrorCode, msg.Description); } // If all goes well, we just return //return true; } public override Mapping[] EndGetAllMappings(IAsyncResult result) { if (result == null) throw new ArgumentNullException("result"); var mappingResult = result as GetAllMappingsAsyncResult; if (mappingResult == null) throw new ArgumentException("Invalid AsyncResult", "result"); if (!mappingResult.IsCompleted) mappingResult.AsyncWaitHandle.WaitOne(); if (mappingResult.SavedMessage is ErrorMessage) { var msg = mappingResult.SavedMessage as ErrorMessage; if (msg.ErrorCode != 713) throw new MappingException(msg.ErrorCode, msg.Description); } return mappingResult.Mappings.ToArray(); } /// <summary> /// Ends an async request to get the external ip address of the router /// </summary> public override IPAddress EndGetExternalIP(IAsyncResult result) { if (result == null) throw new ArgumentNullException("result"); var mappingResult = result as PortMapAsyncResult; if (mappingResult == null) throw new ArgumentException("Invalid AsyncResult", "result"); if (!result.IsCompleted) result.AsyncWaitHandle.WaitOne(); if (mappingResult.SavedMessage is ErrorMessage) { var msg = mappingResult.SavedMessage as ErrorMessage; throw new MappingException(msg.ErrorCode, msg.Description); } return ((GetExternalIPAddressResponseMessage)mappingResult.SavedMessage).ExternalIPAddress; } public override Mapping EndGetSpecificMapping(IAsyncResult result) { if (result == null) throw new ArgumentNullException("result"); var mappingResult = result as GetAllMappingsAsyncResult; if (mappingResult == null) throw new ArgumentException("Invalid AsyncResult", "result"); if (!mappingResult.IsCompleted) mappingResult.AsyncWaitHandle.WaitOne(); if (mappingResult.SavedMessage is ErrorMessage) { var message = mappingResult.SavedMessage as ErrorMessage; if (message.ErrorCode != 0x2ca) { throw new MappingException(message.ErrorCode, message.Description); } } if (mappingResult.Mappings.Count == 0) return new Mapping (Protocol.Tcp, -1, -1); return mappingResult.Mappings[0]; } public override bool Equals(object obj) { var device = obj as UpnpNatDevice; return (device == null) ? false : this.Equals((device)); } public bool Equals(UpnpNatDevice other) { return (other == null) ? false : (this.hostEndPoint.Equals(other.hostEndPoint) //&& this.controlUrl == other.controlUrl && this.serviceDescriptionUrl == other.serviceDescriptionUrl); } public override int GetHashCode() { return (this.hostEndPoint.GetHashCode() ^ this.controlUrl.GetHashCode() ^ this.serviceDescriptionUrl.GetHashCode()); } private IAsyncResult BeginMessageInternal(MessageBase message, AsyncCallback storedCallback, object asyncState, AsyncCallback callback) { byte[] body; var request = message.Encode(out body); var mappingResult = PortMapAsyncResult.Create(message, request, storedCallback, asyncState); if (body.Length > 0) { request.ContentLength = body.Length; request.BeginGetRequestStream(delegate(IAsyncResult result) { try { var s = request.EndGetRequestStream(result); s.Write(body, 0, body.Length); request.BeginGetResponse(callback, mappingResult); } catch (Exception ex) { mappingResult.Complete(ex); } }, null); } else { request.BeginGetResponse(callback, mappingResult); } return mappingResult; } private void CompleteMessage(IAsyncResult result) { var mappingResult = result.AsyncState as PortMapAsyncResult; mappingResult.CompletedSynchronously = result.CompletedSynchronously; mappingResult.Complete(); } private MessageBase DecodeMessageFromResponse(Stream s, long length) { var data = new StringBuilder(); var bytesRead = 0; var totalBytesRead = 0; var buffer = new byte[10240]; // Read out the content of the message, hopefully picking everything up in the case where we have no contentlength if (length != -1) { while (totalBytesRead < length) { bytesRead = s.Read(buffer, 0, buffer.Length); data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); totalBytesRead += bytesRead; } } else { while ((bytesRead = s.Read(buffer, 0, buffer.Length)) != 0) data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); } // Once we have our content, we need to see what kind of message it is. It'll either a an error // or a response based on the action we performed. return MessageBase.Decode(this, data.ToString()); } private void EndCreatePortMapInternal(IAsyncResult result) { EndMessageInternal(result); CompleteMessage(result); } private void EndMessageInternal(IAsyncResult result) { HttpWebResponse response = null; var mappingResult = result.AsyncState as PortMapAsyncResult; try { try { response = (HttpWebResponse)mappingResult.Request.EndGetResponse(result); } catch (WebException ex) { // Even if the request "failed" i want to continue on to read out the response from the router response = ex.Response as HttpWebResponse; if (response == null) mappingResult.SavedMessage = new ErrorMessage((int)ex.Status, ex.Message); } if (response != null) mappingResult.SavedMessage = DecodeMessageFromResponse(response.GetResponseStream(), response.ContentLength); } finally { if (response != null) response.Close(); } } private void EndDeletePortMapInternal(IAsyncResult result) { EndMessageInternal(result); CompleteMessage(result); } private void EndGetAllMappingsInternal(IAsyncResult result) { EndMessageInternal(result); var mappingResult = result.AsyncState as GetAllMappingsAsyncResult; var message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage; if (message != null) { var mapping = new Mapping (message.Protocol, message.InternalPort, message.ExternalPort, message.LeaseDuration); mapping.Description = message.PortMappingDescription; mappingResult.Mappings.Add(mapping); var next = new GetGenericPortMappingEntry(mappingResult.Mappings.Count, this); // It's ok to do this synchronously because we should already be on anther thread // and this won't block the user. byte[] body; var request = next.Encode(out body); if (body.Length > 0) { request.ContentLength = body.Length; request.GetRequestStream().Write(body, 0, body.Length); } mappingResult.Request = request; request.BeginGetResponse(EndGetAllMappingsInternal, mappingResult); return; } CompleteMessage(result); } private void EndGetExternalIPInternal(IAsyncResult result) { EndMessageInternal(result); CompleteMessage(result); } private void EndGetSpecificMappingInternal(IAsyncResult result) { EndMessageInternal(result); var mappingResult = result.AsyncState as GetAllMappingsAsyncResult; var message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage; if (message != null) { var mapping = new Mapping(mappingResult.SpecificMapping.Protocol, message.InternalPort, mappingResult.SpecificMapping.PublicPort, message.LeaseDuration); mapping.Description = mappingResult.SpecificMapping.Description; mappingResult.Mappings.Add(mapping); } CompleteMessage(result); } internal void GetServicesList(NatDeviceCallback callback) { // Save the callback so i can use it again later when i've finished parsing the services available this.callback = callback; // Create a HTTPWebRequest to download the list of services the device offers byte[] body; var request = new GetServicesMessage(this.serviceDescriptionUrl, this.hostEndPoint).Encode(out body); if (body.Length > 0) NatUtility.Log("Error: Services Message contained a body"); request.BeginGetResponse(this.ServicesReceived, request); } private void ServicesReceived(IAsyncResult result) { HttpWebResponse response = null; try { var abortCount = 0; var bytesRead = 0; var buffer = new byte[10240]; var servicesXml = new StringBuilder(); var xmldoc = new XmlDocument(); var request = result.AsyncState as HttpWebRequest; response = request.EndGetResponse(result) as HttpWebResponse; var s = response.GetResponseStream(); if (response.StatusCode != HttpStatusCode.OK) { NatUtility.Log("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); return; // FIXME: This the best thing to do?? } while (true) { bytesRead = s.Read(buffer, 0, buffer.Length); servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); try { xmldoc.LoadXml(servicesXml.ToString()); response.Close(); break; } catch (XmlException) { // If we can't receive the entire XML within 500ms, then drop the connection // Unfortunately not all routers supply a valid ContentLength (mine doesn't) // so this hack is needed to keep testing our recieved data until it gets successfully // parsed by the xmldoc. Without this, the code will never pick up my router. if (abortCount++ > 50) { response.Close(); return; } NatUtility.Log("{0}: Couldn't parse services list", HostEndPoint); System.Threading.Thread.Sleep(10); } } NatUtility.Log("{0}: Parsed services list", HostEndPoint); var ns = new XmlNamespaceManager(xmldoc.NameTable); ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0"); var nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns); foreach (XmlNode node in nodes) { //Go through each service there foreach (XmlNode service in node.ChildNodes) { //If the service is a WANIPConnection, then we have what we want var type = service["serviceType"].InnerText; NatUtility.Log("{0}: Found service: {1}", HostEndPoint, type); var c = StringComparison.OrdinalIgnoreCase; if (type.Equals (this.serviceType, c)) { this.controlUrl = service["controlURL"].InnerText; NatUtility.Log("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); try { var u = new Uri(controlUrl); if (u.IsAbsoluteUri) { var old = hostEndPoint; this.hostEndPoint = new IPEndPoint(IPAddress.Parse(u.Host), u.Port); NatUtility.Log("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length); NatUtility.Log("{0}: New control url: {1}", HostEndPoint, controlUrl); } } catch { NatUtility.Log("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); } NatUtility.Log("{0}: Handshake Complete", HostEndPoint); this.callback(this); return; } } } //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding //So we don't invoke the callback, so this device is never added to our lists } catch (WebException ex) { // Just drop the connection, FIXME: Should i retry? NatUtility.Log("{0}: Device denied the connection attempt: {1}", HostEndPoint, ex); } finally { if (response != null) response.Close(); } } /// <summary> /// Overridden. /// </summary> /// <returns></returns> public override string ToString( ) { //GetExternalIP is blocking and can throw exceptions, can't use it here. return String.Format( "UpnpNatDevice - EndPoint: {0}, External IP: {1}, Control Url: {2}, Service Description Url: {3}, Service Type: {4}, Last Seen: {5}", this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen); } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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.Live.Serialization { using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; /// <summary> /// Represents a text writer that supports indentation. /// </summary> internal sealed class IndentedTextWriter : TextWriter { /// <summary> /// The underlying text writer. /// </summary> private readonly TextWriter writer; /// <summary> /// Indicates whether the text should be minimized. /// </summary> private readonly bool minimized; /// <summary> /// The current indentation level. /// </summary> private int indentLevel; /// <summary> /// Indicates whether tabs are pending. /// </summary> private bool tabsPending; /// <summary> /// The string used for tabs. /// </summary> private string tabString; /// <summary> /// Initializes a new instance of the IndentedTextWriter class. /// </summary> public IndentedTextWriter(TextWriter writer, bool minimized) : base(CultureInfo.InvariantCulture) { this.writer = writer; this.minimized = minimized; this.NewLine = minimized ? "" : "\r"; this.tabString = " "; this.indentLevel = 0; this.tabsPending = false; } public override Encoding Encoding { get { return this.writer.Encoding; } } public override string NewLine { get { return this.writer.NewLine; } set { this.writer.NewLine = value; } } public int Indent { get { return this.indentLevel; } set { Debug.Assert(value >= 0); if (value < 0) { value = 0; } this.indentLevel = value; } } protected override void Dispose(bool disposing) { if (disposing) { this.writer.Dispose(); } base.Dispose(disposing); } public override void Flush() { this.writer.Flush(); } public override void Write(string s) { this.OutputTabs(); this.writer.Write(s); } public override void Write(bool value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(char value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(char[] buffer) { this.OutputTabs(); this.writer.Write(buffer); } public override void Write(char[] buffer, int index, int count) { this.OutputTabs(); this.writer.Write(buffer, index, count); } public override void Write(double value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(float value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(int value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(long value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(object value) { this.OutputTabs(); this.writer.Write(value); } public override void Write(string format, params object[] arg) { this.OutputTabs(); this.writer.Write(format, arg); } public override void Write(uint value) { this.OutputTabs(); this.writer.Write(value); } public void WriteLineNoTabs(string s) { this.writer.WriteLine(s); } public override void WriteLine(string s) { this.OutputTabs(); this.writer.WriteLine(s); this.tabsPending = true; } public override void WriteLine() { this.OutputTabs(); this.writer.WriteLine(); this.tabsPending = true; } public override void WriteLine(bool value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(char value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(char[] buffer) { this.OutputTabs(); this.writer.WriteLine(buffer); this.tabsPending = true; } public override void WriteLine(char[] buffer, int index, int count) { this.OutputTabs(); this.writer.WriteLine(buffer, index, count); this.tabsPending = true; } public override void WriteLine(double value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(float value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(int value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(long value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(object value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public override void WriteLine(string format, params object[] arg) { this.OutputTabs(); this.writer.WriteLine(format, arg); this.tabsPending = true; } public override void WriteLine(UInt32 value) { this.OutputTabs(); this.writer.WriteLine(value); this.tabsPending = true; } public void WriteTrimmed(string text) { if (this.minimized == false) { this.Write(text); } else { this.Write(text.Trim()); } } private void OutputTabs() { if (this.tabsPending) { if (this.minimized == false) { for (int i = 0; i < this.indentLevel; i++) { this.writer.Write(this.tabString); } } this.tabsPending = false; } } } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; namespace BusinessObjects.Documents { [Serializable] public partial class cDocuments_WorkOrder: cDocuments_Document<cDocuments_WorkOrder> { #region Business Methods private static readonly PropertyInfo< System.Int32? > projects_ProjectIdProperty = RegisterProperty<System.Int32?>(p => p.Projects_ProjectId, string.Empty,(System.Int32?)null); public System.Int32? Projects_ProjectId { get { return GetProperty(projects_ProjectIdProperty); } set { SetProperty(projects_ProjectIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > mDSubjects_SubjectIdProperty = RegisterProperty<System.Int32?>(p => p.MDSubjects_SubjectId, string.Empty); public System.Int32? MDSubjects_SubjectId { get { return GetProperty(mDSubjects_SubjectIdProperty); } set { SetProperty(mDSubjects_SubjectIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > documents_OrderFormIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_OrderFormId, string.Empty,(System.Int32?)null); public System.Int32? Documents_OrderFormId { get { return GetProperty(documents_OrderFormIdProperty); } set { SetProperty(documents_OrderFormIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > placeIdProperty = RegisterProperty<System.Int32?>(p => p.PlaceId, string.Empty); public System.Int32? PlaceId { get { return GetProperty(placeIdProperty); } set { SetProperty(placeIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > documents_TravelOrderIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_TravelOrderId, string.Empty,(System.Int32?)null); public System.Int32? Documents_TravelOrderId { get { return GetProperty(documents_TravelOrderIdProperty); } set { SetProperty(documents_TravelOrderIdProperty, value); } } private static readonly PropertyInfo< System.Decimal? > distanceProperty = RegisterProperty<System.Decimal?>(p => p.Distance, string.Empty, (System.Decimal?)null); public System.Decimal? Distance { get { return GetProperty(distanceProperty); } set { SetProperty(distanceProperty, value); } } private static readonly PropertyInfo< bool? > isVerifiedProperty = RegisterProperty<bool?>(p => p.IsVerified, string.Empty,(bool?)null); public bool? IsVerified { get { return GetProperty(isVerifiedProperty); } set { SetProperty(isVerifiedProperty, value); } } private static readonly PropertyInfo< System.String > verifierNameProperty = RegisterProperty<System.String>(p => p.VerifierName, string.Empty, (System.String)null); public System.String VerifierName { get { return GetProperty(verifierNameProperty); } set { SetProperty(verifierNameProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.String > verifierPhoneProperty = RegisterProperty<System.String>(p => p.VerifierPhone, string.Empty, (System.String)null); public System.String VerifierPhone { get { return GetProperty(verifierPhoneProperty); } set { SetProperty(verifierPhoneProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<bool> isBillableProperty = RegisterProperty<bool>(p => p.IsBillable, string.Empty, true); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public bool IsBillable { get { return GetProperty(isBillableProperty); } set { SetProperty(isBillableProperty, value); } } private static readonly PropertyInfo<System.Int32?> documents_InvoiceIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_InvoiceId, string.Empty, (System.Int32?)null); public System.Int32? Documents_InvoiceId { get { return GetProperty(documents_InvoiceIdProperty); } set { SetProperty(documents_InvoiceIdProperty, value); } } private static readonly PropertyInfo<bool?> invoicedProperty = RegisterProperty<bool?>(p => p.Invoiced, string.Empty); public bool? Invoiced { get { return GetProperty(invoicedProperty); } set { SetProperty(invoicedProperty, value); } } private static readonly PropertyInfo<System.Int16?> statusProperty = RegisterProperty<System.Int16?>(p => p.Status, string.Empty, (System.Int16?)null); public System.Int16? Status { get { return GetProperty(statusProperty); } set { SetProperty(statusProperty, value); } } #endregion #region Factory Methods public static cDocuments_WorkOrder NewDocuments_WorkOrder() { return DataPortal.Create<cDocuments_WorkOrder>(); } public static cDocuments_WorkOrder GetDocuments_WorkOrder(int uniqueId) { return DataPortal.Fetch<cDocuments_WorkOrder>(new SingleCriteria<cDocuments_WorkOrder, int>(uniqueId)); } internal static cDocuments_WorkOrder GetDocuments_WorkOrder(Documents_WorkOrder data) { return DataPortal.Fetch<cDocuments_WorkOrder>(data); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cDocuments_WorkOrder, int> criteria) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = ctx.ObjectContext.Documents_Document.OfType<Documents_WorkOrder>().First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<Guid>(GUIDProperty, data.GUID); LoadProperty<short>(documentTypeProperty, data.DocumentType); LoadProperty<string>(uniqueIdentifierProperty, data.UniqueIdentifier); LoadProperty<string>(barcodeProperty, data.Barcode); LoadProperty<int>(ordinalNumberProperty, data.OrdinalNumber); LoadProperty<int>(ordinalNumberInYearProperty, data.OrdinalNumberInYear); LoadProperty<DateTime>(documentDateTimeProperty, data.DocumentDateTime); LoadProperty<DateTime>(creationDateTimeProperty, data.CreationDateTime); LoadProperty<int>(mDSubjects_Employee_AuthorIdProperty, data.MDSubjects_Employee_AuthorId); LoadProperty<string>(descriptionProperty, data.Description); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate); LoadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty, data.MDSubjects_EmployeeWhoChengedId); LoadProperty<int?>(projects_ProjectIdProperty, data.Projects_ProjectId); LoadProperty<int?>(mDSubjects_SubjectIdProperty, data.MDSubjects_SubjectId); LoadProperty<int?>(documents_OrderFormIdProperty, data.Documents_OrderFormId); LoadProperty<int?>(placeIdProperty, data.PlaceId); LoadProperty<int?>(documents_TravelOrderIdProperty, data.Documents_TravelOrderId); LoadProperty<decimal?>(distanceProperty, data.Distance); LoadProperty<bool?>(isVerifiedProperty, data.IsVerified); LoadProperty<string>(verifierNameProperty, data.VerifierName); LoadProperty<string>(verifierPhoneProperty, data.VerifierPhone); LoadProperty<bool>(isBillableProperty, data.IsBillable); LoadProperty<int?>(documents_InvoiceIdProperty, data.Documents_InvoiceId); LoadProperty<bool?>(invoicedProperty, data.Invoiced); LoadProperty<short?>(statusProperty, data.Status); LastChanged = data.LastChanged; //LoadProperty<cDocuments_ItemsCol>(Documents_ItemsColProperty, cDocuments_ItemsCol.GetDocuments_ItemsCol(data.Documents_ItemsCol)); BusinessRules.CheckRules(); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_WorkOrder(); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.GUID = ReadProperty<Guid>(GUIDProperty); data.DocumentType = ReadProperty<short>(documentTypeProperty); data.UniqueIdentifier = ReadProperty<string>(uniqueIdentifierProperty); data.Barcode = ReadProperty<string>(barcodeProperty); data.OrdinalNumber = ReadProperty<int>(ordinalNumberProperty); data.OrdinalNumberInYear = ReadProperty<int>(ordinalNumberInYearProperty); data.DocumentDateTime = ReadProperty<DateTime>(documentDateTimeProperty); data.CreationDateTime = ReadProperty<DateTime>(creationDateTimeProperty); data.MDSubjects_Employee_AuthorId = ReadProperty<int>(mDSubjects_Employee_AuthorIdProperty); data.Description = ReadProperty<string>(descriptionProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty); data.Projects_ProjectId = ReadProperty<int?>(projects_ProjectIdProperty); data.MDSubjects_SubjectId = ReadProperty<int?>(mDSubjects_SubjectIdProperty); data.Documents_OrderFormId = ReadProperty<int?>(documents_OrderFormIdProperty); data.PlaceId = ReadProperty<int?>(placeIdProperty); data.Documents_TravelOrderId = ReadProperty<int?>(documents_TravelOrderIdProperty); data.Distance = ReadProperty<decimal?>(distanceProperty); data.IsVerified = ReadProperty<bool?>(isVerifiedProperty); data.VerifierName = ReadProperty<string>(verifierNameProperty); data.VerifierPhone = ReadProperty<string>(verifierPhoneProperty); data.IsBillable = ReadProperty<bool>(isBillableProperty); data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty); data.Invoiced = ReadProperty<bool?>(invoicedProperty); data.Status = ReadProperty<short?>(statusProperty); ctx.ObjectContext.AddToDocuments_Document(data); //DataPortal.UpdateChild(ReadProperty<cDocuments_ItemsCol>(Documents_ItemsColProperty), data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_WorkOrder(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.GUID = ReadProperty<Guid>(GUIDProperty); data.DocumentType = ReadProperty<short>(documentTypeProperty); data.UniqueIdentifier = ReadProperty<string>(uniqueIdentifierProperty); data.Barcode = ReadProperty<string>(barcodeProperty); data.OrdinalNumber = ReadProperty<int>(ordinalNumberProperty); data.OrdinalNumberInYear = ReadProperty<int>(ordinalNumberInYearProperty); data.DocumentDateTime = ReadProperty<DateTime>(documentDateTimeProperty); data.CreationDateTime = ReadProperty<DateTime>(creationDateTimeProperty); data.MDSubjects_Employee_AuthorId = ReadProperty<int>(mDSubjects_Employee_AuthorIdProperty); data.Description = ReadProperty<string>(descriptionProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty); data.Projects_ProjectId = ReadProperty<int?>(projects_ProjectIdProperty); data.MDSubjects_SubjectId = ReadProperty<int?>(mDSubjects_SubjectIdProperty); data.Documents_OrderFormId = ReadProperty<int?>(documents_OrderFormIdProperty); data.PlaceId = ReadProperty<int?>(placeIdProperty); data.Documents_TravelOrderId = ReadProperty<int?>(documents_TravelOrderIdProperty); data.Distance = ReadProperty<decimal?>(distanceProperty); data.IsVerified = ReadProperty<bool?>(isVerifiedProperty); data.VerifierName = ReadProperty<string>(verifierNameProperty); data.VerifierPhone = ReadProperty<string>(verifierPhoneProperty); data.IsBillable = ReadProperty<bool>(isBillableProperty); data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty); data.Invoiced = ReadProperty<bool?>(invoicedProperty); data.Status = ReadProperty<short?>(statusProperty); //DataPortal.UpdateChild(ReadProperty<cDocuments_ItemsCol>(Documents_ItemsColProperty), data); ctx.ObjectContext.SaveChanges(); } } #endregion } }
using System; using System.Text; namespace DoFactory.HeadFirst.State.GumballStateWinner { class GumballMachineTestDrive { static void Main(string[] args) { var machine = new GumballMachine(10); Console.WriteLine(machine); machine.InsertQuarter(); machine.TurnCrank(); machine.InsertQuarter(); machine.TurnCrank(); Console.WriteLine(machine); machine.InsertQuarter(); machine.TurnCrank(); machine.InsertQuarter(); machine.TurnCrank(); Console.WriteLine(machine); machine.InsertQuarter(); machine.TurnCrank(); machine.InsertQuarter(); machine.TurnCrank(); Console.WriteLine(machine); machine.InsertQuarter(); machine.TurnCrank(); machine.InsertQuarter(); machine.TurnCrank(); Console.WriteLine(machine); machine.InsertQuarter(); machine.TurnCrank(); machine.InsertQuarter(); machine.TurnCrank(); Console.WriteLine(machine); // Wait for user Console.ReadKey(); } } #region Gumball Machine public class GumballMachine { private IState _soldOutState; private IState _noQuarterState; private IState _hasQuarterState; private IState _soldState; private IState _winnerState; public IState State { get; set; } public int Count { get; private set; } public GumballMachine(int count) { _soldOutState = new SoldOutState(this); _noQuarterState = new NoQuarterState(this); _hasQuarterState = new HasQuarterState(this); _soldState = new SoldState(this); _winnerState = new WinnerState(this); Count = count; if (Count > 0) { State = _noQuarterState; } else { State = _soldOutState; } } public void InsertQuarter() { State.InsertQuarter(); } public void EjectQuarter() { State.EjectQuarter(); } public void TurnCrank() { State.TurnCrank(); State.Dispense(); } public void ReleaseBall() { if (Count > 0) { Console.WriteLine("A gumball comes rolling out the slot..."); Count--; } } void Refill(int count) { Count = count; State = _noQuarterState; } public IState GetSoldOutState() { return _soldOutState; } public IState GetNoQuarterState() { return _noQuarterState; } public IState GetHasQuarterState() { return _hasQuarterState; } public IState GetSoldState() { return _soldState; } public IState GetWinnerState() { return _winnerState; } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append("\nMighty Gumball, Inc."); result.Append("\n.NET-enabled Standing Gumball Model #2004"); result.Append("\nInventory: " + Count + " gumball"); if (Count != 1) { result.Append("s"); } result.Append("\n"); result.Append("Machine is " + State + "\n"); return result.ToString(); } } #endregion #region State public interface IState { void InsertQuarter(); void EjectQuarter(); void TurnCrank(); void Dispense(); } public class SoldState : IState { private GumballMachine _machine; public SoldState(GumballMachine machine) { this._machine = machine; } public void InsertQuarter() { Console.WriteLine("Please wait, we're already giving you a gumball"); } public void EjectQuarter() { Console.WriteLine("Sorry, you already turned the crank"); } public void TurnCrank() { Console.WriteLine("Turning twice doesn't get you another gumball!"); } public void Dispense() { _machine.ReleaseBall(); if (_machine.Count > 0) { _machine.State = _machine.GetNoQuarterState(); } else { Console.WriteLine("Oops, out of gumballs!"); _machine.State = _machine.GetSoldOutState(); } } public override string ToString() { return "dispensing a gumball"; } } public class SoldOutState : IState { private GumballMachine _machine; public SoldOutState(GumballMachine machine) { this._machine = machine; } public void InsertQuarter() { Console.WriteLine("You can't insert a quarter, the machine is sold out"); } public void EjectQuarter() { Console.WriteLine("You can't eject, you haven't inserted a quarter yet"); } public void TurnCrank() { Console.WriteLine("You turned, but there are no gumballs"); } public void Dispense() { Console.WriteLine("No gumball dispensed"); } public override string ToString() { return "sold out"; } } public class NoQuarterState : IState { private GumballMachine _machine; public NoQuarterState(GumballMachine machine) { this._machine = machine; } public void InsertQuarter() { Console.WriteLine("You inserted a quarter"); _machine.State = _machine.GetHasQuarterState(); } public void EjectQuarter() { Console.WriteLine("You haven't inserted a quarter"); } public void TurnCrank() { Console.WriteLine("You turned, but there's no quarter"); } public void Dispense() { Console.WriteLine("You need to pay first"); } public override string ToString() { return "waiting for quarter"; } } public class HasQuarterState : IState { private GumballMachine _machine; public HasQuarterState(GumballMachine machine) { this._machine = machine; } public void InsertQuarter() { Console.WriteLine("You can't insert another quarter"); } public void EjectQuarter() { Console.WriteLine("Quarter returned"); _machine.State = _machine.GetNoQuarterState(); } public void TurnCrank() { Console.WriteLine("You turned..."); Random random = new Random(); int winner = random.Next(11); if ((winner == 0) && (_machine.Count > 1)) { _machine.State = _machine.GetWinnerState(); } else { _machine.State = _machine.GetSoldState(); } } public void Dispense() { Console.WriteLine("No gumball dispensed"); } public override string ToString() { return "waiting for turn of crank"; } } public class WinnerState : IState { private GumballMachine _machine; public WinnerState(GumballMachine machine) { this._machine = machine; } public void InsertQuarter() { Console.WriteLine("Please wait, we're already giving you a Gumball"); } public void EjectQuarter() { Console.WriteLine("Please wait, we're already giving you a Gumball"); } public void TurnCrank() { Console.WriteLine("Turning again doesn't get you another gumball!"); } public void Dispense() { Console.WriteLine("YOU'RE A WINNER! You get two gumballs for your quarter"); _machine.ReleaseBall(); if (_machine.Count == 0) { _machine.State = _machine.GetSoldOutState(); } else { _machine.ReleaseBall(); if (_machine.Count > 0) { _machine.State = _machine.GetNoQuarterState(); } else { Console.WriteLine("Oops, out of gumballs!"); _machine.State = _machine.GetSoldOutState(); } } } public override string ToString() { return "despensing two gumballs for your quarter, because YOU'RE A WINNER!"; } } #endregion }
using Foundation; using System; using System.Threading.Tasks; using System.Collections.Generic; using UIKit; using zsquared; using static zsquared.C_MessageBox; namespace vitavol { public partial class VC_SCSite : UIViewController { C_Global Global; C_VitaUser LoggedInUser; C_VitaSite SelectedSite; public VC_SCSite (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); if (Global.ViewCameFrom == E_ViewCameFrom.Login) B_Back.SetTitle("< Login", UIControlState.Normal); else B_Back.SetTitle("< Back", UIControlState.Normal); B_Back.TouchUpInside += (sender, e) => { if (LoggedInUser.SitesCoordinated.Count == 1) PerformSegue("Segue_SCSiteToLogin", this); else PerformSegue("Segue_SCSiteToSCSites", this); }; B_Closed.TouchUpInside += async (sender, e) => { E_ClientSiteStatus newStatus = E_ClientSiteStatus.Closed; EnableUI(false); AI_Busy.StartAnimating(); C_IOResult ior = await Global.UpdateSiteStatus(SelectedSite, newStatus, LoggedInUser.Token); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } AI_Busy.StopAnimating(); EnableUI(true); }; B_Accepting.TouchUpInside += async (sender, e) => { E_ClientSiteStatus newStatus = E_ClientSiteStatus.Accepting; EnableUI(false); AI_Busy.StartAnimating(); EnableUI(false); AI_Busy.StartAnimating(); C_IOResult ior = await Global.UpdateSiteStatus(SelectedSite, newStatus, LoggedInUser.Token); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } AI_Busy.StopAnimating(); EnableUI(true); }; B_NearLimit.TouchUpInside += async (sender, e) => { E_ClientSiteStatus newStatus = E_ClientSiteStatus.NearLimit; EnableUI(false); AI_Busy.StartAnimating(); C_IOResult ior = await Global.UpdateSiteStatus(SelectedSite, newStatus, LoggedInUser.Token); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } AI_Busy.StopAnimating(); EnableUI(true); }; B_AtLimit.TouchUpInside += async (sender, e) => { E_ClientSiteStatus newStatus = E_ClientSiteStatus.NotAccepting; EnableUI(false); AI_Busy.StartAnimating(); C_IOResult ior = await Global.UpdateSiteStatus(SelectedSite, newStatus, LoggedInUser.Token); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } AI_Busy.StopAnimating(); EnableUI(true); }; B_Volunteers.TouchUpInside += (sender, e) => { // clear all the dirty flags in the WorkItems to avoid saving stuff we shouldn't Global.ClearDirtyFlagOnSignUps(); PerformSegue("Segue_SCSiteToSCSiteVolCal", this); }; B_SiteCalendar.TouchUpInside += (sender, e) => PerformSegue("Segue_SCSiteToSCSiteCalendar", this); B_UpdateProfile.TouchUpInside += (sender, e) => { Global.ViewCameFrom = E_ViewCameFrom.SCSite; PerformSegue("Segue_SCSiteToUpdateProfile", this); }; bool killChanges = false; SW_DropOff.ValueChanged += async (sender, e) => { if (killChanges) return; C_IOResult ior = await UpdateSiteCapabilities(); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } }; SW_Express.ValueChanged += async (sender, e) => { if (killChanges) return; C_IOResult ior = await UpdateSiteCapabilities(); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } }; SW_MFT.ValueChanged += async (sender, e) => { if (killChanges) return; C_IOResult ior = await UpdateSiteCapabilities(); if (!ior.Success) { var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok); } }; AI_Busy.StartAnimating(); EnableUI(false); Task.Run(async () => { SelectedSite = await Global.GetSiteWithSlug(Global.SelectedSiteSlug); UIApplication.SharedApplication.InvokeOnMainThread( new Action(() => { AI_Busy.StopAnimating(); EnableUI(true); L_SiteName.Text = SelectedSite.Name; killChanges = true; SW_DropOff.On = SelectedSite.SiteCapabilities.Contains(E_SiteCapabilities.DropOff); SW_Express.On = SelectedSite.SiteCapabilities.Contains(E_SiteCapabilities.Express); SW_MFT.On = SelectedSite.SiteCapabilities.Contains(E_SiteCapabilities.MFT); killChanges = false; })); }); } private void EnableUI(bool enable) { if (SelectedSite != null) { int isiteStatus = (int)SelectedSite.ClientStatus; string ssitestatus = C_VitaSite.N_ClientStatusNames[isiteStatus]; L_ClientStatus.Text = ssitestatus; switch (SelectedSite.ClientStatus) { case E_ClientSiteStatus.Closed: IMG_Currently.Image = UIImage.FromBundle("blackstatus.jpg"); break; case E_ClientSiteStatus.Accepting: IMG_Currently.Image = UIImage.FromBundle("greenstatus.jpg"); break; case E_ClientSiteStatus.NearLimit: IMG_Currently.Image = UIImage.FromBundle("yellowstatus.jpg"); break; case E_ClientSiteStatus.NotAccepting: IMG_Currently.Image = UIImage.FromBundle("redstatus.jpg"); break; } B_Closed.Enabled = enable && SelectedSite.ClientStatus != E_ClientSiteStatus.Closed; B_Accepting.Enabled = enable && SelectedSite.ClientStatus != E_ClientSiteStatus.Accepting; B_NearLimit.Enabled = enable && SelectedSite.ClientStatus != E_ClientSiteStatus.NearLimit; B_AtLimit.Enabled = enable && SelectedSite.ClientStatus != E_ClientSiteStatus.NotAccepting; } else { B_Closed.Enabled = false; B_Accepting.Enabled = false; B_NearLimit.Enabled = false; B_AtLimit.Enabled = false; } B_Volunteers.Enabled = enable; B_SiteCalendar.Enabled = enable; B_UpdateProfile.Enabled = enable; SW_DropOff.Enabled = enable; SW_Express.Enabled = enable; SW_MFT.Enabled = enable; B_Back.Enabled = enable; } private async Task<C_IOResult> UpdateSiteCapabilities() { EnableUI(false); AI_Busy.StartAnimating(); SelectedSite.SiteCapabilities = new List<E_SiteCapabilities>(); if (SW_DropOff.On) SelectedSite.SiteCapabilities.Add(E_SiteCapabilities.DropOff); if (SW_Express.On) SelectedSite.SiteCapabilities.Add(E_SiteCapabilities.Express); if (SW_MFT.On) SelectedSite.SiteCapabilities.Add(E_SiteCapabilities.MFT); C_IOResult ior = await Global.UpdateSiteCapabilities(SelectedSite, LoggedInUser.Token); EnableUI(true); AI_Busy.StopAnimating(); return ior; } public override void ViewDidAppear(bool animated) { // set the standard background color View.BackgroundColor = C_Common.StandardBackground; } } }
using System.Security.Cryptography; using GitVersion.Cache; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.Model.Configuration; using Microsoft.Extensions.Options; namespace GitVersion.VersionCalculation.Cache; public class GitVersionCacheKeyFactory : IGitVersionCacheKeyFactory { private readonly IFileSystem fileSystem; private readonly ILog log; private readonly IOptions<GitVersionOptions> options; private readonly IConfigFileLocator configFileLocator; private readonly IGitRepository gitRepository; private readonly IGitRepositoryInfo repositoryInfo; public GitVersionCacheKeyFactory(IFileSystem fileSystem, ILog log, IOptions<GitVersionOptions> options, IConfigFileLocator configFileLocator, IGitRepository gitRepository, IGitRepositoryInfo repositoryInfo) { this.fileSystem = fileSystem.NotNull(); this.log = log.NotNull(); this.options = options.NotNull(); this.configFileLocator = configFileLocator.NotNull(); this.gitRepository = gitRepository.NotNull(); this.repositoryInfo = repositoryInfo.NotNull(); } public GitVersionCacheKey Create(Config? overrideConfig) { var gitSystemHash = GetGitSystemHash(); var configFileHash = GetConfigFileHash(); var repositorySnapshotHash = GetRepositorySnapshotHash(); var overrideConfigHash = GetOverrideConfigHash(overrideConfig); var compositeHash = GetHash(gitSystemHash, configFileHash, repositorySnapshotHash, overrideConfigHash); return new GitVersionCacheKey(compositeHash); } private string GetGitSystemHash() { var dotGitDirectory = this.repositoryInfo.DotGitDirectory; // traverse the directory and get a list of files, use that for GetHash var contents = CalculateDirectoryContents(PathHelper.Combine(dotGitDirectory, "refs")); return GetHash(contents.ToArray()); } // based on https://msdn.microsoft.com/en-us/library/bb513869.aspx private List<string> CalculateDirectoryContents(string root) { var result = new List<string>(); // Data structure to hold names of subfolders to be // examined for files. var dirs = new Stack<string>(); if (!Directory.Exists(root)) { throw new DirectoryNotFoundException($"Root directory does not exist: {root}"); } dirs.Push(root); while (dirs.Any()) { var currentDir = dirs.Pop(); var di = new DirectoryInfo(currentDir); result.Add(di.Name); string[] subDirs; try { subDirs = Directory.GetDirectories(currentDir); } // An UnauthorizedAccessException exception will be thrown if we do not have // discovery permission on a folder or file. It may or may not be acceptable // to ignore the exception and continue enumerating the remaining files and // folders. It is also possible (but unlikely) that a DirectoryNotFound exception // will be raised. This will happen if currentDir has been deleted by // another application or thread after our call to Directory.Exists. The // choice of which exceptions to catch depends entirely on the specific task // you are intending to perform and also on how much you know with certainty // about the systems on which this code will run. catch (UnauthorizedAccessException e) { this.log.Error(e.Message); continue; } catch (DirectoryNotFoundException e) { this.log.Error(e.Message); continue; } string[] files; try { files = Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { this.log.Error(e.Message); continue; } catch (DirectoryNotFoundException e) { this.log.Error(e.Message); continue; } foreach (var file in files) { try { var fi = new FileInfo(file); result.Add(fi.Name); result.Add(File.ReadAllText(file)); } catch (IOException e) { this.log.Error(e.Message); } } // Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. // push in reverse order for (var i = subDirs.Length - 1; i >= 0; i--) { dirs.Push(subDirs[i]); } } return result; } private string GetRepositorySnapshotHash() { var head = this.gitRepository.Head; if (head.Tip == null) { return head.Name.Canonical; } var hash = string.Join(":", head.Name.Canonical, head.Tip.Sha); return GetHash(hash); } private static string GetOverrideConfigHash(Config? overrideConfig) { if (overrideConfig == null) { return string.Empty; } // Doesn't depend on command line representation and // includes possible changes in default values of Config per se. var stringBuilder = new StringBuilder(); using (var stream = new StringWriter(stringBuilder)) { ConfigSerializer.Write(overrideConfig, stream); stream.Flush(); } var configContent = stringBuilder.ToString(); return GetHash(configContent); } private string GetConfigFileHash() { // will return the same hash even when config file will be moved // from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same. var configFilePath = this.configFileLocator.SelectConfigFilePath(this.options.Value, this.repositoryInfo); if (configFilePath == null || !this.fileSystem.Exists(configFilePath)) { return string.Empty; } var configFileContent = this.fileSystem.ReadAllText(configFilePath); return GetHash(configFileContent); } private static string GetHash(params string[] textsToHash) { var textToHash = string.Join(":", textsToHash); return GetHash(textToHash); } private static string GetHash(string textToHash) { if (textToHash.IsNullOrEmpty()) { return string.Empty; } using var sha1 = SHA1.Create(); var bytes = Encoding.UTF8.GetBytes(textToHash); var hashedBytes = sha1.ComputeHash(bytes); var hashedString = BitConverter.ToString(hashedBytes); return hashedString.Replace("-", ""); } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.IO; using System.Xml; using log4net.Config; using log4net.Util; using log4net.Layout; using log4net.Core; using log4net.Repository; using log4net.Tests.Appender; using NUnit.Framework; namespace log4net.Tests.Layout { [TestFixture] public class XmlLayoutTest { /// <summary> /// Build a basic <see cref="LoggingEventData"/> object with some default values. /// </summary> /// <returns>A useful LoggingEventData object</returns> private LoggingEventData createBaseEvent() { LoggingEventData ed=new LoggingEventData(); ed.Domain="Tests"; ed.ExceptionString=""; ed.Identity="TestRunner"; ed.Level=Level.Info; ed.LocationInfo=new LocationInfo(this.GetType()); ed.LoggerName="TestLogger"; ed.Message="Test message"; ed.ThreadName="TestThread"; ed.TimeStamp=DateTime.Today; ed.UserName="TestRunner"; ed.Properties=new PropertiesDictionary(); return ed; } private string createEventNode(string message) { return String.Format("<event logger=\"TestLogger\" timestamp=\"{0}\" level=\"INFO\" thread=\"TestThread\" domain=\"Tests\" identity=\"TestRunner\" username=\"TestRunner\"><message>{1}</message></event>\r\n", #if NET_2_0 XmlConvert.ToString(DateTime.Today, XmlDateTimeSerializationMode.Local), #else XmlConvert.ToString(DateTime.Today), #endif message); } private string createEventNode(string key, string value) { return String.Format("<event logger=\"TestLogger\" timestamp=\"{0:s}\" level=\"INFO\" thread=\"TestThread\" domain=\"Tests\" identity=\"TestRunner\" username=\"TestRunner\"><message>Test message</message><properties><data name=\"{1}\" value=\"{2}\" /></properties></event>\r\n", #if NET_2_0 XmlConvert.ToString(DateTime.Today, XmlDateTimeSerializationMode.Local), #else XmlConvert.ToString(DateTime.Today), #endif key, value); } [Test] public void TestBasicEventLogging() { TextWriter writer=new StringWriter(); XmlLayout layout=new XmlLayout(); LoggingEventData evt=createBaseEvent(); layout.Format(writer,new LoggingEvent(evt)); string expected = createEventNode("Test message"); Assert.AreEqual (expected, writer.ToString()); } [Test] public void TestIllegalCharacterMasking() { TextWriter writer=new StringWriter(); XmlLayout layout=new XmlLayout(); LoggingEventData evt=createBaseEvent(); evt.Message="This is a masked char->\uFFFF"; layout.Format(writer,new LoggingEvent(evt)); string expected = createEventNode("This is a masked char-&gt;?"); Assert.AreEqual (expected, writer.ToString()); } [Test] public void TestCDATAEscaping1() { TextWriter writer=new StringWriter(); XmlLayout layout=new XmlLayout(); LoggingEventData evt=createBaseEvent(); //The &'s trigger the use of a cdata block evt.Message="&&&&&&&Escape this ]]>. End here."; layout.Format(writer,new LoggingEvent(evt)); string expected = createEventNode("<![CDATA[&&&&&&&Escape this ]]>]]<![CDATA[>. End here.]]>"); Assert.AreEqual (expected, writer.ToString()); } [Test] public void TestCDATAEscaping2() { TextWriter writer=new StringWriter(); XmlLayout layout=new XmlLayout(); LoggingEventData evt=createBaseEvent(); //The &'s trigger the use of a cdata block evt.Message="&&&&&&&Escape the end ]]>"; layout.Format(writer,new LoggingEvent(evt)); string expected = createEventNode("<![CDATA[&&&&&&&Escape the end ]]>]]&gt;"); Assert.AreEqual (expected, writer.ToString()); } [Test] public void TestCDATAEscaping3() { TextWriter writer=new StringWriter(); XmlLayout layout=new XmlLayout(); LoggingEventData evt=createBaseEvent(); //The &'s trigger the use of a cdata block evt.Message="]]>&&&&&&&Escape the begining"; layout.Format(writer,new LoggingEvent(evt)); string expected = createEventNode("<![CDATA[]]>]]<![CDATA[>&&&&&&&Escape the begining]]>"); Assert.AreEqual (expected, writer.ToString()); } [Test] public void TestBase64EventLogging() { TextWriter writer=new StringWriter(); XmlLayout layout=new XmlLayout(); LoggingEventData evt=createBaseEvent(); layout.Base64EncodeMessage=true; layout.Format(writer,new LoggingEvent(evt)); string expected = createEventNode("VGVzdCBtZXNzYWdl"); Assert.AreEqual (expected, writer.ToString()); } [Test] public void TestPropertyEventLogging() { LoggingEventData evt=createBaseEvent(); evt.Properties["Property1"]="prop1"; XmlLayout layout=new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = createEventNode("Property1", "prop1"); Assert.AreEqual (expected, stringAppender.GetString()); } [Test] public void TestBase64PropertyEventLogging() { LoggingEventData evt=createBaseEvent(); evt.Properties["Property1"]="prop1"; XmlLayout layout=new XmlLayout(); layout.Base64EncodeProperties=true; StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = createEventNode("Property1", "cHJvcDE="); Assert.AreEqual (expected, stringAppender.GetString()); } [Test] public void TestPropertyCharacterEscaping() { LoggingEventData evt=createBaseEvent(); evt.Properties["Property1"]="prop1 \"quoted\""; XmlLayout layout=new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = createEventNode("Property1", "prop1 &quot;quoted&quot;"); Assert.AreEqual (expected, stringAppender.GetString()); } [Test] public void TestPropertyIllegalCharacterMasking() { LoggingEventData evt=createBaseEvent(); evt.Properties["Property1"]="mask this ->\uFFFF"; XmlLayout layout=new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = createEventNode("Property1", "mask this -&gt;?"); Assert.AreEqual (expected, stringAppender.GetString()); } [Test] public void TestPropertyIllegalCharacterMaskingInName() { LoggingEventData evt=createBaseEvent(); evt.Properties["Property\uFFFF"]="mask this ->\uFFFF"; XmlLayout layout=new XmlLayout(); StringAppender stringAppender = new StringAppender(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern"); log1.Logger.Log(new LoggingEvent(evt)); string expected = createEventNode("Property?", "mask this -&gt;?"); Assert.AreEqual (expected, stringAppender.GetString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.NetworkInformation; using System.Text; // Relevant cookie specs: // // PERSISTENT CLIENT STATE HTTP COOKIES (1996) // From <http:// web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html> // // RFC2109 HTTP State Management Mechanism (February 1997) // From <http:// tools.ietf.org/html/rfc2109> // // RFC2965 HTTP State Management Mechanism (October 2000) // From <http:// tools.ietf.org/html/rfc2965> // // RFC6265 HTTP State Management Mechanism (April 2011) // From <http:// tools.ietf.org/html/rfc6265> // // The Version attribute of the cookie header is defined and used only in RFC2109 and RFC2965 cookie // specs and specifies Version=1. The Version attribute is not used in the Netscape cookie spec // (considered as Version=0). Nor is it used in the most recent cookie spec, RFC6265, introduced in 2011. // RFC6265 deprecates all previous cookie specs including the Version attribute. // // Cookies without an explicit Domain attribute will only match a potential uri that matches the original // uri from where the cookie came from. // // For explicit Domain attribute in the cookie, the following rules apply: // // Version=0 (Netscape, RFC6265) allows the Domain attribute of the cookie to match any tail substring // of the host uri. // // Version=1 related cookie specs only allows the Domain attribute to match the host uri based on a // more restricted set of rules. // // According to RFC2109/RFC2965, the cookie will be rejected for matching if: // * The value for the Domain attribute contains no embedded dots or does not start with a dot. // * The value for the request-host does not domain-match the Domain attribute. // " The request-host is a FQDN (not IP address) and has the form HD, where D is the value of the Domain // attribute, and H is a string that contains one or more dots. // // Examples: // * A cookie from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x // and contains a dot. // // * A cookie from request-host x.foo.com for Domain=.foo.com would be accepted. // // * A cookie with Domain=.com or Domain=.com., will always be rejected, because there is no embedded dot. // // * A cookie with Domain=ajax.com will be rejected because the value for Domain does not begin with a dot. namespace System.Net { internal struct HeaderVariantInfo { private readonly string _name; private readonly CookieVariant _variant; internal HeaderVariantInfo(string name, CookieVariant variant) { _name = name; _variant = variant; } internal string Name { get { return _name; } } internal CookieVariant Variant { get { return _variant; } } } // CookieContainer // // Manage cookies for a user (implicit). Based on RFC 2965. [Serializable] public class CookieContainer { public const int DefaultCookieLimit = 300; public const int DefaultPerDomainCookieLimit = 20; public const int DefaultCookieLengthLimit = 4096; private static readonly HeaderVariantInfo[] s_headerInfo = { new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie, CookieVariant.Rfc2109), new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie2, CookieVariant.Rfc2965) }; // NOTE: all accesses of _domainTable must be performed with _domainTable locked. private readonly Dictionary<string, PathList> _domainTable = new Dictionary<string, PathList>(); private int _maxCookieSize = DefaultCookieLengthLimit; private int _maxCookies = DefaultCookieLimit; private int _maxCookiesPerDomain = DefaultPerDomainCookieLimit; private int _count = 0; private string _fqdnMyDomain = string.Empty; public CookieContainer() { string domain = HostInformation.DomainName; if (domain != null && domain.Length > 1) { _fqdnMyDomain = '.' + domain; } // Otherwise it will remain string.Empty. } public CookieContainer(int capacity) : this() { if (capacity <= 0) { throw new ArgumentException(SR.net_toosmall, "Capacity"); } _maxCookies = capacity; } public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : this(capacity) { if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity)) { throw new ArgumentOutOfRangeException(nameof(perDomainCapacity), SR.Format(SR.net_cookie_capacity_range, "PerDomainCapacity", 0, capacity)); } _maxCookiesPerDomain = perDomainCapacity; if (maxCookieSize <= 0) { throw new ArgumentException(SR.net_toosmall, "MaxCookieSize"); } _maxCookieSize = maxCookieSize; } // NOTE: after shrinking the capacity, Count can become greater than Capacity. public int Capacity { get { return _maxCookies; } set { if (value <= 0 || (value < _maxCookiesPerDomain && _maxCookiesPerDomain != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value), SR.Format(SR.net_cookie_capacity_range, "Capacity", 0, _maxCookiesPerDomain)); } if (value < _maxCookies) { _maxCookies = value; AgeCookies(null); } _maxCookies = value; } } /// <devdoc> /// <para>Returns the total number of cookies in the container.</para> /// </devdoc> public int Count { get { return _count; } } public int MaxCookieSize { get { return _maxCookieSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxCookieSize = value; } } /// <devdoc> /// <para>After shrinking domain capacity, each domain will less hold than new domain capacity.</para> /// </devdoc> public int PerDomainCapacity { get { return _maxCookiesPerDomain; } set { if (value <= 0 || (value > _maxCookies && value != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value < _maxCookiesPerDomain) { _maxCookiesPerDomain = value; AgeCookies(null); } _maxCookiesPerDomain = value; } } // This method will construct a faked URI: the Domain property is required for param. public void Add(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } if (cookie.Domain.Length == 0) { throw new ArgumentException(SR.net_emptystringcall, "cookie.Domain"); } Uri uri; var uriSb = new StringBuilder(); // We cannot add an invalid cookie into the container. // Trying to prepare Uri for the cookie verification. uriSb.Append(cookie.Secure ? UriScheme.Https : UriScheme.Http).Append(UriScheme.SchemeDelimiter); // If the original cookie has an explicitly set domain, copy it over to the new cookie. if (!cookie.DomainImplicit) { if (cookie.Domain[0] == '.') { uriSb.Append("0"); // URI cctor should consume this faked host. } } uriSb.Append(cookie.Domain); // Either keep Port as implicit or set it according to original cookie. if (cookie.PortList != null) { uriSb.Append(":").Append(cookie.PortList[0]); } // Path must be present, set to root by default. uriSb.Append(cookie.Path); if (!Uri.TryCreate(uriSb.ToString(), UriKind.Absolute, out uri)) throw new CookieException(SR.Format(SR.net_cookie_attribute, "Domain", cookie.Domain)); // We don't know cookie verification status, so re-create the cookie and verify it. Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true); Add(new_cookie, true); } // This method is called *only* when cookie verification is done, so unlike with public // Add(Cookie cookie) the cookie is in a reasonable condition. internal void Add(Cookie cookie, bool throwOnError) { PathList pathList; if (cookie.Value.Length > _maxCookieSize) { if (throwOnError) { throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), _maxCookieSize)); } return; } try { lock (_domainTable) { if (!_domainTable.TryGetValue(cookie.DomainKey, out pathList)) { _domainTable[cookie.DomainKey] = (pathList = PathList.Create()); } } int domain_count = pathList.GetCookiesCount(); CookieCollection cookies; lock (pathList.SyncRoot) { cookies = pathList[cookie.Path]; if (cookies == null) { cookies = new CookieCollection(); pathList[cookie.Path] = cookies; } } if (cookie.Expired) { // Explicit removal command (Max-Age == 0) lock (cookies) { int idx = cookies.IndexOf(cookie); if (idx != -1) { cookies.RemoveAt(idx); --_count; } } } else { // This is about real cookie adding, check Capacity first if (domain_count >= _maxCookiesPerDomain && !AgeCookies(cookie.DomainKey)) { return; // Cannot age: reject new cookie } else if (_count >= _maxCookies && !AgeCookies(null)) { return; // Cannot age: reject new cookie } // About to change the collection lock (cookies) { _count += cookies.InternalAdd(cookie, true); } } } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (throwOnError) { throw new CookieException(SR.net_container_add_cookie, e); } } } // This function, when called, must delete at least one cookie. // If there are expired cookies in given scope they are cleaned up. // If nothing is found the least used Collection will be found and removed // from the container. // // Also note that expired cookies are also removed during request preparation // (this.GetCookies method). // // Param. 'domain' == null means to age in the whole container. private bool AgeCookies(string domain) { Debug.Assert(_maxCookies != 0); Debug.Assert(_maxCookiesPerDomain != 0); int removed = 0; DateTime oldUsed = DateTime.MaxValue; DateTime tempUsed; CookieCollection lruCc = null; string lruDomain = null; string tempDomain = null; PathList pathList; int domain_count = 0; int itemp = 0; float remainingFraction = 1.0F; // The container was shrunk, might need additional cleanup for each domain if (_count > _maxCookies) { // Means the fraction of the container to be left. // Each domain will be cut accordingly. remainingFraction = (float)_maxCookies / (float)_count; } lock (_domainTable) { foreach (KeyValuePair<string, PathList> entry in _domainTable) { if (domain == null) { tempDomain = entry.Key; pathList = entry.Value; // Aliasing to trick foreach } else { tempDomain = domain; _domainTable.TryGetValue(domain, out pathList); } domain_count = 0; // Cookies in the domain lock (pathList.SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in pathList) { CookieCollection cc = pair.Value; itemp = ExpireCollection(cc); removed += itemp; _count -= itemp; // Update this container's count domain_count += cc.Count; // We also find the least used cookie collection in ENTIRE container. // We count the collection as LRU only if it holds 1+ elements. if (cc.Count > 0 && (tempUsed = cc.TimeStamp(CookieCollection.Stamp.Check)) < oldUsed) { lruDomain = tempDomain; lruCc = cc; oldUsed = tempUsed; } } } // Check if we have reduced to the limit of the domain by expiration only. int min_count = Math.Min((int)(domain_count * remainingFraction), Math.Min(_maxCookiesPerDomain, _maxCookies) - 1); if (domain_count > min_count) { // This case requires sorting all domain collections by timestamp. KeyValuePair<DateTime, CookieCollection>[] cookies; lock (pathList.SyncRoot) { cookies = new KeyValuePair<DateTime, CookieCollection>[pathList.Count]; foreach (KeyValuePair<string, CookieCollection> pair in pathList) { CookieCollection cc = pair.Value; cookies[itemp] = new KeyValuePair<DateTime, CookieCollection>(cc.TimeStamp(CookieCollection.Stamp.Check), cc); ++itemp; } } Array.Sort(cookies, (a, b) => a.Key.CompareTo(b.Key)); itemp = 0; for (int i = 0; i < cookies.Length; ++i) { CookieCollection cc = cookies[i].Value; lock (cc) { while (domain_count > min_count && cc.Count > 0) { cc.RemoveAt(0); --domain_count; --_count; ++removed; } } if (domain_count <= min_count) { break; } } if (domain_count > min_count && domain != null) { // Cannot complete aging of explicit domain (no cookie adding allowed). return false; } } } } // We have completed aging of the specified domain. if (domain != null) { return true; } // The rest is for entire container aging. // We must get at least one free slot. // Don't need to apply LRU if we already cleaned something. if (removed != 0) { return true; } if (oldUsed == DateTime.MaxValue) { // Something strange. Either capacity is 0 or all collections are locked with cc.Used. return false; } // Remove oldest cookies from the least used collection. lock (lruCc) { while (_count >= _maxCookies && lruCc.Count > 0) { lruCc.RemoveAt(0); --_count; } } return true; } // Return number of cookies removed from the collection. private int ExpireCollection(CookieCollection cc) { lock (cc) { int oldCount = cc.Count; int idx = oldCount - 1; // Cannot use enumerator as we are going to alter collection. while (idx >= 0) { Cookie cookie = cc[idx]; if (cookie.Expired) { cc.RemoveAt(idx); } --idx; } return oldCount - cc.Count; } } public void Add(CookieCollection cookies) { if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } foreach (Cookie c in cookies) { Add(c); } } // This will try (if needed) get the full domain name of the host given the Uri. // NEVER call this function from internal methods with 'fqdnRemote' == null. // Since this method counts security issue for DNS and hence will slow // the performance. internal bool IsLocalDomain(string host) { int dot = host.IndexOf('.'); if (dot == -1) { // No choice but to treat it as a host on the local domain. // This also covers 'localhost' and 'loopback'. return true; } // Quick test for typical cases: loopback addresses for IPv4 and IPv6. if ((host == "127.0.0.1") || (host == "::1") || (host == "0:0:0:0:0:0:0:1")) { return true; } // Test domain membership. if (string.Compare(_fqdnMyDomain, 0, host, dot, _fqdnMyDomain.Length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } // Test for "127.###.###.###" without using regex. string[] ipParts = host.Split('.'); if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127") { int i; for (i = 1; i < ipParts.Length; i++) { string part = ipParts[i]; switch (part.Length) { case 3: if (part[2] < '0' || part[2] > '9') { break; } goto case 2; case 2: if (part[1] < '0' || part[1] > '9') { break; } goto case 1; case 1: if (part[0] < '0' || part[0] > '9') { break; } continue; } break; } if (i == 4) { return true; } } return false; } public void Add(Uri uri, Cookie cookie) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true); Add(new_cookie, true); } public void Add(Uri uri, CookieCollection cookies) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { Cookie new_cookie = c.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, _fqdnMyDomain, true, true); Add(new_cookie, true); } } internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow) { if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}"); } CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; if (headerName == null) { variant = CookieVariant.Default; } else { for (int i = 0; i < s_headerInfo.Length; ++i) { if ((String.Compare(headerName, s_headerInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0)) { variant = s_headerInfo[i].Variant; } } } bool isLocalDomain = IsLocalDomain(uri.Host); try { CookieParser parser = new CookieParser(setCookieHeader); do { Cookie cookie = parser.Get(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}"); if (cookie == null) { break; } // Parser marks invalid cookies this way if (String.IsNullOrEmpty(cookie.Name)) { if (isThrow) { throw new CookieException(SR.net_cookie_format); } // Otherwise, ignore (reject) cookie continue; } // This will set the default values from the response URI // AND will check for cookie validity if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, _fqdnMyDomain, true, isThrow)) { continue; } // If many same cookies arrive we collapse them into just one, hence setting // parameter isStrict = true below cookies.InternalAdd(cookie, true); } while (true); } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (isThrow) { throw new CookieException(SR.Format(SR.net_cookie_parse_header, uri.AbsoluteUri), e); } } foreach (Cookie c in cookies) { Add(c, isThrow); } return cookies; } public CookieCollection GetCookies(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } return InternalGetCookies(uri) ?? new CookieCollection(); } internal CookieCollection InternalGetCookies(Uri uri) { if (_count == 0) { return null; } bool isSecure = (uri.Scheme == UriScheme.Https); int port = uri.Port; CookieCollection cookies = null; List<string> domainAttributeMatchAnyCookieVariant = new List<string>(); List<string> domainAttributeMatchOnlyCookieVariantPlain = null; string fqdnRemote = uri.Host; // Add initial candidates to match Domain attribute of possible cookies. // For these Domains, cookie can have any CookieVariant enum value. domainAttributeMatchAnyCookieVariant.Add(fqdnRemote); domainAttributeMatchAnyCookieVariant.Add("." + fqdnRemote); int dot = fqdnRemote.IndexOf('.'); if (dot == -1) { // DNS.resolve may return short names even for other inet domains ;-( // We _don't_ know what the exact domain is, so try also grab short hostname cookies. // Grab long name from the local domain if (_fqdnMyDomain != null && _fqdnMyDomain.Length != 0) { domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + _fqdnMyDomain); // Grab the local domain itself domainAttributeMatchAnyCookieVariant.Add(_fqdnMyDomain); } } else { // Grab the host domain domainAttributeMatchAnyCookieVariant.Add(fqdnRemote.Substring(dot)); // The following block is only for compatibility with Version0 spec. // Still, we'll add only Plain-Variant cookies if found under below keys if (fqdnRemote.Length > 2) { // We ignore the '.' at the end on the name int last = fqdnRemote.LastIndexOf('.', fqdnRemote.Length - 2); // AND keys with <2 dots inside. if (last > 0) { last = fqdnRemote.LastIndexOf('.', last - 1); } if (last != -1) { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1) { if (domainAttributeMatchOnlyCookieVariantPlain == null) { domainAttributeMatchOnlyCookieVariantPlain = new List<string>(); } // These candidates can only match CookieVariant.Plain cookies. domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot)); } } } } BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchAnyCookieVariant, false); if (domainAttributeMatchOnlyCookieVariantPlain != null) { BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchOnlyCookieVariantPlain, true); } return cookies; } private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, ref CookieCollection cookies, List<string> domainAttribute, bool matchOnlyPlainCookie) { for (int i = 0; i < domainAttribute.Count; i++) { bool found = false; bool defaultAdded = false; PathList pathList; lock (_domainTable) { if (!_domainTable.TryGetValue(domainAttribute[i], out pathList)) { continue; } } lock (pathList.SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in pathList) { string path = pair.Key; if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path))) { found = true; CookieCollection cc = pair.Value; cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie); if (path == "/") { defaultAdded = true; } } else if (found) { break; } } } if (!defaultAdded) { CookieCollection cc = pathList["/"]; if (cc != null) { cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie); } } // Remove unused domain // (This is the only place that does domain removal) if (pathList.Count == 0) { lock (_domainTable) { _domainTable.Remove(domainAttribute[i]); } } } } private void MergeUpdateCollections(ref CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly) { lock (source) { // Cannot use foreach as we are going to update 'source' for (int idx = 0; idx < source.Count; ++idx) { bool to_add = false; Cookie cookie = source[idx]; if (cookie.Expired) { // If expired, remove from container and don't add to the destination source.RemoveAt(idx); --_count; --idx; } else { // Add only if port does match to this request URI // or was not present in the original response. if (isPlainOnly && cookie.Variant != CookieVariant.Plain) { ; // Don't add } else if (cookie.PortList != null) { foreach (int p in cookie.PortList) { if (p == port) { to_add = true; break; } } } else { // It was implicit Port, always OK to add. to_add = true; } // Refuse to add a secure cookie into an 'unsecure' destination if (cookie.Secure && !isSecure) { to_add = false; } if (to_add) { // In 'source' are already ordered. // If two same cookies come from different 'source' then they // will follow (not replace) each other. if (destination == null) { destination = new CookieCollection(); } destination.InternalAdd(cookie, false); } } } } } public string GetCookieHeader(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } string dummy; return GetCookieHeader(uri, out dummy); } internal string GetCookieHeader(Uri uri, out string optCookie2) { CookieCollection cookies = InternalGetCookies(uri); if (cookies == null) { optCookie2 = string.Empty; return string.Empty; } string delimiter = string.Empty; var builder = StringBuilderCache.Acquire(); for (int i = 0; i < cookies.Count; i++) { builder.Append(delimiter); cookies[i].ToString(builder); delimiter = "; "; } optCookie2 = cookies.IsOtherVersionSeen ? (Cookie.SpecialAttributeLiteral + CookieFields.VersionAttributeName + Cookie.EqualsLiteral + Cookie.MaxSupportedVersionString) : string.Empty; return StringBuilderCache.GetStringAndRelease(builder); } public void SetCookies(Uri uri, string cookieHeader) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookieHeader == null) { throw new ArgumentNullException(nameof(cookieHeader)); } CookieCutter(uri, null, cookieHeader, true); // Will throw on error } } internal struct PathList { // Usage of PathList depends on it being shallowly immutable; // adding any mutable fields to it would result in breaks. private readonly SortedList<string, CookieCollection> _list; public static PathList Create() => new PathList(new SortedList<string, CookieCollection>(PathListComparer.StaticInstance)); private PathList(SortedList<string, CookieCollection> list) { Debug.Assert(list != null, $"{nameof(list)} must not be null."); _list = list; } public int Count { get { lock (SyncRoot) { return _list.Count; } } } public int GetCookiesCount() { int count = 0; lock (SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in _list) { CookieCollection cc = pair.Value; count += cc.Count; } } return count; } public CookieCollection this[string s] { get { lock (SyncRoot) { CookieCollection value; _list.TryGetValue(s, out value); return value; } } set { lock (SyncRoot) { Debug.Assert(value != null); _list[s] = value; } } } public IEnumerator<KeyValuePair<string, CookieCollection>> GetEnumerator() { lock (SyncRoot) { return _list.GetEnumerator(); } } public object SyncRoot { get { Debug.Assert(_list != null, $"{nameof(PathList)} should never be default initialized and only ever created with {nameof(Create)}."); return _list; } } private sealed class PathListComparer : IComparer<string> { internal static readonly PathListComparer StaticInstance = new PathListComparer(); int IComparer<string>.Compare(string x, string y) { string pathLeft = CookieParser.CheckQuoted(x); string pathRight = CookieParser.CheckQuoted(y); int ll = pathLeft.Length; int lr = pathRight.Length; int length = Math.Min(ll, lr); for (int i = 0; i < length; ++i) { if (pathLeft[i] != pathRight[i]) { return pathLeft[i] - pathRight[i]; } } return lr - ll; } } } }
// 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.Net; using System.Threading.Tasks; namespace System.Net.Sockets { // The System.Net.Sockets.TcpListener class provide TCP services at a higher level of abstraction // than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpListener is used to create a // host process that listens for connections from TCP clients. public class TcpListener { private IPEndPoint _serverSocketEP; private Socket _serverSocket; private bool _active; private bool _exclusiveAddressUse; // Initializes a new instance of the TcpListener class with the specified local end point. public TcpListener(IPEndPoint localEP) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpListener", localEP); } if (localEP == null) { throw new ArgumentNullException("localEP"); } _serverSocketEP = localEP; _serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpListener", null); } } // Initializes a new instance of the TcpListener class that listens to the specified IP address // and port. public TcpListener(IPAddress localaddr, int port) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpListener", localaddr); } if (localaddr == null) { throw new ArgumentNullException("localaddr"); } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException("port"); } _serverSocketEP = new IPEndPoint(localaddr, port); _serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpListener", null); } } // Used by the class to provide the underlying network socket. public Socket Server { get { return _serverSocket; } } // Used by the class to indicate that the listener's socket has been bound to a port // and started listening. protected bool Active { get { return _active; } } // Gets the m_Active EndPoint for the local listener socket. public EndPoint LocalEndpoint { get { return _active ? _serverSocket.LocalEndPoint : _serverSocketEP; } } public bool ExclusiveAddressUse { get { return _serverSocket.ExclusiveAddressUse; } set { if (_active) { throw new InvalidOperationException(SR.net_tcplistener_mustbestopped); } _serverSocket.ExclusiveAddressUse = value; _exclusiveAddressUse = value; } } // Starts listening to network requests. public void Start() { Start((int)SocketOptionName.MaxConnections); } public void Start(int backlog) { if (backlog > (int)SocketOptionName.MaxConnections || backlog < 0) { throw new ArgumentOutOfRangeException("backlog"); } if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Start", null); } if (GlobalLog.IsEnabled) { GlobalLog.Print("TCPListener::Start()"); } if (_serverSocket == null) { throw new InvalidOperationException(SR.net_InvalidSocketHandle); } // Already listening. if (_active) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Start", null); } return; } _serverSocket.Bind(_serverSocketEP); try { _serverSocket.Listen(backlog); } catch (SocketException) { // When there is an exception, unwind previous actions (bind, etc). Stop(); throw; } _active = true; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Start", null); } } // Closes the network connection. public void Stop() { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Stop", null); } if (GlobalLog.IsEnabled) { GlobalLog.Print("TCPListener::Stop()"); } if (_serverSocket != null) { _serverSocket.Dispose(); _serverSocket = null; } _active = false; _serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (_exclusiveAddressUse) { _serverSocket.ExclusiveAddressUse = true; } if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Stop", null); } } // Determine if there are pending connection requests. public bool Pending() { if (!_active) { throw new InvalidOperationException(SR.net_stopped); } return _serverSocket.Poll(0, SelectMode.SelectRead); } internal IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginAcceptSocket", null); } if (!_active) { throw new InvalidOperationException(SR.net_stopped); } IAsyncResult result = _serverSocket.BeginAccept(callback, state); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginAcceptSocket", null); } return result; } internal Socket EndAcceptSocket(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndAcceptSocket", null); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult; Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket; if (asyncSocket == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult"); } // This will throw ObjectDisposedException if Stop() has been called. Socket socket = asyncSocket.EndAccept(asyncResult); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndAcceptSocket", socket); } return socket; } internal IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginAcceptTcpClient", null); } if (!_active) { throw new InvalidOperationException(SR.net_stopped); } IAsyncResult result = _serverSocket.BeginAccept(callback, state); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginAcceptTcpClient", null); } return result; } internal TcpClient EndAcceptTcpClient(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndAcceptTcpClient", null); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult; Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket; if (asyncSocket == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult"); } // This will throw ObjectDisposedException if Stop() has been called. Socket socket = asyncSocket.EndAccept(asyncResult); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndAcceptTcpClient", socket); } return new TcpClient(socket); } public Task<Socket> AcceptSocketAsync() { return Task<Socket>.Factory.FromAsync( (callback, state) => ((TcpListener)state).BeginAcceptSocket(callback, state), asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptSocket(asyncResult), state: this); } public Task<TcpClient> AcceptTcpClientAsync() { return Task<TcpClient>.Factory.FromAsync( (callback, state) => ((TcpListener)state).BeginAcceptTcpClient(callback, state), asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptTcpClient(asyncResult), state: this); } } }
// 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 gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAccountLinkServiceClientTest { [Category("Autogenerated")][Test] public void GetAccountLinkRequestObject() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); GetAccountLinkRequest request = new GetAccountLinkRequest { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), }; gagvr::AccountLink expectedResponse = new gagvr::AccountLink { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), Status = gagve::AccountLinkStatusEnum.Types.AccountLinkStatus.Enabled, Type = gagve::LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified, ThirdPartyAppAnalytics = new gagvr::ThirdPartyAppAnalyticsLinkIdentifier(), DataPartner = new gagvr::DataPartnerLinkIdentifier(), GoogleAds = new gagvr::GoogleAdsLinkIdentifier(), AccountLinkId = 2714466098325457917L, }; mockGrpcClient.Setup(x => x.GetAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountLink response = client.GetAccountLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountLinkRequestObjectAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); GetAccountLinkRequest request = new GetAccountLinkRequest { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), }; gagvr::AccountLink expectedResponse = new gagvr::AccountLink { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), Status = gagve::AccountLinkStatusEnum.Types.AccountLinkStatus.Enabled, Type = gagve::LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified, ThirdPartyAppAnalytics = new gagvr::ThirdPartyAppAnalyticsLinkIdentifier(), DataPartner = new gagvr::DataPartnerLinkIdentifier(), GoogleAds = new gagvr::GoogleAdsLinkIdentifier(), AccountLinkId = 2714466098325457917L, }; mockGrpcClient.Setup(x => x.GetAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountLink responseCallSettings = await client.GetAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountLink responseCancellationToken = await client.GetAccountLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountLink() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); GetAccountLinkRequest request = new GetAccountLinkRequest { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), }; gagvr::AccountLink expectedResponse = new gagvr::AccountLink { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), Status = gagve::AccountLinkStatusEnum.Types.AccountLinkStatus.Enabled, Type = gagve::LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified, ThirdPartyAppAnalytics = new gagvr::ThirdPartyAppAnalyticsLinkIdentifier(), DataPartner = new gagvr::DataPartnerLinkIdentifier(), GoogleAds = new gagvr::GoogleAdsLinkIdentifier(), AccountLinkId = 2714466098325457917L, }; mockGrpcClient.Setup(x => x.GetAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountLink response = client.GetAccountLink(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountLinkAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); GetAccountLinkRequest request = new GetAccountLinkRequest { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), }; gagvr::AccountLink expectedResponse = new gagvr::AccountLink { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), Status = gagve::AccountLinkStatusEnum.Types.AccountLinkStatus.Enabled, Type = gagve::LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified, ThirdPartyAppAnalytics = new gagvr::ThirdPartyAppAnalyticsLinkIdentifier(), DataPartner = new gagvr::DataPartnerLinkIdentifier(), GoogleAds = new gagvr::GoogleAdsLinkIdentifier(), AccountLinkId = 2714466098325457917L, }; mockGrpcClient.Setup(x => x.GetAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountLink responseCallSettings = await client.GetAccountLinkAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountLink responseCancellationToken = await client.GetAccountLinkAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountLinkResourceNames() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); GetAccountLinkRequest request = new GetAccountLinkRequest { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), }; gagvr::AccountLink expectedResponse = new gagvr::AccountLink { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), Status = gagve::AccountLinkStatusEnum.Types.AccountLinkStatus.Enabled, Type = gagve::LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified, ThirdPartyAppAnalytics = new gagvr::ThirdPartyAppAnalyticsLinkIdentifier(), DataPartner = new gagvr::DataPartnerLinkIdentifier(), GoogleAds = new gagvr::GoogleAdsLinkIdentifier(), AccountLinkId = 2714466098325457917L, }; mockGrpcClient.Setup(x => x.GetAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountLink response = client.GetAccountLink(request.ResourceNameAsAccountLinkName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountLinkResourceNamesAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); GetAccountLinkRequest request = new GetAccountLinkRequest { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), }; gagvr::AccountLink expectedResponse = new gagvr::AccountLink { ResourceNameAsAccountLinkName = gagvr::AccountLinkName.FromCustomerAccountLink("[CUSTOMER_ID]", "[ACCOUNT_LINK_ID]"), Status = gagve::AccountLinkStatusEnum.Types.AccountLinkStatus.Enabled, Type = gagve::LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified, ThirdPartyAppAnalytics = new gagvr::ThirdPartyAppAnalyticsLinkIdentifier(), DataPartner = new gagvr::DataPartnerLinkIdentifier(), GoogleAds = new gagvr::GoogleAdsLinkIdentifier(), AccountLinkId = 2714466098325457917L, }; mockGrpcClient.Setup(x => x.GetAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountLink responseCallSettings = await client.GetAccountLinkAsync(request.ResourceNameAsAccountLinkName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountLink responseCancellationToken = await client.GetAccountLinkAsync(request.ResourceNameAsAccountLinkName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void CreateAccountLinkRequestObject() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); CreateAccountLinkRequest request = new CreateAccountLinkRequest { CustomerId = "customer_id3b3724cb", AccountLink = new gagvr::AccountLink(), }; CreateAccountLinkResponse expectedResponse = new CreateAccountLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.CreateAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); CreateAccountLinkResponse response = client.CreateAccountLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task CreateAccountLinkRequestObjectAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); CreateAccountLinkRequest request = new CreateAccountLinkRequest { CustomerId = "customer_id3b3724cb", AccountLink = new gagvr::AccountLink(), }; CreateAccountLinkResponse expectedResponse = new CreateAccountLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.CreateAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CreateAccountLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); CreateAccountLinkResponse responseCallSettings = await client.CreateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); CreateAccountLinkResponse responseCancellationToken = await client.CreateAccountLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void CreateAccountLink() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); CreateAccountLinkRequest request = new CreateAccountLinkRequest { CustomerId = "customer_id3b3724cb", AccountLink = new gagvr::AccountLink(), }; CreateAccountLinkResponse expectedResponse = new CreateAccountLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.CreateAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); CreateAccountLinkResponse response = client.CreateAccountLink(request.CustomerId, request.AccountLink); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task CreateAccountLinkAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); CreateAccountLinkRequest request = new CreateAccountLinkRequest { CustomerId = "customer_id3b3724cb", AccountLink = new gagvr::AccountLink(), }; CreateAccountLinkResponse expectedResponse = new CreateAccountLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.CreateAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CreateAccountLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); CreateAccountLinkResponse responseCallSettings = await client.CreateAccountLinkAsync(request.CustomerId, request.AccountLink, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); CreateAccountLinkResponse responseCancellationToken = await client.CreateAccountLinkAsync(request.CustomerId, request.AccountLink, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAccountLinkRequestObject() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); MutateAccountLinkRequest request = new MutateAccountLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountLinkOperation(), PartialFailure = false, ValidateOnly = true, }; MutateAccountLinkResponse expectedResponse = new MutateAccountLinkResponse { Result = new MutateAccountLinkResult(), }; mockGrpcClient.Setup(x => x.MutateAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); MutateAccountLinkResponse response = client.MutateAccountLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAccountLinkRequestObjectAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); MutateAccountLinkRequest request = new MutateAccountLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountLinkOperation(), PartialFailure = false, ValidateOnly = true, }; MutateAccountLinkResponse expectedResponse = new MutateAccountLinkResponse { Result = new MutateAccountLinkResult(), }; mockGrpcClient.Setup(x => x.MutateAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAccountLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); MutateAccountLinkResponse responseCallSettings = await client.MutateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAccountLinkResponse responseCancellationToken = await client.MutateAccountLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAccountLink() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); MutateAccountLinkRequest request = new MutateAccountLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountLinkOperation(), }; MutateAccountLinkResponse expectedResponse = new MutateAccountLinkResponse { Result = new MutateAccountLinkResult(), }; mockGrpcClient.Setup(x => x.MutateAccountLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); MutateAccountLinkResponse response = client.MutateAccountLink(request.CustomerId, request.Operation); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAccountLinkAsync() { moq::Mock<AccountLinkService.AccountLinkServiceClient> mockGrpcClient = new moq::Mock<AccountLinkService.AccountLinkServiceClient>(moq::MockBehavior.Strict); MutateAccountLinkRequest request = new MutateAccountLinkRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountLinkOperation(), }; MutateAccountLinkResponse expectedResponse = new MutateAccountLinkResponse { Result = new MutateAccountLinkResult(), }; mockGrpcClient.Setup(x => x.MutateAccountLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAccountLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountLinkServiceClient client = new AccountLinkServiceClientImpl(mockGrpcClient.Object, null); MutateAccountLinkResponse responseCallSettings = await client.MutateAccountLinkAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAccountLinkResponse responseCancellationToken = await client.MutateAccountLinkAsync(request.CustomerId, request.Operation, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using Citrix.XenCenter; using XenAdmin; using XenAdmin.Core; using XenAdmin.Network; using System.Diagnostics; namespace XenAPI { public partial class Host : IComparable<Host>, IEquatable<Host> { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public enum Edition { Free, PerSocket, //Added in Clearwater (PR-1589) XenDesktop, //Added in Clearwater (PR-1589) and is new form of "EnterpriseXD" EnterprisePerSocket, // Added in Creedence (enterprise-per-socket) EnterprisePerUser, // Added in Creedence (enterprise-per-user) StandardPerSocket, // Added in Creedence (standard-per-socket) Desktop, // Added in Creedence (desktop) DesktopPlus, // Added in Creedence (desktop-plus) Standard, // Added in Dundee/Violet (standard) Premium // Added in Indigo (premium) } public const string LicenseServerWebConsolePort = "8082"; public override string Name() { return name_label; } public static Edition GetEdition(string editionText) { switch (editionText) { case "xendesktop": return Edition.XenDesktop; case "per-socket": return Edition.PerSocket; case "enterprise-per-socket": return Edition.EnterprisePerSocket; case "enterprise-per-user": return Edition.EnterprisePerUser; case "standard-per-socket": return Edition.StandardPerSocket; case "desktop": return Edition.Desktop; case "desktop-plus": return Edition.DesktopPlus; case "basic": return Edition.Free; case "premium": return Edition.Premium; case "standard": return Edition.Standard; default: return Edition.Free; } } public bool CanSeeNetwork(XenAPI.Network network) { System.Diagnostics.Trace.Assert(network != null); // Special case for local networks. if (network.PIFs.Count == 0) return true; foreach (var pifRef in network.PIFs) { PIF pif = network.Connection.Resolve(pifRef); if (pif != null && pif.host != null && pif.host.opaque_ref == opaque_ref) return true; } return false; } public static string GetEditionText(Edition edition) { switch (edition) { case Edition.XenDesktop: return "xendesktop"; case Edition.PerSocket: return "per-socket"; case Edition.EnterprisePerSocket: return "enterprise-per-socket"; case Edition.EnterprisePerUser: return "enterprise-per-user"; case Edition.StandardPerSocket: return "standard-per-socket"; case Edition.Desktop: return "desktop"; case Edition.DesktopPlus: return "desktop-plus"; case Edition.Premium: return "premium"; case Edition.Standard: return "standard"; default: return "free"; } } public string GetIscsiIqn() { return Get(other_config, "iscsi_iqn") ?? ""; } public void SetIscsiIqn(string value) { SetDictionaryKey(other_config, "iscsi_iqn", value); } public override string ToString() { return this.name_label; } public override string Description() { if (name_description == "Default install of XenServer" || name_description == "Default install") // i18n: CA-30372, CA-207273 return Messages.DEFAULT_INSTALL_OF_XENSERVER; else if (name_description == null) return ""; else return name_description; } /// <summary> /// The expiry date of this host's license in UTC. /// </summary> public virtual DateTime LicenseExpiryUTC() { if (license_params != null && license_params.ContainsKey("expiry")) return TimeUtil.ParseISO8601DateTime(license_params["expiry"]); return new DateTime(2030, 1, 1); } public static bool RestrictRBAC(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_rbac"); } public static bool RestrictDMC(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_dmc"); } /// <summary> /// Added for Clearwater /// </summary> /// <param name="h"></param> /// <returns></returns> public static bool RestrictHotfixApply(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_hotfix_apply"); } /// <summary> /// Restrict Automated Updates /// </summary> /// <param name="h">host</param> /// <returns></returns> public static bool RestrictBatchHotfixApply(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_batch_hotfix_apply"); } public static bool RestrictCheckpoint(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_checkpoint"); } public static bool RestrictCifs(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_cifs"); } public static bool RestrictVendorDevice(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_pci_device_for_auto_update"); } public static bool RestrictWLB(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_wlb"); } public static bool RestrictVSwitchController(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_vswitch_controller"); } public static bool RestrictPooling(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_pooling"); } public static bool RestrictVMSnapshotSchedule(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_vmss"); } public static bool RestrictVMAppliances(Host h) { return false; } public static bool RestrictDR(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_dr"); } public static bool RestrictCrossPoolMigrate(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_storage_xen_motion"); } public static bool RestrictChangedBlockTracking(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_cbt"); } public virtual bool IsFreeLicense() { return edition == "free"; } public virtual bool IsFreeLicenseOrExpired() { if (Connection != null && Connection.CacheIsPopulated) return IsFreeLicense() || LicenseExpiryUTC() < DateTime.UtcNow - Connection.ServerTimeOffset; return true; } public static bool RestrictHA(Host h) { return !BoolKey(h.license_params, "enable_xha"); } public static bool RestrictAlerts(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_email_alerting"); } public static bool RestrictStorageChoices(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_netapp"); } public static bool RestrictPerformanceGraphs(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_historical_performance"); } public static bool RestrictCpuMasking(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_cpu_masking"); } public static bool RestrictGpu(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_gpu"); } public static bool RestrictUsbPassthrough(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_usb_passthrough"); } public static bool RestrictVgpu(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_vgpu"); } public static bool RestrictManagementOnVLAN(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_management_on_vlan"); } public static bool RestrictIntegratedGpuPassthrough(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_integrated_gpu_passthrough"); } public static bool RestrictExportResourceData(Host h) { if (Helpers.CreedenceOrGreater(h.Connection)) { return BoolKeyPreferTrue(h.license_params, "restrict_export_resource_data"); } // Pre-Creedence hosts: // allowed on Per-Socket edition for Clearwater hosts var hostEdition = GetEdition(h.edition); if (hostEdition == Edition.PerSocket) { return h.LicenseExpiryUTC() < DateTime.UtcNow - h.Connection.ServerTimeOffset; // restrict if the license has expired } return true; } public static bool RestrictIntraPoolMigrate(Host h) { return BoolKey(h.license_params, "restrict_xen_motion"); } /// <summary> /// Active directory is restricted only if the "restrict_ad" key exists and it is true /// </summary> public static bool RestrictAD(Host h) { return BoolKey(h.license_params, "restrict_ad"); } public static bool RestrictReadCaching(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_read_caching"); } public static bool RestrictHealthCheck(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_health_check"); } /// <summary> /// Vss feature is restricted only if the "restrict_vss" key exists and it is true /// </summary> public static bool RestrictVss(Host h) { return BoolKey(h.license_params, "restrict_vss"); } public static bool RestrictPoolSize(Host h) { return BoolKey(h.license_params, "restrict_pool_size"); } public static bool RestrictPvsCache(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_pvs_proxy"); } /// <summary> /// For Dundee and greater hosts: the feature is restricted only if the "restrict_ssl_legacy_switch" key exists and it is true /// For pre-Dundee hosts: the feature is restricted if the "restrict_ssl_legacy_switch" key is absent or it is true /// </summary> public static bool RestrictSslLegacySwitch(Host h) { return Helpers.DundeeOrGreater(h) ? BoolKey(h.license_params, "restrict_ssl_legacy_switch") : BoolKeyPreferTrue(h.license_params, "restrict_ssl_legacy_switch"); } public static bool RestrictLivePatching(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_live_patching"); } public static bool RestrictIGMPSnooping(Host h) { return BoolKeyPreferTrue(h.license_params, "restrict_igmp_snooping"); } public static bool RestrictVcpuHotplug(Host h) { if (Helpers.ElyOrGreater(h.Connection)) { return BoolKeyPreferTrue(h.license_params, "restrict_set_vcpus_number_live"); } // Pre-Ely hosts: // allowed on Premium edition only var hostEdition = GetEdition(h.edition); if (hostEdition == Edition.Premium) { return h.LicenseExpiryUTC() < DateTime.UtcNow - h.Connection.ServerTimeOffset; // restrict if the license has expired } return true; } /// <summary> /// The feature is restricted if the "restrict_rpu" key exists and it is true /// or if the key is absent and the host is unlicensed /// </summary> public static bool RestrictRpu(Host h) { return h.license_params.ContainsKey("restrict_rpu") ? BoolKey(h.license_params, "restrict_rpu") : h.IsFreeLicenseOrExpired(); // restrict on Free edition or if the license has expired } public bool HasPBDTo(SR sr) { foreach (XenRef<PBD> pbd in PBDs) { PBD thePBD = sr.Connection.Resolve<PBD>(pbd); if (thePBD != null && thePBD.SR.opaque_ref == sr.opaque_ref) { return true; } } return false; } public PBD GetPBDTo(SR sr) { foreach (XenRef<PBD> pbd in PBDs) { PBD thePBD = sr.Connection.Resolve<PBD>(pbd); if (thePBD != null && thePBD.SR.opaque_ref == sr.opaque_ref) { return thePBD; } } return null; } // Constants for other-config from CP-329 public const String MULTIPATH = "multipathing"; public const String MULTIPATH_HANDLE = "multipathhandle"; public const String DMP = "dmp"; public bool MultipathEnabled() { return BoolKey(other_config, MULTIPATH); } public String MultipathHandle() { return Get(other_config, MULTIPATH_HANDLE); } public override int CompareTo(Host other) { // CA-20865 Sort in the following order: // * Masters first // * Then connected slaves // * Then disconnected servers // Within each group, in NaturalCompare order bool thisConnected = (Connection.IsConnected && Helpers.GetMaster(Connection) != null); bool otherConnected = (other.Connection.IsConnected && Helpers.GetMaster(other.Connection) != null); if (thisConnected && !otherConnected) return -1; else if (!thisConnected && otherConnected) return 1; else if (thisConnected) { bool thisIsMaster = IsMaster(); bool otherIsMaster = other.IsMaster(); if (thisIsMaster && !otherIsMaster) return -1; else if (!thisIsMaster && otherIsMaster) return 1; } return base.CompareTo(other); } public virtual bool IsMaster() { Pool pool = Helpers.GetPoolOfOne(Connection); if (pool == null) return false; Host master = Connection.Resolve<Host>(pool.master); return master != null && master.uuid == this.uuid; } /// <summary> /// Return this host's product version triplet (e.g. 5.6.100), or null if it can't be found. /// </summary> public virtual string ProductVersion() { return Get(software_version, "product_version"); } private string MarketingVersion(string field) { string s = Get(software_version, field); return string.IsNullOrEmpty(s) ? ProductVersion() : s; } /// <summary> /// Return this host's marketing version number (e.g. 5.6 Feature Pack 1), /// or ProductVersion (which can still be null) if it can't be found, including pre-Cowley hosts. /// </summary> public string ProductVersionText() { return MarketingVersion("product_version_text"); } /// <summary> /// Return this host's marketing version number in short form (e.g. 5.6 FP1), /// or ProductVersion (which can still be null) if it can't be found, including pre-Cowley hosts. /// </summary> public string ProductVersionTextShort() { return MarketingVersion("product_version_text_short"); } /// <summary> /// Return this host's XCP version triplet (e.g. 1.0.50), or null if it can't be found, /// including all pre-Tampa hosts. /// </summary> public virtual string PlatformVersion() { return Get(software_version, "platform_version"); } /// <summary> /// For legacy build numbers only (used to be integers + one char at the end) /// From Falcon, this property is not used. /// </summary> /// <remarks> /// Return the build number of this host, or -1 if none can be found. This will often be /// 0 or -1 for developer builds, so comparisons should generally treat those numbers as if /// they were brand new. /// </remarks> internal int BuildNumber() { Debug.Assert(!Helpers.ElyOrGreater(this)); string bn = BuildNumberRaw(); if (bn == null) return -1; while (bn.Length > 0 && !char.IsDigit(bn[bn.Length - 1])) { bn = bn.Substring(0, bn.Length - 1); } int result; if (int.TryParse(bn, out result)) return result; else return -1; } /// <summary> /// Return the exact build_number of this host /// </summary> /// <remarks> /// null if not found /// </remarks> public virtual string BuildNumberRaw() { return Get(software_version, "build_number"); } /// <summary> /// Return this host's product version and build number (e.g. 5.6.100.72258), or null if product version can't be found. /// </summary> public virtual string LongProductVersion() { string productVersion = ProductVersion(); return productVersion != null ? string.Format("{0}.{1}", productVersion, Helpers.ElyOrGreater(this) ? BuildNumberRaw() : BuildNumber().ToString()) : null; } /// <summary> /// Return the product_brand of this host, or null if none can be found. /// </summary> public string ProductBrand() { return Get(software_version, "product_brand"); } /// <summary> /// The remote syslog target. May return null if not set on the server. /// </summary> public string GetSysLogDestination() { return logging != null && logging.ContainsKey("syslog_destination") ? logging["syslog_destination"] : null; } /// <summary> /// Set to null to unset /// </summary> public void SetSysLogDestination(string value) { SetDictionaryKey(logging, "syslog_destination", value); } public static bool IsFullyPatched(Host host,IEnumerable<IXenConnection> connections) { List<Pool_patch> patches = Pool_patch.GetAllThatApply(host,connections); List<Pool_patch> appliedPatches = host.AppliedPatches(); if (appliedPatches.Count == patches.Count) return true; foreach (Pool_patch patch in patches) { Pool_patch patch1 = patch; if (!appliedPatches.Exists(otherPatch => string.Equals(patch1.uuid, otherPatch.uuid, StringComparison.OrdinalIgnoreCase))) return false; } return true; } public virtual List<Pool_patch> AppliedPatches() { List<Pool_patch> patches = new List<Pool_patch>(); foreach (Host_patch hostPatch in Connection.ResolveAll(this.patches)) { Pool_patch patch = Connection.Resolve(hostPatch.pool_patch); if (patch != null) patches.Add(patch); } return patches; } public virtual List<Pool_update> AppliedUpdates() { var updates = new List<Pool_update>(); foreach (var hostUpdate in Connection.ResolveAll(this.updates)) { if (hostUpdate != null) updates.Add(hostUpdate); } return updates; } public string XAPI_version() { return Get(software_version, "xapi"); } public bool LinuxPackPresent() { return software_version.ContainsKey("xs:linux"); } public bool HasCrashDumps() { return crashdumps != null && crashdumps.Count > 0; } public bool IsLive() { if (Connection == null) return false; Host_metrics hm = Connection.Resolve(metrics); return hm != null && hm.live; } public const string MAINTENANCE_MODE = "MAINTENANCE_MODE"; public bool MaintenanceMode() { return BoolKey(other_config, MAINTENANCE_MODE); } public const string BOOT_TIME = "boot_time"; public double BootTime() { if (other_config == null) return 0.0; if (!other_config.ContainsKey(BOOT_TIME)) return 0.0; double bootTime; if (!double.TryParse(other_config[BOOT_TIME], NumberStyles.Number, CultureInfo.InvariantCulture, out bootTime)) return 0.0; return bootTime; } public PrettyTimeSpan Uptime() { double bootTime = BootTime(); if (bootTime == 0.0) return null; return new PrettyTimeSpan(DateTime.UtcNow - Util.FromUnixTime(bootTime) - Connection.ServerTimeOffset); } public const string AGENT_START_TIME = "agent_start_time"; public double AgentStartTime() { if (other_config == null) return 0.0; if (!other_config.ContainsKey(AGENT_START_TIME)) return 0.0; double agentStartTime; if (!double.TryParse(other_config[AGENT_START_TIME], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out agentStartTime)) return 0.0; return agentStartTime; } public PrettyTimeSpan AgentUptime() { double startTime = AgentStartTime(); if (startTime == 0.0) return null; return new PrettyTimeSpan(DateTime.UtcNow - Util.FromUnixTime(startTime) - Connection.ServerTimeOffset); } // Get the path counts from the Multipath Boot From SAN feature (see PR-1034 and CP-1696). // Returns true if the Host.other_config contains the multipathed and mpath-boot keys, // and the mpath-boot key is parseable. In this case, current and max will contain the result; // otherwise they will contain zero. public bool GetBootPathCounts(out int current, out int max) { current = max = 0; return (BoolKey(other_config, "multipathed") && other_config.ContainsKey("mpath-boot") && PBD.ParsePathCounts(other_config["mpath-boot"], out current, out max)); } public bool HasRunningVMs() { // 2 not 1, because the Control Domain doesn't count return resident_VMs != null && resident_VMs.Count >= 2; } #region Save Evacuated VMs for later public const String MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED = "MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED"; public const String MAINTENANCE_MODE_EVACUATED_VMS_SUSPENDED = "MAINTENANCE_MODE_EVACUATED_VMS_SUSPENDED"; public const String MAINTENANCE_MODE_EVACUATED_VMS_HALTED = "MAINTENANCE_MODE_EVACUATED_VMS_HALTED"; /// <summary> /// Save the list of VMs on this host, so we can try and put them back when finished. /// This may get run multiple times, after which some vms will have been suspended / shutdown. /// </summary> /// <param name="session">Pass in the session you want to use for the other config writing</param> public void SaveEvacuatedVMs(Session session) { //Program.AssertOffEventThread(); XenRef<Host> opaque_ref = get_by_uuid(session, uuid); List<VM> migratedVMs = GetVMs(MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED); List<VM> suspendedVMs = GetVMs(MAINTENANCE_MODE_EVACUATED_VMS_SUSPENDED); List<VM> haltedVMs = GetVMs(MAINTENANCE_MODE_EVACUATED_VMS_HALTED); List<VM> allVMs = new List<VM>(); allVMs.AddRange(migratedVMs); allVMs.AddRange(suspendedVMs); allVMs.AddRange(haltedVMs); // First time round there will be no saved VMs, // (or less saved VMs than currently resident) // so just save them all as migrated // don't forget the control domain if (allVMs.Count < resident_VMs.Count - 1) { SaveVMList(session, opaque_ref, MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED, Connection.ResolveAll(resident_VMs)); return; } // We've been round once, so just make sure all the vms are in the correct list // and then save the lists again migratedVMs.Clear(); suspendedVMs.Clear(); haltedVMs.Clear(); foreach (VM vm in allVMs) { switch (vm.power_state) { case vm_power_state.Halted: haltedVMs.Add(vm); break; case vm_power_state.Running: migratedVMs.Add(vm); break; case vm_power_state.Suspended: suspendedVMs.Add(vm); break; } } SaveVMList(session, opaque_ref, MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED, migratedVMs); SaveVMList(session, opaque_ref, MAINTENANCE_MODE_EVACUATED_VMS_HALTED, haltedVMs); SaveVMList(session, opaque_ref, MAINTENANCE_MODE_EVACUATED_VMS_SUSPENDED, suspendedVMs); } private static void SaveVMList(Session session, String serverOpaqueRef, String key, List<VM> vms) { //Program.AssertOffEventThread(); List<String> vmUUIDs = new List<String>(); foreach (VM vm in vms) { if (vm.is_control_domain) continue; vmUUIDs.Add(vm.uuid); } Host.remove_from_other_config(session, serverOpaqueRef, key); Host.add_to_other_config(session, serverOpaqueRef, key, String.Join(",", vmUUIDs.ToArray())); } private List<VM> GetVMs(String key) { List<VM> vms = new List<VM>(); if (other_config == null || !other_config.ContainsKey(key)) return vms; String vmUUIDs = other_config[key]; if (String.IsNullOrEmpty(vmUUIDs)) return vms; foreach (String vmUUID in vmUUIDs.Split(new char[] { ',' })) foreach (VM vm in Connection.Cache.VMs) if (vm.uuid == vmUUID) { if (!vms.Contains(vm)) vms.Add(vm); break; } return vms; } public void ClearEvacuatedVMs(Session session) { XenRef<Host> serverOpaqueRef1 = get_by_uuid(session, uuid); remove_from_other_config(session, serverOpaqueRef1, MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED); remove_from_other_config(session, serverOpaqueRef1, MAINTENANCE_MODE_EVACUATED_VMS_HALTED); remove_from_other_config(session, serverOpaqueRef1, MAINTENANCE_MODE_EVACUATED_VMS_SUSPENDED); } public List<VM> GetMigratedEvacuatedVMs() { return GetEvacuatedVMs(MAINTENANCE_MODE_EVACUATED_VMS_MIGRATED, vm_power_state.Running); } public List<VM> GetSuspendedEvacuatedVMs() { return GetEvacuatedVMs(MAINTENANCE_MODE_EVACUATED_VMS_SUSPENDED, vm_power_state.Suspended); } public List<VM> GetHaltedEvacuatedVMs() { return GetEvacuatedVMs(MAINTENANCE_MODE_EVACUATED_VMS_HALTED, vm_power_state.Halted); } private List<VM> GetEvacuatedVMs(String key, vm_power_state expectedPowerState) { List<VM> vms = GetVMs(key); foreach (VM vm in vms.ToArray()) if (vm.power_state != expectedPowerState) vms.Remove(vm); return vms; } #endregion /// <summary> /// Will return null if cannot find connection or any control domain in list of vms /// </summary> public VM ControlDomainZero() { if (Connection == null) return null; if (!Helper.IsNullOrEmptyOpaqueRef(control_domain)) return Connection.Resolve(control_domain); var vms = Connection.ResolveAll(resident_VMs); return vms.FirstOrDefault(vm => vm.is_control_domain && vm.domid == 0); } public bool HasManyControlDomains() { if (Connection == null) return false; var vms = Connection.ResolveAll(resident_VMs); return vms.FindAll(v => v.is_control_domain).Count > 1; } public IEnumerable<VM> OtherControlDomains() { if (Connection == null) return null; var vms = Connection.ResolveAll(resident_VMs); if (!Helper.IsNullOrEmptyOpaqueRef(control_domain)) return vms.Where(v => v.is_control_domain && v.opaque_ref != control_domain); return vms.Where(v => v.is_control_domain && v.domid != 0); } /// <summary> /// Interpret a value from the software_version dictionary as a int, or 0 if we couldn't parse it. /// </summary> private int GetSVAsInt(string key) { string s = Get(software_version, key); if (s == null) return 0; return (int)Helper.GetAPIVersion(s); } /// <summary> /// The xencenter_min as a int, or 0. if we couldn't parse it. /// </summary> public int XenCenterMin() { return GetSVAsInt("xencenter_min"); } /// <summary> /// The xencenter_max as a int, or 0 if we couldn't parse it. /// </summary> public int XenCenterMax() { return GetSVAsInt("xencenter_max"); } public string GetDatabaseSchema() { return Get(software_version, "db_schema"); } /// <summary> /// The amount of memory free on the host. For George and earlier hosts, we use to use /// the obvious Host_metrics.memory_free. Since Midnight Ride, however, we use /// the same calculation as xapi, adding the used memory and the virtualisation overheads /// on each of the VMs. This is a more conservative estimate (i.e., it reports less memory /// free), but it's the one we need to make the memory go down to zero when ballooning /// takes place. /// </summary> public long memory_free_calc() { Host_metrics host_metrics = Connection.Resolve(this.metrics); if (host_metrics == null) return 0; long used = memory_overhead; foreach (VM vm in Connection.ResolveAll(resident_VMs)) { used += vm.memory_overhead; VM_metrics vm_metrics = vm.Connection.Resolve(vm.metrics); if (vm_metrics != null) used += vm_metrics.memory_actual; } // This hack is needed because of bug CA-32509. xapi uses a deliberately generous // estimate of VM.memory_overhead: but the low-level squeezer code doesn't (and can't) // know about the same calculation, and so uses some of this memory_overhead for the // VM's memory_actual. This causes up to 1MB of double-counting per VM. return ((host_metrics.memory_total > used) ? (host_metrics.memory_total - used) : 0); } /// <summary> /// The total of all the dynamic_minimum memories of all resident VMs other than the control domain. /// For non-ballonable VMs, we use the static_maximum instead, because the dynamic_minimum has no effect. /// </summary> public long tot_dyn_min() { long ans = 0; foreach (VM vm in Connection.ResolveAll(resident_VMs)) { if (!vm.is_control_domain) ans += vm.has_ballooning() ? vm.memory_dynamic_min : vm.memory_static_max; } return ans; } /// <summary> /// The total of all the dynamic_maximum memories of all resident VMs other than the control domain. /// For non-ballonable VMs, we use the static_maximum instead, because the dynamic_maximum has no effect. /// </summary> public long tot_dyn_max() { long ans = 0; foreach (VM vm in Connection.ResolveAll(resident_VMs)) { if (!vm.is_control_domain) ans += vm.has_ballooning() ? vm.memory_dynamic_max : vm.memory_static_max; } return ans; } /// <summary> /// The amount of available memory on the host. This is not the same as the amount of free memory, because /// it includes the memory that could be freed by reducing balloonable VMs to their dynamic_minimum memory. /// </summary> public long memory_available_calc() { Host_metrics host_metrics = Connection.Resolve(this.metrics); if (host_metrics == null) return 0; long avail = host_metrics.memory_total - tot_dyn_min() - xen_memory_calc(); if (avail < 0) avail = 0; // I don't think this can happen, but I'm nervous about CA-32509: play it safe return avail; } /// <summary> /// The amount of memory used by Xen, including the control domain plus host and VM overheads. /// Used to calculate this as total - free - tot_vm_mem, but that caused xen_mem to jump around /// during VM startup/shutdown because some changes happen before others. /// </summary> public long xen_memory_calc() { long xen_mem = memory_overhead; foreach (VM vm in Connection.ResolveAll(resident_VMs)) { xen_mem += vm.memory_overhead; if (vm.is_control_domain) { VM_metrics vmMetrics = vm.Connection.Resolve(vm.metrics); if (vmMetrics != null) xen_mem += vmMetrics.memory_actual; } } return xen_mem; } public long dom0_memory() { long dom0_mem = 0; VM vm = ControlDomainZero(); if (vm != null) { VM_metrics vmMetrics = vm.Connection.Resolve(vm.metrics); dom0_mem = vmMetrics != null ? vmMetrics.memory_actual : vm.memory_dynamic_min; } return dom0_mem; } public long dom0_memory_extra() { VM vm = ControlDomainZero(); return vm != null ? vm.memory_static_max - vm.memory_static_min : 0; } /// <summary> /// Friendly string showing memory usage on the host /// </summary> public string HostMemoryString() { Host_metrics m = Connection.Resolve(metrics); if (m == null) return Messages.GENERAL_UNKNOWN; long ServerMBAvail = memory_available_calc(); long ServerMBTotal = m.memory_total; return string.Format(Messages.GENERAL_MEMORY_SERVER_FREE, Util.MemorySizeStringSuitableUnits(ServerMBAvail, true), Util.MemorySizeStringSuitableUnits(ServerMBTotal, true)); } /// <summary> /// A friendly string for the XenMemory on this host /// </summary> public string XenMemoryString() { if (Connection.Resolve(metrics) == null) return Messages.GENERAL_UNKNOWN; return Util.MemorySizeStringSuitableUnits(xen_memory_calc(), true); } /// <summary> /// A friendly string of the resident VM's memory usage, with each entry separated by a line break /// </summary> public string ResidentVMMemoryUsageString() { Host_metrics m = Connection.Resolve(metrics); if (m == null) return Messages.GENERAL_UNKNOWN; else { List<string> lines = new List<string>(); foreach (VM vm in Connection.ResolveAll(resident_VMs)) { if (vm.is_control_domain) continue; VM_metrics VMMetrics = Connection.Resolve(vm.metrics); if (VMMetrics == null) continue; string message = string.Format(Messages.GENERAL_MEMORY_VM_USED, vm.Name(), Util.MemorySizeStringSuitableUnits(VMMetrics.memory_actual, true)); lines.Add(message); } return string.Join("\n", lines.ToArray()); } } /// <summary> /// Wait about two minutes for all the PBDs on this host to become plugged: /// if they do not, try and plug them. (Refs: CA-41219, CA-41305, CA-66496). /// </summary> public void CheckAndPlugPBDs() { bool allPBDsReady = false; int timeout = 120; log.DebugFormat("Waiting for PBDs on host {0} to become plugged", Name()); do { if (this.enabled) // if the Host is not yet enabled, pbd.currently_attached may not be accurate: see CA-66496. { allPBDsReady = true; foreach (PBD pbd in Connection.ResolveAll(PBDs)) { if (!pbd.currently_attached) { allPBDsReady = false; break; } } } if (!allPBDsReady) { Thread.Sleep(1000); timeout--; } } while (!allPBDsReady && timeout > 0); if (allPBDsReady) return; foreach (var pbd in Connection.ResolveAll(PBDs)) { if (pbd.currently_attached) continue; Session session = Connection.DuplicateSession(); // If we still havent plugged, then try and plug it - this will probably // fail, but at least we'll get a better error message. try { log.DebugFormat("Plugging PBD {0} on host {1}", pbd.Name(), Name()); PBD.plug(session, pbd.opaque_ref); } catch (Exception e) { log.Debug(string.Format("Error plugging PBD {0} on host {1}", pbd.Name(), Name()), e); } } } /// <summary> /// Whether the host is running the vSwitch network stack /// </summary> public bool vSwitchNetworkBackend() { return software_version.ContainsKey("network_backend") && software_version["network_backend"] == "openvswitch"; } /// <summary> /// The number of CPU sockets the host has /// Return 0 if a problem is found /// </summary> public virtual int CpuSockets() { const string key = "socket_count"; const int defaultSockets = 0; if (cpu_info == null || !cpu_info.ContainsKey(key)) return defaultSockets; int sockets; bool parsed = int.TryParse(cpu_info[key], out sockets); if (!parsed) return defaultSockets; return sockets; } /// <summary> /// The number of cpus the host has /// Return 0 if a problem is found /// </summary> public int CpuCount() { const string key = "cpu_count"; const int defaultCpuCount = 0; if (cpu_info == null || !cpu_info.ContainsKey(key)) return defaultCpuCount; int cpuCount; bool parsed = int.TryParse(cpu_info[key], out cpuCount); if (!parsed) return defaultCpuCount; return cpuCount; } /// <summary> /// The number of cores per socket the host has /// Return 0 if a problem is found /// </summary> public int CoresPerSocket() { var sockets = CpuSockets(); var cpuCount = CpuCount(); if (sockets > 0 && cpuCount > 0) return (cpuCount/sockets); return 0; } /// <summary> /// Is the host allowed to install hotfixes or are they restricted? /// </summary> public virtual bool CanApplyHotfixes() { return !Helpers.FeatureForbidden(Connection, RestrictHotfixApply); } /// <summary> /// Grace is either upgrade or regular /// </summary> public virtual bool InGrace() { return license_params.ContainsKey("grace"); } internal override string LocationString() { //for standalone hosts we do not show redundant location info return Helpers.GetPool(Connection) == null ? string.Empty : base.LocationString(); } public bool EnterpriseFeaturesEnabled() { var hostEdition = GetEdition(edition); return EligibleForSupport() && (hostEdition == Edition.EnterprisePerSocket || hostEdition == Edition.EnterprisePerUser || hostEdition == Edition.PerSocket); } public bool DesktopPlusFeaturesEnabled() { return GetEdition(edition) == Edition.DesktopPlus; } public bool DesktopFeaturesEnabled() { return GetEdition(edition) == Edition.Desktop; } public bool PremiumFeaturesEnabled() { return GetEdition(edition) == Edition.Premium; } public bool StandardFeaturesEnabled() { return GetEdition(edition) == Edition.Standard; } public bool EligibleForSupport() { return (Helpers.CreedenceOrGreater(this) && GetEdition(edition) != Edition.Free); } #region Supplemental Packs // From http://scale.uk.xensource.com/confluence/display/engp/Supplemental+Pack+product+design+notes#SupplementalPackproductdesignnotes-XenAPI: // The supplemental packs that are installed on a host are listed in the host's Host.software_version field in the data model. // The keys of the entries have the form "<originator>:<name>", the value is "<description>, version <version>", appended by // ", build <build>" if the build number is present in the XML file, and further appended by ", homogeneous" if the // enforce-homogeneity attribute is present and set to true. // // Examples: // xs:main: Base Pack, version 5.5.900, build 19689c // xs:linux: Linux Pack, version 5.5.900, build 19689c, homogeneous public class SuppPack { private string originator, name, description, version, build; private bool homogeneous; public string Originator { get { return originator; } } public string Name { get { return name; } } public string Description { get { return description; } } public string Version { get { return version; } } public string Build { get { return build; } } public bool Homogeneous { get { return homogeneous; } } public string OriginatorAndName { get { return originator + ":" + name; } } private bool parsed = false; public bool IsValid { get { return parsed; } } public string LongDescription { get { return string.Format(Messages.SUPP_PACK_DESCRIPTION, description, version); } } /// <summary> /// Try to parse the supp pack information from one key of software_version /// </summary> public SuppPack(string key, string value) { // Parse the key string[] splitKey = key.Split(':'); if (splitKey.Length != 2) return; originator = splitKey[0]; name = splitKey[1]; // Parse the value. The description may contain arbitrary text, so we have to be a bit subtle: // we first search from the end to find where the description ends. int x = value.LastIndexOf(", version "); if (x <= 0) return; description = value.Substring(0, x); string val = value.Substring(x + 10); string[] delims = new string[] {", "}; string[] splitValue = val.Split(delims, StringSplitOptions.None); if (splitValue.Length == 0 || splitValue.Length > 3) return; version = splitValue[0]; if (splitValue.Length >= 2) { if (!splitValue[1].StartsWith("build ")) return; build = splitValue[1].Substring(6); } if (splitValue.Length >= 3) { if (splitValue[2] != "homogeneous") return; homogeneous = true; } else homogeneous = false; parsed = true; } } /// <summary> /// Return a list of the supplemental packs /// </summary> public List<SuppPack> SuppPacks() { List<SuppPack> packs = new List<SuppPack>(); if (software_version == null) return packs; foreach (string key in software_version.Keys) { SuppPack pack = new SuppPack(key, software_version[key]); if (pack.IsValid) packs.Add(pack); } return packs; } #endregion /// <summary> /// The PGPU that is the system display device or null /// </summary> public PGPU SystemDisplayDevice() { var pGpus = Connection.ResolveAll(PGPUs); return pGpus.FirstOrDefault(pGpu => pGpu.is_system_display_device); } /// <summary> /// Is the host allowed to enable/disable integrated GPU passthrough or is the feature unavailable/restricted? /// </summary> public bool CanEnableDisableIntegratedGpu() { return Helpers.CreamOrGreater(Connection) && Helpers.GpuCapability(Connection) && !Helpers.FeatureForbidden(Connection, RestrictIntegratedGpuPassthrough); } #region IEquatable<Host> Members /// <summary> /// Indicates whether the current object is equal to the specified object. This calls the implementation from XenObject. /// This implementation is required for ToStringWrapper. /// </summary> public bool Equals(Host other) { return base.Equals(other); } #endregion } }
using Android.App; using Android.OS; using Android.Support.V7.App; using Android.Views; using Android.Support.V4.Widget; using Android.Widget; using Com.Krkadoni.App.SignalMeter.Layout; using Com.Krkadoni.App.SignalMeter.Model; using System; using System.Xml; using System.Collections.Generic; using System.IO; using Android.Content; using Com.Krkadoni.App.SignalMeter.Utils; using Com.Krkadoni.Utils; using Xamarin; using Android.Util; using System.Threading.Tasks; namespace Com.Krkadoni.App.SignalMeter.Layout { [Activity(Name = "com.krkadoni.app.signalmeter.layout.MainActivity", Label = "@string/AppName", MainLauncher = true, Icon = "@drawable/icon", LaunchMode = Android.Content.PM.LaunchMode.SingleTask)] public class MainActivity : AppCompatActivity { #region "Private Declarations" private const string selectedViewKey = "selectedView"; private const string TAG = "MainActivity"; GlobalApp app; private Android.Support.V7.Widget.Toolbar mToolbar; private FragmentDrawer drawerFragment; private ProfilesFragment profilesFragment; private BouquetsFragment bouquetsFragment; private ServicesFragment servicesFragment; private SignalFragment signalFragment; private MainEventHandlers.ViewsEnum selectedView = MainEventHandlers.ViewsEnum.Profiles; private bool backButtonPressed; private IMenuItem screenShotMenu; private IMenuItem streamMenu; private IMenuItem restartMenu; private IMenuItem sleepMenu; private IMenuItem aboutMenu; private IMenuItem coinsMenu; private bool IsTabletLandscapeLayout; private StreamManager streamManager; private MainEventHandlers eventHandlers; private void ResetFragmentPositions() { var fragment = SupportFragmentManager.FindFragmentById(Resource.Id.container_body); if (fragment != null) { SupportFragmentManager.BeginTransaction().Remove(fragment).Commit(); } if (fragment != null) { bool matched = false; var tProfiles = fragment as ProfilesFragment; if (tProfiles != null) { profilesFragment = tProfiles; matched = true; } if (!matched) { var tBouquets = fragment as BouquetsFragment; if (tBouquets != null) { bouquetsFragment = tBouquets; matched = true; } } if (!matched) { var tServices = fragment as ServicesFragment; if (tServices != null) { servicesFragment = tServices; matched = true; } } if (!matched) { var tSignal = fragment as SignalFragment; if (tSignal != null) { signalFragment = tSignal; } } } if (profilesFragment == null) { profilesFragment = (ProfilesFragment)SupportFragmentManager.FindFragmentById(Resource.Id.profiles_layout); if (profilesFragment != null) { SupportFragmentManager.BeginTransaction().Remove(profilesFragment).Commit(); } } if (bouquetsFragment == null) { bouquetsFragment = (BouquetsFragment)SupportFragmentManager.FindFragmentById(Resource.Id.bouquets_layout); if (bouquetsFragment != null) { SupportFragmentManager.BeginTransaction().Remove(bouquetsFragment).Commit(); } } if (servicesFragment == null) { servicesFragment = (ServicesFragment)SupportFragmentManager.FindFragmentById(Resource.Id.services_layout); if (servicesFragment != null) { SupportFragmentManager.BeginTransaction().Remove(servicesFragment).Commit(); } } if (signalFragment == null) { signalFragment = (SignalFragment)SupportFragmentManager.FindFragmentById(Resource.Id.signal_layout); if (signalFragment != null) { SupportFragmentManager.BeginTransaction().Remove(signalFragment).Commit(); } } SupportFragmentManager.ExecutePendingTransactions(); if (profilesFragment == null) profilesFragment = new ProfilesFragment(); if (bouquetsFragment == null) bouquetsFragment = new BouquetsFragment(); if (servicesFragment == null) servicesFragment = new ServicesFragment(); if (signalFragment == null) signalFragment = new SignalFragment(); } private bool savedInstanceState; #endregion #region "Activity LifeCycle" protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); InitializeInsights(); //Read application wide values app = ((GlobalApp)this.ApplicationContext); app.Settings = ((PreferenceManager)app.PreferenceManager).LoadSettings(this); savedInstanceState = false; if (bundle != null) { selectedView = (MainEventHandlers.ViewsEnum)bundle.GetInt(selectedViewKey); } var tapjoyPayload = Intent.GetStringExtra(Tapjoy.Tapjoy.IntentExtraPushPayload); if (tapjoyPayload != null) { TapjoyManager.HandlePushPayload(tapjoyPayload); } // Set our view from the "main" layout resource SetContentView(Resource.Layout.main_material); mToolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(mToolbar); SupportActionBar.SetDisplayShowHomeEnabled(true); IsTabletLandscapeLayout = (FindViewById<LinearLayout>(Resource.Id.tablet_layout) != null); ResetFragmentPositions(); if (!IsTabletLandscapeLayout && drawerFragment == null) { drawerFragment = (FragmentDrawer)SupportFragmentManager.FindFragmentById(Resource.Id.fragment_navigation_drawer); drawerFragment.SetUpDrawer(Resource.Id.fragment_navigation_drawer, FindViewById<DrawerLayout>(Resource.Id.drawer_layout), mToolbar); drawerFragment.ListItemClicked += (sender, e) => { if (ConnectionManager.Connected) DisplayView((MainEventHandlers.ViewsEnum)e.Position); }; } ReadSatellitesXml(); } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.menu_main, menu); streamMenu = menu.FindItem(Resource.Id.action_stream); screenShotMenu = menu.FindItem(Resource.Id.action_screenshot); sleepMenu = menu.FindItem(Resource.Id.action_sleep); restartMenu = menu.FindItem(Resource.Id.action_restart); aboutMenu = menu.FindItem(Resource.Id.action_about); coinsMenu = menu.FindItem(Resource.Id.action_coins); SetMenuVisibility(); return true; } protected override void OnResume() { base.OnResume(); app.ActivityResumed = true; } protected override void OnStart() { base.OnStart(); app.ActivityStarted = true; if (eventHandlers == null) { eventHandlers = new MainEventHandlers(this); eventHandlers.DisplayView = this.DisplayView; eventHandlers.SetMenuVisibility = () => this.SetMenuVisibility(); profilesFragment.ListItemClicked += eventHandlers.ProfileSelectedHandler; bouquetsFragment.ListItemClicked += eventHandlers.BouquetSelectedHandler; servicesFragment.ListItemClicked += eventHandlers.ServiceSelectedHandler; servicesFragment.ListItemLongClicked += eventHandlers.ServiceLongClickedHandler; ConnectionManager.GetInstance().PropertyChanged -= eventHandlers.ConnectionManager_PropertyChanged; ConnectionManager.GetInstance().PropertyChanged += eventHandlers.ConnectionManager_PropertyChanged; ConnectionManager.GetInstance().ExceptionRaised -= eventHandlers.ConnectionManager_ExceptionRaised; ConnectionManager.GetInstance().ExceptionRaised += eventHandlers.ConnectionManager_ExceptionRaised; } if (streamManager == null) streamManager = new StreamManager(this); Tapjoy.Tapjoy.OnActivityStart(this); if (!ConnectionManager.Connected) DisplayView(MainEventHandlers.ViewsEnum.Profiles); else DisplayView(selectedView); if (ConnectionManager.Connected) ConnectionManager.CurrentServiceMonitor.Start(); if (ConnectionManager.ConnectionStatus == ConnectionManager.ConnectionStatusEnum.Connecting) eventHandlers.ShowProgressDialog(); } protected override void OnStop() { app.ActivityStopped = true; ConnectionManager.CurrentServiceMonitor.Stop(); Tapjoy.Tapjoy.OnActivityStop(this); base.OnStop(); } protected override void OnSaveInstanceState(Bundle outState) { savedInstanceState = true; base.OnSaveInstanceState(outState); outState.PutInt(selectedViewKey, (int)selectedView); } protected override void OnDestroy() { if (eventHandlers != null) { eventHandlers.HideProgressDialog(); } if (backButtonPressed) { backButtonPressed = false; ConnectionManager.Disconnect(); ConnectionManager.SelectedProfile = null; Finish(); Process.KillProcess(Process.MyPid()); } base.OnDestroy(); } public override void OnBackPressed() { if (selectedView == MainEventHandlers.ViewsEnum.Profiles || IsTabletLandscapeLayout) { backButtonPressed = true; base.OnBackPressed(); } else { DisplayView(MainEventHandlers.ViewsEnum.Profiles); } } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); var payload = intent.GetStringExtra(Tapjoy.Tapjoy.IntentExtraPushPayload); if (payload != null) { TapjoyManager.HandlePushPayload(payload); } } #endregion #region "Event Handlers" public override bool OnOptionsItemSelected(IMenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.ItemId; if (id == Resource.Id.action_stream) { streamManager.InitStream(ConnectionManager.CurrentService); return true; } else if (id == Resource.Id.action_screenshot) { ; InitScreenShot(); return true; } else if (id == Resource.Id.action_sleep) { SleepProfile(); return true; } else if (id == Resource.Id.action_restart) { RestartGui(); return true; } else if (id == Resource.Id.action_coins) { if (TapjoyManager.StreamPlacementAvailable) TapjoyManager.ShowStreamPlacement(); } else if (id == Resource.Id.action_about) { ShowAbout(); return true; } return base.OnOptionsItemSelected(item); } private void SetMenuVisibility(bool forceHide = false) { if (!app.ActivityStarted) return; if (ConnectionManager.GetInstance() == null) return; if (TapjoyManager.GetInstance() == null) return; if (screenShotMenu != null) screenShotMenu.SetVisible(ConnectionManager.Connected && !forceHide); if (streamMenu != null && screenShotMenu != null) streamMenu.SetVisible(screenShotMenu.IsVisible && ConnectionManager.CurrentProfile != null && ConnectionManager.CurrentProfile.Streaming && !TapjoyManager.ConnectFailed); if (screenShotMenu != null && sleepMenu != null) sleepMenu.SetVisible(screenShotMenu.IsVisible); if (screenShotMenu != null && restartMenu != null) restartMenu.SetVisible(screenShotMenu.IsVisible); if (coinsMenu != null) coinsMenu.SetVisible(TapjoyManager.StreamPlacementAvailable); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); SetMenuVisibility(); } #endregion #region "Private Methods" private async void InitializeInsights() { if (System.Diagnostics.Debugger.IsAttached) return; await Task.Delay(TimeSpan.FromSeconds(2)); try { var key = FileSystem.ReadStringAsset(this, GetString(Resource.String.insights_key)); if (!string.IsNullOrEmpty(key)) Insights.Initialize(key, this.ApplicationContext); } catch (Exception ex) { Log.Error(TAG, string.Format("Failed to initialize Xamarin Insights! {0}", ex.Message)); } } private async void SleepProfile() { if (!ConnectionManager.Connected || ConnectionManager.CurrentProfile == null) return; await ConnectionManager.SendToSleepAndDisconnectCurrentProfile(); DisplayView(MainEventHandlers.ViewsEnum.Profiles); Toast.MakeText(this, GetString(Resource.String.inf_disconnected), ToastLength.Short).Show(); } private async void InitScreenShot() { var screenShotActivity = new Intent(this, typeof(ScreenShotActivity)); StartActivity(screenShotActivity); } private void RestartGui() { if (!ConnectionManager.Connected || ConnectionManager.CurrentProfile == null) return; var message = string.Format(GetString(Resource.String.question_restart_gui), ConnectionManager.CurrentProfile.Name); Action<object, DialogClickEventArgs> positiveAction = (sender, e) => { ConnectionManager.RestartAndDisconnectCurrentProfile(); SetMenuVisibility(true); DisplayView(MainEventHandlers.ViewsEnum.Profiles); Toast.MakeText(this, GetString(Resource.String.inf_disconnected), ToastLength.Short).Show(); }; Dialogs.QuestionDialog(this, message, positiveAction, (sender, e) => { }).Show(); } private void ReadSatellitesXml() { string xml = string.Empty; Dictionary<int, string> satellites = new Dictionary<int, string>(); ConnectionManager.Satellites = satellites; xml = FileSystem.ReadStringAsset(this, GetString(Resource.String.satellites_xml_path)); if (!string.IsNullOrEmpty(xml)) { using (var reader = XmlReader.Create(new StringReader(xml))) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "sat" && reader.AttributeCount >= 2) { var satName = reader.GetAttribute("name"); var satPosition = reader.GetAttribute("position"); var positionInt = 0; if (int.TryParse(satPosition, out positionInt)) { if (!satellites.ContainsKey(positionInt)) satellites.Add(positionInt, satName); } } break; } } } } } private void ShowAbout() { var aboutActivity = new Intent(this, typeof(AboutActivity)); StartActivity(aboutActivity); } #endregion public void DisplayView(MainEventHandlers.ViewsEnum position) { string title = GetString(Resource.String.AppName); Android.Support.V4.App.Fragment fragment; if (!app.ActivityStarted) { selectedView = position; return; } if (savedInstanceState) { return; } if (!IsTabletLandscapeLayout) { switch (position) { case MainEventHandlers.ViewsEnum.Profiles: fragment = profilesFragment; title = GetString(Resource.String.ProfileTitle); break; case MainEventHandlers.ViewsEnum.Bouquets: fragment = bouquetsFragment; title = GetString(Resource.String.BouquetsTitle); break; case MainEventHandlers.ViewsEnum.Services: fragment = servicesFragment; title = GetString(Resource.String.ServicesTitle); break; case MainEventHandlers.ViewsEnum.Signal: fragment = signalFragment; title = GetString(Resource.String.SignalTitle); break; default: fragment = profilesFragment; title = GetString(Resource.String.ProfileTitle); break; } selectedView = position; if (savedInstanceState) return; SupportFragmentManager.BeginTransaction().Replace(Resource.Id.container_body, fragment).CommitAllowingStateLoss(); SupportFragmentManager.ExecutePendingTransactions(); drawerFragment.Adapter.ClearSelections(); drawerFragment.Adapter.ToggleSelection((int)position); SupportActionBar.Title = title; } else { if (savedInstanceState) return; SupportFragmentManager.BeginTransaction().Replace(Resource.Id.profiles_layout, profilesFragment).CommitAllowingStateLoss(); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.bouquets_layout, bouquetsFragment).CommitAllowingStateLoss(); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.services_layout, servicesFragment).CommitAllowingStateLoss(); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.signal_layout, signalFragment).CommitAllowingStateLoss(); SupportFragmentManager.ExecutePendingTransactions(); SupportActionBar.Title = title; } } } }
// 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="KeywordPlanAdGroupKeywordServiceClient"/> instances.</summary> public sealed partial class KeywordPlanAdGroupKeywordServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="KeywordPlanAdGroupKeywordServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="KeywordPlanAdGroupKeywordServiceSettings"/>.</returns> public static KeywordPlanAdGroupKeywordServiceSettings GetDefault() => new KeywordPlanAdGroupKeywordServiceSettings(); /// <summary> /// Constructs a new <see cref="KeywordPlanAdGroupKeywordServiceSettings"/> object with default settings. /// </summary> public KeywordPlanAdGroupKeywordServiceSettings() { } private KeywordPlanAdGroupKeywordServiceSettings(KeywordPlanAdGroupKeywordServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetKeywordPlanAdGroupKeywordSettings = existing.GetKeywordPlanAdGroupKeywordSettings; MutateKeywordPlanAdGroupKeywordsSettings = existing.MutateKeywordPlanAdGroupKeywordsSettings; OnCopy(existing); } partial void OnCopy(KeywordPlanAdGroupKeywordServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanAdGroupKeywordServiceClient.GetKeywordPlanAdGroupKeyword</c> and /// <c>KeywordPlanAdGroupKeywordServiceClient.GetKeywordPlanAdGroupKeywordAsync</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 GetKeywordPlanAdGroupKeywordSettings { 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>KeywordPlanAdGroupKeywordServiceClient.MutateKeywordPlanAdGroupKeywords</c> and /// <c>KeywordPlanAdGroupKeywordServiceClient.MutateKeywordPlanAdGroupKeywordsAsync</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 MutateKeywordPlanAdGroupKeywordsSettings { 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="KeywordPlanAdGroupKeywordServiceSettings"/> object.</returns> public KeywordPlanAdGroupKeywordServiceSettings Clone() => new KeywordPlanAdGroupKeywordServiceSettings(this); } /// <summary> /// Builder class for <see cref="KeywordPlanAdGroupKeywordServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class KeywordPlanAdGroupKeywordServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanAdGroupKeywordServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public KeywordPlanAdGroupKeywordServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public KeywordPlanAdGroupKeywordServiceClientBuilder() { UseJwtAccessWithScopes = KeywordPlanAdGroupKeywordServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref KeywordPlanAdGroupKeywordServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanAdGroupKeywordServiceClient> task); /// <summary>Builds the resulting client.</summary> public override KeywordPlanAdGroupKeywordServiceClient Build() { KeywordPlanAdGroupKeywordServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<KeywordPlanAdGroupKeywordServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<KeywordPlanAdGroupKeywordServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private KeywordPlanAdGroupKeywordServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return KeywordPlanAdGroupKeywordServiceClient.Create(callInvoker, Settings); } private async stt::Task<KeywordPlanAdGroupKeywordServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return KeywordPlanAdGroupKeywordServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => KeywordPlanAdGroupKeywordServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanAdGroupKeywordServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanAdGroupKeywordServiceClient.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>KeywordPlanAdGroupKeywordService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad group keywords. KeywordPlanAdGroup is /// required to add ad group keywords. Positive and negative keywords are /// supported. A maximum of 10,000 positive keywords are allowed per keyword /// plan. A maximum of 1,000 negative keywords are allower per keyword plan. This /// includes campaign negative keywords and ad group negative keywords. /// </remarks> public abstract partial class KeywordPlanAdGroupKeywordServiceClient { /// <summary> /// The default endpoint for the KeywordPlanAdGroupKeywordService 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 KeywordPlanAdGroupKeywordService scopes.</summary> /// <remarks> /// The default KeywordPlanAdGroupKeywordService 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="KeywordPlanAdGroupKeywordServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupKeywordServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="KeywordPlanAdGroupKeywordServiceClient"/>.</returns> public static stt::Task<KeywordPlanAdGroupKeywordServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new KeywordPlanAdGroupKeywordServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="KeywordPlanAdGroupKeywordServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanAdGroupKeywordServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="KeywordPlanAdGroupKeywordServiceClient"/>.</returns> public static KeywordPlanAdGroupKeywordServiceClient Create() => new KeywordPlanAdGroupKeywordServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="KeywordPlanAdGroupKeywordServiceClient"/> 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="KeywordPlanAdGroupKeywordServiceSettings"/>.</param> /// <returns>The created <see cref="KeywordPlanAdGroupKeywordServiceClient"/>.</returns> internal static KeywordPlanAdGroupKeywordServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanAdGroupKeywordServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient grpcClient = new KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient(callInvoker); return new KeywordPlanAdGroupKeywordServiceClientImpl(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 KeywordPlanAdGroupKeywordService client</summary> public virtual KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(GetKeywordPlanAdGroupKeywordRequest request, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupKeywordAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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 keyword to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeyword(new GetKeywordPlanAdGroupKeywordRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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 keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeywordAsync(new GetKeywordPlanAdGroupKeywordRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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 keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(string resourceName, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupKeywordAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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 keyword to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(gagvr::KeywordPlanAdGroupKeywordName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeyword(new GetKeywordPlanAdGroupKeywordRequest { ResourceNameAsKeywordPlanAdGroupKeywordName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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 keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(gagvr::KeywordPlanAdGroupKeywordName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordPlanAdGroupKeywordAsync(new GetKeywordPlanAdGroupKeywordRequest { ResourceNameAsKeywordPlanAdGroupKeywordName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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 keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(gagvr::KeywordPlanAdGroupKeywordName resourceName, st::CancellationToken cancellationToken) => GetKeywordPlanAdGroupKeywordAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupKeywordsResponse MutateKeywordPlanAdGroupKeywords(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(MutateKeywordPlanAdGroupKeywordsRequest request, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupKeywordsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad group keywords are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad group /// keywords. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateKeywordPlanAdGroupKeywordsResponse MutateKeywordPlanAdGroupKeywords(string customerId, scg::IEnumerable<KeywordPlanAdGroupKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroupKeywords(new MutateKeywordPlanAdGroupKeywordsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad group keywords are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad group /// keywords. /// </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<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateKeywordPlanAdGroupKeywordsAsync(new MutateKeywordPlanAdGroupKeywordsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose Keyword Plan ad group keywords are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual Keyword Plan ad group /// keywords. /// </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<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanAdGroupKeywordOperation> operations, st::CancellationToken cancellationToken) => MutateKeywordPlanAdGroupKeywordsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>KeywordPlanAdGroupKeywordService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage Keyword Plan ad group keywords. KeywordPlanAdGroup is /// required to add ad group keywords. Positive and negative keywords are /// supported. A maximum of 10,000 positive keywords are allowed per keyword /// plan. A maximum of 1,000 negative keywords are allower per keyword plan. This /// includes campaign negative keywords and ad group negative keywords. /// </remarks> public sealed partial class KeywordPlanAdGroupKeywordServiceClientImpl : KeywordPlanAdGroupKeywordServiceClient { private readonly gaxgrpc::ApiCall<GetKeywordPlanAdGroupKeywordRequest, gagvr::KeywordPlanAdGroupKeyword> _callGetKeywordPlanAdGroupKeyword; private readonly gaxgrpc::ApiCall<MutateKeywordPlanAdGroupKeywordsRequest, MutateKeywordPlanAdGroupKeywordsResponse> _callMutateKeywordPlanAdGroupKeywords; /// <summary> /// Constructs a client wrapper for the KeywordPlanAdGroupKeywordService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="KeywordPlanAdGroupKeywordServiceSettings"/> used within this client. /// </param> public KeywordPlanAdGroupKeywordServiceClientImpl(KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient grpcClient, KeywordPlanAdGroupKeywordServiceSettings settings) { GrpcClient = grpcClient; KeywordPlanAdGroupKeywordServiceSettings effectiveSettings = settings ?? KeywordPlanAdGroupKeywordServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetKeywordPlanAdGroupKeyword = clientHelper.BuildApiCall<GetKeywordPlanAdGroupKeywordRequest, gagvr::KeywordPlanAdGroupKeyword>(grpcClient.GetKeywordPlanAdGroupKeywordAsync, grpcClient.GetKeywordPlanAdGroupKeyword, effectiveSettings.GetKeywordPlanAdGroupKeywordSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetKeywordPlanAdGroupKeyword); Modify_GetKeywordPlanAdGroupKeywordApiCall(ref _callGetKeywordPlanAdGroupKeyword); _callMutateKeywordPlanAdGroupKeywords = clientHelper.BuildApiCall<MutateKeywordPlanAdGroupKeywordsRequest, MutateKeywordPlanAdGroupKeywordsResponse>(grpcClient.MutateKeywordPlanAdGroupKeywordsAsync, grpcClient.MutateKeywordPlanAdGroupKeywords, effectiveSettings.MutateKeywordPlanAdGroupKeywordsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateKeywordPlanAdGroupKeywords); Modify_MutateKeywordPlanAdGroupKeywordsApiCall(ref _callMutateKeywordPlanAdGroupKeywords); 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_GetKeywordPlanAdGroupKeywordApiCall(ref gaxgrpc::ApiCall<GetKeywordPlanAdGroupKeywordRequest, gagvr::KeywordPlanAdGroupKeyword> call); partial void Modify_MutateKeywordPlanAdGroupKeywordsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanAdGroupKeywordsRequest, MutateKeywordPlanAdGroupKeywordsResponse> call); partial void OnConstruction(KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient grpcClient, KeywordPlanAdGroupKeywordServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC KeywordPlanAdGroupKeywordService client</summary> public override KeywordPlanAdGroupKeywordService.KeywordPlanAdGroupKeywordServiceClient GrpcClient { get; } partial void Modify_GetKeywordPlanAdGroupKeywordRequest(ref GetKeywordPlanAdGroupKeywordRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateKeywordPlanAdGroupKeywordsRequest(ref MutateKeywordPlanAdGroupKeywordsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested Keyword Plan ad group keyword 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::KeywordPlanAdGroupKeyword GetKeywordPlanAdGroupKeyword(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordPlanAdGroupKeywordRequest(ref request, ref callSettings); return _callGetKeywordPlanAdGroupKeyword.Sync(request, callSettings); } /// <summary> /// Returns the requested Keyword Plan ad group keyword 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::KeywordPlanAdGroupKeyword> GetKeywordPlanAdGroupKeywordAsync(GetKeywordPlanAdGroupKeywordRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordPlanAdGroupKeywordRequest(ref request, ref callSettings); return _callGetKeywordPlanAdGroupKeyword.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateKeywordPlanAdGroupKeywordsResponse MutateKeywordPlanAdGroupKeywords(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupKeywordsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroupKeywords.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes Keyword Plan ad group keywords. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanAdGroupKeywordError]() /// [KeywordPlanError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateKeywordPlanAdGroupKeywordsResponse> MutateKeywordPlanAdGroupKeywordsAsync(MutateKeywordPlanAdGroupKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateKeywordPlanAdGroupKeywordsRequest(ref request, ref callSettings); return _callMutateKeywordPlanAdGroupKeywords.Async(request, callSettings); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using TestSupport; namespace TestSupport.Collections { public class ICollection_Test : IEnumerable_Test { private ICollection _collection; private bool _expectedIsSynchronized; private CreateNewICollection _createNewCollection; private Type[] _validArrayTypes; private Type[] _invalidArrayTypes; private bool _copyToOnlySupportsZeroLowerBounds; private ICollection_Test() : base(null, null) { } /// <summary> /// Initializes a new instance of the ICollection_Test. /// </summary> /// <param name="collection">The collection to run the tests on.</param> /// <param name="items">The items currently in the collection.</param> /// <param name="expectedIsSynchronized">The expected value of IsSynchronized</param> public ICollection_Test(ICollection collection, Object[] items, bool expectedIsSynchronized) : this(collection, items, expectedIsSynchronized, null) { } /// <summary> /// Initializes a new instance of the ICollection_Test. /// </summary> /// <param name="collection">The collection to run the tests on.</param> /// <param name="items">The items currently in the collection.</param> /// <param name="expectedIsSynchronized">The expected value of IsSynchronized</param> /// <param name="createNewCollection">Creates a new Collection. This is used to verify /// that SyncRoot returns different values from different collections.</param> public ICollection_Test(ICollection collection, Object[] items, bool expectedIsSynchronized, CreateNewICollection createNewCollection) : base(collection, items) { _collection = collection; _expectedIsSynchronized = expectedIsSynchronized; _createNewCollection = createNewCollection; _validArrayTypes = new Type[] { typeof(Object) }; _invalidArrayTypes = new Type[] { typeof(MyInvalidReferenceType), typeof(MyInvalidValueType) }; _copyToOnlySupportsZeroLowerBounds = false; } /// <summary> /// Runs all of the ICollection tests. /// </summary> /// <returns>true if all of the tests passed else false</returns> new public bool RunAllTests() { bool retValue = true; retValue &= Count_Tests(); retValue &= IsSynchronized_Tests(); retValue &= SyncRoot_Tests(); retValue &= CopyTo_Tests(); retValue &= base.RunAllTests(); return retValue; } /// <summary> /// The collection to run the tests on. /// </summary> /// <value>The collection to run the tests on.</value> new public ICollection Collection { get { return _collection; } set { if (null == value) { throw new ArgumentNullException("value"); } _collection = value; } } /// <summary> /// Creates a new Collection. This is used to verify /// that SyncRoot returns different values from different collections. /// If this is null the test that use this will not be run. /// </summary> /// <value>Creates a new Collection.</value> public CreateNewICollection CreateNewCollection { get { return _createNewCollection; } set { _createNewCollection = value; } } /// <summary> /// Specifies the types that are valid with CopyTo(Array). /// By default this is a Type array containing only typeof(Object). /// </summary> /// <value>Specifies the types that are valid with CopyTo(Array)</value> public Type[] ValidArrayTypes { get { return _validArrayTypes; } set { if (value == null) _validArrayTypes = new Type[0]; _validArrayTypes = value; } } /// <summary> /// Specifies the types that are not valid with CopyTo(Array). /// By default this is a Type array containing only /// typeof(MyInvalidReferenceType) and typeof(MyInvalidValueType). /// </summary> /// <value>Specifies the types that are invalid with CopyTo(Array)</value> public Type[] InvalidArrayTypes { get { return _invalidArrayTypes; } set { if (value == null) _invalidArrayTypes = new Type[0]; _invalidArrayTypes = value; } } /// <summary> /// Specifies if CopyTo(Array) only supports Arrays with a zero lower bound. /// </summary> /// <value></value> public bool CopyToOnlySupportsZeroLowerBounds { get { return _copyToOnlySupportsZeroLowerBounds; } set { _copyToOnlySupportsZeroLowerBounds = value; } } /// <summary> /// Runs all of the tests on Count. /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool Count_Tests() { bool retValue = true; String testDescription = "No description of test available"; try { //[] Verify Count returns the expected value testDescription = "Verify Count returns the expected value"; retValue &= Test.Eval(_items.Length, _collection.Count, "Error Count"); } catch (Exception e) { retValue &= Test.Eval(false, "The following Count test: \n{0} threw the following exception: \n {1}\n", testDescription, e); } return retValue; } /// <summary> /// Runs all of the tests on IsSynchronized. /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool IsSynchronized_Tests() { bool retValue = true; String testDescription = "No description of test available"; try { //[] Verify IsSynchronized returns the expected value testDescription = "3458ahoh Verify IsSynchronized returns the expected value"; retValue &= Test.Eval(_expectedIsSynchronized, _collection.IsSynchronized, "Err IsSynchronized"); } catch (Exception e) { retValue &= Test.Eval(false, "The following IsSynchronized test: \n{0} threw the following exception: \n {1}\n", testDescription, e); } return retValue; } /// <summary> /// Runs all of the tests on MoveNext(). /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool SyncRoot_Tests() { bool retValue = true; String testDescription = "No description of test available"; try { //[] Verify SyncRoot is not null testDescription = "Verify SyncRoot is not null"; retValue &= Test.Eval(null != _collection.SyncRoot, "Err SyncRoot is null"); //[] Verify SyncRoot returns consistent results testDescription = "Verify SyncRoot returns consistent results"; Object syncRoot1 = _collection.SyncRoot; Object syncRoot2 = _collection.SyncRoot; retValue &= Test.Eval(null != syncRoot1, "Err SyncRoot is null"); retValue &= Test.Eval(syncRoot1 == syncRoot2, "Err SyncRoot is did not return the same result"); //[] Verify SyncRoot can be used in a lock statement testDescription = "Verify SyncRoot can be used in a lock statement"; lock (_collection.SyncRoot) { } //[] Verify that calling SyncRoot on different collections returns different values testDescription = "Verify that calling SyncRoot on different collections returns different values"; if (null != _createNewCollection) { for (int i = 0; i < 3; i++) { ICollection c = _createNewCollection(); if (!(retValue &= Test.Eval(null != c, "CreateNewCollection returned null"))) { retValue &= Test.Eval(_collection.SyncRoot.Equals(c.SyncRoot), "SyncRoot returned on this collection and on another collection returned the same value iteration={0}", i); } } } } catch (Exception e) { retValue &= Test.Eval(false, "The following SyncRoot test: \n{0} threw the following exception: \n {1}\n", testDescription, e); } return retValue; } /// <summary> /// Runs all of the tests on CopyTo(Array). /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool CopyTo_Tests() { bool retValue = true; retValue &= CopyTo_Argument_Tests(); retValue &= CopyTo_Valid_Tests(); return retValue; } /// <summary> /// Runs all of the invalid(argument checking) tests on CopyTo(Array). /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool CopyTo_Argument_Tests() { bool retValue = true; String testDescription = "No description of test available"; Object[] itemObjectArray = null, tempItemObjectArray = null; Array itemArray = null, tempItemArray = null; try { //[] Verify CopyTo with null array testDescription = "Verify CopyTo with null array"; retValue &= Test.Eval(Test.VerifyException<ArgumentNullException>(delegate () { _collection.CopyTo(null, 0); }), "ErrExpected ArgumentNullException with null array"); // [] Verify CopyTo with index=Int32.MinValue testDescription = "Verify CopyTo with index=Int32.MinValue"; itemObjectArray = GenerateArray(_collection.Count); tempItemObjectArray = (Object[])itemObjectArray.Clone(); retValue &= Test.Eval(Test.VerifyException<ArgumentOutOfRangeException>(delegate () { _collection.CopyTo(itemObjectArray, Int32.MinValue); }), "ErrException not thrown with index=Int32.MinValue"); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray, VerificationLevel.Extensive), "Err_" + testDescription + " verifying item array FAILED"); // [] Verify CopyTo with index=-1 testDescription = "Verify CopyTo with index=-1"; itemObjectArray = GenerateArray(_collection.Count); tempItemObjectArray = (Object[])itemObjectArray.Clone(); retValue &= Test.Eval(Test.VerifyException<ArgumentOutOfRangeException>(delegate () { _collection.CopyTo(itemObjectArray, -1); }), "ErrException not thrown with index=-1"); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray, VerificationLevel.Extensive), "Err_" + testDescription + " verifying item array FAILED"); // [] Verify CopyTo with index=Int32.MaxValue testDescription = "3987ahso Verify CopyTo with index=Int32.MaxValue"; itemObjectArray = GenerateArray(_collection.Count); tempItemObjectArray = (Object[])itemObjectArray.Clone(); retValue &= Test.Eval(Test.VerifyException<ArgumentException>(delegate () { _collection.CopyTo(itemObjectArray, Int32.MaxValue); }), "ErrException not thrown with index=Int32.MaxValue"); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray, VerificationLevel.Extensive), "Err_" + testDescription + " verifying item array FAILED"); if (0 < _collection.Count) { // [] Verify CopyTo with index=array.length testDescription = "Verify CopyTo with index=array.Length"; itemObjectArray = GenerateArray(_collection.Count); tempItemObjectArray = (Object[])itemObjectArray.Clone(); retValue &= Test.Eval(Test.VerifyException<ArgumentException>(delegate () { _collection.CopyTo(itemObjectArray, _collection.Count); }), "Err Exception not throw with index=array.Length"); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray, VerificationLevel.Extensive), "Err_" + testDescription + " verifying item array FAILED"); } if (1 < _collection.Count) { // [] Verify CopyTo with collection.Count > array.length - index testDescription = "Verify CopyTo with collection.Count > array.length - index"; itemObjectArray = GenerateArray(_collection.Count + 1); tempItemObjectArray = (Object[])itemObjectArray.Clone(); retValue &= Test.Eval(Test.VerifyException<ArgumentException>(delegate () { _collection.CopyTo(itemObjectArray, 2); }), "Err Exception not thrown with collection.Count > array.length - index"); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray, VerificationLevel.Extensive), "Err_" + testDescription + " verifying item array FAILED"); } // [] Verify CopyTo with array is multidimensional testDescription = "Verify CopyTo with array is multidimensional"; retValue &= Test.Eval(Test.VerifyException<ArgumentException>(delegate () { _collection.CopyTo(new Object[1, _collection.Count], 0); }), "Err Exception not thrown with multidimensional array"); if (0 != _items.Length) { //[] Verify CopyTo with invalid types testDescription = "5688apied Verify CopyTo with invalid types"; Type invalidCastExceptionType = _isGenericCompatibility ? null : typeof(InvalidCastException); for (int i = 0; i < _invalidArrayTypes.Length; ++i) { itemArray = Array.CreateInstance(_invalidArrayTypes[i], _collection.Count); tempItemArray = (Array)itemArray.Clone(); retValue &= Test.Eval(Test.VerifyException(typeof(ArgumentException), invalidCastExceptionType, delegate () { _collection.CopyTo(itemArray, 0); }), "Err Exception not thrown invalid array type {0} iteration:{1}", _invalidArrayTypes[i], i); retValue &= Test.Eval(VerifyItems(itemArray, tempItemArray, VerificationLevel.Extensive), "Err_" + testDescription + " verifying item array FAILED"); } } } catch (Exception e) { retValue &= Test.Eval(false, "The following CopyTo test: \n{0} threw the following exception: \n {1}\n", testDescription, e); } return retValue; } /// <summary> /// Runs all of the valid test on CopyTo(Array). /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool CopyTo_Valid_Tests() { bool retValue = true; String testDescription = "No description of test available"; Object[] itemObjectArray = null, tempItemObjectArray = null; try { // [] CopyTo with index=0 and the array is 4 items larger then size as the collection testDescription = "CopyTo with index=0 and the array is 4 items larger then size as the collection"; itemObjectArray = GenerateArrayWithRandomItems(_items.Length + 4); tempItemObjectArray = new Object[_items.Length + 4]; Array.Copy(itemObjectArray, tempItemObjectArray, itemObjectArray.Length); Array.Copy(_items, 0, tempItemObjectArray, 0, _items.Length); _collection.CopyTo(itemObjectArray, 0); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray), "Err_" + testDescription + " FAILED"); // [] CopyTo with index=4 and the array is 4 items larger then size as the collection testDescription = "CopyTo with index=4 and the array is 4 items larger then size as the collection"; itemObjectArray = GenerateArrayWithRandomItems(_items.Length + 4); tempItemObjectArray = new Object[_items.Length + 4]; Array.Copy(itemObjectArray, tempItemObjectArray, itemObjectArray.Length); Array.Copy(_items, 0, tempItemObjectArray, 4, _items.Length); _collection.CopyTo(itemObjectArray, 4); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray), "Err_" + testDescription + " FAILED"); // [] CopyTo with index=4 and the array is 8 items larger then size as the collection testDescription = "CopyTo with index=4 and the array is 8 items larger then size as the collection"; itemObjectArray = GenerateArrayWithRandomItems(_items.Length + 8); tempItemObjectArray = new Object[_items.Length + 8]; Array.Copy(itemObjectArray, tempItemObjectArray, itemObjectArray.Length); Array.Copy(_items, 0, tempItemObjectArray, 4, _items.Length); _collection.CopyTo(itemObjectArray, 4); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray), "Err_" + testDescription + " FAILED"); //[] Verify CopyTo with valid types testDescription = "Verify CopyTo with valid types"; for (int i = 0; i < _validArrayTypes.Length; ++i) { _collection.CopyTo(Array.CreateInstance(_validArrayTypes[i], _collection.Count), 0); retValue &= Test.Eval(VerifyItems(itemObjectArray, tempItemObjectArray), "Err_" + testDescription + " FAILED"); } } catch (Exception e) { retValue &= Test.Eval(false, "The following CopyTo test: \n{0} threw the following exception: \n {1}\n", testDescription, e); } return retValue; } private Object[] GenerateArrayWithRandomItems(int length) { Object[] items = new Object[length]; Random rndGen = new Random(-55); for (int i = 0; i < items.Length; i++) { items[i] = rndGen.Next(); } return items; } protected bool VerifyCollection(ICollection collection, Object[] items) { return VerifyCollection(collection, items, 0, items.Length, VerificationLevel.Normal); } private bool VerifyCollection(ICollection collection, Object[] items, VerificationLevel verificationLevel) { return VerifyCollection(collection, items, 0, items.Length, verificationLevel); } protected bool VerifyCollection(ICollection collection, Object[] items, int index, int count) { return VerifyCollection(collection, items, index, count, VerificationLevel.Normal); } private bool VerifyCollection(ICollection collection, Object[] items, int index, int count, VerificationLevel verificationLevel) { bool retValue = true; if (verificationLevel <= _verificationLevel) { retValue &= Verify_Count(collection, items, index, count); retValue &= Verify_CopyTo(collection, items, index, count); retValue &= base.VerifyCollection(collection, items, index, count); } return retValue; } private bool VerifyItems(Object[] actualItems, Object[] expectedItems) { return VerifyItems(actualItems, expectedItems, VerificationLevel.Normal); } private bool VerifyItems(Object[] actualItems, Object[] expectedItems, VerificationLevel verificationLevel) { if (verificationLevel <= _verificationLevel) { if (!Test.Eval(expectedItems.Length, actualItems.Length, "The length of the items")) { return false; } for (int i = 0; i < expectedItems.Length; i++) { if (!Test.Eval(_comparer.Equals(actualItems[i], expectedItems[i]), "The actual item and expected items differ at {0} actual={1} expected={2}", i, actualItems[i], expectedItems[i])) { return false; } } return true; } return true; } private bool VerifyItems(Array actualItems, Array expectedItems) { return VerifyItems(actualItems, expectedItems, VerificationLevel.Normal); } private bool VerifyItems(Array actualItems, Array expectedItems, VerificationLevel verificationLevel) { if (verificationLevel <= _verificationLevel) { if (!Test.Eval(expectedItems.Length, actualItems.Length, "The length of the items")) { return false; } int actualItemsLowerBounds = actualItems.GetLowerBound(0); int expectedItemsLowerBounds = expectedItems.GetLowerBound(0); for (int i = 0; i < expectedItems.Length; i++) { if (!Test.Eval(_comparer.Equals(actualItems.GetValue(i + actualItemsLowerBounds), expectedItems.GetValue(i + expectedItemsLowerBounds)), "The actual item and expected items differ at {0} actual={1} expected={2}", i, actualItems.GetValue(i + actualItemsLowerBounds), expectedItems.GetValue(i + expectedItemsLowerBounds))) { return false; } } return true; } return true; } private bool Verify_Count(ICollection collection, Object[] items, int index, int count) { return Test.Eval(count, collection.Count, "Verifying Count"); } private bool Verify_CopyTo(ICollection collection, Object[] items, int index, int count) { bool retValue = true; if ((retValue &= Test.Eval(count, collection.Count, "Verifying CopyTo the actual count and expected count differ"))) { Object[] actualItems = new Object[count]; collection.CopyTo(actualItems, 0); for (int i = 0; i < count && retValue; i++) { int itemsIndex = i + index; retValue &= Test.Eval(_comparer.Equals(items[itemsIndex], actualItems[i]), "Expected item and actual item from copied array differ"); } } return retValue; } private Object[] GenerateArray(int length) { Object[] itemArray = new Object[length]; for (int i = 0; i < length; ++i) itemArray[i] = i ^ length; return itemArray; } internal class MyInvalidReferenceType { } internal struct MyInvalidValueType { } } }
using System; using System.Collections.Generic; using System.Linq; using Orchard.Logging; namespace Orchard.ContentManagement.Handlers { public abstract class ContentHandler : IContentHandler { protected ContentHandler() { Filters = new List<IContentFilter>(); Logger = NullLogger.Instance; } public List<IContentFilter> Filters { get; set; } public ILogger Logger { get; set; } protected void OnActivated<TPart>(Action<ActivatedContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnActivated = handler }); } protected void OnInitializing<TPart>(Action<InitializingContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnInitializing = handler }); } protected void OnInitialized<TPart>(Action<InitializingContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnInitialized = handler }); } protected void OnCreating<TPart>(Action<CreateContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnCreating = handler }); } protected void OnCreated<TPart>(Action<CreateContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnCreated = handler }); } protected void OnLoading<TPart>(Action<LoadContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnLoading = handler }); } protected void OnLoaded<TPart>(Action<LoadContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnLoaded = handler }); } protected void OnUpdating<TPart>(Action<UpdateContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnUpdating = handler }); } protected void OnUpdated<TPart>(Action<UpdateContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnUpdated = handler }); } protected void OnVersioning<TPart>(Action<VersionContentContext, TPart, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnVersioning = handler }); } protected void OnVersioned<TPart>(Action<VersionContentContext, TPart, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnVersioned = handler }); } protected void OnPublishing<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnPublishing = handler }); } protected void OnPublished<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnPublished = handler }); } protected void OnUnpublishing<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnUnpublishing = handler }); } protected void OnUnpublished<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnUnpublished = handler }); } protected void OnRemoving<TPart>(Action<RemoveContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnRemoving = handler }); } protected void OnRemoved<TPart>(Action<RemoveContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnRemoved = handler }); } protected void OnIndexing<TPart>(Action<IndexContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnIndexing = handler }); } protected void OnIndexed<TPart>(Action<IndexContentContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineStorageFilter<TPart> { OnIndexed = handler }); } protected void OnGetContentItemMetadata<TPart>(Action<GetContentItemMetadataContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineTemplateFilter<TPart> { OnGetItemMetadata = handler }); } protected void OnGetDisplayShape<TPart>(Action<BuildDisplayContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineTemplateFilter<TPart> { OnGetDisplayShape = handler }); } protected void OnGetEditorShape<TPart>(Action<BuildEditorContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineTemplateFilter<TPart> { OnGetEditorShape = handler }); } protected void OnUpdateEditorShape<TPart>(Action<UpdateEditorContext, TPart> handler) where TPart : class, IContent { Filters.Add(new InlineTemplateFilter<TPart> { OnUpdateEditorShape = handler }); } class InlineStorageFilter<TPart> : StorageFilterBase<TPart> where TPart : class, IContent { public Action<ActivatedContentContext, TPart> OnActivated { get; set; } public Action<InitializingContentContext, TPart> OnInitializing { get; set; } public Action<InitializingContentContext, TPart> OnInitialized { get; set; } public Action<CreateContentContext, TPart> OnCreating { get; set; } public Action<CreateContentContext, TPart> OnCreated { get; set; } public Action<LoadContentContext, TPart> OnLoading { get; set; } public Action<LoadContentContext, TPart> OnLoaded { get; set; } public Action<UpdateContentContext, TPart> OnUpdating { get; set; } public Action<UpdateContentContext, TPart> OnUpdated { get; set; } public Action<VersionContentContext, TPart, TPart> OnVersioning { get; set; } public Action<VersionContentContext, TPart, TPart> OnVersioned { get; set; } public Action<PublishContentContext, TPart> OnPublishing { get; set; } public Action<PublishContentContext, TPart> OnPublished { get; set; } public Action<PublishContentContext, TPart> OnUnpublishing { get; set; } public Action<PublishContentContext, TPart> OnUnpublished { get; set; } public Action<RemoveContentContext, TPart> OnRemoving { get; set; } public Action<RemoveContentContext, TPart> OnRemoved { get; set; } public Action<IndexContentContext, TPart> OnIndexing { get; set; } public Action<IndexContentContext, TPart> OnIndexed { get; set; } protected override void Activated(ActivatedContentContext context, TPart instance) { if (OnActivated != null) OnActivated(context, instance); } protected override void Initializing(InitializingContentContext context, TPart instance) { if (OnInitializing != null) OnInitializing(context, instance); } protected override void Initialized(InitializingContentContext context, TPart instance) { if (OnInitialized != null) OnInitialized(context, instance); } protected override void Creating(CreateContentContext context, TPart instance) { if (OnCreating != null) OnCreating(context, instance); } protected override void Created(CreateContentContext context, TPart instance) { if (OnCreated != null) OnCreated(context, instance); } protected override void Loading(LoadContentContext context, TPart instance) { if (OnLoading != null) OnLoading(context, instance); } protected override void Loaded(LoadContentContext context, TPart instance) { if (OnLoaded != null) OnLoaded(context, instance); } protected override void Updating(UpdateContentContext context, TPart instance) { if (OnUpdating != null) OnUpdating(context, instance); } protected override void Updated(UpdateContentContext context, TPart instance) { if (OnUpdated != null) OnUpdated(context, instance); } protected override void Versioning(VersionContentContext context, TPart existing, TPart building) { if (OnVersioning != null) OnVersioning(context, existing, building); } protected override void Versioned(VersionContentContext context, TPart existing, TPart building) { if (OnVersioned != null) OnVersioned(context, existing, building); } protected override void Publishing(PublishContentContext context, TPart instance) { if (OnPublishing != null) OnPublishing(context, instance); } protected override void Published(PublishContentContext context, TPart instance) { if (OnPublished != null) OnPublished(context, instance); } protected override void Unpublishing(PublishContentContext context, TPart instance) { if (OnUnpublishing != null) OnUnpublishing(context, instance); } protected override void Unpublished(PublishContentContext context, TPart instance) { if (OnUnpublished != null) OnUnpublished(context, instance); } protected override void Removing(RemoveContentContext context, TPart instance) { if (OnRemoving != null) OnRemoving(context, instance); } protected override void Removed(RemoveContentContext context, TPart instance) { if (OnRemoved != null) OnRemoved(context, instance); } protected override void Indexing(IndexContentContext context, TPart instance) { if ( OnIndexing != null ) OnIndexing(context, instance); } protected override void Indexed(IndexContentContext context, TPart instance) { if ( OnIndexed != null ) OnIndexed(context, instance); } } class InlineTemplateFilter<TPart> : TemplateFilterBase<TPart> where TPart : class, IContent { public Action<GetContentItemMetadataContext, TPart> OnGetItemMetadata { get; set; } public Action<BuildDisplayContext, TPart> OnGetDisplayShape { get; set; } public Action<BuildEditorContext, TPart> OnGetEditorShape { get; set; } public Action<UpdateEditorContext, TPart> OnUpdateEditorShape { get; set; } protected override void GetContentItemMetadata(GetContentItemMetadataContext context, TPart instance) { if (OnGetItemMetadata != null) OnGetItemMetadata(context, instance); } protected override void BuildDisplayShape(BuildDisplayContext context, TPart instance) { if (OnGetDisplayShape != null) OnGetDisplayShape(context, instance); } protected override void BuildEditorShape(BuildEditorContext context, TPart instance) { if (OnGetEditorShape != null) OnGetEditorShape(context, instance); } protected override void UpdateEditorShape(UpdateEditorContext context, TPart instance) { if (OnUpdateEditorShape != null) OnUpdateEditorShape(context, instance); } } void IContentHandler.Activating(ActivatingContentContext context) { foreach (var filter in Filters.OfType<IContentActivatingFilter>()) filter.Activating(context); Activating(context); } void IContentHandler.Activated(ActivatedContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Activated(context); Activated(context); } void IContentHandler.Initializing(InitializingContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Initializing(context); Initializing(context); } void IContentHandler.Initialized(InitializingContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Initialized(context); Initialized(context); } void IContentHandler.Creating(CreateContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Creating(context); Creating(context); } void IContentHandler.Created(CreateContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Created(context); Created(context); } void IContentHandler.Loading(LoadContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Loading(context); Loading(context); } void IContentHandler.Loaded(LoadContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Loaded(context); Loaded(context); } void IContentHandler.Updating(UpdateContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Updating(context); Updating(context); } void IContentHandler.Updated(UpdateContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Updated(context); Updated(context); } void IContentHandler.Versioning(VersionContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Versioning(context); Versioning(context); } void IContentHandler.Versioned(VersionContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Versioned(context); Versioned(context); } void IContentHandler.Publishing(PublishContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Publishing(context); Publishing(context); } void IContentHandler.Published(PublishContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Published(context); Published(context); } void IContentHandler.Unpublishing(PublishContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Unpublishing(context); Unpublishing(context); } void IContentHandler.Unpublished(PublishContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Unpublished(context); Unpublished(context); } void IContentHandler.Removing(RemoveContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Removing(context); Removing(context); } void IContentHandler.Removed(RemoveContentContext context) { foreach (var filter in Filters.OfType<IContentStorageFilter>()) filter.Removed(context); Removed(context); } void IContentHandler.Indexing(IndexContentContext context) { foreach ( var filter in Filters.OfType<IContentStorageFilter>() ) filter.Indexing(context); Indexing(context); } void IContentHandler.Indexed(IndexContentContext context) { foreach ( var filter in Filters.OfType<IContentStorageFilter>() ) filter.Indexed(context); Indexed(context); } void IContentHandler.Importing(ImportContentContext context) { Importing(context); } void IContentHandler.Imported(ImportContentContext context) { Imported(context); } void IContentHandler.Exporting(ExportContentContext context) { Exporting(context); } void IContentHandler.Exported(ExportContentContext context) { Exported(context); } void IContentHandler.GetContentItemMetadata(GetContentItemMetadataContext context) { foreach (var filter in Filters.OfType<IContentTemplateFilter>()) filter.GetContentItemMetadata(context); GetItemMetadata(context); } void IContentHandler.BuildDisplay(BuildDisplayContext context) { foreach (var filter in Filters.OfType<IContentTemplateFilter>()) filter.BuildDisplayShape(context); BuildDisplayShape(context); } void IContentHandler.BuildEditor(BuildEditorContext context) { foreach (var filter in Filters.OfType<IContentTemplateFilter>()) filter.BuildEditorShape(context); BuildEditorShape(context); } void IContentHandler.UpdateEditor(UpdateEditorContext context) { foreach (var filter in Filters.OfType<IContentTemplateFilter>()) filter.UpdateEditorShape(context); UpdateEditorShape(context); } protected virtual void Activating(ActivatingContentContext context) { } protected virtual void Activated(ActivatedContentContext context) { } protected virtual void Initializing(InitializingContentContext context) { } protected virtual void Initialized(InitializingContentContext context) { } protected virtual void Creating(CreateContentContext context) { } protected virtual void Created(CreateContentContext context) { } protected virtual void Loading(LoadContentContext context) { } protected virtual void Loaded(LoadContentContext context) { } protected virtual void Updating(UpdateContentContext context) { } protected virtual void Updated(UpdateContentContext context) { } protected virtual void Versioning(VersionContentContext context) { } protected virtual void Versioned(VersionContentContext context) { } protected virtual void Publishing(PublishContentContext context) { } protected virtual void Published(PublishContentContext context) { } protected virtual void Unpublishing(PublishContentContext context) { } protected virtual void Unpublished(PublishContentContext context) { } protected virtual void Removing(RemoveContentContext context) { } protected virtual void Removed(RemoveContentContext context) { } protected virtual void Indexing(IndexContentContext context) { } protected virtual void Indexed(IndexContentContext context) { } protected virtual void Importing(ImportContentContext context) { } protected virtual void Imported(ImportContentContext context) { } protected virtual void Exporting(ExportContentContext context) { } protected virtual void Exported(ExportContentContext context) { } protected virtual void GetItemMetadata(GetContentItemMetadataContext context) { } protected virtual void BuildDisplayShape(BuildDisplayContext context) { } protected virtual void BuildEditorShape(BuildEditorContext context) { } protected virtual void UpdateEditorShape(UpdateEditorContext context) { } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Runtime.InteropServices; using System.Reflection; using System.Threading; using System.Windows.Forms; using System.ComponentModel; namespace WOSI.Utilities { /// <summary> /// This class allows you to tap keyboard and mouse and / or to detect their activity even when an /// application runes in background or does not have any user interface at all. This class raises /// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need. /// </summary> public class UserActivityHook { #region Windows structure definitions /// <summary> /// The POINT structure defines the x- and y- coordinates of a point. /// </summary> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp /// </remarks> [StructLayout(LayoutKind.Sequential)] private class POINT { /// <summary> /// Specifies the x-coordinate of the point. /// </summary> public int x; /// <summary> /// Specifies the y-coordinate of the point. /// </summary> public int y; } /// <summary> /// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure, MouseProc. /// </summary> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp /// </remarks> [StructLayout(LayoutKind.Sequential)] private class MouseHookStruct { /// <summary> /// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates. /// </summary> public POINT pt; /// <summary> /// Handle to the window that will receive the mouse message corresponding to the mouse event. /// </summary> public int hwnd; /// <summary> /// Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message. /// </summary> public int wHitTestCode; /// <summary> /// Specifies extra information associated with the message. /// </summary> public int dwExtraInfo; } /// <summary> /// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event. /// </summary> [StructLayout(LayoutKind.Sequential)] private class MouseLLHookStruct { /// <summary> /// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates. /// </summary> public POINT pt; /// <summary> /// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta. /// The low-order word is reserved. A positive value indicates that the wheel was rotated forward, /// away from the user; a negative value indicates that the wheel was rotated backward, toward the user. /// One wheel click is defined as WHEEL_DELTA, which is 120. ///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, /// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released, /// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, mouseData is not used. ///XBUTTON1 ///The first X button was pressed or released. ///XBUTTON2 ///The second X button was pressed or released. /// </summary> public int mouseData; /// <summary> /// Specifies the event-injected flag. An application can use the following value to test the mouse flags. Value Purpose ///LLMHF_INJECTED Test the event-injected flag. ///0 ///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0. ///1-15 ///Reserved. /// </summary> public int flags; /// <summary> /// Specifies the time stamp for this message. /// </summary> public int time; /// <summary> /// Specifies extra information associated with the message. /// </summary> public int dwExtraInfo; } /// <summary> /// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event. /// </summary> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp /// </remarks> [StructLayout(LayoutKind.Sequential)] private class KeyboardHookStruct { /// <summary> /// Specifies a virtual-key code. The code must be a value in the range 1 to 254. /// </summary> public int vkCode; /// <summary> /// Specifies a hardware scan code for the key. /// </summary> public int scanCode; /// <summary> /// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag. /// </summary> public int flags; /// <summary> /// Specifies the time stamp for this message. /// </summary> public int time; /// <summary> /// Specifies extra information associated with the message. /// </summary> public int dwExtraInfo; } #endregion #region Windows function imports /// <summary> /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. /// You would install a hook procedure to monitor the system for certain types of events. These events /// are associated either with a specific thread or with all threads in the same desktop as the calling thread. /// </summary> /// <param name="idHook"> /// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values. /// </param> /// <param name="lpfn"> /// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a /// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link /// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process. /// </param> /// <param name="hMod"> /// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter. /// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by /// the current process and if the hook procedure is within the code associated with the current process. /// </param> /// <param name="dwThreadId"> /// [in] Specifies the identifier of the thread with which the hook procedure is to be associated. /// If this parameter is zero, the hook procedure is associated with all existing threads running in the /// same desktop as the calling thread. /// </param> /// <returns> /// If the function succeeds, the return value is the handle to the hook procedure. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp /// </remarks> [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern int SetWindowsHookEx( int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId); /// <summary> /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function. /// </summary> /// <param name="idHook"> /// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx. /// </param> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp /// </remarks> [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern int UnhookWindowsHookEx(int idHook); /// <summary> /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain. /// A hook procedure can call this function either before or after processing the hook information. /// </summary> /// <param name="idHook">Ignored.</param> /// <param name="nCode"> /// [in] Specifies the hook code passed to the current hook procedure. /// The next hook procedure uses this code to determine how to process the hook information. /// </param> /// <param name="wParam"> /// [in] Specifies the wParam value passed to the current hook procedure. /// The meaning of this parameter depends on the type of hook associated with the current hook chain. /// </param> /// <param name="lParam"> /// [in] Specifies the lParam value passed to the current hook procedure. /// The meaning of this parameter depends on the type of hook associated with the current hook chain. /// </param> /// <returns> /// This value is returned by the next hook procedure in the chain. /// The current hook procedure must also return this value. The meaning of the return value depends on the hook type. /// For more information, see the descriptions of the individual hook procedures. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp /// </remarks> [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] private static extern int CallNextHookEx( int idHook, int nCode, int wParam, IntPtr lParam); /// <summary> /// The CallWndProc hook procedure is an application-defined or library-defined callback /// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer /// to this callback function. CallWndProc is a placeholder for the application-defined /// or library-defined function name. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp /// </remarks> private delegate int HookProc(int nCode, int wParam, IntPtr lParam); /// <summary> /// The ToAscii function translates the specified virtual-key code and keyboard /// state to the corresponding character or characters. The function translates the code /// using the input language and physical keyboard layout identified by the keyboard layout handle. /// </summary> /// <param name="uVirtKey"> /// [in] Specifies the virtual-key code to be translated. /// </param> /// <param name="uScanCode"> /// [in] Specifies the hardware scan code of the key to be translated. /// The high-order bit of this value is set if the key is up (not pressed). /// </param> /// <param name="lpbKeyState"> /// [in] Pointer to a 256-byte array that contains the current keyboard state. /// Each element (byte) in the array contains the state of one key. /// If the high-order bit of a byte is set, the key is down (pressed). /// The low bit, if set, indicates that the key is toggled on. In this function, /// only the toggle bit of the CAPS LOCK key is relevant. The toggle state /// of the NUM LOCK and SCROLL LOCK keys is ignored. /// </param> /// <param name="lpwTransKey"> /// [out] Pointer to the buffer that receives the translated character or characters. /// </param> /// <param name="fuState"> /// [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise. /// </param> /// <returns> /// If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values. /// Value Meaning /// 0 The specified virtual key has no translation for the current state of the keyboard. /// 1 One character was copied to the buffer. /// 2 Two characters were copied to the buffer. This usually happens when a dead-key character /// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified /// virtual key to form a single character. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp /// </remarks> [DllImport("user32")] private static extern int ToAscii( int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState); /// <summary> /// The GetKeyboardState function copies the status of the 256 virtual keys to the /// specified buffer. /// </summary> /// <param name="pbKeyState"> /// [in] Pointer to a 256-byte array that contains keyboard key states. /// </param> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks> /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp /// </remarks> [DllImport("user32")] private static extern int GetKeyboardState(byte[] pbKeyState); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] private static extern short GetKeyState(int vKey); #endregion #region Windows constants //values from Winuser.h in Microsoft SDK. /// <summary> /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events. /// </summary> private const int WH_MOUSE_LL = 14; /// <summary> /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events. /// </summary> private const int WH_KEYBOARD_LL = 13; /// <summary> /// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure. /// </summary> private const int WH_MOUSE = 7; /// <summary> /// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure. /// </summary> private const int WH_KEYBOARD = 2; /// <summary> /// The WM_MOUSEMOVE message is posted to a window when the cursor moves. /// </summary> private const int WM_MOUSEMOVE = 0x200; /// <summary> /// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button /// </summary> private const int WM_LBUTTONDOWN = 0x201; /// <summary> /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button /// </summary> private const int WM_RBUTTONDOWN = 0x204; /// <summary> /// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button /// </summary> private const int WM_MBUTTONDOWN = 0x207; /// <summary> /// The WM_LBUTTONUP message is posted when the user releases the left mouse button /// </summary> private const int WM_LBUTTONUP = 0x202; /// <summary> /// The WM_RBUTTONUP message is posted when the user releases the right mouse button /// </summary> private const int WM_RBUTTONUP = 0x205; /// <summary> /// The WM_MBUTTONUP message is posted when the user releases the middle mouse button /// </summary> private const int WM_MBUTTONUP = 0x208; /// <summary> /// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button /// </summary> private const int WM_LBUTTONDBLCLK = 0x203; /// <summary> /// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button /// </summary> private const int WM_RBUTTONDBLCLK = 0x206; /// <summary> /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button /// </summary> private const int WM_MBUTTONDBLCLK = 0x209; /// <summary> /// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel. /// </summary> private const int WM_MOUSEWHEEL = 0x020A; /// <summary> /// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem /// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed. /// </summary> private const int WM_KEYDOWN = 0x100; /// <summary> /// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem /// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed, /// or a keyboard key that is pressed when a window has the keyboard focus. /// </summary> private const int WM_KEYUP = 0x101; /// <summary> /// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user /// presses the F10 key (which activates the menu bar) or holds down the ALT key and then /// presses another key. It also occurs when no window currently has the keyboard focus; /// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that /// receives the message can distinguish between these two contexts by checking the context /// code in the lParam parameter. /// </summary> private const int WM_SYSKEYDOWN = 0x104; /// <summary> /// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user /// releases a key that was pressed while the ALT key was held down. It also occurs when no /// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent /// to the active window. The window that receives the message can distinguish between /// these two contexts by checking the context code in the lParam parameter. /// </summary> private const int WM_SYSKEYUP = 0x105; private const byte VK_SHIFT = 0x10; private const byte VK_CAPITAL = 0x14; private const byte VK_NUMLOCK = 0x90; #endregion /// <summary> /// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks. /// </summary> /// <exception cref="Win32Exception">Any windows problem.</exception> public UserActivityHook() { Start(); } /// <summary> /// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events /// </summary> /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param> /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param> /// <exception cref="Win32Exception">Any windows problem.</exception> /// <remarks> /// To create an instance without installing hooks call new UserActivityHook(false, false) /// </remarks> public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook) { Start(InstallMouseHook, InstallKeyboardHook); } /// <summary> /// Destruction. /// </summary> ~UserActivityHook() { //uninstall hooks and do not throw exceptions Stop(true, true, false); } /// <summary> /// Occurs when the user moves the mouse, presses any mouse button or scrolls the wheel /// </summary> public event MouseEventHandler OnMouseActivity; /// <summary> /// Occurs when the user presses a key /// </summary> public event KeyEventHandler KeyDown; /// <summary> /// Occurs when the user presses and releases /// </summary> public event KeyPressEventHandler KeyPress; /// <summary> /// Occurs when the user releases a key /// </summary> public event KeyEventHandler KeyUp; /// <summary> /// Stores the handle to the mouse hook procedure. /// </summary> private int hMouseHook = 0; /// <summary> /// Stores the handle to the keyboard hook procedure. /// </summary> private int hKeyboardHook = 0; /// <summary> /// Declare MouseHookProcedure as HookProc type. /// </summary> private static HookProc MouseHookProcedure; /// <summary> /// Declare KeyboardHookProcedure as HookProc type. /// </summary> private static HookProc KeyboardHookProcedure; /// <summary> /// Installs both mouse and keyboard hooks and starts rasing events /// </summary> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Start() { this.Start(true, true); } /// <summary> /// Installs both or one of mouse and/or keyboard hooks and starts rasing events /// </summary> /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param> /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Start(bool InstallMouseHook, bool InstallKeyboardHook) { // install Mouse hook only if it is not installed and must be installed if (hMouseHook == 0 && InstallMouseHook) { // Create an instance of HookProc. MouseHookProcedure = new HookProc(MouseHookProc); //install hook hMouseHook = SetWindowsHookEx( WH_MOUSE_LL, MouseHookProcedure, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); //If SetWindowsHookEx fails. if (hMouseHook == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup Stop(true, false, false); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } // install Keyboard hook only if it is not installed and must be installed if (hKeyboardHook == 0 && InstallKeyboardHook) { // Create an instance of HookProc. KeyboardHookProcedure = new HookProc(KeyboardHookProc); //install hook hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); //If SetWindowsHookEx fails. if (hKeyboardHook == 0) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //do cleanup Stop(false, true, false); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } /// <summary> /// Stops monitoring both mouse and keyboard events and rasing events. /// </summary> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Stop() { this.Stop(true, true, true); } /// <summary> /// Stops monitoring both or one of mouse and/or keyboard events and rasing events. /// </summary> /// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param> /// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param> /// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param> /// <exception cref="Win32Exception">Any windows problem.</exception> public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions) { //if mouse hook set and must be uninstalled if (hMouseHook != 0 && UninstallMouseHook) { //uninstall hook int retMouse = UnhookWindowsHookEx(hMouseHook); //reset invalid handle hMouseHook = 0; //if failed and exception must be thrown if (retMouse == 0 && ThrowExceptions) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } //if keyboard hook set and must be uninstalled if (hKeyboardHook != 0 && UninstallKeyboardHook) { //uninstall hook int retKeyboard = UnhookWindowsHookEx(hKeyboardHook); //reset invalid handle hKeyboardHook = 0; //if failed and exception must be thrown if (retKeyboard == 0 && ThrowExceptions) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. int errorCode = Marshal.GetLastWin32Error(); //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } } } /// <summary> /// A callback function which will be called every time a mouse activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private int MouseHookProc(int nCode, int wParam, IntPtr lParam) { // if ok and someone listens to our events if ((nCode >= 0) && (OnMouseActivity != null)) { //Marshall the data from callback. MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct)); //detect button clicked MouseButtons button = MouseButtons.None; short mouseDelta = 0; switch (wParam) { case WM_LBUTTONDOWN: //case WM_LBUTTONUP: //case WM_LBUTTONDBLCLK: button = MouseButtons.Left; break; case WM_RBUTTONDOWN: //case WM_RBUTTONUP: //case WM_RBUTTONDBLCLK: button = MouseButtons.Right; break; case WM_MOUSEWHEEL: //If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta. //One wheel click is defined as WHEEL_DELTA, which is 120. //(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff); //TODO: X BUTTONS (I havent them so was unable to test) //If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, //or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released, //and the low-order word is reserved. This value can be one or more of the following values. //Otherwise, mouseData is not used. break; } //double clicks int clickCount = 0; if (button != MouseButtons.None) if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2; else clickCount = 1; //generate event MouseEventArgs e = new MouseEventArgs( button, clickCount, mouseHookStruct.pt.x, mouseHookStruct.pt.y, mouseDelta); //raise it OnMouseActivity(this, e); } //call next hook return CallNextHookEx(hMouseHook, nCode, wParam, lParam); } /// <summary> /// A callback function which will be called every time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //indicates if any of underlaing events set e.Handled flag bool handled = false; //it was ok and someone listens to events if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null)) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyDown(this, e); handled = handled || e.Handled; } // raise KeyPress if (KeyPress != null && wParam == WM_KEYDOWN) { bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { char key = (char)inBuffer[0]; if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key); KeyPressEventArgs e = new KeyPressEventArgs(key); KeyPress(this, e); handled = handled || e.Handled; } } // raise KeyUp if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUp(this, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) return 1; else return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DomainServiceConfigurationRecordsCollectionRequest. /// </summary> public partial class DomainServiceConfigurationRecordsCollectionRequest : BaseRequest, IDomainServiceConfigurationRecordsCollectionRequest { /// <summary> /// Constructs a new DomainServiceConfigurationRecordsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DomainServiceConfigurationRecordsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified DomainDnsRecord to the collection via POST. /// </summary> /// <param name="domainDnsRecord">The DomainDnsRecord to add.</param> /// <returns>The created DomainDnsRecord.</returns> public System.Threading.Tasks.Task<DomainDnsRecord> AddAsync(DomainDnsRecord domainDnsRecord) { return this.AddAsync(domainDnsRecord, CancellationToken.None); } /// <summary> /// Adds the specified DomainDnsRecord to the collection via POST. /// </summary> /// <param name="domainDnsRecord">The DomainDnsRecord to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DomainDnsRecord.</returns> public System.Threading.Tasks.Task<DomainDnsRecord> AddAsync(DomainDnsRecord domainDnsRecord, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<DomainDnsRecord>(domainDnsRecord, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IDomainServiceConfigurationRecordsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IDomainServiceConfigurationRecordsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<DomainServiceConfigurationRecordsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Expand(Expression<Func<DomainDnsRecord, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Select(Expression<Func<DomainDnsRecord, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IDomainServiceConfigurationRecordsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition.Hosting; using System.Composition.Hosting.Core; using System.Composition.Runtime; using System.Composition.UnitTests.Util; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Composition.UnitTests { public class ExportFactoryTests : ContainerTests { private static class Boundaries { public const string DataConsistency = "DataConsistency"; public const string UserIdentity = "UserIdentity"; } [Shared, Export] public class SharedUnbounded { } [Shared(Boundaries.DataConsistency), Export] public class SharedBoundedByDC { } [Export] public class DataConsistencyBoundaryProvider { [Import, SharingBoundary(Boundaries.DataConsistency)] public ExportFactory<CompositionContext> SharingScopeFactory { get; set; } } [Export] public class SharedPartConsumer { public SharedBoundedByDC Sc1, Sc2; [ImportingConstructor] public SharedPartConsumer(SharedBoundedByDC sc1, SharedBoundedByDC sc2) { Sc1 = sc1; Sc2 = sc2; } } public interface IA { } [Export(typeof(IA))] public class A : IA, IDisposable { public bool IsDisposed; public void Dispose() { IsDisposed = true; } } [Shared, Export] public class GloballySharedWithDependency { public IA A; [ImportingConstructor] public GloballySharedWithDependency(IA a) { A = a; } } [Export] public class UseExportFactory { [Import] public ExportFactory<IA> AFactory { get; set; } } [Export] public class DisposesFactoryProduct : IDisposable { private readonly ExportFactory<IA> _factory; [ImportingConstructor] public DisposesFactoryProduct(ExportFactory<IA> factory) { _factory = factory; } public Export<IA> Product { get; set; } public void CreateProduct() { Product = _factory.CreateExport(); } public void Dispose() { Product.Dispose(); } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void SharedPartsAreSharedBetweenAllScopes() { var cc = CreateContainer(typeof(SharedUnbounded), typeof(DataConsistencyBoundaryProvider)); var bp = cc.GetExport<DataConsistencyBoundaryProvider>().SharingScopeFactory; var x = bp.CreateExport().Value.GetExport<SharedUnbounded>(); var y = bp.CreateExport().Value.GetExport<SharedUnbounded>(); Assert.Same(x, y); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void TheSameSharedInstanceIsReusedWithinItsSharingBoundary() { var cc = CreateContainer(typeof(SharedBoundedByDC), typeof(SharedPartConsumer), typeof(DataConsistencyBoundaryProvider)); var sf = cc.GetExport<DataConsistencyBoundaryProvider>().SharingScopeFactory; var s = sf.CreateExport(); var s2 = sf.CreateExport(); var x = s.Value.GetExport<SharedPartConsumer>(); var y = s2.Value.GetExport<SharedPartConsumer>(); Assert.Same(x.Sc1, x.Sc2); Assert.NotSame(x.Sc1, y.Sc1); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void NonSharedInstancesCreatedByAnExportFactoryAreControlledByTheirExportLifetimeContext() { var cc = CreateContainer(typeof(A), typeof(UseExportFactory)); var bef = cc.GetExport<UseExportFactory>(); var a = bef.AFactory.CreateExport(); Assert.IsAssignableFrom(typeof(A), a.Value); Assert.False(((A)a.Value).IsDisposed); a.Dispose(); Assert.True(((A)a.Value).IsDisposed); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void DependenciesOfSharedPartsAreResolvedInTheGlobalScope() { var cc = new ContainerConfiguration() .WithParts(typeof(GloballySharedWithDependency), typeof(A), typeof(DataConsistencyBoundaryProvider)) .CreateContainer(); var s = cc.GetExport<DataConsistencyBoundaryProvider>().SharingScopeFactory.CreateExport(); var g = s.Value.GetExport<GloballySharedWithDependency>(); s.Dispose(); var a = (A)g.A; Assert.False(a.IsDisposed); cc.Dispose(); Assert.True(a.IsDisposed); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WhenABoundaryIsPresentBoundedPartsCannotBeCreatedOutsideIt() { var container = CreateContainer(typeof(DataConsistencyBoundaryProvider), typeof(SharedBoundedByDC)); var x = Assert.Throws<CompositionFailedException>(() => container.GetExport<SharedBoundedByDC>()); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void TheProductOfAnExportFactoryCanBeDisposedDuringDisposalOfTheParent() { var container = new ContainerConfiguration() .WithPart<DisposesFactoryProduct>() .WithPart<A>() .CreateContainer(); var dfp = container.GetExport<DisposesFactoryProduct>(); dfp.CreateProduct(); var a = dfp.Product.Value as A; container.Dispose(); Assert.True(a.IsDisposed); } [Export("Special", typeof(IA))] public class A1 : IA { } [Export("Special", typeof(IA))] public class A2 : IA { } [Export] public class AConsumer { [ImportMany("Special")] public ExportFactory<IA>[] AFactories { get; set; } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ExportFactoryCanBeComposedWithImportManyAndNames() { var cc = CreateContainer(typeof(AConsumer), typeof(A1), typeof(A2)); var cons = cc.GetExport<AConsumer>(); Assert.Equal(2, cons.AFactories.Length); } [Export] public class Disposable : IDisposable { public bool IsDisposed { get; set; } public void Dispose() { IsDisposed = true; } } [Export] public class HasDisposableDependency { [Import] public Disposable Dependency { get; set; } } [Export] public class HasFactory { [Import] public ExportFactory<HasDisposableDependency> Factory { get; set; } } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void WhenReleasingAnExportFromAnExportFactoryItsNonSharedDependenciesAreDisposed() { var cc = CreateContainer(typeof(Disposable), typeof(HasDisposableDependency), typeof(HasFactory)); var hf = cc.GetExport<HasFactory>(); var hddx = hf.Factory.CreateExport(); var hdd = hddx.Value; hddx.Dispose(); Assert.True(hdd.Dependency.IsDisposed); } } }
using System.Diagnostics; namespace Lucene.Net.Index { using NUnit.Framework; using System; using System.IO; using Util; using Directory = Lucene.Net.Store.Directory; /* * 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 Document = Documents.Document; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; [TestFixture] public class TestPersistentSnapshotDeletionPolicy : TestSnapshotDeletionPolicy { [SetUp] public override void SetUp() { base.SetUp(); } [TearDown] public override void TearDown() { base.TearDown(); } private SnapshotDeletionPolicy GetDeletionPolicy(Directory dir) { return new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.CREATE); } [Test] public virtual void TestExistingSnapshots() { int numSnapshots = 3; MockDirectoryWrapper dir = NewMockDirectory(); IndexWriter writer = new IndexWriter(dir, GetConfig(Random(), GetDeletionPolicy(dir))); PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy; Assert.IsNull(psdp.LastSaveFile); PrepareIndexAndSnapshots(psdp, writer, numSnapshots); Assert.IsNotNull(psdp.LastSaveFile); writer.Dispose(); // Make sure only 1 save file exists: int count = 0; foreach (string file in dir.ListAll()) { if (file.StartsWith(PersistentSnapshotDeletionPolicy.SNAPSHOTS_PREFIX, StringComparison.Ordinal)) { count++; } } Assert.AreEqual(1, count); // Make sure we fsync: dir.Crash(); dir.ClearCrash(); // Re-initialize and verify snapshots were persisted psdp = new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND); writer = new IndexWriter(dir, GetConfig(Random(), psdp)); psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy; Assert.AreEqual(numSnapshots, psdp.GetSnapshots().Count); Assert.AreEqual(numSnapshots, psdp.SnapshotCount); AssertSnapshotExists(dir, psdp, numSnapshots, false); writer.AddDocument(new Document()); writer.Commit(); Snapshots.Add(psdp.Snapshot()); Assert.AreEqual(numSnapshots + 1, psdp.GetSnapshots().Count); Assert.AreEqual(numSnapshots + 1, psdp.SnapshotCount); AssertSnapshotExists(dir, psdp, numSnapshots + 1, false); writer.Dispose(); dir.Dispose(); } [Test] public virtual void TestNoSnapshotInfos() { Directory dir = NewDirectory(); new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.CREATE); dir.Dispose(); } [Test] public virtual void TestMissingSnapshots() { Directory dir = NewDirectory(); try { new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND); Assert.Fail("did not hit expected exception"); } #pragma warning disable 168 catch (InvalidOperationException ise) #pragma warning restore 168 { // expected } dir.Dispose(); } [Test] public virtual void TestExceptionDuringSave() { MockDirectoryWrapper dir = NewMockDirectory(); dir.FailOn(new FailureAnonymousInnerClassHelper(this, dir)); IndexWriter writer = new IndexWriter(dir, GetConfig(Random(), new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.CREATE_OR_APPEND))); writer.AddDocument(new Document()); writer.Commit(); PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy; try { psdp.Snapshot(); } catch (IOException ioe) { if (ioe.Message.Equals("now fail on purpose")) { // ok } else { throw ioe; } } Assert.AreEqual(0, psdp.SnapshotCount); writer.Dispose(); Assert.AreEqual(1, DirectoryReader.ListCommits(dir).Count); dir.Dispose(); } private class FailureAnonymousInnerClassHelper : MockDirectoryWrapper.Failure { private readonly TestPersistentSnapshotDeletionPolicy OuterInstance; private MockDirectoryWrapper Dir; public FailureAnonymousInnerClassHelper(TestPersistentSnapshotDeletionPolicy outerInstance, MockDirectoryWrapper dir) { this.OuterInstance = outerInstance; this.Dir = dir; } public override void Eval(MockDirectoryWrapper dir) { // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)] // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods. if (StackTraceHelper.DoesStackTraceContainMethod(typeof(PersistentSnapshotDeletionPolicy).Name, "Persist")) { throw new IOException("now fail on purpose"); } } } [Test] public virtual void TestSnapshotRelease() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, GetConfig(Random(), GetDeletionPolicy(dir))); PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy; PrepareIndexAndSnapshots(psdp, writer, 1); writer.Dispose(); psdp.Release(Snapshots[0]); psdp = new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND); Assert.AreEqual(0, psdp.SnapshotCount, "Should have no snapshots !"); dir.Dispose(); } [Test] public virtual void TestSnapshotReleaseByGeneration() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, GetConfig(Random(), GetDeletionPolicy(dir))); PersistentSnapshotDeletionPolicy psdp = (PersistentSnapshotDeletionPolicy)writer.Config.IndexDeletionPolicy; PrepareIndexAndSnapshots(psdp, writer, 1); writer.Dispose(); psdp.Release(Snapshots[0].Generation); psdp = new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND); Assert.AreEqual(0, psdp.SnapshotCount, "Should have no snapshots !"); dir.Dispose(); } #region TestSnapshotDeletionPolicy // LUCENENET NOTE: Tests in a base class are not pulled into the correct // context in Visual Studio. This fixes that with the minimum amount of code necessary // to run them in the correct context without duplicating all of the tests. [Test] public override void TestSnapshotDeletionPolicy_Mem() { base.TestSnapshotDeletionPolicy_Mem(); } [Test] public override void TestBasicSnapshots() { base.TestBasicSnapshots(); } [Test] public override void TestMultiThreadedSnapshotting() { base.TestMultiThreadedSnapshotting(); } [Test] public override void TestRollbackToOldSnapshot() { base.TestRollbackToOldSnapshot(); } [Test] public override void TestReleaseSnapshot() { base.TestReleaseSnapshot(); } [Test] public override void TestSnapshotLastCommitTwice() { base.TestSnapshotLastCommitTwice(); } [Test] public override void TestMissingCommits() { base.TestMissingCommits(); } #endregion } }
namespace LuceneSearch { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers.Classic; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util; public partial class Index : IDisposable { private readonly Directory _dir; private readonly Lazy<SearcherManager> _sm; private readonly Analyzer _analyzer; private readonly IDisposable _disposable; private readonly Dictionary<string, Func<string, IIndexableField>> _mapping; private readonly HashSet<string> _termFields; private IndexWriter _writer; private IndexWriter Writer => _writer = _writer ?? new IndexWriter(_dir, new IndexWriterConfig(LuceneVersion.LUCENE_48, _analyzer) { IndexDeletionPolicy = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()) }); public Index(string directory, IEnumerable<Field> mapping) { _mapping = FieldMapper.Create(mapping); _termFields = FieldMapper.GetTermFields(mapping); var analyzerMap = mapping .Where(x => !string.IsNullOrEmpty(x.SpecificAnalyzer)) .ToDictionary(x => x.Name, x => x.SpecificAnalyzer); IDisposable d; (_analyzer, d) = PerFieldAnalyzer.Create("StandardAnalyzer", analyzerMap); _dir = DirectoryProvider.Create(directory); _sm = new Lazy<SearcherManager>(() => new SearcherManager(_dir, null), true); _disposable = new DelegateDisposable(() => { d.Dispose(); _writer?.Dispose(); _writer = null; if (_sm.IsValueCreated) _sm.Value.Dispose(); _dir.Dispose(); }); } public long LoadDocuments(IEnumerable<IEnumerable<KeyValuePair<string, string>>> docs) { long count = 0; var ixw = Writer; { foreach(var doc in docs) { var luceneDoc = new Document(); foreach (var f in doc.Where(f => _mapping.ContainsKey(f.Key))) { luceneDoc.Add(_mapping[f.Key](f.Value)); } ixw.AddDocument(luceneDoc); count++; } } Commit(); return count; } public int Count { get { var searcher = _sm.Value.Acquire(); try { return searcher.IndexReader.NumDocs; } finally { _sm.Value.Release(searcher); } } } public IReadOnlyCollection<KeyValuePair<string, string>> GetByTerm(string name, string value) { var searcher = _sm.Value.Acquire(); try { var scores = searcher.Search(new TermQuery(new Term(name, new BytesRef(value))), 1).ScoreDocs; if (scores.Length > 0) { var doc = searcher.Doc(scores[0].Doc); return doc.Select(x => new KeyValuePair<string, string>(x.Name, x.GetStringValue())).ToArray(); } return null; } finally { _sm.Value.Release(searcher); } } public void DeleteByTerm(string name, string value, bool commit = true) { var ixw = Writer; ixw.DeleteDocuments(new Term(name, new BytesRef(value))); if (commit) Commit(); } public void UpdateByTerm(string name, string value, IEnumerable<KeyValuePair<string, string>> doc, bool commit = true) { var ixw = Writer; var luceneDoc = new Document(); foreach (var f in doc.Where(f => _mapping.ContainsKey(f.Key))) { luceneDoc.Add(_mapping[f.Key](f.Value)); } ixw.UpdateDocument(new Term(name, new BytesRef(value)), luceneDoc); if (commit) Commit(); } public void Commit() { Writer.Commit(); if (_sm.IsValueCreated) _sm.Value.MaybeRefreshBlocking(); } public SearchResult Search( IDictionary<string, IReadOnlyCollection<string>> filters, int take = 128, int skip = 0, string sort = null, bool reverseSort = false, ISet<string> fieldsToLoad = null) => QuerySearch(QueryHelper.BooleanAnd(Parse(filters).ToArray()), take, skip, sort, reverseSort, fieldsToLoad); public SearchResult Search( IndexQuery query, int take = 128, int skip = 0, string sort = null, bool reverseSort = false, ISet<string> fieldsToLoad = null) => QuerySearch(query.Query, take, skip, sort, reverseSort, fieldsToLoad); public SearchResult Search( string query, IDictionary<string, IReadOnlyCollection<string>> filters, int take = 128, int skip = 0, string sort = null, bool reverseSort = false, ISet<string> fieldsToLoad = null) { var queries = Parse(filters); var mainQuery = QueryHelper.BooleanAnd(queries.Concat(new[] { Parse(query, null) }).ToArray()); return QuerySearch(mainQuery, take, skip, sort, reverseSort, fieldsToLoad); } public IndexQuery Parse(string query) => new IndexQuery(Parse(query, null)); private Query Parse(string query, string fieldName = null) { var analyzer = _analyzer; if (fieldName != null && _mapping.ContainsKey(fieldName) && _termFields.Contains(fieldName) && !QueryHelper.IsRange(query)) { return QueryHelper.Wildcard(fieldName, query); } var parser = new QueryParser( LuceneVersion.LUCENE_48, fieldName ?? _mapping.Keys.First(), _analyzer); parser.AllowLeadingWildcard = true; parser.LowercaseExpandedTerms = false; return parser.Parse(query); } private IEnumerable<Query> Parse(IDictionary<string, IReadOnlyCollection<string>> filters) => from filter in filters let valueQueries = filter.Value.Select(v => Parse(v, fieldName: filter.Key)).ToArray() select QueryHelper.BooleanOr(valueQueries); public SearchResult Search( string query, int take = 128, int skip = 0, string sort = null, bool reverseSort = false, ISet<string> fieldsToLoad = null) => QuerySearch(Parse(query, null), take, skip, sort, reverseSort, fieldsToLoad); private SearchResult QuerySearch( Query mainQuery, int take, int skip, string sort, bool reverseSort, ISet<string> fieldsToLoad) { var sw = Stopwatch.StartNew(); var searcher = _sm.Value.Acquire(); try { var res = sort == null ? searcher.Search(mainQuery, take + skip) : searcher.Search(mainQuery, take + skip, new Sort(new SortField(sort, SortFieldType.STRING, reverseSort))); var docs = new List<IReadOnlyCollection<KeyValuePair<string, string>>>(take); var scores = res.ScoreDocs; for (int i = skip; i < scores.Length; i++) { var doc = searcher.Doc(scores[i].Doc, fieldsToLoad); docs.Add(doc.Select(x => new KeyValuePair<string, string>(x.Name, x.GetStringValue())).ToArray()); } return new SearchResult(res.TotalHits, sw.Elapsed, docs); } finally { _sm.Value.Release(searcher); } } public IEnumerable<string> GetTerms( string termName, bool prefix = false, string from = null, int? take = null, CancellationToken cancellationToken = default(CancellationToken)) { var searcher = _sm.Value.Acquire(); try { var ir = searcher.IndexReader; var terms = MultiFields.GetTerms(ir, termName); if (terms == null) yield break; var termsEnum = terms.GetIterator(null); BytesRef term; if (from != null) { termsEnum = prefix ? (TermsEnum) new PrefixTermsEnum(termsEnum, new BytesRef(from)) : new TermRangeTermsEnum(termsEnum, new BytesRef(from), null, true, false); } int count = 0; while ((term = termsEnum.Next()) != null) { var stringTerm = term.Utf8ToString(); yield return stringTerm; if (take.HasValue && ++count == take.Value) yield break; } } finally { _sm.Value.Release(searcher); } } public void Copy(string dest) { var destDir = DirectoryProvider.Create(dest); var policy = (SnapshotDeletionPolicy) Writer.Config.IndexDeletionPolicy; var commit = policy.Snapshot(); try { foreach (var file in commit.FileNames) { _dir.Copy(destDir, file, file, IOContext.READ_ONCE); } } finally { policy.Release(commit); Writer.DeleteUnusedFiles(); } } public void Dispose() => _disposable?.Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Reflection; namespace System.ComponentModel { /// <summary> /// Declares an array of attributes for a member and defines /// the properties and methods that give you access to the attributes in the array. /// All attributes must derive from <see cref='System.Attribute'/>. /// </summary> public abstract class MemberDescriptor { private readonly string _name; private readonly string _displayName; private readonly int _nameHash; private AttributeCollection _attributeCollection; private Attribute[] _attributes; private Attribute[] _originalAttributes; private bool _attributesFiltered; private bool _attributesFilled; private int _metadataVersion; private string _category; private string _description; private readonly object _lockCookie = new object(); /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and no attributes. /// </summary> protected MemberDescriptor(string name) : this(name, null) { } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and <paramref name="attributes "/> array. /// </summary> protected MemberDescriptor(string name, Attribute[] attributes) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException(SR.InvalidMemberName, nameof(name)); } _name = name; _displayName = name; _nameHash = name.GetHashCode(); if (attributes != null) { _attributes = attributes; _attributesFiltered = false; } _originalAttributes = _attributes; } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <see cref='System.ComponentModel.MemberDescriptor'/>. /// </summary> protected MemberDescriptor(MemberDescriptor descr) { if (descr == null) { throw new ArgumentNullException(nameof(descr)); } _name = descr.Name; _displayName = _name; _nameHash = _name?.GetHashCode() ?? 0; _attributes = new Attribute[descr.Attributes.Count]; descr.Attributes.CopyTo(_attributes, 0); _attributesFiltered = true; _originalAttributes = _attributes; } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the name in the specified /// <see cref='System.ComponentModel.MemberDescriptor'/> and the attributes /// in both the old <see cref='System.ComponentModel.MemberDescriptor'/> and the <see cref='System.Attribute'/> array. /// </summary> protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] newAttributes) { if (oldMemberDescriptor == null) { throw new ArgumentNullException(nameof(oldMemberDescriptor)); } _name = oldMemberDescriptor.Name; _displayName = oldMemberDescriptor.DisplayName; _nameHash = _name.GetHashCode(); List<Attribute> newList = new List<Attribute>(); if (oldMemberDescriptor.Attributes.Count != 0) { foreach (Attribute o in oldMemberDescriptor.Attributes) { newList.Add(o); } } if (newAttributes != null) { foreach (Attribute o in newAttributes) { newList.Add(o); } } _attributes = new Attribute[newList.Count]; newList.CopyTo(_attributes, 0); _attributesFiltered = false; _originalAttributes = _attributes; } /// <summary> /// Gets or sets an array of attributes. /// </summary> protected virtual Attribute[] AttributeArray { get { CheckAttributesValid(); FilterAttributesIfNeeded(); return _attributes; } set { lock (_lockCookie) { _attributes = value; _originalAttributes = value; _attributesFiltered = false; _attributeCollection = null; } } } /// <summary> /// Gets the collection of attributes for this member. /// </summary> public virtual AttributeCollection Attributes { get { CheckAttributesValid(); AttributeCollection attrs = _attributeCollection; if (attrs == null) { lock (_lockCookie) { attrs = CreateAttributeCollection(); _attributeCollection = attrs; } } return attrs; } } /// <summary> /// Gets the name of the category that the member belongs to, as specified /// in the <see cref='System.ComponentModel.CategoryAttribute'/>. /// </summary> public virtual string Category => _category ?? (_category = ((CategoryAttribute)Attributes[typeof(CategoryAttribute)]).Category); /// <summary> /// Gets the description of the member as specified in the <see cref='System.ComponentModel.DescriptionAttribute'/>. /// </summary> public virtual string Description => _description ?? (_description = ((DescriptionAttribute)Attributes[typeof(DescriptionAttribute)]).Description); /// <summary> /// Gets a value indicating whether the member is browsable as specified in the /// <see cref='System.ComponentModel.BrowsableAttribute'/>. /// </summary> public virtual bool IsBrowsable => ((BrowsableAttribute)Attributes[typeof(BrowsableAttribute)]).Browsable; /// <summary> /// Gets the name of the member. /// </summary> public virtual string Name => _name ?? ""; /// <summary> /// Gets the hash code for the name of the member as specified in <see cref='string.GetHashCode()'/>. /// </summary> protected virtual int NameHashCode => _nameHash; /// <summary> /// Determines whether this member should be set only at /// design time as specified in the <see cref='System.ComponentModel.DesignOnlyAttribute'/>. /// </summary> public virtual bool DesignTimeOnly => (DesignOnlyAttribute.Yes.Equals(Attributes[typeof(DesignOnlyAttribute)])); /// <summary> /// Gets the name that can be displayed in a window like a properties window. /// </summary> public virtual string DisplayName { get { if (!(Attributes[typeof(DisplayNameAttribute)] is DisplayNameAttribute displayNameAttr) || displayNameAttr.IsDefaultAttribute()) { return _displayName; } return displayNameAttr.DisplayName; } } /// <summary> /// Called each time we access the attributes on /// this member descriptor to give deriving classes /// a chance to change them on the fly. /// </summary> private void CheckAttributesValid() { if (_attributesFiltered) { if (_metadataVersion != TypeDescriptor.MetadataVersion) { _attributesFilled = false; _attributesFiltered = false; _attributeCollection = null; } } } /// <summary> /// Creates a collection of attributes using the /// array of attributes that you passed to the constructor. /// </summary> protected virtual AttributeCollection CreateAttributeCollection() { return new AttributeCollection(AttributeArray); } /// <summary> /// Compares this instance to the specified <see cref='System.ComponentModel.MemberDescriptor'/> to see if they are equivalent. /// NOTE: If you make a change here, you likely need to change GetHashCode() as well. /// </summary> public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.GetType() != GetType()) { return false; } MemberDescriptor mdObj = (MemberDescriptor)obj; FilterAttributesIfNeeded(); mdObj.FilterAttributesIfNeeded(); if (mdObj._nameHash != _nameHash) { return false; } if ((mdObj._category == null) != (_category == null) || (_category != null && !mdObj._category.Equals(_category))) { return false; } if ((mdObj._description == null) != (_description == null) || (_description != null && !mdObj._description.Equals(_description))) { return false; } if ((mdObj._attributes == null) != (_attributes == null)) { return false; } bool sameAttrs = true; if (_attributes != null) { if (_attributes.Length != mdObj._attributes.Length) { return false; } for (int i = 0; i < _attributes.Length; i++) { if (!_attributes[i].Equals(mdObj._attributes[i])) { sameAttrs = false; break; } } } return sameAttrs; } /// <summary> /// In an inheriting class, adds the attributes of the inheriting class to the /// specified list of attributes in the parent class. For duplicate attributes, /// the last one added to the list will be kept. /// </summary> protected virtual void FillAttributes(IList attributeList) { if (attributeList == null) { throw new ArgumentNullException(nameof(attributeList)); } if (_originalAttributes != null) { foreach (Attribute attr in _originalAttributes) { attributeList.Add(attr); } } } private void FilterAttributesIfNeeded() { if (!_attributesFiltered) { List<Attribute> list; if (!_attributesFilled) { list = new List<Attribute>(); try { FillAttributes(list); } catch (Exception) { } } else { list = new List<Attribute>(_attributes); } var map = new Dictionary<object, int>(); for (int i = 0; i < list.Count;) { int savedIndex = -1; object typeId = list[i]?.TypeId; if (typeId == null) { list.RemoveAt(i); } else if (!map.TryGetValue(typeId, out savedIndex)) { map.Add(typeId, i); i++; } else { list[savedIndex] = list[i]; list.RemoveAt(i); } } Attribute[] newAttributes = list.ToArray(); lock (_lockCookie) { _attributes = newAttributes; _attributesFiltered = true; _attributesFilled = true; _metadataVersion = TypeDescriptor.MetadataVersion; } } } /// <summary> /// Finds the given method through reflection. This method only looks for public methods. /// </summary> protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType) { return FindMethod(componentClass, name, args, returnType, true); } /// <summary> /// Finds the given method through reflection. /// </summary> protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType, bool publicOnly) { if (componentClass == null) { throw new ArgumentNullException(nameof(componentClass)); } MethodInfo result = null; if (publicOnly) { result = componentClass.GetMethod(name, args); } else { result = componentClass.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); } if (result != null && !result.ReturnType.IsEquivalentTo(returnType)) { result = null; } return result; } /// <summary> /// Try to keep this reasonable in [....] with Equals(). Specifically, /// if A.Equals(B) returns true, A &amp; B should have the same hash code. /// </summary> public override int GetHashCode() => _nameHash; /// <summary> /// This method returns the object that should be used during invocation of members. /// Normally the return value will be the same as the instance passed in. If /// someone associated another object with this instance, or if the instance is a /// custom type descriptor, GetInvocationTarget may return a different value. /// </summary> protected virtual object GetInvocationTarget(Type type, object instance) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return TypeDescriptor.GetAssociation(type, instance); } /// <summary> /// Gets a component site for the given component. /// </summary> protected static ISite GetSite(object component) => (component as IComponent)?.Site; [Obsolete("This method has been deprecated. Use GetInvocationTarget instead. https://go.microsoft.com/fwlink/?linkid=14202")] protected static object GetInvokee(Type componentClass, object component) { if (componentClass == null) { throw new ArgumentNullException(nameof(componentClass)); } if (component == null) { throw new ArgumentNullException(nameof(component)); } return TypeDescriptor.GetAssociation(componentClass, component); } } }
// 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.Win32.SafeHandles; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.Sys.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.Value; } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (IOException) when (!disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } private void FlushWriteBufferForWriteByte() { _asyncState?.Wait(); try { FlushWriteBuffer(); } finally { _asyncState?.Release(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> private int ReadSpan(Span<byte> destination) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (destination.Length >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(destination); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer()); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, destination.Length); new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < destination.Length) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(destination.Slice(bytesRead)); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary> /// <param name="buffer">The buffer into which data from the file is read.</param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(Span<byte> buffer) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference()) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length)); Debug.Assert(bytesRead <= buffer.Length); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_useAsyncIO) { if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= count) { try { PrepareForReading(); Buffer.BlockCopy(GetBuffer(), _readPos, buffer, offset, count); _readPos += count; return _asyncState._lastSuccessfulReadTask != null && _asyncState._lastSuccessfulReadTask.Result == count ? _asyncState._lastSuccessfulReadTask : (_asyncState._lastSuccessfulReadTask = Task.FromResult(count)); } catch (Exception exc) { return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.Update(buffer, offset, count); return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { byte[] b = thisRef._asyncState._buffer; thisRef._asyncState._buffer = null; // remove reference to user's buffer return thisRef.ReadSpan(new Span<byte>(b, thisRef._asyncState._offset, thisRef._asyncState._count)); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } else { return base.ReadAsync(buffer, offset, count, cancellationToken); } } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() { _asyncState?.Wait(); try { return ReadNative(_buffer); } finally { _asyncState?.Release(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private void WriteSpan(ReadOnlySpan<byte> source) { PrepareForWriting(); // If no data is being written, nothing more to do. if (source.Length == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += source.Length; return; } else if (spaceRemaining > 0) { source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += spaceRemaining; source = source.Slice(spaceRemaining); } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (source.Length >= _bufferLength) { WriteNative(source); } else { source.CopyTo(new Span<byte>(GetBuffer())); _writePos = source.Length; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private unsafe void WriteNative(ReadOnlySpan<byte> source) { VerifyOSHandlePosition(); fixed (byte* bufPtr = &source.DangerousGetPinnableReference()) { int offset = 0; int count = source.Length; while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); _filePosition += bytesWritten; offset += bytesWritten; count -= bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_useAsyncIO) { if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= count) { try { PrepareForWriting(); Buffer.BlockCopy(buffer, offset, GetBuffer(), _writePos, count); _writePos += count; return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.Update(buffer, offset, count); return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position/length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { byte[] b = thisRef._asyncState._buffer; thisRef._asyncState._buffer = null; // remove reference to user's buffer thisRef.WriteSpan(new ReadOnlySpan<byte>(b, thisRef._asyncState._offset, thisRef._asyncState._count)); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } else { return base.WriteAsync(buffer, offset, count, cancellationToken); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { /// <summary>The caller's buffer currently being used by the active async operation.</summary> internal byte[] _buffer; /// <summary>The caller's offset currently being used by the active async operation.</summary> internal int _offset; /// <summary>The caller's count currently being used by the active async operation.</summary> internal int _count; /// <summary>The last task successfully, synchronously returned task from ReadAsync.</summary> internal Task<int> _lastSuccessfulReadTask; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } /// <summary>Sets the active buffer, offset, and count.</summary> internal void Update(byte[] buffer, int offset, int count) { _buffer = buffer; _offset = offset; _count = count; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using 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 Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.SiteRecovery.Models; using Microsoft.Azure.Management.SiteRecoveryVault; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.SiteRecoveryVault { /// <summary> /// Definition of vault extended info operations for the Site Recovery /// extension. /// </summary> internal partial class VaultExtendedInfoOperations : IServiceOperations<SiteRecoveryVaultManagementClient>, IVaultExtendedInfoOperations { /// <summary> /// Initializes a new instance of the VaultExtendedInfoOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VaultExtendedInfoOperations(SiteRecoveryVaultManagementClient client) { this._client = client; } private SiteRecoveryVaultManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.SiteRecoveryVaultManagementClient. /// </summary> public SiteRecoveryVaultManagementClient Client { get { return this._client; } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Required. Create resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs == null) { throw new ArgumentNullException("extendedInfoArgs"); } if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } // 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("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CreateExtendedInfoAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); 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 httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject resourceExtendedInformationArgsValue = new JObject(); requestDoc = resourceExtendedInformationArgsValue; resourceExtendedInformationArgsValue["ContractVersion"] = extendedInfoArgs.ContractVersion; resourceExtendedInformationArgsValue["ExtendedInfo"] = extendedInfoArgs.ExtendedInfo; resourceExtendedInformationArgsValue["ExtendedInfoETag"] = extendedInfoArgs.ExtendedInfoETag; 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.BadRequest) { 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> GetExtendedInfoAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // 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("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetExtendedInfoAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); 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 httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["extendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["extendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } 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> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Optional. Update resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs != null) { if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } } // 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("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateExtendedInfoAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["extendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["extendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } 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> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='parameters'> /// Required. Upload Vault Certificate input parameters. /// </param> /// <param name='certFriendlyName'> /// Required. Certificate friendly name /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the upload certificate response /// </returns> public async Task<UploadCertificateResponse> UploadCertificateAsync(string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (certFriendlyName == null) { throw new ArgumentNullException("certFriendlyName"); } // 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("resourceName", resourceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("certFriendlyName", certFriendlyName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UploadCertificateAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certFriendlyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-08-15"); 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 httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject parametersValue = new JObject(); requestDoc = parametersValue; if (parameters.Properties != null) { if (parameters.Properties is ILazyCollection == false || ((ILazyCollection)parameters.Properties).IsInitialized) { JObject propertiesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties) { string propertiesKey = pair.Key; string propertiesValue = pair.Value; propertiesDictionary[propertiesKey] = propertiesValue; } parametersValue["properties"] = propertiesDictionary; } } 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) { 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 UploadCertificateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UploadCertificateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { CertificateProperties propertiesInstance = new CertificateProperties(); result.Properties = propertiesInstance; JToken friendlyNameValue = propertiesValue2["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); propertiesInstance.FriendlyName = friendlyNameInstance; } JToken globalAcsHostNameValue = propertiesValue2["globalAcsHostName"]; if (globalAcsHostNameValue != null && globalAcsHostNameValue.Type != JTokenType.Null) { string globalAcsHostNameInstance = ((string)globalAcsHostNameValue); propertiesInstance.GlobalAcsHostName = globalAcsHostNameInstance; } JToken globalAcsNamespaceValue = propertiesValue2["globalAcsNamespace"]; if (globalAcsNamespaceValue != null && globalAcsNamespaceValue.Type != JTokenType.Null) { string globalAcsNamespaceInstance = ((string)globalAcsNamespaceValue); propertiesInstance.GlobalAcsNamespace = globalAcsNamespaceInstance; } JToken globalAcsRPRealmValue = propertiesValue2["globalAcsRPRealm"]; if (globalAcsRPRealmValue != null && globalAcsRPRealmValue.Type != JTokenType.Null) { string globalAcsRPRealmInstance = ((string)globalAcsRPRealmValue); propertiesInstance.GlobalAcsRPRealm = globalAcsRPRealmInstance; } JToken resourceIdValue = propertiesValue2["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } JToken clientRequestIdValue = responseDoc["ClientRequestId"]; if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null) { string clientRequestIdInstance = ((string)clientRequestIdValue); result.ClientRequestId = clientRequestIdInstance; } JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"]; if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null) { string correlationRequestIdInstance = ((string)correlationRequestIdValue); result.CorrelationRequestId = correlationRequestIdInstance; } JToken dateValue = responseDoc["Date"]; if (dateValue != null && dateValue.Type != JTokenType.Null) { string dateInstance = ((string)dateValue); result.Date = dateInstance; } JToken contentTypeValue = responseDoc["ContentType"]; if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null) { string contentTypeInstance = ((string)contentTypeValue); result.ContentType = contentTypeInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; #if !SILVERLIGHT && !NETSTANDARD1_0 namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Net; using System.Net.Mail; using System.Text; using System.IO; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; // For issue #1351 - These are not available for Android or IOS #if !__ANDROID__ && !__IOS__ using System.Configuration; #endif #if !__ANDROID__ && !__IOS__&& !NETSTANDARD using System.Net.Configuration; #endif /// <summary> /// Sends log messages by email using SMTP protocol. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" /> /// <p> /// Mail target works best when used with BufferingWrapper target /// which lets you send multiple log messages in single mail /// </p> /// <p> /// To set up the buffered mail target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" /> /// <p> /// To set up the buffered mail target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" /> /// </example> [Target("Mail")] public class MailTarget : TargetWithLayoutHeaderAndFooter { private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent."; private Layout _from; /// <summary> /// Initializes a new instance of the <see cref="MailTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")] public MailTarget() { Body = "${message}${newline}"; Subject = "Message from NLog on ${machinename}"; Encoding = Encoding.UTF8; SmtpPort = 25; SmtpAuthentication = SmtpAuthenticationMode.None; Timeout = 10000; } #if !__ANDROID__ && !__IOS__ && !NETSTANDARD private SmtpSection _currentailSettings; /// <summary> /// Gets the mailSettings/smtp configuration from app.config in cases when we need those configuration. /// E.g when UseSystemNetMailSettings is enabled and we need to read the From attribute from system.net/mailSettings/smtp /// </summary> /// <remarks>Internal for mocking</remarks> internal SmtpSection SmtpSection { get { if (_currentailSettings == null) { try { _currentailSettings = System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; } catch (Exception ex) { InternalLogger.Warn(ex, "MailTarget(Name={0}): Reading 'From' from .config failed.", Name); if (ex.MustBeRethrown()) { throw; } _currentailSettings = new SmtpSection(); } } return _currentailSettings; } set => _currentailSettings = value; } #endif /// <summary> /// Initializes a new instance of the <see cref="MailTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public MailTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets sender's email address (e.g. joe@domain.com). /// </summary> /// <docgen category='Message Options' order='10' /> public Layout From { get { #if !__ANDROID__ && !__IOS__ && !NETSTANDARD // In contrary to other settings, System.Net.Mail.SmtpClient doesn't read the 'From' attribute from the system.net/mailSettings/smtp section in the config file. // Thus, when UseSystemNetMailSettings is enabled we have to read the configuration section of system.net/mailSettings/smtp to initialize the 'From' address. // It will do so only if the 'From' attribute in system.net/mailSettings/smtp is not empty. //only use from config when not set in current if (UseSystemNetMailSettings && _from == null) { var from = SmtpSection.From; return from; } #endif return _from; } set { _from = value; } } /// <summary> /// Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='11' /> [RequiredParameter] public Layout To { get; set; } /// <summary> /// Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='12' /> public Layout CC { get; set; } /// <summary> /// Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='13' /> public Layout Bcc { get; set; } /// <summary> /// Gets or sets a value indicating whether to add new lines between log entries. /// </summary> /// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value> /// <docgen category='Message Options' order='99' /> public bool AddNewLines { get; set; } /// <summary> /// Gets or sets the mail subject. /// </summary> /// <docgen category='Message Options' order='5' /> [DefaultValue("Message from NLog on ${machinename}")] [RequiredParameter] public Layout Subject { get; set; } /// <summary> /// Gets or sets mail message body (repeated for each log message send in one mail). /// </summary> /// <remarks>Alias for the <c>Layout</c> property.</remarks> /// <docgen category='Message Options' order='6' /> [DefaultValue("${message}${newline}")] public Layout Body { get => Layout; set => Layout = value; } /// <summary> /// Gets or sets encoding to be used for sending e-mail. /// </summary> /// <docgen category='Message Options' order='20' /> [DefaultValue("UTF8")] public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value indicating whether to send message as HTML instead of plain text. /// </summary> /// <docgen category='Message Options' order='11' /> [DefaultValue(false)] public bool Html { get; set; } /// <summary> /// Gets or sets SMTP Server to be used for sending. /// </summary> /// <docgen category='SMTP Options' order='10' /> public Layout SmtpServer { get; set; } /// <summary> /// Gets or sets SMTP Authentication mode. /// </summary> /// <docgen category='SMTP Options' order='11' /> [DefaultValue("None")] public SmtpAuthenticationMode SmtpAuthentication { get; set; } /// <summary> /// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='12' /> public Layout SmtpUserName { get; set; } /// <summary> /// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='13' /> public Layout SmtpPassword { get; set; } /// <summary> /// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server. /// </summary> /// <docgen category='SMTP Options' order='14' />. [DefaultValue(false)] public bool EnableSsl { get; set; } /// <summary> /// Gets or sets the port number that SMTP Server is listening on. /// </summary> /// <docgen category='SMTP Options' order='15' /> [DefaultValue(25)] public int SmtpPort { get; set; } /// <summary> /// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used. /// </summary> /// <docgen category='SMTP Options' order='16' /> [DefaultValue(false)] public bool UseSystemNetMailSettings { get; set; } /// <summary> /// Specifies how outgoing email messages will be handled. /// </summary> /// <docgen category='SMTP Options' order='18' /> [DefaultValue(SmtpDeliveryMethod.Network)] public SmtpDeliveryMethod DeliveryMethod { get; set; } /// <summary> /// Gets or sets the folder where applications save mail messages to be processed by the local SMTP server. /// </summary> /// <docgen category='SMTP Options' order='17' /> [DefaultValue(null)] public string PickupDirectoryLocation { get; set; } /// <summary> /// Gets or sets the priority used for sending mails. /// </summary> /// <docgen category='Message Options' order='100' /> public Layout Priority { get; set; } /// <summary> /// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags. /// </summary> /// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks> /// <docgen category='Message Options' order='100' /> [DefaultValue(false)] public bool ReplaceNewlineWithBrTagInHtml { get; set; } /// <summary> /// Gets or sets a value indicating the SMTP client timeout. /// </summary> /// <remarks>Warning: zero is not infinite waiting</remarks> /// <docgen category='SMTP Options' order='100' /> [DefaultValue(10000)] public int Timeout { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method.")] internal virtual ISmtpClient CreateSmtpClient() { return new MySmtpClient(); } /// <summary> /// Renders the logging event message and adds it to the internal ArrayList of log messages. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { Write((IList<AsyncLogEventInfo>)new[] { logEvent }); } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected override void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Renders an array logging events. /// </summary> /// <param name="logEvents">Array of logging events.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { var buckets = logEvents.BucketSort(c => GetSmtpSettingsKey(c.LogEvent)); foreach (var bucket in buckets) { var eventInfos = bucket.Value; ProcessSingleMailMessage(eventInfos); } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected override void InitializeTarget() { CheckRequiredParameters(); base.InitializeTarget(); } /// <summary> /// Create mail and send with SMTP /// </summary> /// <param name="events">event printed in the body of the event</param> private void ProcessSingleMailMessage([NotNull] IList<AsyncLogEventInfo> events) { try { if (events.Count == 0) { throw new NLogRuntimeException("We need at least one event."); } LogEventInfo firstEvent = events[0].LogEvent; LogEventInfo lastEvent = events[events.Count - 1].LogEvent; // unbuffered case, create a local buffer, append header, body and footer var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent); using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString())) { using (ISmtpClient client = CreateSmtpClient()) { if (!UseSystemNetMailSettings) { ConfigureMailClient(lastEvent, client); } if (client.EnableSsl) InternalLogger.Debug("MailTarget(Name={0}): Sending mail to {1} using {2}:{3} (ssl=true)", Name, msg.To, client.Host, client.Port); else InternalLogger.Debug("MailTarget(Name={0}): Sending mail to {1} using {2}:{3} (ssl=false)", Name, msg.To, client.Host, client.Port); InternalLogger.Trace("MailTarget(Name={0}): Subject: '{1}'", Name, msg.Subject); InternalLogger.Trace("MailTarget(Name={0}): From: '{1}'", Name, msg.From.ToString()); client.Send(msg); foreach (var ev in events) { ev.Continuation(null); } } } } catch (Exception exception) { //always log InternalLogger.Error(exception, "MailTarget(Name={0}): Error sending mail.", Name); if (exception.MustBeRethrown()) { throw; } foreach (var ev in events) { ev.Continuation(exception); } } } /// <summary> /// Create buffer for body /// </summary> /// <param name="events">all events</param> /// <param name="firstEvent">first event for header</param> /// <param name="lastEvent">last event for footer</param> /// <returns></returns> private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent) { var bodyBuffer = new StringBuilder(); if (Header != null) { bodyBuffer.Append(Header.Render(firstEvent)); if (AddNewLines) { bodyBuffer.Append("\n"); } } foreach (AsyncLogEventInfo eventInfo in events) { bodyBuffer.Append(Layout.Render(eventInfo.LogEvent)); if (AddNewLines) { bodyBuffer.Append("\n"); } } if (Footer != null) { bodyBuffer.Append(Footer.Render(lastEvent)); if (AddNewLines) { bodyBuffer.Append("\n"); } } return bodyBuffer; } /// <summary> /// Set properties of <paramref name="client"/> /// </summary> /// <param name="lastEvent">last event for username/password</param> /// <param name="client">client to set properties on</param> /// <remarks>Configure not at <see cref="InitializeTarget"/>, as the properties could have layout renderers.</remarks> internal void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client) { CheckRequiredParameters(); if (SmtpServer == null && string.IsNullOrEmpty(PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation")); } if (DeliveryMethod == SmtpDeliveryMethod.Network && SmtpServer == null) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer")); } if (DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation")); } if (SmtpServer != null && DeliveryMethod == SmtpDeliveryMethod.Network) { var renderedSmtpServer = SmtpServer.Render(lastEvent); if (string.IsNullOrEmpty(renderedSmtpServer)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer")); } client.Host = renderedSmtpServer; client.Port = SmtpPort; client.EnableSsl = EnableSsl; if (SmtpAuthentication == SmtpAuthenticationMode.Ntlm) { InternalLogger.Trace("MailTarget(Name={0}): Using NTLM authentication.", Name); client.Credentials = CredentialCache.DefaultNetworkCredentials; } else if (SmtpAuthentication == SmtpAuthenticationMode.Basic) { string username = SmtpUserName.Render(lastEvent); string password = SmtpPassword.Render(lastEvent); InternalLogger.Trace("MailTarget(Name={0}): Using basic authentication: Username='{1}' Password='{2}'", Name, username, new string('*', password.Length)); client.Credentials = new NetworkCredential(username, password); } } if (!string.IsNullOrEmpty(PickupDirectoryLocation) && DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { client.PickupDirectoryLocation = ConvertDirectoryLocation(PickupDirectoryLocation); } // In case DeliveryMethod = PickupDirectoryFromIis we will not require Host nor PickupDirectoryLocation client.DeliveryMethod = DeliveryMethod; client.Timeout = Timeout; } /// <summary> /// Handle <paramref name="pickupDirectoryLocation"/> if it is a virtual directory. /// </summary> /// <param name="pickupDirectoryLocation"></param> /// <returns></returns> internal static string ConvertDirectoryLocation(string pickupDirectoryLocation) { const string virtualPathPrefix = "~/"; if (!pickupDirectoryLocation.StartsWith(virtualPathPrefix)) { return pickupDirectoryLocation; } // Support for Virtual Paths var root = AppDomain.CurrentDomain.BaseDirectory; var directory = pickupDirectoryLocation.Substring(virtualPathPrefix.Length).Replace('/', Path.DirectorySeparatorChar); var pickupRoot = Path.Combine(root, directory); return pickupRoot; } private void CheckRequiredParameters() { if (!UseSystemNetMailSettings && SmtpServer == null && DeliveryMethod == SmtpDeliveryMethod.Network) { throw new NLogConfigurationException("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=Network. The email message will not be sent.", "SmtpServer"); } if (!UseSystemNetMailSettings && string.IsNullOrEmpty(PickupDirectoryLocation) && DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { throw new NLogConfigurationException("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=SpecifiedPickupDirectory. The email message will not be sent.", "PickupDirectoryLocation"); } if (From == null) { throw new NLogConfigurationException(RequiredPropertyIsEmptyFormat, "From"); } } /// <summary> /// Create key for grouping. Needed for multiple events in one mail message /// </summary> /// <param name="logEvent">event for rendering layouts </param> ///<returns>string to group on</returns> private string GetSmtpSettingsKey(LogEventInfo logEvent) { var sb = new StringBuilder(); AppendLayout(sb, logEvent, From); AppendLayout(sb, logEvent, To); AppendLayout(sb, logEvent, CC); AppendLayout(sb, logEvent, Bcc); AppendLayout(sb, logEvent, SmtpServer); AppendLayout(sb, logEvent, SmtpPassword); AppendLayout(sb, logEvent, SmtpUserName); return sb.ToString(); } /// <summary> /// Append rendered <paramref name="layout"/> to <paramref name="sb"/> /// </summary> /// <param name="sb">append to this</param> /// <param name="logEvent">event for rendering <paramref name="layout"/></param> /// <param name="layout">append if not <c>null</c></param> private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout) { sb.Append("|"); if (layout != null) sb.Append(layout.Render(logEvent)); } /// <summary> /// Create the mail message with the addresses, properties and body. /// </summary> private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body) { var msg = new MailMessage(); var renderedFrom = From?.Render(lastEvent); if (string.IsNullOrEmpty(renderedFrom)) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From"); } msg.From = new MailAddress(renderedFrom); var addedTo = AddAddresses(msg.To, To, lastEvent); var addedCc = AddAddresses(msg.CC, CC, lastEvent); var addedBcc = AddAddresses(msg.Bcc, Bcc, lastEvent); if (!addedTo && !addedCc && !addedBcc) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc"); } msg.Subject = Subject == null ? string.Empty : Subject.Render(lastEvent).Trim(); msg.BodyEncoding = Encoding; msg.IsBodyHtml = Html; if (Priority != null) { var renderedPriority = Priority.Render(lastEvent); if (string.IsNullOrEmpty(renderedPriority)) { msg.Priority = MailPriority.Normal; } else if (ConversionHelpers.TryParseEnum(renderedPriority, out MailPriority mailPriority)) { msg.Priority = mailPriority; } else { msg.Priority = MailPriority.Normal; InternalLogger.Warn("MailTarget(Name={0}): Could not convert '{1}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback.", Name, renderedPriority); } } msg.Body = body; if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null) msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>"); return msg; } /// <summary> /// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/> /// </summary> /// <param name="mailAddressCollection">Addresses appended to this list</param> /// <param name="layout">layout with addresses, ; separated</param> /// <param name="logEvent">event for rendering the <paramref name="layout"/></param> /// <returns>added a address?</returns> private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent) { var added = false; if (layout != null) { foreach (string mail in layout.Render(logEvent).SplitAndTrimTokens(';')) { mailAddressCollection.Add(mail); added = true; } } return added; } } } #endif
/* * Base oAuth Class for Twitter and LinkedIn * Author: Eran Sandler * Code Url: http://oauth.net/code/ * Author Url: http://eran.sandler.co.il/ * * Some modifications by Shannon Whitley * Author Url: http://voiceoftech.com/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ namespace YAF.Core.Services.Auth { #region using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; using YAF.Types.Extensions; #endregion /// <summary> /// Oauth implementation by shannon whitley /// </summary> public class OAuthBase { #region Constants and Fields /// <summary> /// The hmacsh a 1 signature type. /// </summary> protected const string HMACSHA1SignatureType = "HMAC-SHA1"; /// <summary> /// The o auth callback key. /// </summary> protected const string OAuthCallbackKey = "oauth_callback"; /// <summary> /// The o auth consumer key key. /// </summary> protected const string OAuthConsumerKeyKey = "oauth_consumer_key"; /// <summary> /// The o auth nonce key. /// </summary> protected const string OAuthNonceKey = "oauth_nonce"; /// <summary> /// The o auth parameter prefix. /// </summary> protected const string OAuthParameterPrefix = "oauth_"; /// <summary> /// The o auth signature key. /// </summary> protected const string OAuthSignatureKey = "oauth_signature"; /// <summary> /// The o auth signature method key. /// </summary> protected const string OAuthSignatureMethodKey = "oauth_signature_method"; /// <summary> /// The o auth timestamp key. /// </summary> protected const string OAuthTimestampKey = "oauth_timestamp"; /// <summary> /// The o auth token key. /// </summary> protected const string OAuthTokenKey = "oauth_token"; /// <summary> /// The o auth token secret key. /// </summary> protected const string OAuthTokenSecretKey = "oauth_token_secret"; /// <summary> /// The o auth verifier key. /// </summary> protected const string OAuthVerifierKey = "oauth_verifier"; /// <summary> /// The o auth version. /// </summary> protected const string OAuthVersion = "1.0"; /// <summary> /// The o auth version key. /// </summary> protected const string OAuthVersionKey = "oauth_version"; /// <summary> /// The plain text signature type. /// </summary> protected const string PlainTextSignatureType = "PLAINTEXT"; /// <summary> /// The rsash a 1 signature type. /// </summary> protected const string RSASHA1SignatureType = "RSA-SHA1"; /// <summary> /// The random. /// </summary> private readonly Random random = new Random(); /// <summary> /// The unreserved chars. /// </summary> private const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; #endregion #region Enums /// <summary> /// Provides a predefined set of algorithms that are supported officially by the protocol /// </summary> public enum SignatureTypes { /// <summary> /// The hmacsh a 1. /// </summary> HMACSHA1, /// <summary> /// The plaintext. /// </summary> PLAINTEXT, /// <summary> /// The rsash a 1. /// </summary> RSASHA1 } #endregion #region Public Methods /// <summary> /// Generate a nonce /// </summary> /// <returns> /// The generate nonce. /// </returns> public virtual string GenerateNonce() { return this.random.Next(123400, 9999999).ToString(); } /// <summary> /// Generates a signature using the HMAC-SHA1 algorithm /// </summary> /// <param name="url"> /// The full url that needs to be signed including its non OAuth url parameters /// </param> /// <param name="consumerKey"> /// The consumer key /// </param> /// <param name="consumerSecret"> /// The consumer seceret /// </param> /// <param name="token"> /// The token, if available. If not available pass null or an empty string /// </param> /// <param name="tokenSecret"> /// The token secret, if available. If not available pass null or an empty string /// </param> /// <param name="callBackUrl"> /// The call Back Url. /// </param> /// <param name="httpMethod"> /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc) /// </param> /// <param name="timeStamp"> /// The time Stamp. /// </param> /// <param name="nonce"> /// The nonce. /// </param> /// <param name="pin"> /// The PIN. /// </param> /// <param name="normalizedUrl"> /// The normalized Url. /// </param> /// <param name="normalizedRequestParameters"> /// The normalized Request Parameters. /// </param> /// <returns> /// A base64 string of the hash value /// </returns> public string GenerateSignature( Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string callBackUrl, string httpMethod, string timeStamp, string nonce, string pin, out string normalizedUrl, out string normalizedRequestParameters) { return this.GenerateSignature( url, consumerKey, consumerSecret, token, tokenSecret, callBackUrl, httpMethod, timeStamp, nonce, pin, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters); } /// <summary> /// Generates a signature using the specified signatureType /// </summary> /// <param name="url"> /// The full url that needs to be signed including its non OAuth url parameters /// </param> /// <param name="consumerKey"> /// The consumer key /// </param> /// <param name="consumerSecret"> /// The consumer seceret /// </param> /// <param name="token"> /// The token, if available. If not available pass null or an empty string /// </param> /// <param name="tokenSecret"> /// The token secret, if available. If not available pass null or an empty string /// </param> /// <param name="callBackUrl"> /// The call Back Url. /// </param> /// <param name="httpMethod"> /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc) /// </param> /// <param name="timeStamp"> /// The time Stamp. /// </param> /// <param name="nonce"> /// The nonce. /// </param> /// <param name="pin"> /// The PIN. /// </param> /// <param name="signatureType"> /// The type of signature to use /// </param> /// <param name="normalizedUrl"> /// The normalized Url. /// </param> /// <param name="normalizedRequestParameters"> /// The normalized Request Parameters. /// </param> /// <returns> /// A base64 string of the hash value /// </returns> /// <exception cref="ArgumentException">Unknown signature type</exception> public string GenerateSignature( Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string callBackUrl, string httpMethod, string timeStamp, string nonce, string pin, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) { normalizedUrl = null; normalizedRequestParameters = null; switch (signatureType) { case SignatureTypes.PLAINTEXT: return HttpUtility.UrlEncode($"{consumerSecret}&{tokenSecret}"); case SignatureTypes.HMACSHA1: var signatureBase = this.GenerateSignatureBase( url, consumerKey, token, tokenSecret, callBackUrl, httpMethod, timeStamp, nonce, pin, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters); var hmacsha1 = new HMACSHA1 { Key = Encoding.ASCII.GetBytes( $"{this.UrlEncode(consumerSecret)}&{(tokenSecret.IsNotSet() ? string.Empty : this.UrlEncode(tokenSecret))}") }; return this.GenerateSignatureUsingHash(signatureBase, hmacsha1); default: throw new ArgumentException("Unknown signature type", nameof(signatureType)); } } /// <summary> /// Generate the signature base that is used to produce the signature /// </summary> /// <param name="url"> /// The full url that needs to be signed including its non OAuth url parameters /// </param> /// <param name="consumerKey"> /// The consumer key /// </param> /// <param name="token"> /// The token, if available. If not available pass null or an empty string /// </param> /// <param name="tokenSecret"> /// The token secret, if available. If not available pass null or an empty string /// </param> /// <param name="callBackUrl"> /// The call Back Url. /// </param> /// <param name="httpMethod"> /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc) /// </param> /// <param name="timeStamp"> /// The time Stamp. /// </param> /// <param name="nonce"> /// The nonce. /// </param> /// <param name="pin"> /// The PIN. /// </param> /// <param name="signatureType"> /// The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>. /// </param> /// <param name="normalizedUrl"> /// The normalized Url. /// </param> /// <param name="normalizedRequestParameters"> /// The normalized Request Parameters. /// </param> /// <returns> /// The signature base /// </returns> /// <exception cref="ArgumentNullException">ConsumerKey Not found</exception> public string GenerateSignatureBase( Uri url, string consumerKey, string token, string tokenSecret, string callBackUrl, string httpMethod, string timeStamp, string nonce, string pin, string signatureType, out string normalizedUrl, out string normalizedRequestParameters) { if (token == null) { token = string.Empty; } if (consumerKey.IsNotSet()) { throw new ArgumentNullException(nameof(consumerKey)); } if (httpMethod.IsNotSet()) { throw new ArgumentNullException(nameof(httpMethod)); } if (signatureType.IsNotSet()) { throw new ArgumentNullException(nameof(signatureType)); } var parameters = GetQueryParameters(url.Query); parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion)); parameters.Add(new QueryParameter(OAuthNonceKey, nonce)); parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp)); parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType)); parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey)); if (callBackUrl.IsSet()) { parameters.Add(new QueryParameter(OAuthCallbackKey, this.UrlEncode(callBackUrl))); } if (token.IsSet()) { parameters.Add(new QueryParameter(OAuthTokenKey, token)); } // Pin Based Authentication if (pin.IsSet()) { parameters.Add(new QueryParameter(OAuthVerifierKey, pin)); } parameters.Sort(new QueryParameterComparer()); normalizedUrl = $"{url.Scheme}://{url.Host}"; if (!(url.Scheme == "http" && url.Port == 80 || url.Scheme == "https" && url.Port == 443)) { normalizedUrl += $":{url.Port}"; } normalizedUrl += url.AbsolutePath; normalizedRequestParameters = this.NormalizeRequestParameters(parameters); var signatureBase = new StringBuilder(); signatureBase.AppendFormat("{0}&", httpMethod.ToUpper()); signatureBase.AppendFormat("{0}&", this.UrlEncode(normalizedUrl)); signatureBase.AppendFormat("{0}", this.UrlEncode(normalizedRequestParameters)); return signatureBase.ToString(); } /// <summary> /// Generate the signature value based on the given signature base and hash algorithm /// </summary> /// <param name="signatureBase"> /// The signature based as produced by the GenerateSignatureBase method or by any other means /// </param> /// <param name="hash"> /// The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method /// </param> /// <returns> /// A base64 string of the hash value /// </returns> public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) { return this.ComputeHash(hash, signatureBase); } /// <summary> /// Generates timestamp for the signature /// </summary> /// <returns> /// The generate time stamp. /// </returns> public virtual string GenerateTimeStamp() { var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return ts.TotalSeconds.ToType<long>().ToString(); } #endregion #region Methods /// <summary> /// Normalizes the request parameters according to the spec /// </summary> /// <param name="parameters"> /// The list of parameters already sorted /// </param> /// <returns> /// a string representing the normalized parameters /// </returns> protected string NormalizeRequestParameters(IList<QueryParameter> parameters) { var sb = new StringBuilder(); for (var i = 0; i < parameters.Count; i++) { var p = parameters[i]; sb.AppendFormat("{0}={1}", p.Name, p.Value); if (i < parameters.Count - 1) { sb.Append("&"); } } return sb.ToString(); } /// <summary> /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth /// </summary> /// <param name="value"> /// The value to Url encode /// </param> /// <returns> /// Returns a Url encoded string /// </returns> protected string UrlEncode(string value) { var result = new StringBuilder(); foreach (var symbol in value) { if (UnreservedChars.IndexOf(symbol) != -1) { result.Append(symbol); } else { result.AppendFormat("{0}{1}", '%', $"{(int)symbol:X2}"); } } return result.ToString(); } /// <summary> /// Helper function to compute a hash value /// </summary> /// <param name="hashAlgorithm"> /// The hashing algorithm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function /// </param> /// <param name="data"> /// The data to hash /// </param> /// <returns> /// a Base64 string of the hash value /// </returns> /// <exception cref="ArgumentNullException">hash Algorithm</exception> private string ComputeHash(HashAlgorithm hashAlgorithm, string data) { if (hashAlgorithm == null) { throw new ArgumentNullException(nameof(hashAlgorithm)); } if (data.IsNotSet()) { throw new ArgumentNullException(nameof(data)); } var dataBuffer = Encoding.ASCII.GetBytes(data); var hashBytes = hashAlgorithm.ComputeHash(dataBuffer); return Convert.ToBase64String(hashBytes); } /// <summary> /// Internal function to cut out all non oauth query string parameters (all parameters not beginning with "oauth_") /// </summary> /// <param name="parameters"> /// The query string part of the Url /// </param> /// <returns> /// A list of QueryParameter each containing the parameter name and value /// </returns> private static List<QueryParameter> GetQueryParameters(string parameters) { if (parameters.StartsWith("?")) { parameters = parameters.Remove(0, 1); } var result = new List<QueryParameter>(); if (parameters.IsNotSet()) { return result; } var p = parameters.Split('&'); foreach (var s in p.Where(s => s.IsSet() && !s.StartsWith(OAuthParameterPrefix))) { if (s.IndexOf('=') > -1) { var temp = s.Split('='); result.Add(new QueryParameter(temp[0], temp[1])); } else { result.Add(new QueryParameter(s, string.Empty)); } } return result; } #endregion /// <summary> /// Provides an internal structure to sort the query parameter /// </summary> protected class QueryParameter { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="QueryParameter"/> class. /// </summary> /// <param name="name"> /// The name. /// </param> /// <param name="value"> /// The value. /// </param> public QueryParameter(string name, string value) { this.Name = name; this.Value = value; } #endregion #region Properties /// <summary> /// Gets Name. /// </summary> public string Name { get; } /// <summary> /// Gets Value. /// </summary> public string Value { get; } #endregion } /// <summary> /// Comparer class used to perform the sorting of the query parameters /// </summary> protected class QueryParameterComparer : IComparer<QueryParameter> { #region Implemented Interfaces #region IComparer<QueryParameter> /// <summary> /// Compares the specified x. /// </summary> /// <param name="x"> /// The x. /// </param> /// <param name="y"> /// The y. /// </param> /// <returns> /// The compare. /// </returns> public int Compare(QueryParameter x, QueryParameter y) { return x.Name == y.Name ? string.CompareOrdinal(x.Value, y.Value) : string.CompareOrdinal(x.Name, y.Name); } #endregion #endregion } } }
// // Color.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.ComponentModel; namespace Xwt.Drawing { struct Color { double r, g, b, a; [NonSerialized] HslColor hsl; public double Red { get { return r; } set { r = Normalize (value); hsl = null; } } public double Green { get { return g; } set { g = Normalize (value); hsl = null; } } public double Blue { get { return b; } set { b = Normalize (value); hsl = null; } } public double Alpha { get { return a; } set { a = Normalize (value); } } public double Hue { get { return Hsl.H; } set { Hsl = new HslColor (Normalize (value), Hsl.S, Hsl.L); } } public double Saturation { get { return Hsl.S; } set { Hsl = new HslColor (Hsl.H, Normalize (value), Hsl.L); } } public double Light { get { return Hsl.L; } set { Hsl = new HslColor (Hsl.H, Hsl.S, Normalize (value)); } } double Normalize (double v) { if (v < 0) return 0; if (v > 1) return 1; return v; } public double Brightness { get { return System.Math.Sqrt (Red * .241 + Green * .691 + Blue * .068); } } HslColor Hsl { get { if (hsl == null) hsl = (HslColor)this; return hsl; } set { hsl = value; Color c = (Color)value; r = c.r; b = c.b; g = c.g; } } public Color (double red, double green, double blue): this () { Red = red; Green = green; Blue = blue; Alpha = 1f; } public Color (double red, double green, double blue, double alpha): this () { Red = red; Green = green; Blue = blue; Alpha = alpha; } public Color WithAlpha (double alpha) { Color c = this; c.Alpha = alpha; return c; } public Color WithIncreasedLight (double lightIncrement) { Color c = this; c.Light += lightIncrement; return c; } /// <summary> /// Returns a color which looks more contrasted (or less, if amount is negative) /// </summary> /// <returns>The new color</returns> /// <param name="amount">Amount to change (can be positive or negative).</param> /// <remarks> /// This method adds or removes light to/from the color to make it more contrasted when /// compared to a neutral grey. /// The resulting effect is that light colors are made lighter, and dark colors /// are made darker. If the amount is negative, the effect is inversed (colors are /// made less contrasted) /// </remarks> public Color WithIncreasedContrast (double amount) { return WithIncreasedContrast (new Color (0.5, 0.5, 0.5), amount); } /// <summary> /// Returns a color which looks more contrasted (or less, if amount is negative) with /// respect to a provided reference color. /// </summary> /// <returns>The new color</returns> /// <param name="referenceColor">Reference color.</param> /// <param name="amount">Amount to change (can be positive or negative).</param> public Color WithIncreasedContrast (Color referenceColor, double amount) { Color c = this; if (referenceColor.Light > Light) c.Light -= amount; else c.Light += amount; return c; } public Color BlendWith (Color target, double amount) { if (amount < 0 || amount > 1) throw new ArgumentException ("Blend amount must be between 0 and 1"); return new Color (BlendValue (r, target.r, amount), BlendValue (g, target.g, amount), BlendValue (b, target.b, amount), target.Alpha); } double BlendValue (double s, double t, double amount) { return s + (t - s) * amount; } public static Color FromBytes (byte red, byte green, byte blue) { return FromBytes (red, green, blue, 255); } public static Color FromBytes (byte red, byte green, byte blue, byte alpha) { return new Color { Red = ((double)red) / 255.0, Green = ((double)green) / 255.0, Blue = ((double)blue) / 255.0, Alpha = ((double)alpha) / 255.0 }; } public static Color FromHsl (double h, double s, double l) { return FromHsl (h, s, l, 1); } public static Color FromHsl (double h, double s, double l, double alpha) { HslColor hsl = new HslColor (h, s, l); Color c = (Color)hsl; c.Alpha = alpha; c.hsl = hsl; return c; } public static Color FromName (string name) { Color color; TryParse (name, out color); return color; } public static bool TryParse (string name, out Color color) { if (name == null) throw new ArgumentNullException ("name"); uint val; if (name.Length == 0 || !TryParseColourFromHex (name, out val)) { color = default (Color); return false; } color = Color.FromBytes ((byte)(val >> 24), (byte)((val >> 16) & 0xff), (byte)((val >> 8) & 0xff), (byte)(val & 0xff)); return true; } static bool TryParseColourFromHex (string str, out uint val) { val = 0; if (str[0] != '#' || str.Length > 9) return false; if (!uint.TryParse (str.Substring (1), System.Globalization.NumberStyles.HexNumber, null, out val)) return false; val = val << ((9 - str.Length) * 4); if (str.Length <= 7) val |= 0xff; return true; } public static bool operator == (Color c1, Color c2) { return c1.r == c2.r && c1.g == c2.g && c1.b == c2.b && c1.a == c2.a; } public static bool operator != (Color c1, Color c2) { return c1.r != c2.r || c1.g != c2.g || c1.b != c2.b || c1.a != c2.a; } public override bool Equals (object o) { if (!(o is Color)) return false; return (this == (Color) o); } public override int GetHashCode () { unchecked { var hash = r.GetHashCode (); hash = (hash * 397) ^ g.GetHashCode (); hash = (hash * 397) ^ b.GetHashCode (); hash = (hash * 397) ^ a.GetHashCode (); return hash; } } public override string ToString () { return string.Format ("[Color: Red={0}, Green={1}, Blue={2}, Alpha={3}]", Red, Green, Blue, Alpha); } public string ToHexString () { return "#" + ((int)(Red * 255)).ToString ("x2") + ((int)(Green * 255)).ToString ("x2") + ((int)(Blue * 255)).ToString ("x2") + ((int)(Alpha * 255)).ToString ("x2"); } } }
/* * 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.Impl.Common { using System; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; /// <summary> /// Converts generic and non-generic delegates. /// </summary> public static class DelegateConverter { /** */ private const string DefaultMethodName = "Invoke"; /// <summary> /// Compiles a function without arguments. /// </summary> /// <param name="targetType">Type of the target.</param> /// <returns>Compiled function that calls specified method on specified target.</returns> public static Func<object, object> CompileFunc(Type targetType) { var method = targetType.GetMethod(DefaultMethodName); var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, targetType); var callExpr = Expression.Call(targetParamConverted, method); var convertResultExpr = Expression.Convert(callExpr, typeof(object)); return Expression.Lambda<Func<object, object>>(convertResultExpr, targetParam).Compile(); } /// <summary> /// Compiles a function with arbitrary number of arguments. /// </summary> /// <typeparam name="T">Resulting delegate type.</typeparam> /// <param name="targetType">Type of the target.</param> /// <param name="argTypes">Argument types.</param> /// <param name="convertToObject"> /// Flags that indicate whether func params and/or return value should be converted from/to object. /// </param> /// <param name="methodName">Name of the method.</param> /// <returns> /// Compiled function that calls specified method on specified target. /// </returns> public static T CompileFunc<T>(Type targetType, Type[] argTypes, bool[] convertToObject = null, string methodName = null) where T : class { var method = targetType.GetMethod(methodName ?? DefaultMethodName, argTypes); return CompileFunc<T>(targetType, method, argTypes, convertToObject); } /// <summary> /// Compiles a function with arbitrary number of arguments. /// </summary> /// <typeparam name="T">Resulting delegate type.</typeparam> /// <param name="method">Method.</param> /// <param name="targetType">Type of the target.</param> /// <param name="argTypes">Argument types.</param> /// <param name="convertToObject"> /// Flags that indicate whether func params and/or return value should be converted from/to object. /// </param> /// <returns> /// Compiled function that calls specified method on specified target. /// </returns> public static T CompileFunc<T>(Type targetType, MethodInfo method, Type[] argTypes, bool[] convertToObject = null) where T : class { if (argTypes == null) { var args = method.GetParameters(); argTypes = new Type[args.Length]; for (int i = 0; i < args.Length; i++) argTypes[i] = args[i].ParameterType; } Debug.Assert(convertToObject == null || (convertToObject.Length == argTypes.Length + 1)); Debug.Assert(method != null); targetType = method.IsStatic ? null : (targetType ?? method.DeclaringType); var targetParam = Expression.Parameter(typeof(object)); Expression targetParamConverted = null; ParameterExpression[] argParams; int argParamsOffset = 0; if (targetType != null) { targetParamConverted = Expression.Convert(targetParam, targetType); argParams = new ParameterExpression[argTypes.Length + 1]; argParams[0] = targetParam; argParamsOffset = 1; } else argParams = new ParameterExpression[argTypes.Length]; // static method var argParamsConverted = new Expression[argTypes.Length]; for (var i = 0; i < argTypes.Length; i++) { if (convertToObject == null || convertToObject[i]) { var argParam = Expression.Parameter(typeof (object)); argParams[i + argParamsOffset] = argParam; argParamsConverted[i] = Expression.Convert(argParam, argTypes[i]); } else { var argParam = Expression.Parameter(argTypes[i]); argParams[i + argParamsOffset] = argParam; argParamsConverted[i] = argParam; } } Expression callExpr = Expression.Call(targetParamConverted, method, argParamsConverted); if (convertToObject == null || convertToObject[argTypes.Length]) callExpr = Expression.Convert(callExpr, typeof(object)); return Expression.Lambda<T>(callExpr, argParams).Compile(); } /// <summary> /// Compiles a generic ctor with arbitrary number of arguments. /// </summary> /// <typeparam name="T">Result func type.</typeparam> /// <param name="ctor">Contructor info.</param> /// <param name="argTypes">Argument types.</param> /// <param name="convertResultToObject">if set to <c>true</c> [convert result to object]. /// Flag that indicates whether ctor return value should be converted to object.</param> /// <returns> /// Compiled generic constructor. /// </returns> public static T CompileCtor<T>(ConstructorInfo ctor, Type[] argTypes, bool convertResultToObject = true) { Debug.Assert(ctor != null); var args = new ParameterExpression[argTypes.Length]; var argsConverted = new Expression[argTypes.Length]; for (var i = 0; i < argTypes.Length; i++) { var arg = Expression.Parameter(typeof(object)); args[i] = arg; argsConverted[i] = Expression.Convert(arg, argTypes[i]); } Expression ctorExpr = Expression.New(ctor, argsConverted); // ctor takes args of specific types if (convertResultToObject) ctorExpr = Expression.Convert(ctorExpr, typeof(object)); // convert ctor result to object return Expression.Lambda<T>(ctorExpr, args).Compile(); // lambda takes args as objects } /// <summary> /// Compiles a generic ctor with arbitrary number of arguments. /// </summary> /// <typeparam name="T">Result func type.</typeparam> /// <param name="type">Type to be created by ctor.</param> /// <param name="argTypes">Argument types.</param> /// <param name="convertResultToObject">if set to <c>true</c> [convert result to object]. /// Flag that indicates whether ctor return value should be converted to object. /// </param> /// <returns> /// Compiled generic constructor. /// </returns> public static T CompileCtor<T>(Type type, Type[] argTypes, bool convertResultToObject = true) { var ctor = type.GetConstructor(argTypes); return CompileCtor<T>(ctor, argTypes, convertResultToObject); } /// <summary> /// Compiles the field setter. /// </summary> /// <param name="field">The field.</param> /// <returns>Compiled field setter.</returns> public static Action<object, object> CompileFieldSetter(FieldInfo field) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); var valParam = Expression.Parameter(typeof(object)); var valParamConverted = Expression.Convert(valParam, field.FieldType); var assignExpr = Expression.Call(GetWriteFieldMethod(field), targetParamConverted, valParamConverted); return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile(); } /// <summary> /// Compiles the property setter. /// </summary> /// <param name="prop">The property.</param> /// <returns>Compiled property setter.</returns> public static Action<object, object> CompilePropertySetter(PropertyInfo prop) { Debug.Assert(prop != null); Debug.Assert(prop.DeclaringType != null); // non-static var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, prop.DeclaringType); var valParam = Expression.Parameter(typeof(object)); var valParamConverted = Expression.Convert(valParam, prop.PropertyType); var fld = Expression.Property(targetParamConverted, prop); var assignExpr = Expression.Assign(fld, valParamConverted); return Expression.Lambda<Action<object, object>>(assignExpr, targetParam, valParam).Compile(); } /// <summary> /// Gets a method to write a field (including private and readonly). /// NOTE: Expression Trees can't write readonly fields. /// </summary> /// <param name="field">The field.</param> /// <returns>Resulting MethodInfo.</returns> public static DynamicMethod GetWriteFieldMethod(FieldInfo field) { Debug.Assert(field != null); var declaringType = field.DeclaringType; Debug.Assert(declaringType != null); // static fields are not supported var method = new DynamicMethod(string.Empty, null, new[] { typeof(object), field.FieldType }, declaringType, true); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); if (declaringType.IsValueType) il.Emit(OpCodes.Unbox, declaringType); // modify boxed copy il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, field); il.Emit(OpCodes.Ret); return method; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Buffers { using System; using System.IO; using System.Threading; using System.Threading.Tasks; using DotNetty.Common; using DotNetty.Common.Utilities; sealed class PooledHeapByteBuffer : PooledByteBuffer<byte[]> { static readonly ThreadLocalPool<PooledHeapByteBuffer> Recycler = new ThreadLocalPool<PooledHeapByteBuffer>(handle => new PooledHeapByteBuffer(handle, 0)); internal static PooledHeapByteBuffer NewInstance(int maxCapacity) { PooledHeapByteBuffer buf = Recycler.Take(); buf.SetReferenceCount(1); // todo: reuse method? buf.MaxCapacity = maxCapacity; buf.SetIndex(0, 0); buf.DiscardMarkers(); return buf; } PooledHeapByteBuffer(ThreadLocalPool.Handle recyclerHandle, int maxCapacity) : base(recyclerHandle, maxCapacity) { } protected override byte _GetByte(int index) => this.Memory[this.Idx(index)]; protected override short _GetShort(int index) { index = this.Idx(index); return (short)(this.Memory[index] << 8 | this.Memory[index + 1] & 0xFF); } protected override int _GetInt(int index) { index = this.Idx(index); return (this.Memory[index] & 0xff) << 24 | (this.Memory[index + 1] & 0xff) << 16 | (this.Memory[index + 2] & 0xff) << 8 | this.Memory[index + 3] & 0xff; } protected override long _GetLong(int index) { index = this.Idx(index); return ((long)this.Memory[index] & 0xff) << 56 | ((long)this.Memory[index + 1] & 0xff) << 48 | ((long)this.Memory[index + 2] & 0xff) << 40 | ((long)this.Memory[index + 3] & 0xff) << 32 | ((long)this.Memory[index + 4] & 0xff) << 24 | ((long)this.Memory[index + 5] & 0xff) << 16 | ((long)this.Memory[index + 6] & 0xff) << 8 | (long)this.Memory[index + 7] & 0xff; } public override IByteBuffer GetBytes(int index, IByteBuffer dst, int dstIndex, int length) { this.CheckDstIndex(index, length, dstIndex, dst.Capacity); if (dst.HasArray) { this.GetBytes(index, dst.Array, dst.ArrayOffset + dstIndex, length); } else { dst.SetBytes(dstIndex, this.Memory, this.Idx(index), length); } return this; } public override IByteBuffer GetBytes(int index, byte[] dst, int dstIndex, int length) { this.CheckDstIndex(index, length, dstIndex, dst.Length); System.Array.Copy(this.Memory, this.Idx(index), dst, dstIndex, length); return this; } public override IByteBuffer GetBytes(int index, Stream destination, int length) { this.CheckIndex(index, length); destination.Write(this.Memory, this.Idx(index), length); return this; } protected override void _SetByte(int index, int value) => this.Memory[this.Idx(index)] = (byte)value; protected override void _SetShort(int index, int value) { index = this.Idx(index); this.Memory[index] = (byte)value.RightUShift(8); this.Memory[index + 1] = (byte)value; } protected override void _SetInt(int index, int value) { index = this.Idx(index); this.Memory[index] = (byte)value.RightUShift(24); this.Memory[index + 1] = (byte)value.RightUShift(16); this.Memory[index + 2] = (byte)value.RightUShift(8); this.Memory[index + 3] = (byte)value; } protected override void _SetLong(int index, long value) { index = this.Idx(index); this.Memory[index] = (byte)value.RightUShift(56); this.Memory[index + 1] = (byte)value.RightUShift(48); this.Memory[index + 2] = (byte)value.RightUShift(40); this.Memory[index + 3] = (byte)value.RightUShift(32); this.Memory[index + 4] = (byte)value.RightUShift(24); this.Memory[index + 5] = (byte)value.RightUShift(16); this.Memory[index + 6] = (byte)value.RightUShift(8); this.Memory[index + 7] = (byte)value; } public override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length) { this.CheckSrcIndex(index, length, srcIndex, src.Capacity); if (src.HasArray) { this.SetBytes(index, src.Array, src.ArrayOffset + srcIndex, length); } else { src.GetBytes(srcIndex, this.Memory, this.Idx(index), length); } return this; } public override async Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken) { int readTotal = 0; int read; int offset = this.ArrayOffset + index; do { read = await src.ReadAsync(this.Array, offset + readTotal, length - readTotal, cancellationToken); readTotal += read; } while (read > 0 && readTotal < length); return readTotal; } public override IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length) { this.CheckSrcIndex(index, length, srcIndex, src.Length); System.Array.Copy(src, srcIndex, this.Memory, this.Idx(index), length); return this; } public override IByteBuffer Copy(int index, int length) { this.CheckIndex(index, length); IByteBuffer copy = this.Allocator.Buffer(length, this.MaxCapacity); copy.WriteBytes(this.Memory, this.Idx(index), length); return copy; } //public int nioBufferCount() //{ // return 1; //} //public ByteBuffer[] nioBuffers(int index, int length) //{ // return new ByteBuffer[] { this.nioBuffer(index, length) }; //} //public ByteBuffer nioBuffer(int index, int length) //{ // checkIndex(index, length); // index = idx(index); // ByteBuffer buf = ByteBuffer.wrap(this.memory, index, length); // return buf.slice(); //} //public ByteBuffer internalNioBuffer(int index, int length) //{ // checkIndex(index, length); // index = idx(index); // return (ByteBuffer)internalNioBuffer().clear().position(index).limit(index + length); //} public override int IoBufferCount => 1; public override ArraySegment<byte> GetIoBuffer(int index, int length) { this.CheckIndex(index, length); index = index + this.Offset; return new ArraySegment<byte>(this.Memory, index, length); } public override ArraySegment<byte>[] GetIoBuffers(int index, int length) => new[] { this.GetIoBuffer(index, length) }; public override bool HasArray => true; public override byte[] Array { get { this.EnsureAccessible(); return this.Memory; } } public override int ArrayOffset => this.Offset; //protected ByteBuffer newInternalNioBuffer(byte[] memory) //{ // return ByteBuffer.wrap(memory); //} } }
// 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; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; namespace OmniSharp.Intellisense { public static partial class EnumerableExtensions { public static IEnumerable<T> Do<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } // perf optimization. try to not use enumerator if possible var list = source as IList<T>; if (list != null) { for (int i = 0, count = list.Count; i < count; i++) { action(list[i]); } } else { foreach (var value in source) { action(value); } } return source; } public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return new ReadOnlyCollection<T>(source.ToList()); } public static IEnumerable<T> Concat<T>(this IEnumerable<T> source, T value) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.ConcatWorker(value); } private static IEnumerable<T> ConcatWorker<T>(this IEnumerable<T> source, T value) { foreach (var v in source) { yield return v; } yield return value; } public static bool SetEquals<T>(this IEnumerable<T> source1, IEnumerable<T> source2, IEqualityComparer<T> comparer) { if (source1 == null) { throw new ArgumentNullException(nameof(source1)); } if (source2 == null) { throw new ArgumentNullException(nameof(source2)); } return source1.ToSet(comparer).SetEquals(source2); } public static bool SetEquals<T>(this IEnumerable<T> source1, IEnumerable<T> source2) { if (source1 == null) { throw new ArgumentNullException(nameof(source1)); } if (source2 == null) { throw new ArgumentNullException(nameof(source2)); } return source1.ToSet().SetEquals(source2); } public static ISet<T> ToSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return new HashSet<T>(source, comparer); } public static ISet<T> ToSet<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source as ISet<T> ?? new HashSet<T>(source); } public static T? FirstOrNullable<T>(this IEnumerable<T> source) where T : struct { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Cast<T?>().FirstOrDefault(); } public static T? FirstOrNullable<T>(this IEnumerable<T> source, Func<T, bool> predicate) where T : struct { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Cast<T?>().FirstOrDefault(v => predicate(v.Value)); } public static T? LastOrNullable<T>(this IEnumerable<T> source) where T : struct { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Cast<T?>().LastOrDefault(); } public static bool IsSingle<T>(this IEnumerable<T> list) { using (var enumerator = list.GetEnumerator()) { return enumerator.MoveNext() && !enumerator.MoveNext(); } } public static bool IsEmpty<T>(this IEnumerable<T> source) { var readOnlyCollection = source as IReadOnlyCollection<T>; if (readOnlyCollection != null) { return readOnlyCollection.Count == 0; } var genericCollection = source as ICollection<T>; if (genericCollection != null) { return genericCollection.Count == 0; } var collection = source as ICollection; if (collection != null) { return collection.Count == 0; } var str = source as string; if (str != null) { return str.Length == 0; } foreach (var t in source) { return false; } return true; } public static bool IsEmpty<T>(this IReadOnlyCollection<T> source) { return source.Count == 0; } public static bool IsEmpty<T>(this ICollection<T> source) { return source.Count == 0; } public static bool IsEmpty(this string source) { return source.Length == 0; } /// <remarks> /// This method is necessary to avoid an ambiguity between <see cref="IsEmpty{T}(IReadOnlyCollection{T})"/> and <see cref="IsEmpty{T}(ICollection{T})"/>. /// </remarks> public static bool IsEmpty<T>(this T[] source) { return source.Length == 0; } /// <remarks> /// This method is necessary to avoid an ambiguity between <see cref="IsEmpty{T}(IReadOnlyCollection{T})"/> and <see cref="IsEmpty{T}(ICollection{T})"/>. /// </remarks> public static bool IsEmpty<T>(this List<T> source) { return source.Count == 0; } private static readonly Func<object, bool> s_notNullTest = x => x != null; public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source) where T : class { if (source == null) { return SpecializedCollections.EmptyEnumerable<T>(); } return source.Where((Func<T, bool>)s_notNullTest); } public static bool All(this IEnumerable<bool> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } foreach (var b in source) { if (!b) { return false; } } return true; } public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence) { if (sequence == null) { throw new ArgumentNullException(nameof(sequence)); } return sequence.SelectMany(s => s); } public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, IComparer<T> comparer) { return source.OrderBy(t => t, comparer); } // public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, Comparison<T> compare) // { // return source.OrderBy(new ComparisonComparer<T>(compare)); // } // public static IEnumerable<T> Order<T>(this IEnumerable<T> source) where T : IComparable<T> // { // return source.OrderBy((t1, t2) => t1.CompareTo(t2)); // } public static bool IsSorted<T>(this IEnumerable<T> enumerable, IComparer<T> comparer) { using (var e = enumerable.GetEnumerator()) { if (!e.MoveNext()) { return true; } var previous = e.Current; while (e.MoveNext()) { if (comparer.Compare(previous, e.Current) > 0) { return false; } previous = e.Current; } return true; } } public static bool SequenceEqual<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, bool> comparer) { Debug.Assert(comparer != null); if (first == second) { return true; } if (first == null || second == null) { return false; } using (var enumerator = first.GetEnumerator()) using (var enumerator2 = second.GetEnumerator()) { while (enumerator.MoveNext()) { if (!enumerator2.MoveNext() || !comparer(enumerator.Current, enumerator2.Current)) { return false; } } if (enumerator2.MoveNext()) { return false; } } return true; } public static bool Contains<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { return sequence.Any(predicate); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// SenderEmailNotifications /// </summary> [DataContract] public partial class SenderEmailNotifications : IEquatable<SenderEmailNotifications>, IValidatableObject { public SenderEmailNotifications() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="SenderEmailNotifications" /> class. /// </summary> /// <param name="ChangedSigner">When set to **true**, the sender receives notification if the signer changes..</param> /// <param name="ClickwrapResponsesLimitNotificationEmail">ClickwrapResponsesLimitNotificationEmail.</param> /// <param name="CommentsOnlyPrivateAndMention">CommentsOnlyPrivateAndMention.</param> /// <param name="CommentsReceiveAll">CommentsReceiveAll.</param> /// <param name="DeliveryFailed">When set to **true**, the sender receives notification if the delivery of the envelope fails..</param> /// <param name="EnvelopeComplete">When set to **true**, the user receives notification that the envelope has been completed..</param> /// <param name="OfflineSigningFailed">When set to **true**, the user receives notification if the offline signing failed..</param> /// <param name="PowerformResponsesLimitNotificationEmail">PowerformResponsesLimitNotificationEmail.</param> /// <param name="PurgeDocuments">PurgeDocuments.</param> /// <param name="RecipientViewed">When set to **true**, the sender receives notification that the recipient viewed the enveloper..</param> /// <param name="SenderEnvelopeDeclined">SenderEnvelopeDeclined.</param> /// <param name="WithdrawnConsent">When set to **true**, the user receives notification if consent is withdrawn..</param> public SenderEmailNotifications(string ChangedSigner = default(string), string ClickwrapResponsesLimitNotificationEmail = default(string), string CommentsOnlyPrivateAndMention = default(string), string CommentsReceiveAll = default(string), string DeliveryFailed = default(string), string EnvelopeComplete = default(string), string OfflineSigningFailed = default(string), string PowerformResponsesLimitNotificationEmail = default(string), string PurgeDocuments = default(string), string RecipientViewed = default(string), string SenderEnvelopeDeclined = default(string), string WithdrawnConsent = default(string)) { this.ChangedSigner = ChangedSigner; this.ClickwrapResponsesLimitNotificationEmail = ClickwrapResponsesLimitNotificationEmail; this.CommentsOnlyPrivateAndMention = CommentsOnlyPrivateAndMention; this.CommentsReceiveAll = CommentsReceiveAll; this.DeliveryFailed = DeliveryFailed; this.EnvelopeComplete = EnvelopeComplete; this.OfflineSigningFailed = OfflineSigningFailed; this.PowerformResponsesLimitNotificationEmail = PowerformResponsesLimitNotificationEmail; this.PurgeDocuments = PurgeDocuments; this.RecipientViewed = RecipientViewed; this.SenderEnvelopeDeclined = SenderEnvelopeDeclined; this.WithdrawnConsent = WithdrawnConsent; } /// <summary> /// When set to **true**, the sender receives notification if the signer changes. /// </summary> /// <value>When set to **true**, the sender receives notification if the signer changes.</value> [DataMember(Name="changedSigner", EmitDefaultValue=false)] public string ChangedSigner { get; set; } /// <summary> /// Gets or Sets ClickwrapResponsesLimitNotificationEmail /// </summary> [DataMember(Name="clickwrapResponsesLimitNotificationEmail", EmitDefaultValue=false)] public string ClickwrapResponsesLimitNotificationEmail { get; set; } /// <summary> /// Gets or Sets CommentsOnlyPrivateAndMention /// </summary> [DataMember(Name="commentsOnlyPrivateAndMention", EmitDefaultValue=false)] public string CommentsOnlyPrivateAndMention { get; set; } /// <summary> /// Gets or Sets CommentsReceiveAll /// </summary> [DataMember(Name="commentsReceiveAll", EmitDefaultValue=false)] public string CommentsReceiveAll { get; set; } /// <summary> /// When set to **true**, the sender receives notification if the delivery of the envelope fails. /// </summary> /// <value>When set to **true**, the sender receives notification if the delivery of the envelope fails.</value> [DataMember(Name="deliveryFailed", EmitDefaultValue=false)] public string DeliveryFailed { get; set; } /// <summary> /// When set to **true**, the user receives notification that the envelope has been completed. /// </summary> /// <value>When set to **true**, the user receives notification that the envelope has been completed.</value> [DataMember(Name="envelopeComplete", EmitDefaultValue=false)] public string EnvelopeComplete { get; set; } /// <summary> /// When set to **true**, the user receives notification if the offline signing failed. /// </summary> /// <value>When set to **true**, the user receives notification if the offline signing failed.</value> [DataMember(Name="offlineSigningFailed", EmitDefaultValue=false)] public string OfflineSigningFailed { get; set; } /// <summary> /// Gets or Sets PowerformResponsesLimitNotificationEmail /// </summary> [DataMember(Name="powerformResponsesLimitNotificationEmail", EmitDefaultValue=false)] public string PowerformResponsesLimitNotificationEmail { get; set; } /// <summary> /// Gets or Sets PurgeDocuments /// </summary> [DataMember(Name="purgeDocuments", EmitDefaultValue=false)] public string PurgeDocuments { get; set; } /// <summary> /// When set to **true**, the sender receives notification that the recipient viewed the enveloper. /// </summary> /// <value>When set to **true**, the sender receives notification that the recipient viewed the enveloper.</value> [DataMember(Name="recipientViewed", EmitDefaultValue=false)] public string RecipientViewed { get; set; } /// <summary> /// Gets or Sets SenderEnvelopeDeclined /// </summary> [DataMember(Name="senderEnvelopeDeclined", EmitDefaultValue=false)] public string SenderEnvelopeDeclined { get; set; } /// <summary> /// When set to **true**, the user receives notification if consent is withdrawn. /// </summary> /// <value>When set to **true**, the user receives notification if consent is withdrawn.</value> [DataMember(Name="withdrawnConsent", EmitDefaultValue=false)] public string WithdrawnConsent { 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 SenderEmailNotifications {\n"); sb.Append(" ChangedSigner: ").Append(ChangedSigner).Append("\n"); sb.Append(" ClickwrapResponsesLimitNotificationEmail: ").Append(ClickwrapResponsesLimitNotificationEmail).Append("\n"); sb.Append(" CommentsOnlyPrivateAndMention: ").Append(CommentsOnlyPrivateAndMention).Append("\n"); sb.Append(" CommentsReceiveAll: ").Append(CommentsReceiveAll).Append("\n"); sb.Append(" DeliveryFailed: ").Append(DeliveryFailed).Append("\n"); sb.Append(" EnvelopeComplete: ").Append(EnvelopeComplete).Append("\n"); sb.Append(" OfflineSigningFailed: ").Append(OfflineSigningFailed).Append("\n"); sb.Append(" PowerformResponsesLimitNotificationEmail: ").Append(PowerformResponsesLimitNotificationEmail).Append("\n"); sb.Append(" PurgeDocuments: ").Append(PurgeDocuments).Append("\n"); sb.Append(" RecipientViewed: ").Append(RecipientViewed).Append("\n"); sb.Append(" SenderEnvelopeDeclined: ").Append(SenderEnvelopeDeclined).Append("\n"); sb.Append(" WithdrawnConsent: ").Append(WithdrawnConsent).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 SenderEmailNotifications); } /// <summary> /// Returns true if SenderEmailNotifications instances are equal /// </summary> /// <param name="other">Instance of SenderEmailNotifications to be compared</param> /// <returns>Boolean</returns> public bool Equals(SenderEmailNotifications other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ChangedSigner == other.ChangedSigner || this.ChangedSigner != null && this.ChangedSigner.Equals(other.ChangedSigner) ) && ( this.ClickwrapResponsesLimitNotificationEmail == other.ClickwrapResponsesLimitNotificationEmail || this.ClickwrapResponsesLimitNotificationEmail != null && this.ClickwrapResponsesLimitNotificationEmail.Equals(other.ClickwrapResponsesLimitNotificationEmail) ) && ( this.CommentsOnlyPrivateAndMention == other.CommentsOnlyPrivateAndMention || this.CommentsOnlyPrivateAndMention != null && this.CommentsOnlyPrivateAndMention.Equals(other.CommentsOnlyPrivateAndMention) ) && ( this.CommentsReceiveAll == other.CommentsReceiveAll || this.CommentsReceiveAll != null && this.CommentsReceiveAll.Equals(other.CommentsReceiveAll) ) && ( this.DeliveryFailed == other.DeliveryFailed || this.DeliveryFailed != null && this.DeliveryFailed.Equals(other.DeliveryFailed) ) && ( this.EnvelopeComplete == other.EnvelopeComplete || this.EnvelopeComplete != null && this.EnvelopeComplete.Equals(other.EnvelopeComplete) ) && ( this.OfflineSigningFailed == other.OfflineSigningFailed || this.OfflineSigningFailed != null && this.OfflineSigningFailed.Equals(other.OfflineSigningFailed) ) && ( this.PowerformResponsesLimitNotificationEmail == other.PowerformResponsesLimitNotificationEmail || this.PowerformResponsesLimitNotificationEmail != null && this.PowerformResponsesLimitNotificationEmail.Equals(other.PowerformResponsesLimitNotificationEmail) ) && ( this.PurgeDocuments == other.PurgeDocuments || this.PurgeDocuments != null && this.PurgeDocuments.Equals(other.PurgeDocuments) ) && ( this.RecipientViewed == other.RecipientViewed || this.RecipientViewed != null && this.RecipientViewed.Equals(other.RecipientViewed) ) && ( this.SenderEnvelopeDeclined == other.SenderEnvelopeDeclined || this.SenderEnvelopeDeclined != null && this.SenderEnvelopeDeclined.Equals(other.SenderEnvelopeDeclined) ) && ( this.WithdrawnConsent == other.WithdrawnConsent || this.WithdrawnConsent != null && this.WithdrawnConsent.Equals(other.WithdrawnConsent) ); } /// <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.ChangedSigner != null) hash = hash * 59 + this.ChangedSigner.GetHashCode(); if (this.ClickwrapResponsesLimitNotificationEmail != null) hash = hash * 59 + this.ClickwrapResponsesLimitNotificationEmail.GetHashCode(); if (this.CommentsOnlyPrivateAndMention != null) hash = hash * 59 + this.CommentsOnlyPrivateAndMention.GetHashCode(); if (this.CommentsReceiveAll != null) hash = hash * 59 + this.CommentsReceiveAll.GetHashCode(); if (this.DeliveryFailed != null) hash = hash * 59 + this.DeliveryFailed.GetHashCode(); if (this.EnvelopeComplete != null) hash = hash * 59 + this.EnvelopeComplete.GetHashCode(); if (this.OfflineSigningFailed != null) hash = hash * 59 + this.OfflineSigningFailed.GetHashCode(); if (this.PowerformResponsesLimitNotificationEmail != null) hash = hash * 59 + this.PowerformResponsesLimitNotificationEmail.GetHashCode(); if (this.PurgeDocuments != null) hash = hash * 59 + this.PurgeDocuments.GetHashCode(); if (this.RecipientViewed != null) hash = hash * 59 + this.RecipientViewed.GetHashCode(); if (this.SenderEnvelopeDeclined != null) hash = hash * 59 + this.SenderEnvelopeDeclined.GetHashCode(); if (this.WithdrawnConsent != null) hash = hash * 59 + this.WithdrawnConsent.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.Util; namespace Pathfinding { [AddComponentMenu("Pathfinding/Modifiers/Funnel")] [System.Serializable] /** Simplifies paths on navmesh graphs using the funnel algorithm. * The funnel algorithm is an algorithm which can, given a path corridor with nodes in the path where the nodes have an area, like triangles, it can find the shortest path inside it. * This makes paths on navmeshes look much cleaner and smoother. * \image html images/funnelModifier_on.png * \ingroup modifiers */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_funnel_modifier.php")] public class FunnelModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem("CONTEXT/Seeker/Add Funnel Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent(typeof(FunnelModifier)); } #endif public override int Order { get { return 10; } } public override void Apply (Path p) { List<GraphNode> path = p.path; List<Vector3> vectorPath = p.vectorPath; if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count) { return; } List<Vector3> funnelPath = ListPool<Vector3>.Claim(); // Claim temporary lists and try to find lists with a high capacity List<Vector3> left = ListPool<Vector3>.Claim(path.Count+1); List<Vector3> right = ListPool<Vector3>.Claim(path.Count+1); AstarProfiler.StartProfile("Construct Funnel"); // Add start point left.Add(vectorPath[0]); right.Add(vectorPath[0]); // Loop through all nodes in the path (except the last one) for (int i = 0; i < path.Count-1; i++) { // Get the portal between path[i] and path[i+1] and add it to the left and right lists bool portalWasAdded = path[i].GetPortal(path[i+1], left, right, false); if (!portalWasAdded) { // Fallback, just use the positions of the nodes left.Add((Vector3)path[i].position); right.Add((Vector3)path[i].position); left.Add((Vector3)path[i+1].position); right.Add((Vector3)path[i+1].position); } } // Add end point left.Add(vectorPath[vectorPath.Count-1]); right.Add(vectorPath[vectorPath.Count-1]); if (!RunFunnel(left, right, funnelPath)) { // If funnel algorithm failed, degrade to simple line funnelPath.Add(vectorPath[0]); funnelPath.Add(vectorPath[vectorPath.Count-1]); } // Release lists back to the pool ListPool<Vector3>.Release(p.vectorPath); p.vectorPath = funnelPath; ListPool<Vector3>.Release(left); ListPool<Vector3>.Release(right); } /** Calculate a funnel path from the \a left and \a right portal lists. * The result will be appended to \a funnelPath */ public static bool RunFunnel (List<Vector3> left, List<Vector3> right, List<Vector3> funnelPath) { if (left == null) throw new System.ArgumentNullException("left"); if (right == null) throw new System.ArgumentNullException("right"); if (funnelPath == null) throw new System.ArgumentNullException("funnelPath"); if (left.Count != right.Count) throw new System.ArgumentException("left and right lists must have equal length"); if (left.Count < 3) { return false; } //Remove identical vertices while (left[1] == left[2] && right[1] == right[2]) { //System.Console.WriteLine ("Removing identical left and right"); left.RemoveAt(1); right.RemoveAt(1); if (left.Count <= 3) { return false; } } Vector3 swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } //Test while (VectorMath.IsColinearXZ(left[0], left[1], right[1]) || VectorMath.RightOrColinearXZ(left[1], right[1], swPoint) == VectorMath.RightOrColinearXZ(left[1], right[1], left[0])) { left.RemoveAt(1); right.RemoveAt(1); if (left.Count <= 3) { return false; } swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } } //Switch left and right to really be on the "left" and "right" sides /** \todo The colinear check should not be needed */ if (!VectorMath.IsClockwiseXZ(left[0], left[1], right[1]) && !VectorMath.IsColinearXZ(left[0], left[1], right[1])) { //System.Console.WriteLine ("Wrong Side 2"); List<Vector3> tmp = left; left = right; right = tmp; } funnelPath.Add(left[0]); Vector3 portalApex = left[0]; Vector3 portalLeft = left[1]; Vector3 portalRight = right[1]; int apexIndex = 0; int rightIndex = 1; int leftIndex = 1; for (int i = 2; i < left.Count; i++) { if (funnelPath.Count > 2000) { Debug.LogWarning("Avoiding infinite loop. Remove this check if you have this long paths."); break; } Vector3 pLeft = left[i]; Vector3 pRight = right[i]; /*Debug.DrawLine (portalApex,portalLeft,Color.red); * Debug.DrawLine (portalApex,portalRight,Color.yellow); * Debug.DrawLine (portalApex,left,Color.cyan); * Debug.DrawLine (portalApex,right,Color.cyan);*/ if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pRight) >= 0) { if (portalApex == portalRight || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pRight) <= 0) { portalRight = pRight; rightIndex = i; } else { funnelPath.Add(portalLeft); portalApex = portalLeft; apexIndex = leftIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pLeft) <= 0) { if (portalApex == portalLeft || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pLeft) >= 0) { portalLeft = pLeft; leftIndex = i; } else { funnelPath.Add(portalRight); portalApex = portalRight; apexIndex = rightIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } } funnelPath.Add(left[left.Count-1]); return true; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="BillingSetupServiceClient"/> instances.</summary> public sealed partial class BillingSetupServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="BillingSetupServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="BillingSetupServiceSettings"/>.</returns> public static BillingSetupServiceSettings GetDefault() => new BillingSetupServiceSettings(); /// <summary>Constructs a new <see cref="BillingSetupServiceSettings"/> object with default settings.</summary> public BillingSetupServiceSettings() { } private BillingSetupServiceSettings(BillingSetupServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateBillingSetupSettings = existing.MutateBillingSetupSettings; OnCopy(existing); } partial void OnCopy(BillingSetupServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BillingSetupServiceClient.MutateBillingSetup</c> and <c>BillingSetupServiceClient.MutateBillingSetupAsync</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 MutateBillingSetupSettings { 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="BillingSetupServiceSettings"/> object.</returns> public BillingSetupServiceSettings Clone() => new BillingSetupServiceSettings(this); } /// <summary> /// Builder class for <see cref="BillingSetupServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class BillingSetupServiceClientBuilder : gaxgrpc::ClientBuilderBase<BillingSetupServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public BillingSetupServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BillingSetupServiceClientBuilder() { UseJwtAccessWithScopes = BillingSetupServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref BillingSetupServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BillingSetupServiceClient> task); /// <summary>Builds the resulting client.</summary> public override BillingSetupServiceClient Build() { BillingSetupServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<BillingSetupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<BillingSetupServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private BillingSetupServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return BillingSetupServiceClient.Create(callInvoker, Settings); } private async stt::Task<BillingSetupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return BillingSetupServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => BillingSetupServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => BillingSetupServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => BillingSetupServiceClient.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>BillingSetupService client wrapper, for convenient use.</summary> /// <remarks> /// A service for designating the business entity responsible for accrued costs. /// /// A billing setup is associated with a payments account. Billing-related /// activity for all billing setups associated with a particular payments account /// will appear on a single invoice generated monthly. /// /// Mutates: /// The REMOVE operation cancels a pending billing setup. /// The CREATE operation creates a new billing setup. /// </remarks> public abstract partial class BillingSetupServiceClient { /// <summary> /// The default endpoint for the BillingSetupService 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 BillingSetupService scopes.</summary> /// <remarks> /// The default BillingSetupService 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="BillingSetupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="BillingSetupServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="BillingSetupServiceClient"/>.</returns> public static stt::Task<BillingSetupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new BillingSetupServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="BillingSetupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="BillingSetupServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="BillingSetupServiceClient"/>.</returns> public static BillingSetupServiceClient Create() => new BillingSetupServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="BillingSetupServiceClient"/> 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="BillingSetupServiceSettings"/>.</param> /// <returns>The created <see cref="BillingSetupServiceClient"/>.</returns> internal static BillingSetupServiceClient Create(grpccore::CallInvoker callInvoker, BillingSetupServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } BillingSetupService.BillingSetupServiceClient grpcClient = new BillingSetupService.BillingSetupServiceClient(callInvoker); return new BillingSetupServiceClientImpl(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 BillingSetupService client</summary> public virtual BillingSetupService.BillingSetupServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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 MutateBillingSetupResponse MutateBillingSetup(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, st::CancellationToken cancellationToken) => MutateBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. Id of the customer to apply the billing setup mutate operation to. /// </param> /// <param name="operation"> /// Required. The operation to perform. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateBillingSetupResponse MutateBillingSetup(string customerId, BillingSetupOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateBillingSetup(new MutateBillingSetupRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. Id of the customer to apply the billing setup mutate operation to. /// </param> /// <param name="operation"> /// Required. The operation to perform. /// </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<MutateBillingSetupResponse> MutateBillingSetupAsync(string customerId, BillingSetupOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateBillingSetupAsync(new MutateBillingSetupRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. Id of the customer to apply the billing setup mutate operation to. /// </param> /// <param name="operation"> /// Required. The operation to perform. /// </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<MutateBillingSetupResponse> MutateBillingSetupAsync(string customerId, BillingSetupOperation operation, st::CancellationToken cancellationToken) => MutateBillingSetupAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>BillingSetupService client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service for designating the business entity responsible for accrued costs. /// /// A billing setup is associated with a payments account. Billing-related /// activity for all billing setups associated with a particular payments account /// will appear on a single invoice generated monthly. /// /// Mutates: /// The REMOVE operation cancels a pending billing setup. /// The CREATE operation creates a new billing setup. /// </remarks> public sealed partial class BillingSetupServiceClientImpl : BillingSetupServiceClient { private readonly gaxgrpc::ApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse> _callMutateBillingSetup; /// <summary> /// Constructs a client wrapper for the BillingSetupService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="BillingSetupServiceSettings"/> used within this client.</param> public BillingSetupServiceClientImpl(BillingSetupService.BillingSetupServiceClient grpcClient, BillingSetupServiceSettings settings) { GrpcClient = grpcClient; BillingSetupServiceSettings effectiveSettings = settings ?? BillingSetupServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateBillingSetup = clientHelper.BuildApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse>(grpcClient.MutateBillingSetupAsync, grpcClient.MutateBillingSetup, effectiveSettings.MutateBillingSetupSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateBillingSetup); Modify_MutateBillingSetupApiCall(ref _callMutateBillingSetup); 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_MutateBillingSetupApiCall(ref gaxgrpc::ApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse> call); partial void OnConstruction(BillingSetupService.BillingSetupServiceClient grpcClient, BillingSetupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC BillingSetupService client</summary> public override BillingSetupService.BillingSetupServiceClient GrpcClient { get; } partial void Modify_MutateBillingSetupRequest(ref MutateBillingSetupRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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 MutateBillingSetupResponse MutateBillingSetup(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBillingSetupRequest(ref request, ref callSettings); return _callMutateBillingSetup.Sync(request, callSettings); } /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [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<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBillingSetupRequest(ref request, ref callSettings); return _callMutateBillingSetup.Async(request, callSettings); } } }
using J2N.Numerics; using YAF.Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace YAF.Lucene.Net.Util { /* * 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. */ /// <summary> /// Class that Posting and PostingVector use to write byte /// streams into shared fixed-size <see cref="T:byte[]"/> arrays. The idea /// is to allocate slices of increasing lengths. For /// example, the first slice is 5 bytes, the next slice is /// 14, etc. We start by writing our bytes into the first /// 5 bytes. When we hit the end of the slice, we allocate /// the next slice and then write the address of the new /// slice into the last 4 bytes of the previous slice (the /// "forwarding address"). /// <para/> /// Each slice is filled with 0's initially, and we mark /// the end with a non-zero byte. This way the methods /// that are writing into the slice don't need to record /// its length and instead allocate a new slice once they /// hit a non-zero byte. /// <para/> /// @lucene.internal /// </summary> public sealed class ByteBlockPool { public static readonly int BYTE_BLOCK_SHIFT = 15; public static readonly int BYTE_BLOCK_SIZE = 1 << BYTE_BLOCK_SHIFT; public static readonly int BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1; /// <summary> /// Abstract class for allocating and freeing byte /// blocks. /// </summary> public abstract class Allocator { protected readonly int m_blockSize; protected Allocator(int blockSize) { this.m_blockSize = blockSize; } public abstract void RecycleByteBlocks(byte[][] blocks, int start, int end); public virtual void RecycleByteBlocks(IList<byte[]> blocks) { var b = blocks.ToArray(); RecycleByteBlocks(b, 0, b.Length); } public virtual byte[] GetByteBlock() { return new byte[m_blockSize]; } } /// <summary> /// A simple <see cref="Allocator"/> that never recycles. </summary> public sealed class DirectAllocator : Allocator { public DirectAllocator() : this(BYTE_BLOCK_SIZE) { } public DirectAllocator(int blockSize) : base(blockSize) { } public override void RecycleByteBlocks(byte[][] blocks, int start, int end) { } } /// <summary> /// A simple <see cref="Allocator"/> that never recycles, but /// tracks how much total RAM is in use. /// </summary> public class DirectTrackingAllocator : Allocator { private readonly Counter bytesUsed; public DirectTrackingAllocator(Counter bytesUsed) : this(BYTE_BLOCK_SIZE, bytesUsed) { } public DirectTrackingAllocator(int blockSize, Counter bytesUsed) : base(blockSize) { this.bytesUsed = bytesUsed; } public override byte[] GetByteBlock() { bytesUsed.AddAndGet(m_blockSize); return new byte[m_blockSize]; } public override void RecycleByteBlocks(byte[][] blocks, int start, int end) { bytesUsed.AddAndGet(-((end - start) * m_blockSize)); for (var i = start; i < end; i++) { blocks[i] = null; } } } /// <summary> /// Array of buffers currently used in the pool. Buffers are allocated if /// needed don't modify this outside of this class. /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public byte[][] Buffers { get { return buffers; } set { buffers = value; } } private byte[][] buffers = new byte[10][]; /// <summary> /// index into the buffers array pointing to the current buffer used as the head </summary> private int bufferUpto = -1; // Which buffer we are upto /// <summary> /// Where we are in head buffer </summary> public int ByteUpto { get; set; } /// <summary> /// Current head buffer /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public byte[] Buffer { get { return buffer; } set { buffer = value; } } private byte[] buffer; /// <summary> /// Current head offset </summary> public int ByteOffset { get; set; } private readonly Allocator allocator; public ByteBlockPool(Allocator allocator) { // set defaults ByteUpto = BYTE_BLOCK_SIZE; ByteOffset = -BYTE_BLOCK_SIZE; this.allocator = allocator; } /// <summary> /// Resets the pool to its initial state reusing the first buffer and fills all /// buffers with <c>0</c> bytes before they reused or passed to /// <see cref="Allocator.RecycleByteBlocks(byte[][], int, int)"/>. Calling /// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset. /// </summary> public void Reset() { Reset(true, true); } /// <summary> /// Expert: Resets the pool to its initial state reusing the first buffer. Calling /// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset. </summary> /// <param name="zeroFillBuffers"> if <c>true</c> the buffers are filled with <tt>0</tt>. /// this should be set to <c>true</c> if this pool is used with slices. </param> /// <param name="reuseFirst"> if <c>true</c> the first buffer will be reused and calling /// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset if the /// block pool was used before ie. <see cref="ByteBlockPool.NextBuffer()"/> was called before. </param> public void Reset(bool zeroFillBuffers, bool reuseFirst) { if (bufferUpto != -1) { // We allocated at least one buffer if (zeroFillBuffers) { for (int i = 0; i < bufferUpto; i++) { // Fully zero fill buffers that we fully used Arrays.Fill(buffers[i], (byte)0); } // Partial zero fill the final buffer Arrays.Fill(buffers[bufferUpto], 0, ByteUpto, (byte)0); } if (bufferUpto > 0 || !reuseFirst) { int offset = reuseFirst ? 1 : 0; // Recycle all but the first buffer allocator.RecycleByteBlocks(buffers, offset, 1 + bufferUpto); Arrays.Fill(buffers, offset, 1 + bufferUpto, null); } if (reuseFirst) { // Re-use the first buffer bufferUpto = 0; ByteUpto = 0; ByteOffset = 0; buffer = buffers[0]; } else { bufferUpto = -1; ByteUpto = BYTE_BLOCK_SIZE; ByteOffset = -BYTE_BLOCK_SIZE; buffer = null; } } } /// <summary> /// Advances the pool to its next buffer. This method should be called once /// after the constructor to initialize the pool. In contrast to the /// constructor a <see cref="ByteBlockPool.Reset()"/> call will advance the pool to /// its first buffer immediately. /// </summary> public void NextBuffer() { if (1 + bufferUpto == buffers.Length) { var newBuffers = new byte[ArrayUtil.Oversize(buffers.Length + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][]; Array.Copy(buffers, 0, newBuffers, 0, buffers.Length); buffers = newBuffers; } buffer = buffers[1 + bufferUpto] = allocator.GetByteBlock(); bufferUpto++; ByteUpto = 0; ByteOffset += BYTE_BLOCK_SIZE; } /// <summary> /// Allocates a new slice with the given size.</summary> /// <seealso cref="ByteBlockPool.FIRST_LEVEL_SIZE"/> public int NewSlice(int size) { if (ByteUpto > BYTE_BLOCK_SIZE - size) { NextBuffer(); } int upto = ByteUpto; ByteUpto += size; buffer[ByteUpto - 1] = 16; return upto; } // Size of each slice. These arrays should be at most 16 // elements (index is encoded with 4 bits). First array // is just a compact way to encode X+1 with a max. Second // array is the length of each slice, ie first slice is 5 // bytes, next slice is 14 bytes, etc. /// <summary> /// An array holding the offset into the <see cref="ByteBlockPool.LEVEL_SIZE_ARRAY"/> /// to quickly navigate to the next slice level. /// </summary> public static readonly int[] NEXT_LEVEL_ARRAY = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 }; /// <summary> /// An array holding the level sizes for byte slices. /// </summary> public static readonly int[] LEVEL_SIZE_ARRAY = new int[] { 5, 14, 20, 30, 40, 40, 80, 80, 120, 200 }; /// <summary> /// The first level size for new slices </summary> /// <seealso cref="ByteBlockPool.NewSlice(int)"/> public static readonly int FIRST_LEVEL_SIZE = LEVEL_SIZE_ARRAY[0]; /// <summary> /// Creates a new byte slice with the given starting size and /// returns the slices offset in the pool. /// </summary> public int AllocSlice(byte[] slice, int upto) { int level = slice[upto] & 15; int newLevel = NEXT_LEVEL_ARRAY[level]; int newSize = LEVEL_SIZE_ARRAY[newLevel]; // Maybe allocate another block if (ByteUpto > BYTE_BLOCK_SIZE - newSize) { NextBuffer(); } int newUpto = ByteUpto; int offset = newUpto + ByteOffset; ByteUpto += newSize; // Copy forward the past 3 bytes (which we are about // to overwrite with the forwarding address): buffer[newUpto] = slice[upto - 3]; buffer[newUpto + 1] = slice[upto - 2]; buffer[newUpto + 2] = slice[upto - 1]; // Write forwarding address at end of last slice: slice[upto - 3] = (byte)offset.TripleShift(24); slice[upto - 2] = (byte)offset.TripleShift(16); slice[upto - 1] = (byte)offset.TripleShift(8); slice[upto] = (byte)offset; // Write new level: buffer[ByteUpto - 1] = (byte)(16 | newLevel); return newUpto + 3; } // Fill in a BytesRef from term's length & bytes encoded in // byte block public void SetBytesRef(BytesRef term, int textStart) { var bytes = term.Bytes = buffers[textStart >> BYTE_BLOCK_SHIFT]; var pos = textStart & BYTE_BLOCK_MASK; if ((bytes[pos] & 0x80) == 0) { // length is 1 byte term.Length = bytes[pos]; term.Offset = pos + 1; } else { // length is 2 bytes term.Length = (bytes[pos] & 0x7f) + ((bytes[pos + 1] & 0xff) << 7); term.Offset = pos + 2; } Debug.Assert(term.Length >= 0); } /// <summary> /// Appends the bytes in the provided <see cref="BytesRef"/> at /// the current position. /// </summary> public void Append(BytesRef bytes) { var length = bytes.Length; if (length == 0) { return; } int offset = bytes.Offset; int overflow = (length + ByteUpto) - BYTE_BLOCK_SIZE; do { if (overflow <= 0) { Array.Copy(bytes.Bytes, offset, buffer, ByteUpto, length); ByteUpto += length; break; } else { int bytesToCopy = length - overflow; if (bytesToCopy > 0) { Array.Copy(bytes.Bytes, offset, buffer, ByteUpto, bytesToCopy); offset += bytesToCopy; length -= bytesToCopy; } NextBuffer(); overflow = overflow - BYTE_BLOCK_SIZE; } } while (true); } /// <summary> /// Reads bytes bytes out of the pool starting at the given offset with the given /// length into the given byte array at offset <c>off</c>. /// <para>Note: this method allows to copy across block boundaries.</para> /// </summary> public void ReadBytes(long offset, byte[] bytes, int off, int length) { if (length == 0) { return; } var bytesOffset = off; var bytesLength = length; var bufferIndex = (int)(offset >> BYTE_BLOCK_SHIFT); var buffer = buffers[bufferIndex]; var pos = (int)(offset & BYTE_BLOCK_MASK); var overflow = (pos + length) - BYTE_BLOCK_SIZE; do { if (overflow <= 0) { Array.Copy(buffer, pos, bytes, bytesOffset, bytesLength); break; } else { int bytesToCopy = length - overflow; Array.Copy(buffer, pos, bytes, bytesOffset, bytesToCopy); pos = 0; bytesLength -= bytesToCopy; bytesOffset += bytesToCopy; buffer = buffers[++bufferIndex]; overflow = overflow - BYTE_BLOCK_SIZE; } } while (true); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // SmtpClientTest.cs - NUnit Test Cases for System.Net.Mail.SmtpClient // // Authors: // John Luke (john.luke@gmail.com) // // (C) 2006 John Luke // using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Mail.Tests { public class SmtpClientTest : IDisposable { private SmtpClient _smtp; private string _tempFolder; private SmtpClient Smtp { get { return _smtp ?? (_smtp = new SmtpClient()); } } private string TempFolder { get { if (_tempFolder == null) { _tempFolder = Path.Combine(Path.GetTempPath(), GetType().FullName, Guid.NewGuid().ToString()); if (Directory.Exists(_tempFolder)) Directory.Delete(_tempFolder, true); Directory.CreateDirectory(_tempFolder); } return _tempFolder; } } public void Dispose() { if (_smtp != null) { _smtp.Dispose(); } if (Directory.Exists(_tempFolder)) Directory.Delete(_tempFolder, true); } [Theory] [InlineData(SmtpDeliveryMethod.SpecifiedPickupDirectory)] [InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)] [InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)] public void DeliveryMethodTest(SmtpDeliveryMethod method) { Smtp.DeliveryMethod = method; Assert.Equal(method, Smtp.DeliveryMethod); } [Theory] [InlineData(true)] [InlineData(false)] public void EnableSslTest(bool value) { Smtp.EnableSsl = value; Assert.Equal(value, Smtp.EnableSsl); } [Theory] [InlineData("127.0.0.1")] [InlineData("smtp.ximian.com")] public void HostTest(string host) { Smtp.Host = host; Assert.Equal(host, Smtp.Host); } [Fact] public void InvalidHostTest() { Assert.Throws<ArgumentNullException>(() => Smtp.Host = null); AssertExtensions.Throws<ArgumentException>("value", () => Smtp.Host = ""); } [Fact] public void ServicePoint_GetsCachedInstanceSpecificToHostPort() { using (var smtp1 = new SmtpClient("localhost1", 25)) using (var smtp2 = new SmtpClient("localhost1", 25)) using (var smtp3 = new SmtpClient("localhost2", 25)) using (var smtp4 = new SmtpClient("localhost2", 26)) { ServicePoint s1 = smtp1.ServicePoint; ServicePoint s2 = smtp2.ServicePoint; ServicePoint s3 = smtp3.ServicePoint; ServicePoint s4 = smtp4.ServicePoint; Assert.NotNull(s1); Assert.NotNull(s2); Assert.NotNull(s3); Assert.NotNull(s4); Assert.Same(s1, s2); Assert.NotSame(s2, s3); Assert.NotSame(s2, s4); Assert.NotSame(s3, s4); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [Fact] public void ServicePoint_NetCoreApp_AddressIsAccessible() { using (var smtp = new SmtpClient("localhost", 25)) { Assert.Equal("mailto", smtp.ServicePoint.Address.Scheme); Assert.Equal("localhost", smtp.ServicePoint.Address.Host); Assert.Equal(25, smtp.ServicePoint.Address.Port); } } [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] [Fact] public void ServicePoint_NetFramework_AddressIsInaccessible() { using (var smtp = new SmtpClient("localhost", 25)) { ServicePoint sp = smtp.ServicePoint; Assert.Throws<NotSupportedException>(() => sp.Address); } } [Fact] public void ServicePoint_ReflectsHostAndPortChange() { using (var smtp = new SmtpClient("localhost1", 25)) { ServicePoint s1 = smtp.ServicePoint; smtp.Host = "localhost2"; ServicePoint s2 = smtp.ServicePoint; smtp.Host = "localhost2"; ServicePoint s3 = smtp.ServicePoint; Assert.NotSame(s1, s2); Assert.Same(s2, s3); smtp.Port = 26; ServicePoint s4 = smtp.ServicePoint; smtp.Port = 26; ServicePoint s5 = smtp.ServicePoint; Assert.NotSame(s3, s4); Assert.Same(s4, s5); } } [Theory] [InlineData("")] [InlineData(null)] [InlineData("shouldnotexist")] [InlineData("\0")] [InlineData("C:\\some\\path\\like\\string")] public void PickupDirectoryLocationTest(string folder) { Smtp.PickupDirectoryLocation = folder; Assert.Equal(folder, Smtp.PickupDirectoryLocation); } [Theory] [InlineData(25)] [InlineData(1)] [InlineData(int.MaxValue)] public void PortTest(int value) { Smtp.Port = value; Assert.Equal(value, Smtp.Port); } [Fact] public void TestDefaultsOnProperties() { Assert.Equal(25, Smtp.Port); Assert.Equal(100000, Smtp.Timeout); Assert.Null(Smtp.Host); Assert.Null(Smtp.Credentials); Assert.False(Smtp.EnableSsl); Assert.False(Smtp.UseDefaultCredentials); Assert.Equal(SmtpDeliveryMethod.Network, Smtp.DeliveryMethod); Assert.Null(Smtp.PickupDirectoryLocation); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(int.MinValue)] public void Port_Value_Invalid(int value) { Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Port = value); } [Fact] public void Send_Message_Null() { Assert.Throws<ArgumentNullException>(() => Smtp.Send(null)); } [Fact] public void Send_Network_Host_Null() { Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello")); } [Fact] public void Send_Network_Host_Whitespace() { Smtp.Host = " \r\n "; Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello")); } [Fact] public void Send_SpecifiedPickupDirectory() { Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; Smtp.PickupDirectoryLocation = TempFolder; Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"); string[] files = Directory.GetFiles(TempFolder, "*"); Assert.Equal(1, files.Length); Assert.Equal(".eml", Path.GetExtension(files[0])); } [Theory] [InlineData("some_path_not_exist")] [InlineData("")] [InlineData(null)] [InlineData("\0abc")] public void Send_SpecifiedPickupDirectoryInvalid(string location) { Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; Smtp.PickupDirectoryLocation = location; Assert.Throws<SmtpException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello")); } [Theory] [InlineData(0)] [InlineData(50)] [InlineData(int.MaxValue)] [InlineData(int.MinValue)] [InlineData(-1)] public void TestTimeout(int value) { if (value < 0) { Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Timeout = value); return; } Smtp.Timeout = value; Assert.Equal(value, Smtp.Timeout); } [Fact] public void TestMailDelivery() { SmtpServer server = new SmtpServer(); SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); client.Credentials = new NetworkCredential("user", "password"); MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo"); try { Thread t = new Thread(server.Run); t.Start(); client.Send(msg); t.Join(); Assert.Equal("<foo@example.com>", server.MailFrom); Assert.Equal("<bar@example.com>", server.MailTo); Assert.Equal("hello", server.Subject); Assert.Equal("howdydoo", server.Body); } finally { server.Stop(); } } [Fact] public async Task TestMailDeliveryAsync() { SmtpServer server = new SmtpServer(); SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo"); try { Thread t = new Thread(server.Run); t.Start(); await client.SendMailAsync(msg); t.Join(); Assert.Equal("<foo@example.com>", server.MailFrom); Assert.Equal("<bar@example.com>", server.MailTo); Assert.Equal("hello", server.Subject); Assert.Equal("howdydoo", server.Body); } finally { server.Stop(); } } [Fact] public async Task TestCredentialsCopyInAsyncContext() { SmtpServer server = new SmtpServer(); SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port); MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo"); CredentialCache cache = new CredentialCache(); cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials); client.Credentials = cache; try { Thread t = new Thread(server.Run); t.Start(); await client.SendMailAsync(msg); t.Join(); Assert.Equal("<foo@example.com>", server.MailFrom); Assert.Equal("<bar@example.com>", server.MailTo); Assert.Equal("hello", server.Subject); Assert.Equal("howdydoo", server.Body); } finally { server.Stop(); } } } }
// 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; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Generators; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Metadata; using Avalonia.Styling; using Avalonia.VisualTree; namespace Avalonia.Controls.Primitives { /// <summary> /// An <see cref="ItemsControl"/> that maintains a selection. /// </summary> /// <remarks> /// <para> /// <see cref="SelectingItemsControl"/> provides a base class for <see cref="ItemsControl"/>s /// that maintain a selection (single or multiple). By default only its /// <see cref="SelectedIndex"/> and <see cref="SelectedItem"/> properties are visible; the /// current multiple selection <see cref="SelectedItems"/> together with the /// <see cref="SelectionMode"/> properties are protected, however a derived class can expose /// these if it wishes to support multiple selection. /// </para> /// <para> /// <see cref="SelectingItemsControl"/> maintains a selection respecting the current /// <see cref="SelectionMode"/> but it does not react to user input; this must be handled in a /// derived class. It does, however, respond to <see cref="IsSelectedChangedEvent"/> events /// from items and updates the selection accordingly. /// </para> /// </remarks> public class SelectingItemsControl : ItemsControl { /// <summary> /// Defines the <see cref="AutoScrollToSelectedItem"/> property. /// </summary> public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty = AvaloniaProperty.Register<SelectingItemsControl, bool>( nameof(AutoScrollToSelectedItem), defaultValue: true); /// <summary> /// Defines the <see cref="SelectedIndex"/> property. /// </summary> public static readonly DirectProperty<SelectingItemsControl, int> SelectedIndexProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, int>( nameof(SelectedIndex), o => o.SelectedIndex, (o, v) => o.SelectedIndex = v, unsetValue: -1); /// <summary> /// Defines the <see cref="SelectedItem"/> property. /// </summary> public static readonly DirectProperty<SelectingItemsControl, object> SelectedItemProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, object>( nameof(SelectedItem), o => o.SelectedItem, (o, v) => o.SelectedItem = v, defaultBindingMode: BindingMode.TwoWay); /// <summary> /// Defines the <see cref="SelectedItems"/> property. /// </summary> protected static readonly DirectProperty<SelectingItemsControl, IList> SelectedItemsProperty = AvaloniaProperty.RegisterDirect<SelectingItemsControl, IList>( nameof(SelectedItems), o => o.SelectedItems, (o, v) => o.SelectedItems = v); /// <summary> /// Defines the <see cref="SelectionMode"/> property. /// </summary> protected static readonly StyledProperty<SelectionMode> SelectionModeProperty = AvaloniaProperty.Register<SelectingItemsControl, SelectionMode>( nameof(SelectionMode)); /// <summary> /// Event that should be raised by items that implement <see cref="ISelectable"/> to /// notify the parent <see cref="SelectingItemsControl"/> that their selection state /// has changed. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent = RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>( "IsSelectedChanged", RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="SelectionChanged"/> event. /// </summary> public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = RoutedEvent.Register<SelectingItemsControl, SelectionChangedEventArgs>( "SelectionChanged", RoutingStrategies.Bubble); private static readonly IList Empty = new object[0]; private int _selectedIndex = -1; private object _selectedItem; private IList _selectedItems; private bool _ignoreContainerSelectionChanged; private bool _syncingSelectedItems; private int _updateCount; private int _updateSelectedIndex; private IList _updateSelectedItems; /// <summary> /// Initializes static members of the <see cref="SelectingItemsControl"/> class. /// </summary> static SelectingItemsControl() { IsSelectedChangedEvent.AddClassHandler<SelectingItemsControl>(x => x.ContainerSelectionChanged); } /// <summary> /// Occurs when the control's selection changes. /// </summary> public event EventHandler<SelectionChangedEventArgs> SelectionChanged { add { AddHandler(SelectionChangedEvent, value); } remove { RemoveHandler(SelectionChangedEvent, value); } } /// <summary> /// Gets or sets a value indicating whether to automatically scroll to newly selected items. /// </summary> public bool AutoScrollToSelectedItem { get { return GetValue(AutoScrollToSelectedItemProperty); } set { SetValue(AutoScrollToSelectedItemProperty, value); } } /// <summary> /// Gets or sets the index of the selected item. /// </summary> public int SelectedIndex { get { return _selectedIndex; } set { if (_updateCount == 0) { var old = SelectedIndex; var effective = (value >= 0 && value < Items?.Cast<object>().Count()) ? value : -1; if (old != effective) { _selectedIndex = effective; RaisePropertyChanged(SelectedIndexProperty, old, effective, BindingPriority.LocalValue); SelectedItem = ElementAt(Items, effective); } } else { _updateSelectedIndex = value; _updateSelectedItems = null; } } } /// <summary> /// Gets or sets the selected item. /// </summary> public object SelectedItem { get { return _selectedItem; } set { if (_updateCount == 0) { var old = SelectedItem; var index = IndexOf(Items, value); var effective = index != -1 ? value : null; if (!object.Equals(effective, old)) { _selectedItem = effective; RaisePropertyChanged(SelectedItemProperty, old, effective, BindingPriority.LocalValue); SelectedIndex = index; if (effective != null) { if (SelectedItems.Count != 1 || SelectedItems[0] != effective) { _syncingSelectedItems = true; SelectedItems.Clear(); SelectedItems.Add(effective); _syncingSelectedItems = false; } } else if (SelectedItems.Count > 0) { SelectedItems.Clear(); } } } else { _updateSelectedItems = new AvaloniaList<object>(value); _updateSelectedIndex = int.MinValue; } } } /// <summary> /// Gets the selected items. /// </summary> protected IList SelectedItems { get { if (_selectedItems == null) { _selectedItems = new AvaloniaList<object>(); SubscribeToSelectedItems(); } return _selectedItems; } set { if (value?.IsFixedSize == true || value?.IsReadOnly == true) { throw new NotSupportedException( "Cannot use a fixed size or read-only collection as SelectedItems."); } UnsubscribeFromSelectedItems(); _selectedItems = value ?? new AvaloniaList<object>(); SubscribeToSelectedItems(); } } /// <summary> /// Gets or sets the selection mode. /// </summary> protected SelectionMode SelectionMode { get { return GetValue(SelectionModeProperty); } set { SetValue(SelectionModeProperty, value); } } /// <summary> /// Gets a value indicating whether <see cref="SelectionMode.AlwaysSelected"/> is set. /// </summary> protected bool AlwaysSelected => (SelectionMode & SelectionMode.AlwaysSelected) != 0; /// <inheritdoc/> public override void BeginInit() { base.BeginInit(); ++_updateCount; _updateSelectedIndex = int.MinValue; } /// <inheritdoc/> public override void EndInit() { base.EndInit(); if (--_updateCount == 0) { UpdateFinished(); } } /// <summary> /// Scrolls the specified item into view. /// </summary> /// <param name="item">The item.</param> public void ScrollIntoView(object item) => Presenter?.ScrollIntoView(item); /// <summary> /// Tries to get the container that was the source of an event. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <returns>The container or null if the event did not originate in a container.</returns> protected IControl GetContainerFromEventSource(IInteractive eventSource) { var item = ((IVisual)eventSource).GetSelfAndVisualAncestors() .OfType<IControl>() .FirstOrDefault(x => x.LogicalParent == this && ItemContainerGenerator?.IndexFromContainer(x) != -1); return item as IControl; } /// <inheritdoc/> protected override void ItemsChanged(AvaloniaPropertyChangedEventArgs e) { base.ItemsChanged(e); if (_updateCount == 0) { if (SelectedIndex != -1) { SelectedIndex = IndexOf((IEnumerable)e.NewValue, SelectedItem); } else if (AlwaysSelected && Items != null && Items.Cast<object>().Any()) { SelectedIndex = 0; } } } /// <inheritdoc/> protected override void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { base.ItemsCollectionChanged(sender, e); switch (e.Action) { case NotifyCollectionChangedAction.Add: if (AlwaysSelected && SelectedIndex == -1) { SelectedIndex = 0; } break; case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: var selectedIndex = SelectedIndex; if (selectedIndex >= e.OldStartingIndex && selectedIndex < e.OldStartingIndex + e.OldItems.Count) { if (!AlwaysSelected) { SelectedIndex = -1; } else { LostSelection(); } } break; case NotifyCollectionChangedAction.Reset: SelectedIndex = IndexOf(e.NewItems, SelectedItem); break; } } /// <inheritdoc/> protected override void OnContainersMaterialized(ItemContainerEventArgs e) { base.OnContainersMaterialized(e); var selectedIndex = SelectedIndex; var selectedContainer = e.Containers .FirstOrDefault(x => (x.ContainerControl as ISelectable)?.IsSelected == true); if (selectedContainer != null) { SelectedIndex = selectedContainer.Index; } else if (selectedIndex >= e.StartingIndex && selectedIndex < e.StartingIndex + e.Containers.Count) { var container = e.Containers[selectedIndex - e.StartingIndex]; if (container.ContainerControl != null) { MarkContainerSelected(container.ContainerControl, true); } } } /// <inheritdoc/> protected override void OnContainersDematerialized(ItemContainerEventArgs e) { base.OnContainersDematerialized(e); var panel = (InputElement)Presenter.Panel; foreach (var container in e.Containers) { if (KeyboardNavigation.GetTabOnceActiveElement(panel) == container.ContainerControl) { KeyboardNavigation.SetTabOnceActiveElement(panel, null); break; } } } protected override void OnContainersRecycled(ItemContainerEventArgs e) { foreach (var i in e.Containers) { if (i.ContainerControl != null && i.Item != null) { MarkContainerSelected( i.ContainerControl, SelectedItems.Contains(i.Item)); } } } /// <inheritdoc/> protected override void OnDataContextChanging() { base.OnDataContextChanging(); ++_updateCount; } /// <inheritdoc/> protected override void OnDataContextChanged() { base.OnDataContextChanged(); if (--_updateCount == 0) { UpdateFinished(); } } /// <summary> /// Updates the selection for an item based on user interaction. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="select">Whether the item should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( int index, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { if (index != -1) { if (select) { var mode = SelectionMode; var toggle = toggleModifier || (mode & SelectionMode.Toggle) != 0; var multi = (mode & SelectionMode.Multiple) != 0; var range = multi && SelectedIndex != -1 && rangeModifier; if (!toggle && !range) { SelectedIndex = index; } else if (multi && range) { SynchronizeItems( SelectedItems, GetRange(Items, SelectedIndex, index)); } else { var item = ElementAt(Items, index); var i = SelectedItems.IndexOf(item); if (i != -1 && (!AlwaysSelected || SelectedItems.Count > 1)) { SelectedItems.Remove(item); } else { if (multi) { SelectedItems.Add(item); } else { SelectedIndex = index; } } } if (Presenter?.Panel != null) { var container = ItemContainerGenerator.ContainerFromIndex(index); KeyboardNavigation.SetTabOnceActiveElement( (InputElement)Presenter.Panel, container); } } else { LostSelection(); } } } /// <summary> /// Updates the selection for a container based on user interaction. /// </summary> /// <param name="container">The container.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( IControl container, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { var index = ItemContainerGenerator?.IndexFromContainer(container) ?? -1; if (index != -1) { UpdateSelection(index, select, rangeModifier, toggleModifier); } } /// <summary> /// Updates the selection based on an event that may have originated in a container that /// belongs to the control. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> /// <returns> /// True if the event originated from a container that belongs to the control; otherwise /// false. /// </returns> protected bool UpdateSelectionFromEventSource( IInteractive eventSource, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { var container = GetContainerFromEventSource(eventSource); if (container != null) { UpdateSelection(container, select, rangeModifier, toggleModifier); return true; } return false; } /// <summary> /// Gets a range of items from an IEnumerable. /// </summary> /// <param name="items">The items.</param> /// <param name="first">The index of the first item.</param> /// <param name="last">The index of the last item.</param> /// <returns>The items.</returns> private static IEnumerable<object> GetRange(IEnumerable items, int first, int last) { var list = (items as IList) ?? items.Cast<object>().ToList(); int step = first > last ? -1 : 1; for (int i = first; i != last; i += step) { yield return list[i]; } yield return list[last]; } /// <summary> /// Makes a list of objects equal another. /// </summary> /// <param name="items">The items collection.</param> /// <param name="desired">The desired items.</param> private static void SynchronizeItems(IList items, IEnumerable<object> desired) { int index = 0; foreach (var i in desired) { if (index < items.Count) { if (items[index] != i) { items[index] = i; } } else { items.Add(i); } ++index; } while (index < items.Count) { items.RemoveAt(items.Count - 1); } } /// <summary> /// Called when a container raises the <see cref="IsSelectedChangedEvent"/>. /// </summary> /// <param name="e">The event.</param> private void ContainerSelectionChanged(RoutedEventArgs e) { if (!_ignoreContainerSelectionChanged) { var control = e.Source as IControl; var selectable = e.Source as ISelectable; if (control != null && selectable != null && control.LogicalParent == this && ItemContainerGenerator?.IndexFromContainer(control) != -1) { UpdateSelection(control, selectable.IsSelected); } } if (e.Source != this) { e.Handled = true; } } /// <summary> /// Called when the currently selected item is lost and the selection must be changed /// depending on the <see cref="SelectionMode"/> property. /// </summary> private void LostSelection() { var items = Items?.Cast<object>(); if (items != null && AlwaysSelected) { var index = Math.Min(SelectedIndex, items.Count() - 1); if (index > -1) { SelectedItem = items.ElementAt(index); return; } } SelectedIndex = -1; } /// <summary> /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="container">The container.</param> /// <param name="selected">Whether the control is selected</param> /// <returns>The previous selection state.</returns> private bool MarkContainerSelected(IControl container, bool selected) { try { var selectable = container as ISelectable; bool result; _ignoreContainerSelectionChanged = true; if (selectable != null) { result = selectable.IsSelected; selectable.IsSelected = selected; } else { result = container.Classes.Contains(":selected"); ((IPseudoClasses)container.Classes).Set(":selected", selected); } return result; } finally { _ignoreContainerSelectionChanged = false; } } /// <summary> /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="selected">Whether the item should be selected or deselected.</param> private void MarkItemSelected(int index, bool selected) { var container = ItemContainerGenerator?.ContainerFromIndex(index); if (container != null) { MarkContainerSelected(container, selected); } } /// <summary> /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="item">The item.</param> /// <param name="selected">Whether the item should be selected or deselected.</param> private void MarkItemSelected(object item, bool selected) { var index = IndexOf(Items, item); if (index != -1) { MarkItemSelected(index, selected); } } /// <summary> /// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { var generator = ItemContainerGenerator; IList added = null; IList removed = null; switch (e.Action) { case NotifyCollectionChangedAction.Add: SelectedItemsAdded(e.NewItems.Cast<object>().ToList()); if (AutoScrollToSelectedItem) { ScrollIntoView(e.NewItems[0]); } added = e.NewItems; break; case NotifyCollectionChangedAction.Remove: if (SelectedItems.Count == 0) { if (!_syncingSelectedItems) { SelectedIndex = -1; } } else { foreach (var item in e.OldItems) { MarkItemSelected(item, false); } } removed = e.OldItems; break; case NotifyCollectionChangedAction.Reset: if (generator != null) { removed = new List<object>(); foreach (var item in generator.Containers) { if (item?.ContainerControl != null) { if (MarkContainerSelected(item.ContainerControl, false)) { removed.Add(item.Item); } } } } if (SelectedItems.Count > 0) { _selectedItem = null; SelectedItemsAdded(SelectedItems); added = SelectedItems; } else if (!_syncingSelectedItems) { SelectedIndex = -1; } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems) { MarkItemSelected(item, false); } foreach (var item in e.NewItems) { MarkItemSelected(item, true); } if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems) { var oldItem = SelectedItem; var oldIndex = SelectedIndex; var item = SelectedItems[0]; var index = IndexOf(Items, item); _selectedIndex = index; _selectedItem = item; RaisePropertyChanged(SelectedIndexProperty, oldIndex, index, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, oldItem, item, BindingPriority.LocalValue); } added = e.OldItems; removed = e.NewItems; break; } if (added?.Count > 0 || removed?.Count > 0) { var changed = new SelectionChangedEventArgs( SelectionChangedEvent, added ?? Empty, removed ?? Empty); RaiseEvent(changed); } } /// <summary> /// Called when items are added to the <see cref="SelectedItems"/> collection. /// </summary> /// <param name="items">The added items.</param> private void SelectedItemsAdded(IList items) { if (items.Count > 0) { foreach (var item in items) { MarkItemSelected(item, true); } if (SelectedItem == null && !_syncingSelectedItems) { var index = IndexOf(Items, items[0]); if (index != -1) { _selectedItem = items[0]; _selectedIndex = index; RaisePropertyChanged(SelectedIndexProperty, -1, index, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, null, items[0], BindingPriority.LocalValue); } } } } /// <summary> /// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void SubscribeToSelectedItems() { var incc = _selectedItems as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged += SelectedItemsCollectionChanged; } SelectedItemsCollectionChanged( _selectedItems, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void UnsubscribeFromSelectedItems() { var incc = _selectedItems as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged -= SelectedItemsCollectionChanged; } } private void UpdateFinished() { if (_updateSelectedIndex != int.MinValue) { SelectedIndex = _updateSelectedIndex; } else if (_updateSelectedItems != null) { SelectedItems = _updateSelectedItems; } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapAttribute.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Net.Http; using ArrayEnumeration = Novell.Directory.LDAP.VQ.Utilclass.ArrayEnumeration; using Base64 = Novell.Directory.LDAP.VQ.Utilclass.Base64; namespace Novell.Directory.LDAP.VQ { /// <summary> The name and values of one attribute of a directory entry. /// /// LdapAttribute objects are used when searching for, adding, /// modifying, and deleting attributes from the directory. /// LdapAttributes are often used in conjunction with an /// {@link LdapAttributeSet} when retrieving or adding multiple /// attributes to an entry. /// /// /// /// </summary> /// <seealso cref="LdapEntry"> /// </seealso> /// <seealso cref="LdapAttributeSet"> /// </seealso> /// <seealso cref="LdapModification"> /// </seealso> public class LdapAttribute : IComparable { class URLData { private void InitBlock(LdapAttribute enclosingInstance) { this.enclosingInstance = enclosingInstance; } private LdapAttribute enclosingInstance; public LdapAttribute Enclosing_Instance { get { return enclosingInstance; } } private int length; private sbyte[] data; public URLData(LdapAttribute enclosingInstance, sbyte[] data, int length) { InitBlock(enclosingInstance); this.length = length; this.data = data; } public int getLength() { return length; } public sbyte[] getData() { return data; } } /// <summary> Returns an enumerator for the values of the attribute in byte format. /// /// </summary> /// <returns> The values of the attribute in byte format. /// Note: All string values will be UTF-8 encoded. To decode use the /// String constructor. Example: new String( byteArray, "UTF-8" ); /// </returns> virtual public System.Collections.IEnumerator ByteValues { get { return new ArrayEnumeration(ByteValueArray); } } /// <summary> Returns an enumerator for the string values of an attribute. /// /// </summary> /// <returns> The string values of an attribute. /// </returns> virtual public System.Collections.IEnumerator StringValues { get { return new ArrayEnumeration(StringValueArray); } } /// <summary> Returns the values of the attribute as an array of bytes. /// /// </summary> /// <returns> The values as an array of bytes or an empty array if there are /// no values. /// </returns> [CLSCompliant(false)] virtual public sbyte[][] ByteValueArray { get { if (null == values) return new sbyte[0][]; int size = values.Length; sbyte[][] bva = new sbyte[size][]; // Deep copy so application cannot change values for (int i = 0, u = size; i < u; i++) { bva[i] = new sbyte[((sbyte[])values[i]).Length]; Array.Copy((Array)values[i], 0, (Array)bva[i], 0, bva[i].Length); } return bva; } } /// <summary> Returns the values of the attribute as an array of strings. /// /// </summary> /// <returns> The values as an array of strings or an empty array if there are /// no values /// </returns> virtual public string[] StringValueArray { get { if (null == values) return new string[0]; int size = values.Length; string[] sva = new string[size]; for (int j = 0; j < size; j++) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[j])); // char[] dchar = encoder.GetChars((byte[])values[j]); sva[j] = new string(dchar); // sva[j] = new String((sbyte[]) values[j], "UTF-8"); } catch (System.IO.IOException uee) { // Exception should NEVER get thrown but just in case it does ... throw new Exception(uee.ToString()); } } return sva; } } /// <summary> Returns the the first value of the attribute as a <code>String</code>. /// /// </summary> /// <returns> The UTF-8 encoded<code>String</code> value of the attribute's /// value. If the value wasn't a UTF-8 encoded <code>String</code> /// to begin with the value of the returned <code>String</code> is /// non deterministic. /// /// If <code>this</code> attribute has more than one value the /// first value is converted to a UTF-8 encoded <code>String</code> /// and returned. It should be noted, that the directory may /// return attribute values in any order, so that the first /// value may vary from one call to another. /// /// If the attribute has no values <code>null</code> is returned /// </returns> virtual public string StringValue { get { string rval = null; if (values != null) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[0])); // char[] dchar = encoder.GetChars((byte[]) this.values[0]); rval = new string(dchar); } catch (System.IO.IOException use) { throw new Exception(use.ToString()); } } return rval; } } /// <summary> Returns the the first value of the attribute as a byte array. /// /// </summary> /// <returns> The binary value of <code>this</code> attribute or /// <code>null</code> if <code>this</code> attribute doesn't have a value. /// /// If the attribute has no values <code>null</code> is returned /// </returns> [CLSCompliant(false)] virtual public sbyte[] ByteValue { get { sbyte[] bva = null; if (values != null) { // Deep copy so app can't change the value bva = new sbyte[((sbyte[])values[0]).Length]; Array.Copy((Array)values[0], 0, (Array)bva, 0, bva.Length); } return bva; } } /// <summary> Returns the language subtype of the attribute, if any. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns the string, lang-ja. /// /// </summary> /// <returns> The language subtype of the attribute or null if the attribute /// has none. /// </returns> virtual public string LangSubtype { get { if (subTypes != null) { for (int i = 0; i < subTypes.Length; i++) { if (subTypes[i].StartsWith("lang-")) { return subTypes[i]; } } } return null; } } /// <summary> Returns the name of the attribute. /// /// </summary> /// <returns> The name of the attribute. /// </returns> virtual public string Name { get { return name; } } /// <summary> Replaces all values with the specified value. This protected method is /// used by sub-classes of LdapSchemaElement because the value cannot be set /// with a contructor. /// </summary> virtual protected internal string Value { set { values = null; try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(value); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); } catch (System.IO.IOException ue) { throw new Exception(ue.ToString()); } } } private string name; // full attribute name private string baseName; // cn of cn;lang-ja;phonetic private string[] subTypes = null; // lang-ja of cn;lang-ja private object[] values = null; // Array of byte[] attribute values /// <summary> Constructs an attribute with copies of all values of the input /// attribute. /// /// </summary> /// <param name="attr"> An LdapAttribute to use as a template. /// /// @throws IllegalArgumentException if attr is null /// </param> public LdapAttribute(LdapAttribute attr) { if (attr == null) { throw new ArgumentException("LdapAttribute class cannot be null"); } // Do a deep copy of the LdapAttribute template name = attr.name; baseName = attr.baseName; if (null != attr.subTypes) { subTypes = new string[attr.subTypes.Length]; Array.Copy((Array)attr.subTypes, 0, (Array)subTypes, 0, subTypes.Length); } // OK to just copy attributes, as the app only sees a deep copy of them if (null != attr.values) { values = new object[attr.values.Length]; Array.Copy((Array)attr.values, 0, (Array)values, 0, values.Length); } } /// <summary> Constructs an attribute with no values. /// /// </summary> /// <param name="attrName">Name of the attribute. /// /// @throws IllegalArgumentException if attrName is null /// </param> public LdapAttribute(string attrName) { if ((object)attrName == null) { throw new ArgumentException("Attribute name cannot be null"); } name = attrName; baseName = getBaseName(attrName); subTypes = getSubtypes(attrName); } /// <summary> Constructs an attribute with a byte-formatted value. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrBytes">Value of the attribute as raw bytes. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// /// @throws IllegalArgumentException if attrName or attrBytes is null /// </param> [CLSCompliant(false)] public LdapAttribute(string attrName, sbyte[] attrBytes) : this(attrName) { if (attrBytes == null) { throw new ArgumentException("Attribute value cannot be null"); } // Make our own copy of the byte array to prevent app from changing it sbyte[] tmp = new sbyte[attrBytes.Length]; Array.Copy((Array)attrBytes, 0, (Array)tmp, 0, attrBytes.Length); add(tmp); } /// <summary> Constructs an attribute with a single string value. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrString">Value of the attribute as a string. /// /// @throws IllegalArgumentException if attrName or attrString is null /// </param> public LdapAttribute(string attrName, string attrString) : this(attrName) { if ((object)attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); } catch (System.IO.IOException e) { throw new Exception(e.ToString()); } } /// <summary> Constructs an attribute with an array of string values. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrStrings">Array of values as strings. /// /// @throws IllegalArgumentException if attrName, attrStrings, or a member /// of attrStrings is null /// </param> public LdapAttribute(string attrName, string[] attrStrings) : this(attrName) { if (attrStrings == null) { throw new ArgumentException("Attribute values array cannot be null"); } for (int i = 0, u = attrStrings.Length; i < u; i++) { try { if ((object)attrStrings[i] == null) { throw new ArgumentException("Attribute value " + "at array index " + i + " cannot be null"); } System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrStrings[i]); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); // this.add(attrStrings[i].getBytes("UTF-8")); } catch (System.IO.IOException e) { throw new Exception(e.ToString()); } } } /// <summary> Returns a clone of this LdapAttribute. /// /// </summary> /// <returns> clone of this LdapAttribute. /// </returns> public object Clone() { try { object newObj = MemberwiseClone(); if (values != null) { Array.Copy((Array)values, 0, (Array)((LdapAttribute)newObj).values, 0, values.Length); } return newObj; } catch (Exception ce) { throw new Exception("Internal error, cannot create clone"); } } /// <summary> Adds a string value to the attribute. /// /// </summary> /// <param name="attrString">Value of the attribute as a String. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addValue(string attrString) { if ((object)attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); // this.add(attrString.getBytes("UTF-8")); } catch (System.IO.IOException ue) { throw new Exception(ue.ToString()); } } /// <summary> Adds a byte-formatted value to the attribute. /// /// </summary> /// <param name="attrBytes">Value of the attribute as raw bytes. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// /// @throws IllegalArgumentException if attrBytes is null /// </param> [CLSCompliant(false)] public virtual void addValue(sbyte[] attrBytes) { if (attrBytes == null) { throw new ArgumentException("Attribute value cannot be null"); } add(attrBytes); } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. String /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrString">The base64 value of the attribute as a String. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(string attrString) { if ((object)attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } add(Base64.decode(attrString)); } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. Character /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrString">The base64 value of the attribute as a StringBuffer. /// </param> /// <param name="start"> The start index of base64 encoded part, inclusive. /// </param> /// <param name="end"> The end index of base encoded part, exclusive. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(System.Text.StringBuilder attrString, int start, int end) { if (attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } add(Base64.decode(attrString, start, end)); } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. Character /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrChars">The base64 value of the attribute as an array of /// characters. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(char[] attrChars) { if (attrChars == null) { throw new ArgumentException("Attribute value cannot be null"); } add(Base64.decode(attrChars)); } /// <summary> Adds a URL, indicating a file or other resource that contains /// the value of the attribute. /// /// </summary> /// <param name="url">String value of a URL pointing to the resource containing /// the value of the attribute. /// /// @throws IllegalArgumentException if url is null /// </param> public virtual void addURLValue(string url) { if ((object)url == null) { throw new ArgumentException("Attribute URL cannot be null"); } addURLValue(new Uri(url)); } /// <summary> Adds a URL, indicating a file or other resource that contains /// the value of the attribute. /// /// </summary> /// <param name="url">A URL class pointing to the resource containing the value /// of the attribute. /// /// @throws IllegalArgumentException if url is null /// </param> public virtual void addURLValue(Uri url) { // Class to encapsulate the data bytes and the length if (url == null) { throw new ArgumentException("Attribute URL cannot be null"); } try { using (var httpClient = new HttpClient()) { // Get InputStream from the URL System.IO.Stream in_Renamed = httpClient.GetStreamAsync(url).Result; // Read the bytes into buffers and store the them in an arraylist System.Collections.ArrayList bufs = new System.Collections.ArrayList(); sbyte[] buf = new sbyte[4096]; int len, totalLength = 0; while ((len = SupportClass.ReadInput(in_Renamed, ref buf, 0, 4096)) != -1) { bufs.Add(new URLData(this, buf, len)); buf = new sbyte[4096]; totalLength += len; } /* * Now that the length is known, allocate an array to hold all * the bytes of data and copy the data to that array, store * it in this LdapAttribute */ sbyte[] data = new sbyte[totalLength]; int offset = 0; // for (int i = 0; i < bufs.Count; i++) { URLData b = (URLData)bufs[i]; len = b.getLength(); Array.Copy((Array)b.getData(), 0, (Array)data, offset, len); offset += len; } add(data); } } catch (System.IO.IOException ue) { throw new Exception(ue.ToString()); } } /// <summary> Returns the base name of the attribute. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns cn. /// /// </summary> /// <returns> The base name of the attribute. /// </returns> public virtual string getBaseName() { return baseName; } /// <summary> Returns the base name of the specified attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns cn. /// /// </summary> /// <param name="attrName">Name of the attribute from which to extract the /// base name. /// /// </param> /// <returns> The base name of the attribute. /// /// @throws IllegalArgumentException if attrName is null /// </returns> public static string getBaseName(string attrName) { if ((object)attrName == null) { throw new ArgumentException("Attribute name cannot be null"); } int idx = attrName.IndexOf((Char)';'); if (-1 == idx) { return attrName; } return attrName.Substring(0, (idx) - (0)); } /// <summary> Extracts the subtypes from the attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns an array containing lang-ja and phonetic. /// /// </summary> /// <returns> An array subtypes or null if the attribute has none. /// </returns> public virtual string[] getSubtypes() { return subTypes; } /// <summary> Extracts the subtypes from the specified attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns an array containing lang-ja and phonetic. /// /// </summary> /// <param name="attrName"> Name of the attribute from which to extract /// the subtypes. /// /// </param> /// <returns> An array subtypes or null if the attribute has none. /// /// @throws IllegalArgumentException if attrName is null /// </returns> public static string[] getSubtypes(string attrName) { if ((object)attrName == null) { throw new ArgumentException("Attribute name cannot be null"); } SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";"); string[] subTypes = null; int cnt = st.Count; if (cnt > 0) { st.NextToken(); // skip over basename subTypes = new string[cnt - 1]; int i = 0; while (st.HasMoreTokens()) { subTypes[i++] = st.NextToken(); } } return subTypes; } /// <summary> Reports if the attribute name contains the specified subtype. /// /// For example, if you check for the subtype lang-en and the /// attribute name is cn;lang-en, this method returns true. /// /// </summary> /// <param name="subtype"> The single subtype to check for. /// /// </param> /// <returns> True, if the attribute has the specified subtype; /// false, if it doesn't. /// /// @throws IllegalArgumentException if subtype is null /// </returns> public virtual bool hasSubtype(string subtype) { if ((object)subtype == null) { throw new ArgumentException("subtype cannot be null"); } if (null != subTypes) { for (int i = 0; i < subTypes.Length; i++) { if (subTypes[i].ToUpper().Equals(subtype.ToUpper())) return true; } } return false; } /// <summary> Reports if the attribute name contains all the specified subtypes. /// /// For example, if you check for the subtypes lang-en and phonetic /// and if the attribute name is cn;lang-en;phonetic, this method /// returns true. If the attribute name is cn;phonetic or cn;lang-en, /// this method returns false. /// /// </summary> /// <param name="subtypes"> An array of subtypes to check for. /// /// </param> /// <returns> True, if the attribute has all the specified subtypes; /// false, if it doesn't have all the subtypes. /// /// @throws IllegalArgumentException if subtypes is null or if array member /// is null. /// </returns> public virtual bool hasSubtypes(string[] subtypes) { if (subtypes == null) { throw new ArgumentException("subtypes cannot be null"); } for (int i = 0; i < subtypes.Length; i++) { for (int j = 0; j < subTypes.Length; j++) { if ((object)subTypes[j] == null) { throw new ArgumentException("subtype " + "at array index " + i + " cannot be null"); } if (subTypes[j].ToUpper().Equals(subtypes[i].ToUpper())) { goto gotSubType; } } return false; gotSubType:; } return true; } /// <summary> Removes a string value from the attribute. /// /// </summary> /// <param name="attrString"> Value of the attribute as a string. /// /// Note: Removing a value which is not present in the attribute has /// no effect. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void removeValue(string attrString) { if (null == (object)attrString) { throw new ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); removeValue(sbytes); // this.removeValue(attrString.getBytes("UTF-8")); } catch (System.IO.IOException uee) { // This should NEVER happen but just in case ... throw new Exception(uee.ToString()); } } /// <summary> Removes a byte-formatted value from the attribute. /// /// </summary> /// <param name="attrBytes"> Value of the attribute as raw bytes. /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// Example: <code>String.getBytes("UTF-8");</code> /// /// Note: Removing a value which is not present in the attribute has /// no effect. /// /// @throws IllegalArgumentException if attrBytes is null /// </param> [CLSCompliant(false)] public virtual void removeValue(sbyte[] attrBytes) { if (null == attrBytes) { throw new ArgumentException("Attribute value cannot be null"); } for (int i = 0; i < values.Length; i++) { if (equals(attrBytes, (sbyte[])values[i])) { if (0 == i && 1 == values.Length) { // Optimize if first element of a single valued attr values = null; return; } if (values.Length == 1) { values = null; } else { int moved = values.Length - i - 1; object[] tmp = new object[values.Length - 1]; if (i != 0) { Array.Copy((Array)values, 0, (Array)tmp, 0, i); } if (moved != 0) { Array.Copy((Array)values, i + 1, (Array)tmp, i, moved); } values = tmp; tmp = null; } break; } } } /// <summary> Returns the number of values in the attribute. /// /// </summary> /// <returns> The number of values in the attribute. /// </returns> public virtual int size() { return null == values ? 0 : values.Length; } /// <summary> Compares this object with the specified object for order. /// /// Ordering is determined by comparing attribute names (see /// {@link #getName() }) using the method compareTo() of the String class. /// /// /// </summary> /// <param name="attribute"> The LdapAttribute to be compared to this object. /// /// </param> /// <returns> Returns a negative integer, zero, or a positive /// integer as this object is less than, equal to, or greater than the /// specified object. /// </returns> public virtual int CompareTo(object attribute) { return name.CompareTo(((LdapAttribute)attribute).name); } /// <summary> Adds an object to <code>this</code> object's list of attribute values /// /// </summary> /// <param name="bytes"> Ultimately all of this attribute's values are treated /// as binary data so we simplify the process by requiring /// that all data added to our list is in binary form. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// </param> private void add(sbyte[] bytes) { if (null == values) { values = new object[] { bytes }; } else { // Duplicate attribute values not allowed for (int i = 0; i < values.Length; i++) { if (equals(bytes, (sbyte[])values[i])) { return; // Duplicate, don't add } } object[] tmp = new object[values.Length + 1]; Array.Copy((Array)values, 0, (Array)tmp, 0, values.Length); tmp[values.Length] = bytes; values = tmp; tmp = null; } } /// <summary> Returns true if the two specified arrays of bytes are equal to each /// another. Matches the logic of Arrays.equals which is not available /// in jdk 1.1.x. /// /// </summary> /// <param name="e1">the first array to be tested /// </param> /// <param name="e2">the second array to be tested /// </param> /// <returns> true if the two arrays are equal /// </returns> private bool equals(sbyte[] e1, sbyte[] e2) { // If same object, they compare true if (e1 == e2) return true; // If either but not both are null, they compare false if (e1 == null || e2 == null) return false; // If arrays have different length, they compare false int length = e1.Length; if (e2.Length != length) return false; // If any of the bytes are different, they compare false for (int i = 0; i < length; i++) { if (e1[i] != e2[i]) return false; } return true; } /// <summary> Returns a string representation of this LdapAttribute /// /// </summary> /// <returns> a string representation of this LdapAttribute /// </returns> public override string ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder("LdapAttribute: "); try { result.Append("{type='" + name + "'"); if (values != null) { result.Append(", "); if (values.Length == 1) { result.Append("value='"); } else { result.Append("values='"); } for (int i = 0; i < values.Length; i++) { if (i != 0) { result.Append("','"); } if (((sbyte[])values[i]).Length == 0) { continue; } System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); // char[] dchar = encoder.GetChars((byte[]) values[i]); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[i])); string sval = new string(dchar); // System.String sval = new String((sbyte[]) values[i], "UTF-8"); if (sval.Length == 0) { // didn't decode well, must be binary result.Append("<binary value, length:" + sval.Length); continue; } result.Append(sval); } result.Append("'"); } result.Append("}"); } catch (Exception e) { throw new Exception(e.ToString()); } return result.ToString(); } } }
namespace Factotum { partial class PipeScheduleEdit { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PipeScheduleEdit)); this.btnOK = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.btnCancel = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtNomDia = new Factotum.TextBoxWithUndo(); this.txtPipeSchedule = new Factotum.TextBoxWithUndo(); this.txtNomWall = new Factotum.TextBoxWithUndo(); this.txtOD = new Factotum.TextBoxWithUndo(); this.label5 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(134, 133); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(64, 22); this.btnOK.TabIndex = 8; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(41, 68); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 13); this.label1.TabIndex = 4; this.label1.Text = "Outside Diameter"; // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.Location = new System.Drawing.Point(204, 133); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(64, 22); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 94); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(121, 13); this.label2.TabIndex = 6; this.label2.Text = "Nominal Wall Thickness"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(53, 16); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(76, 13); this.label3.TabIndex = 0; this.label3.Text = "Pipe Schedule"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(39, 42); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(90, 13); this.label4.TabIndex = 2; this.label4.Text = "Nominal Diameter"; // // txtNomDia // this.txtNomDia.Location = new System.Drawing.Point(135, 39); this.txtNomDia.Name = "txtNomDia"; this.txtNomDia.Size = new System.Drawing.Size(100, 20); this.txtNomDia.TabIndex = 3; this.txtNomDia.TextChanged += new System.EventHandler(this.txtNomDia_TextChanged); this.txtNomDia.Validating += new System.ComponentModel.CancelEventHandler(this.txtNomDia_Validating); // // txtPipeSchedule // this.txtPipeSchedule.Location = new System.Drawing.Point(135, 13); this.txtPipeSchedule.Name = "txtPipeSchedule"; this.txtPipeSchedule.Size = new System.Drawing.Size(100, 20); this.txtPipeSchedule.TabIndex = 1; this.txtPipeSchedule.TextChanged += new System.EventHandler(this.txtPipeSchedule_TextChanged); this.txtPipeSchedule.Validating += new System.ComponentModel.CancelEventHandler(this.txtPipeSchedule_Validating); // // txtNomWall // this.txtNomWall.Location = new System.Drawing.Point(135, 91); this.txtNomWall.Name = "txtNomWall"; this.txtNomWall.Size = new System.Drawing.Size(100, 20); this.txtNomWall.TabIndex = 7; this.txtNomWall.TextChanged += new System.EventHandler(this.txtNomWall_TextChanged); this.txtNomWall.Validating += new System.ComponentModel.CancelEventHandler(this.txtNomWall_Validating); // // txtOD // this.txtOD.Location = new System.Drawing.Point(135, 65); this.txtOD.Name = "txtOD"; this.txtOD.Size = new System.Drawing.Size(100, 20); this.txtOD.TabIndex = 5; this.txtOD.TextChanged += new System.EventHandler(this.txtOD_TextChanged); this.txtOD.Validating += new System.ComponentModel.CancelEventHandler(this.txtOD_Validating); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(254, 42); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(18, 13); this.label5.TabIndex = 11; this.label5.Text = "in."; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(254, 94); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(18, 13); this.label7.TabIndex = 13; this.label7.Text = "in."; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(254, 68); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(18, 13); this.label8.TabIndex = 12; this.label8.Text = "in."; // // PipeScheduleEdit // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(293, 167); this.Controls.Add(this.label5); this.Controls.Add(this.label7); this.Controls.Add(this.label8); this.Controls.Add(this.txtNomDia); this.Controls.Add(this.label4); this.Controls.Add(this.txtPipeSchedule); this.Controls.Add(this.label3); this.Controls.Add(this.txtNomWall); this.Controls.Add(this.label2); this.Controls.Add(this.txtOD); this.Controls.Add(this.btnCancel); this.Controls.Add(this.label1); this.Controls.Add(this.btnOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(284, 201); this.Name = "PipeScheduleEdit"; this.Text = "Edit Pipe Schedule Item"; ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Label label1; private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.Button btnCancel; private TextBoxWithUndo txtOD; private TextBoxWithUndo txtNomDia; private System.Windows.Forms.Label label4; private TextBoxWithUndo txtPipeSchedule; private System.Windows.Forms.Label label3; private TextBoxWithUndo txtNomWall; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.UserModel { using System; using System.Collections.Generic; using NPOI.SS.Util; /// <summary> /// Indicate the position of the margin. One of left, right, top and bottom. /// </summary> public enum MarginType : short { /// <summary> /// referes to the left margin /// </summary> LeftMargin = 0, /// <summary> /// referes to the right margin /// </summary> RightMargin = 1, /// <summary> /// referes to the top margin /// </summary> TopMargin = 2, /// <summary> /// referes to the bottom margin /// </summary> BottomMargin = 3, HeaderMargin = 4, FooterMargin = 5 } /// <summary> /// Define the position of the pane. One of lower/right, upper/right, lower/left and upper/left. /// </summary> public enum PanePosition : byte { /// <summary> /// referes to the lower/right corner /// </summary> LowerRight = 0, /// <summary> /// referes to the upper/right corner /// </summary> UpperRight = 1, /// <summary> /// referes to the lower/left corner /// </summary> LowerLeft = 2, /// <summary> /// referes to the upper/left corner /// </summary> UpperLeft = 3, } /// <summary> /// High level representation of a Excel worksheet. /// </summary> /// <remarks> /// Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. /// The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can /// contain text, numbers, dates, and formulas. Cells can also be formatted. /// </remarks> public interface ISheet //: IEnumerator<IRow> { /// <summary> /// Create a new row within the sheet and return the high level representation /// </summary> /// <param name="rownum">The row number.</param> /// <returns>high level Row object representing a row in the sheet</returns> /// <see>RemoveRow(Row)</see> IRow CreateRow(int rownum); /// <summary> /// Remove a row from this sheet. All cells Contained in the row are Removed as well /// </summary> /// <param name="row">a row to Remove.</param> void RemoveRow(IRow row); /// <summary> /// Returns the logical row (not physical) 0-based. If you ask for a row that is not /// defined you get a null. This is to say row 4 represents the fifth row on a sheet. /// </summary> /// <param name="rownum">row to get (0-based).</param> /// <returns>the rownumber or null if its not defined on the sheet</returns> IRow GetRow(int rownum); /// <summary> /// Returns the number of physically defined rows (NOT the number of rows in the sheet) /// </summary> /// <value>the number of physically defined rows in this sheet.</value> int PhysicalNumberOfRows { get; } /// <summary> /// Gets the first row on the sheet /// </summary> /// <value>the number of the first logical row on the sheet (0-based).</value> int FirstRowNum { get; } /// <summary> /// Gets the last row on the sheet /// </summary> /// <value>last row contained n this sheet (0-based)</value> int LastRowNum { get; } /// <summary> /// whether force formula recalculation. /// </summary> bool ForceFormulaRecalculation { get; set; } /// <summary> /// Get the visibility state for a given column /// </summary> /// <param name="columnIndex">the column to get (0-based)</param> /// <param name="hidden">the visiblity state of the column</param> void SetColumnHidden(int columnIndex, bool hidden); /// <summary> /// Get the hidden state for a given column /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>hidden - <c>false</c> if the column is visible</returns> bool IsColumnHidden(int columnIndex); /// <summary> /// Copy the source row to the target row. If the target row exists, the new copied row will be inserted before the existing one /// </summary> /// <param name="sourceIndex">source index</param> /// <param name="targetIndex">target index</param> /// <returns>the new copied row object</returns> IRow CopyRow(int sourceIndex, int targetIndex); /// <summary> /// Set the width (in units of 1/256th of a character width) /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <param name="width">the width in units of 1/256th of a character width</param> /// <remarks> /// The maximum column width for an individual cell is 255 characters. /// This value represents the number of characters that can be displayed /// in a cell that is formatted with the standard font. /// </remarks> void SetColumnWidth(int columnIndex, int width); /// <summary> /// get the width (in units of 1/256th of a character width ) /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>the width in units of 1/256th of a character width</returns> int GetColumnWidth(int columnIndex); /// <summary> /// Get the default column width for the sheet (if the columns do not define their own width) /// in characters /// </summary> /// <value>default column width measured in characters.</value> int DefaultColumnWidth { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// twips (1/20 of a point) /// </summary> /// <value>default row height measured in twips (1/20 of a point)</value> short DefaultRowHeight { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// points. /// </summary> /// <value>The default row height in points.</value> float DefaultRowHeightInPoints { get; set; } /// <summary> /// Returns the CellStyle that applies to the given /// (0 based) column, or null if no style has been /// set for that column /// </summary> /// <param name="column">The column.</param> ICellStyle GetColumnStyle(int column); /// <summary> /// Adds a merged region of cells (hence those cells form one) /// </summary> /// <param name="region">(rowfrom/colfrom-rowto/colto) to merge.</param> /// <returns>index of this region</returns> int AddMergedRegion(NPOI.SS.Util.CellRangeAddress region); /// <summary> /// Determine whether printed output for this sheet will be horizontally centered. /// </summary> bool HorizontallyCenter { get; set; } /// <summary> /// Determine whether printed output for this sheet will be vertically centered. /// </summary> bool VerticallyCenter { get; set; } /// <summary> /// Removes a merged region of cells (hence letting them free) /// </summary> /// <param name="index">index of the region to unmerge</param> void RemoveMergedRegion(int index); /// <summary> /// Returns the number of merged regions /// </summary> int NumMergedRegions { get; } /// <summary> /// Returns the merged region at the specified index /// </summary> /// <param name="index">The index.</param> NPOI.SS.Util.CellRangeAddress GetMergedRegion(int index); /// <summary> /// Gets the row enumerator. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> System.Collections.IEnumerator GetRowEnumerator(); /// <summary> /// Alias for GetRowEnumerator() to allow <c>foreach</c> loops. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> System.Collections.IEnumerator GetEnumerator(); /// <summary> /// Gets the flag indicating whether the window should show 0 (zero) in cells Containing zero value. /// When false, cells with zero value appear blank instead of showing the number zero. /// </summary> /// <value>whether all zero values on the worksheet are displayed.</value> bool DisplayZeros { get; set; } /// <summary> /// Gets or sets a value indicating whether the sheet displays Automatic Page Breaks. /// </summary> bool Autobreaks { get; set; } /// <summary> /// Get whether to display the guts or not, /// </summary> /// <value>default value is true</value> bool DisplayGuts { get; set; } /// <summary> /// Flag indicating whether the Fit to Page print option is enabled. /// </summary> bool FitToPage { get; set; } /// <summary> /// Flag indicating whether summary rows appear below detail in an outline, when applying an outline. /// /// /// When true a summary row is inserted below the detailed data being summarized and a /// new outline level is established on that row. /// /// /// When false a summary row is inserted above the detailed data being summarized and a new outline level /// is established on that row. /// /// </summary> /// <returns><c>true</c> if row summaries appear below detail in the outline</returns> bool RowSumsBelow { get; set; } /// <summary> /// Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. /// /// /// When true a summary column is inserted to the right of the detailed data being summarized /// and a new outline level is established on that column. /// /// /// When false a summary column is inserted to the left of the detailed data being /// summarized and a new outline level is established on that column. /// /// </summary> /// <returns><c>true</c> if col summaries appear right of the detail in the outline</returns> bool RowSumsRight { get; set; } /// <summary> /// Gets the flag indicating whether this sheet displays the lines /// between rows and columns to make editing and reading easier. /// </summary> /// <returns><c>true</c> if this sheet displays gridlines.</returns> bool IsPrintGridlines { get; set; } /// <summary> /// Gets the print Setup object. /// </summary> /// <returns>The user model for the print Setup object.</returns> IPrintSetup PrintSetup { get; } /// <summary> /// Gets the user model for the default document header. /// <p/> /// Note that XSSF offers more kinds of document headers than HSSF does /// /// </summary> /// <returns>the document header. Never <code>null</code></returns> IHeader Header { get; } /// <summary> /// Gets the user model for the default document footer. /// <p/> /// Note that XSSF offers more kinds of document footers than HSSF does. /// </summary> /// <returns>the document footer. Never <code>null</code></returns> IFooter Footer { get; } /// <summary> /// Gets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <returns>the size of the margin</returns> double GetMargin(MarginType margin); /// <summary> /// Sets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <param name="size">the size of the margin</param> void SetMargin(MarginType margin, double size); /// <summary> /// Answer whether protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool Protect { get; } /// <summary> /// Sets the protection enabled as well as the password /// </summary> /// <param name="password">to set for protection. Pass <code>null</code> to remove protection</param> void ProtectSheet(String password); /// <summary> /// Answer whether scenario protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool ScenarioProtect { get; } /// <summary> /// Gets or sets the tab color of the _sheet /// </summary> short TabColorIndex { get; set; } /// <summary> /// Returns the top-level drawing patriach, if there is one. /// This will hold any graphics or charts for the _sheet. /// WARNING - calling this will trigger a parsing of the /// associated escher records. Any that aren't supported /// (such as charts and complex drawing types) will almost /// certainly be lost or corrupted when written out. Only /// use this with simple drawings, otherwise call /// HSSFSheet#CreateDrawingPatriarch() and /// start from scratch! /// </summary> /// <value>The drawing patriarch.</value> IDrawing DrawingPatriarch { get; } /// <summary> /// Sets the zoom magnication for the sheet. The zoom is expressed as a /// fraction. For example to express a zoom of 75% use 3 for the numerator /// and 4 for the denominator. /// </summary> /// <param name="numerator">The numerator for the zoom magnification.</param> /// <param name="denominator">denominator for the zoom magnification.</param> void SetZoom(int numerator, int denominator); /// <summary> /// The top row in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row.</value> short TopRow { get; set; } /// <summary> /// The left col in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row</value> short LeftCol { get; set; } /// <summary> /// Sets desktop window pane display area, when the /// file is first opened in a viewer. /// </summary> /// <param name="toprow"> the top row to show in desktop window pane</param> /// <param name="leftcol"> the left column to show in desktop window pane</param> void ShowInPane(short toprow, short leftcol); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around. /// /// Calls shiftRows(startRow, endRow, n, false, false); /// /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> void ShiftRows(int startRow, int endRow, int n); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> /// <param name="copyRowHeight">whether to copy the row height during the shift</param> /// <param name="resetOriginalRowHeight">whether to set the original row's height to the default</param> void ShiftRows(int startRow, int endRow, int n, bool copyRowHeight, bool resetOriginalRowHeight); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split</param> /// <param name="rowSplit">Vertical position of split</param> /// <param name="leftmostColumn">Top row visible in bottom pane</param> /// <param name="topRow">Left column visible in right pane</param> void CreateFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split.</param> /// <param name="rowSplit">Vertical position of split.</param> void CreateFreezePane(int colSplit, int rowSplit); /// <summary> /// Creates a split pane. Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="xSplitPos">Horizonatal position of split (in 1/20th of a point)</param> /// <param name="ySplitPos">Vertical position of split (in 1/20th of a point)</param> /// <param name="leftmostColumn">Left column visible in right pane</param> /// <param name="topRow">Top row visible in bottom pane</param> /// <param name="activePane">Active pane. One of: PANE_LOWER_RIGHT, PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT</param> /// @see #PANE_LOWER_LEFT /// @see #PANE_LOWER_RIGHT /// @see #PANE_UPPER_LEFT /// @see #PANE_UPPER_RIGHT void CreateSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, PanePosition activePane); /// <summary> /// Returns the information regarding the currently configured pane (split or freeze) /// </summary> /// <value>if no pane configured returns <c>null</c> else return the pane information.</value> PaneInformation PaneInformation { get; } /// <summary> /// Returns if gridlines are displayed /// </summary> bool DisplayGridlines { get; set; } /// <summary> /// Returns if formulas are displayed /// </summary> bool DisplayFormulas { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool DisplayRowColHeadings { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool IsActive { get; set; } /// <summary> /// Determines if there is a page break at the indicated row /// </summary> /// <param name="row">The row.</param> bool IsRowBroken(int row); /// <summary> /// Removes the page break at the indicated row /// </summary> /// <param name="row">The row index.</param> void RemoveRowBreak(int row); /// <summary> /// Retrieves all the horizontal page breaks /// </summary> /// <value>all the horizontal page breaks, or null if there are no row page breaks</value> int[] RowBreaks { get; } /// <summary> /// Retrieves all the vertical page breaks /// </summary> /// <value>all the vertical page breaks, or null if there are no column page breaks.</value> int[] ColumnBreaks { get; } /// <summary> /// Sets the active cell. /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> void SetActiveCell(int row, int column); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="firstRow">The firstrow.</param> /// <param name="lastRow">The lastrow.</param> /// <param name="firstColumn">The firstcolumn.</param> /// <param name="lastColumn">The lastcolumn.</param> void SetActiveCellRange(int firstRow, int lastRow, int firstColumn, int lastColumn); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="cellranges">The cellranges.</param> /// <param name="activeRange">The index of the active range.</param> /// <param name="activeRow">The active row in the active range</param> /// <param name="activeColumn">The active column in the active range</param> void SetActiveCellRange(List<CellRangeAddress8Bit> cellranges, int activeRange, int activeRow, int activeColumn); /// <summary> /// Sets a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void SetColumnBreak(int column); /// <summary> /// Sets the row break. /// </summary> /// <param name="row">The row.</param> void SetRowBreak(int row); /// <summary> /// Determines if there is a page break at the indicated column /// </summary> /// <param name="column">The column index.</param> bool IsColumnBroken(int column); /// <summary> /// Removes a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void RemoveColumnBreak(int column); /// <summary> /// Expands or collapses a column group. /// </summary> /// <param name="columnNumber">One of the columns in the group.</param> /// <param name="collapsed">if set to <c>true</c>collapse group.<c>false</c>expand group.</param> void SetColumnGroupCollapsed(int columnNumber, bool collapsed); /// <summary> /// Create an outline for the provided column range. /// </summary> /// <param name="fromColumn">beginning of the column range.</param> /// <param name="toColumn">end of the column range.</param> void GroupColumn(int fromColumn, int toColumn); /// <summary> /// Ungroup a range of columns that were previously groupped /// </summary> /// <param name="fromColumn">start column (0-based).</param> /// <param name="toColumn">end column (0-based).</param> void UngroupColumn(int fromColumn, int toColumn); /// <summary> /// Tie a range of rows toGether so that they can be collapsed or expanded /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void GroupRow(int fromRow, int toRow); /// <summary> /// Ungroup a range of rows that were previously groupped /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void UngroupRow(int fromRow, int toRow); /// <summary> /// Set view state of a groupped range of rows /// </summary> /// <param name="row">start row of a groupped range of rows (0-based).</param> /// <param name="collapse">whether to expand/collapse the detail rows.</param> void SetRowGroupCollapsed(int row, bool collapse); /// <summary> /// Sets the default column style for a given column. POI will only apply this style to new cells Added to the sheet. /// </summary> /// <param name="column">the column index</param> /// <param name="style">the style to set</param> void SetDefaultColumnStyle(int column, ICellStyle style); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index.</param> /// <param name="useMergedCells">whether to use the contents of merged cells when /// calculating the width of the column. Default is to ignore merged cells.</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column, bool useMergedCells); /// <summary> /// Returns cell comment for the specified row and column /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> IComment GetCellComment(int row, int column); /// <summary> /// Creates the top-level drawing patriarch. /// </summary> IDrawing CreateDrawingPatriarch(); /// <summary> /// Gets the parent workbook. /// </summary> IWorkbook Workbook { get; } /// <summary> /// Gets the name of the sheet. /// </summary> String SheetName { get; } /// <summary> /// Gets or sets a value indicating whether this sheet is currently selected. /// </summary> bool IsSelected { get; set; } /// <summary> /// Sets whether sheet is selected. /// </summary> /// <param name="sel">Whether to select the sheet or deselect the sheet.</param> void SetActive(bool value); /// <summary> /// Sets array formula to specified region for result. /// </summary> /// <param name="formula">text representation of the formula</param> /// <param name="range">Region of array formula for result</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> SetArrayFormula(String formula, CellRangeAddress range); /// <summary> /// Remove a Array Formula from this sheet. All cells contained in the Array Formula range are removed as well /// </summary> /// <param name="cell">any cell within Array Formula range</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> RemoveArrayFormula(ICell cell); /// <summary> /// Checks if the provided region is part of the merged regions. /// </summary> /// <param name="mergedRegion">Region searched in the merged regions</param> /// <returns><c>true</c>, when the region is contained in at least one of the merged regions</returns> bool IsMergedRegion(CellRangeAddress mergedRegion); /// <summary> /// Create an instance of a DataValidationHelper. /// </summary> /// <returns>Instance of a DataValidationHelper</returns> IDataValidationHelper GetDataValidationHelper(); /// <summary> /// Creates a data validation object /// </summary> /// <param name="dataValidation">The data validation object settings</param> void AddValidationData(IDataValidation dataValidation); /// <summary> /// Enable filtering for a range of cells /// </summary> /// <param name="range">the range of cells to filter</param> IAutoFilter SetAutoFilter(CellRangeAddress range); /// <summary> /// The 'Conditional Formatting' facet for this <c>Sheet</c> /// </summary> /// <returns>conditional formatting rule for this sheet</returns> ISheetConditionalFormatting SheetConditionalFormatting { get; } /// <summary> /// Whether the text is displayed in right-to-left mode in the window /// </summary> bool IsRightToLeft { get; set; } /// <summary> /// Get or set the repeating rows used when printing the sheet, as found in File->PageSetup->Sheet. /// <p/> /// Repeating rows cover a range of contiguous rows, e.g.: /// <pre> /// Sheet1!$1:$1 /// Sheet2!$5:$8 /// </pre> /// The {@link CellRangeAddress} returned contains a column part which spans /// all columns, and a row part which specifies the contiguous range of /// repeating rows. /// <p/> /// If the Sheet does not have any repeating rows defined, null is returned. /// </summary> CellRangeAddress RepeatingRows { get; set; } /// <summary> /// Gets or set the repeating columns used when printing the sheet, as found in File->PageSetup->Sheet. /// <p/> /// Repeating columns cover a range of contiguous columns, e.g.: /// <pre> /// Sheet1!$A:$A /// Sheet2!$C:$F /// </pre> /// The {@link CellRangeAddress} returned contains a row part which spans all /// rows, and a column part which specifies the contiguous range of /// repeating columns. /// <p/> /// If the Sheet does not have any repeating columns defined, null is /// returned. /// </summary> CellRangeAddress RepeatingColumns { get; set; } /// <summary> /// Copy sheet with a new name /// </summary> /// <param name="Name">new sheet name</param> /// <returns>cloned sheet</returns> ISheet CopySheet(String Name); /// <summary> /// Copy sheet with a new name /// </summary> /// <param name="Name">new sheet name</param> /// <param name="copyStyle">whether to copy styles</param> /// <returns>cloned sheet</returns> ISheet CopySheet(String Name, Boolean copyStyle); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Reflection.Runtime.General; using System.Reflection.Runtime.MethodInfos; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using Internal.Reflection.Augments; using IRuntimeImplementedType = Internal.Reflection.Core.NonPortable.IRuntimeImplementedType; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // Abstract base class for all TypeInfo's implemented by the runtime. // // This base class performs several services: // // - Provides default implementations whenever possible. Some of these // return the "common" error result for narrowly applicable properties (such as those // that apply only to generic parameters.) // // - Inverts the DeclaredMembers/DeclaredX relationship (DeclaredMembers is auto-implemented, others // are overriden as abstract. This ordering makes more sense when reading from metadata.) // // - Overrides many "NotImplemented" members in TypeInfo with abstracts so failure to implement // shows up as build error. // [Serializable] [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimeTypeInfo : TypeInfo, ISerializable, ITraceableTypeMember, ICloneable, IRuntimeImplementedType { protected RuntimeTypeInfo() { } public abstract override Assembly Assembly { get; } public sealed override string AssemblyQualifiedName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_AssemblyQualifiedName(this); #endif string fullName = FullName; if (fullName == null) // Some Types (such as generic parameters) return null for FullName by design. return null; string assemblyName = InternalFullNameOfAssembly; return fullName + ", " + assemblyName; } } public sealed override Type AsType() { return this; } public sealed override Type BaseType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_BaseType(this); #endif // If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata. RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) { RuntimeTypeHandle baseTypeHandle; if (ReflectionCoreExecution.ExecutionEnvironment.TryGetBaseType(typeHandle, out baseTypeHandle)) return Type.GetTypeFromHandle(baseTypeHandle); } Type baseType = BaseTypeWithoutTheGenericParameterQuirk; if (baseType != null && baseType.IsGenericParameter) { // Desktop quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object // unless that other generic parameter has a "class" constraint. GenericParameterAttributes genericParameterAttributes = baseType.GenericParameterAttributes; if (0 == (genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint)) baseType = CommonRuntimeTypes.Object; } return baseType; } } public abstract override bool ContainsGenericParameters { get; } // // Left unsealed so that RuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo and RuntimeGenericParameterTypeInfo can override. // public override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_CustomAttributes(this); #endif Debug.Assert(IsArray || IsByRef || IsPointer); return Empty<CustomAttributeData>.Enumerable; } } // // Left unsealed as generic parameter types must override. // public override MethodBase DeclaringMethod { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } // // Equals()/GetHashCode() // // RuntimeTypeInfo objects are interned to preserve the app-compat rule that Type objects (which are the same as TypeInfo objects) // can be compared using reference equality. // // We use weak pointers to intern the objects. This means we can use instance equality to implement Equals() but we cannot use // the instance hashcode to implement GetHashCode() (otherwise, the hash code will not be stable if the TypeInfo is released and recreated.) // Thus, we override and seal Equals() here but defer to a flavor-specific hash code implementation. // public sealed override bool Equals(object obj) { return object.ReferenceEquals(this, obj); } public sealed override bool Equals(Type o) { return object.ReferenceEquals(this, o); } public sealed override int GetHashCode() { return InternalGetHashCode(); } public abstract override string FullName { get; } // // Left unsealed as generic parameter types must override. // public override GenericParameterAttributes GenericParameterAttributes { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } // // Left unsealed as generic parameter types must override this. // public override int GenericParameterPosition { get { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } public sealed override Type[] GenericTypeArguments { get { return InternalRuntimeGenericTypeArguments.CloneTypeArray(); } } public sealed override MemberInfo[] GetDefaultMembers() { string defaultMemberName = GetDefaultMemberName(); return defaultMemberName != null ? GetMember(defaultMemberName) : Array.Empty<MemberInfo>(); } public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_InterfaceMap); } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); UnitySerializationHolder.GetUnitySerializationInfo(info, this); } // // Implements the correct GUID behavior for all "constructed" types (i.e. returning an all-zero GUID.) Left unsealed // so that RuntimeNamedTypeInfo can override. // public override Guid GUID { get { return Guid.Empty; } } public sealed override IEnumerable<Type> ImplementedInterfaces { get { LowLevelListWithIList<Type> result = new LowLevelListWithIList<Type>(); bool done = false; // If this has a RuntimeTypeHandle, let the underlying runtime engine have the first crack. If it refuses, fall back to metadata. RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) { IEnumerable<RuntimeTypeHandle> implementedInterfaces = ReflectionCoreExecution.ExecutionEnvironment.TryGetImplementedInterfaces(typeHandle); if (implementedInterfaces != null) { done = true; foreach (RuntimeTypeHandle th in implementedInterfaces) { result.Add(Type.GetTypeFromHandle(th)); } } } if (!done) { TypeContext typeContext = this.TypeContext; Type baseType = this.BaseTypeWithoutTheGenericParameterQuirk; if (baseType != null) result.AddRange(baseType.GetInterfaces()); foreach (QTypeDefRefOrSpec directlyImplementedInterface in this.TypeRefDefOrSpecsForDirectlyImplementedInterfaces) { Type ifc = directlyImplementedInterface.Resolve(typeContext); if (result.Contains(ifc)) continue; result.Add(ifc); foreach (Type indirectIfc in ifc.GetInterfaces()) { if (result.Contains(indirectIfc)) continue; result.Add(indirectIfc); } } } return result.AsNothingButIEnumerable(); } } public sealed override bool IsAssignableFrom(TypeInfo typeInfo) => IsAssignableFrom((Type)typeInfo); public sealed override bool IsAssignableFrom(Type c) { if (c == null) return false; Type typeInfo = c; RuntimeTypeInfo toTypeInfo = this; if (typeInfo == null || !typeInfo.IsRuntimeImplemented()) return false; // Desktop compat: If typeInfo is null, or implemented by a different Reflection implementation, return "false." RuntimeTypeInfo fromTypeInfo = typeInfo.CastToRuntimeTypeInfo(); if (toTypeInfo.Equals(fromTypeInfo)) return true; RuntimeTypeHandle toTypeHandle = toTypeInfo.InternalTypeHandleIfAvailable; RuntimeTypeHandle fromTypeHandle = fromTypeInfo.InternalTypeHandleIfAvailable; bool haveTypeHandles = !(toTypeHandle.IsNull() || fromTypeHandle.IsNull()); if (haveTypeHandles) { // If both types have type handles, let MRT handle this. It's not dependent on metadata. if (ReflectionCoreExecution.ExecutionEnvironment.IsAssignableFrom(toTypeHandle, fromTypeHandle)) return true; // Runtime IsAssignableFrom does not handle casts from generic type definitions: always returns false. For those, we fall through to the // managed implementation. For everyone else, return "false". // // Runtime IsAssignableFrom does not handle pointer -> UIntPtr cast. if (!(fromTypeInfo.IsGenericTypeDefinition || fromTypeInfo.IsPointer)) return false; } // If we got here, the types are open, or reduced away, or otherwise lacking in type handles. Perform the IsAssignability check in managed code. return Assignability.IsAssignableFrom(this, typeInfo); } // // Left unsealed as constructed generic types must override. // public override bool IsConstructedGenericType { get { return false; } } public sealed override bool IsEnum { get { return 0 != (Classification & TypeClassification.IsEnum); } } // // Left unsealed as generic parameter types must override. // public override bool IsGenericParameter { get { return false; } } // // Left unsealed as generic type definitions must override. // public override bool IsGenericTypeDefinition { get { return false; } } public sealed override bool IsSzArray { get { return IsArrayImpl() && !InternalIsMultiDimArray; } } public sealed override MemberTypes MemberType { get { if (IsPublic || IsNotPublic) return MemberTypes.TypeInfo; else return MemberTypes.NestedType; } } // // Left unsealed as there are so many subclasses. Need to be overriden by EcmaFormatRuntimeNamedTypeInfo and RuntimeConstructedGenericTypeInfo // public abstract override int MetadataToken { get; } public sealed override Module Module { get { return Assembly.ManifestModule; } } public abstract override string Namespace { get; } public sealed override Type[] GenericTypeParameters { get { return RuntimeGenericTypeParameters.CloneTypeArray(); } } // // Left unsealed as array types must override this. // public override int GetArrayRank() { Debug.Assert(!IsArray); throw new ArgumentException(SR.Argument_HasToBeArrayClass); } public sealed override Type GetElementType() { return InternalRuntimeElementType; } // // Left unsealed as generic parameter types must override. // public override Type[] GetGenericParameterConstraints() { Debug.Assert(!IsGenericParameter); throw new InvalidOperationException(SR.Arg_NotGenericParameter); } // // Left unsealed as IsGenericType types must override this. // public override Type GetGenericTypeDefinition() { Debug.Assert(!IsGenericType); throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); } public sealed override Type MakeArrayType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeArrayType(this); #endif // Do not implement this as a call to MakeArrayType(1) - they are not interchangable. MakeArrayType() returns a // vector type ("SZArray") while MakeArrayType(1) returns a multidim array of rank 1. These are distinct types // in the ECMA model and in CLR Reflection. return this.GetArrayType(); } public sealed override Type MakeArrayType(int rank) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeArrayType(this, rank); #endif if (rank <= 0) throw new IndexOutOfRangeException(); return this.GetMultiDimArrayType(rank); } public sealed override Type MakeByRefType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeByRefType(this); #endif return this.GetByRefType(); } public sealed override Type MakeGenericType(params Type[] typeArguments) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakeGenericType(this, typeArguments); #endif if (typeArguments == null) throw new ArgumentNullException(nameof(typeArguments)); if (!IsGenericTypeDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); // We intentionally don't validate the number of arguments or their suitability to the generic type's constraints. // In a pay-for-play world, this can cause needless MissingMetadataExceptions. There is no harm in creating // the Type object for an inconsistent generic type - no EEType will ever match it so any attempt to "invoke" it // will throw an exception. for (int i = 0; i < typeArguments.Length; i++) { if (typeArguments[i] == null) throw new ArgumentNullException(); if (!typeArguments[i].IsRuntimeImplemented()) throw new PlatformNotSupportedException(SR.PlatformNotSupported_MakeGenericType); // "PlatformNotSupported" because on desktop, passing in a foreign type is allowed and creates a RefEmit.TypeBuilder } return this.GetConstructedGenericType(typeArguments.ToRuntimeTypeInfoArray()); } public sealed override Type MakePointerType() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_MakePointerType(this); #endif return this.GetPointerType(); } public sealed override Type DeclaringType { get { return this.InternalDeclaringType; } } public sealed override string Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Name(this); #endif Type rootCauseForFailure = null; string name = InternalGetNameIfAvailable(ref rootCauseForFailure); if (name == null) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(rootCauseForFailure); return name; } } public sealed override Type ReflectedType { get { // Desktop compat: For types, ReflectedType == DeclaringType. Nested types are always looked up as BindingFlags.DeclaredOnly was passed. // For non-nested types, the concept of a ReflectedType doesn't even make sense. return DeclaringType; } } public abstract override StructLayoutAttribute StructLayoutAttribute { get; } public abstract override string ToString(); public sealed override RuntimeTypeHandle TypeHandle { get { RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if (!typeHandle.IsNull()) return typeHandle; // If a constructed type doesn't have an type handle, it's either because the reducer tossed it (in which case, // we would thrown a MissingMetadataException when attempting to construct the type) or because one of // component types contains open type parameters. Since we eliminated the first case, it must be the second. // Throwing PlatformNotSupported since the desktop does, in fact, create type handles for open types. if (HasElementType || IsConstructedGenericType || IsGenericParameter) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NoTypeHandleForOpenTypes); // If got here, this is a "plain old type" that has metadata but no type handle. We can get here if the only // representation of the type is in the native metadata and there's no EEType at the runtime side. // If you squint hard, this is a missing metadata situation - the metadata is missing on the runtime side - and // the action for the user to take is the same: go mess with RD.XML. throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override Type UnderlyingSystemType { get { return this; } } protected abstract override TypeAttributes GetAttributeFlagsImpl(); // // Left unsealed so that RuntimeHasElementTypeInfo can override. // protected override bool HasElementTypeImpl() { return false; } protected sealed override TypeCode GetTypeCodeImpl() { return ReflectionAugments.GetRuntimeTypeCode(this); } protected abstract int InternalGetHashCode(); // // Left unsealed since array types must override. // protected override bool IsArrayImpl() { return false; } // // Left unsealed since byref types must override. // protected override bool IsByRefImpl() { return false; } // // Left unsealed since pointer types must override. // protected override bool IsPointerImpl() { return false; } protected sealed override bool IsCOMObjectImpl() { return ReflectionCoreExecution.ExecutionEnvironment.IsCOMObject(this); } protected sealed override bool IsPrimitiveImpl() { return 0 != (Classification & TypeClassification.IsPrimitive); } protected sealed override bool IsValueTypeImpl() { return 0 != (Classification & TypeClassification.IsValueType); } String ITraceableTypeMember.MemberName { get { string name = InternalNameIfAvailable; return name ?? string.Empty; } } Type ITraceableTypeMember.ContainingType { get { return this.InternalDeclaringType; } } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // a base class and interface list based on its constraints. // internal virtual RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return null; } } internal abstract Type InternalDeclaringType { get; } // // Return the full name of the "defining assembly" for the purpose of computing TypeInfo.AssemblyQualifiedName; // internal abstract string InternalFullNameOfAssembly { get; } public abstract override string InternalGetNameIfAvailable(ref Type rootCauseForFailure); // Left unsealed so that multidim arrays can override. internal virtual bool InternalIsMultiDimArray { get { return false; } } // // Left unsealed as HasElement types must override this. // internal virtual RuntimeTypeInfo InternalRuntimeElementType { get { Debug.Assert(!HasElementType); return null; } } // // Left unsealed as constructed generic types must override this. // internal virtual RuntimeTypeInfo[] InternalRuntimeGenericTypeArguments { get { Debug.Assert(!IsConstructedGenericType); return Array.Empty<RuntimeTypeInfo>(); } } internal abstract RuntimeTypeHandle InternalTypeHandleIfAvailable { get; } internal bool IsDelegate { get { return 0 != (Classification & TypeClassification.IsDelegate); } } // // Returns true if it's possible to ask for a list of members and the base type without triggering a MissingMetadataException. // internal abstract bool CanBrowseWithoutMissingMetadataExceptions { get; } // // The non-public version of TypeInfo.GenericTypeParameters (does not array-copy.) // internal virtual RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { Debug.Assert(!(this is RuntimeNamedTypeInfo)); return Array.Empty<RuntimeTypeInfo>(); } } // // Normally returns empty: Overridden by array types to return constructors. // internal virtual IEnumerable<RuntimeConstructorInfo> SyntheticConstructors { get { return Empty<RuntimeConstructorInfo>.Enumerable; } } // // Normally returns empty: Overridden by array types to return the "Get" and "Set" methods. // internal virtual IEnumerable<RuntimeMethodInfo> SyntheticMethods { get { return Empty<RuntimeMethodInfo>.Enumerable; } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // // If you override this method, there is no need to override BaseTypeWithoutTheGenericParameterQuirk. // internal virtual QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { return QTypeDefRefOrSpec.Null; } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal virtual QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { return Array.Empty<QTypeDefRefOrSpec>(); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal virtual TypeContext TypeContext { get { return new TypeContext(null, null); } } // // Note: This can be (and is) called multiple times. We do not do this work in the constructor as calling ToString() // in the constructor causes some serious recursion issues. // internal void EstablishDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. String debugName; #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) debugName = this.GetTraceString(); // If tracing on, call this.GetTraceString() which only gives you useful strings when metadata is available but doesn't pollute the ETW trace. else #endif debugName = this.ToString(); if (debugName == null) debugName = ""; _debugName = debugName; } return; } // // This internal method implements BaseType without the following desktop quirk: // // class Foo<X,Y> // where X:Y // where Y:MyReferenceClass // // The desktop reports "X"'s base type as "System.Object" rather than "Y", even though it does // report any interfaces that are in MyReferenceClass's interface list. // // This seriously messes up the implementation of RuntimeTypeInfo.ImplementedInterfaces which assumes // that it can recover the transitive interface closure by combining the directly mentioned interfaces and // the BaseType's own interface closure. // // To implement this with the least amount of code smell, we'll implement the idealized version of BaseType here // and make the special-case adjustment in the public version of BaseType. // // If you override this method, there is no need to overrride TypeRefDefOrSpecForBaseType. // // This method is left unsealed so that RuntimeCLSIDTypeInfo can override. // internal virtual Type BaseTypeWithoutTheGenericParameterQuirk { get { QTypeDefRefOrSpec baseTypeDefRefOrSpec = TypeRefDefOrSpecForBaseType; RuntimeTypeInfo baseType = null; if (!baseTypeDefRefOrSpec.IsValid) { baseType = baseTypeDefRefOrSpec.Resolve(this.TypeContext); } return baseType; } } private string GetDefaultMemberName() { Type defaultMemberAttributeType = typeof(DefaultMemberAttribute); for (Type type = this; type != null; type = type.BaseType) { foreach (CustomAttributeData attribute in type.CustomAttributes) { if (attribute.AttributeType == defaultMemberAttributeType) { // NOTE: Neither indexing nor cast can fail here. Any attempt to use fewer than 1 argument // or a non-string argument would correctly trigger MissingMethodException before // we reach here as that would be an attempt to reference a non-existent DefaultMemberAttribute // constructor. Debug.Assert(attribute.ConstructorArguments.Count == 1 && attribute.ConstructorArguments[0].Value is string); string memberName = (string)(attribute.ConstructorArguments[0].Value); return memberName; } } } return null; } // // Returns a latched set of flags indicating the value of IsValueType, IsEnum, etc. // private TypeClassification Classification { get { if (_lazyClassification == 0) { TypeClassification classification = TypeClassification.Computed; Type baseType = this.BaseType; if (baseType != null) { Type enumType = CommonRuntimeTypes.Enum; Type valueType = CommonRuntimeTypes.ValueType; if (baseType.Equals(enumType)) classification |= TypeClassification.IsEnum | TypeClassification.IsValueType; if (baseType.Equals(CommonRuntimeTypes.MulticastDelegate)) classification |= TypeClassification.IsDelegate; if (baseType.Equals(valueType) && !(this.Equals(enumType))) { classification |= TypeClassification.IsValueType; foreach (Type primitiveType in ReflectionCoreExecution.ExecutionDomain.PrimitiveTypes) { if (this.Equals(primitiveType)) { classification |= TypeClassification.IsPrimitive; break; } } } } _lazyClassification = classification; } return _lazyClassification; } } [Flags] private enum TypeClassification { Computed = 0x00000001, // Always set (to indicate that the lazy evaluation has occurred) IsValueType = 0x00000002, IsEnum = 0x00000004, IsPrimitive = 0x00000008, IsDelegate = 0x00000010, } object ICloneable.Clone() { return this; } private volatile TypeClassification _lazyClassification; private String _debugName; } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Indicators.Algo File: ParabolicSar.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Indicators { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Ecng.Serialization; using StockSharp.Algo.Candles; using StockSharp.Localization; /// <summary> /// Trend indicator implementation - Parabolic SAR. /// </summary> /// <remarks> /// http://ta.mql4.com/indicators/trends/parabolic_sar. /// </remarks> [DisplayName("Parabolic SAR")] [DescriptionLoc(LocalizedStrings.Str809Key)] public class ParabolicSar : BaseIndicator { private decimal _prevValue; private readonly List<Candle> _candles = new List<Candle>(); private bool _longPosition; private decimal _xp; // Extreme Price private decimal _af; // Acceleration factor private int _prevBar; private bool _afIncreased; private int _reverseBar; private decimal _reverseValue; private decimal _prevSar; private decimal _todaySar; /// <summary> /// Initializes a new instance of the <see cref="ParabolicSar"/>. /// </summary> public ParabolicSar() { Acceleration = 0.02M; AccelerationStep = 0.02M; AccelerationMax = 0.2M; } /// <summary> /// Acceleration factor. /// </summary> [DisplayNameLoc(LocalizedStrings.Str810Key)] [DescriptionLoc(LocalizedStrings.Str811Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal Acceleration { get; set; } /// <summary> /// Acceleration factor step. /// </summary> [DisplayNameLoc(LocalizedStrings.Str812Key)] [DescriptionLoc(LocalizedStrings.Str813Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal AccelerationStep { get; set; } /// <summary> /// Maximum acceleration factor. /// </summary> [DisplayNameLoc(LocalizedStrings.MaxKey)] [DescriptionLoc(LocalizedStrings.Str815Key)] [CategoryLoc(LocalizedStrings.GeneralKey)] public decimal AccelerationMax { get; set; } /// <summary> /// To handle the input value. /// </summary> /// <param name="input">The input value.</param> /// <returns>The resulting value.</returns> protected override IIndicatorValue OnProcess(IIndicatorValue input) { var candle = input.GetValue<Candle>(); if (_candles.Count == 0) _candles.Add(candle); _prevValue = this.GetCurrentValue(); if (candle.OpenTime != _candles[_candles.Count - 1].OpenTime) { _candles.Add(candle); //_prevValue = this.GetCurrentValue(); } else _candles[_candles.Count - 1] = candle; if (_candles.Count < 3) return new DecimalIndicatorValue(this, _prevValue); if (_candles.Count == 3) { _longPosition = _candles[_candles.Count - 1].HighPrice > _candles[_candles.Count - 2].HighPrice; var max = _candles.Max(t => t.HighPrice); var min = _candles.Min(t => t.LowPrice); _xp = _longPosition ? max : min; _af = Acceleration; return new DecimalIndicatorValue(this, _xp + (_longPosition ? -1 : 1) * (max - min) * _af); } if (_afIncreased && _prevBar != _candles.Count) _afIncreased = false; if (input.IsFinal) IsFormed = true; var value = _prevValue; if (_reverseBar != _candles.Count) { _todaySar = TodaySar(_prevValue + _af * (_xp - _prevValue)); for (var x = 1; x <= 2; x++) { if (_longPosition) { if (_todaySar > _candles[_candles.Count - 1 - x].LowPrice) _todaySar = _candles[_candles.Count - 1 - x].LowPrice; } else { if (_todaySar < _candles[_candles.Count - 1 - x].HighPrice) _todaySar = _candles[_candles.Count - 1 - x].HighPrice; } } if ((_longPosition && (_candles[_candles.Count - 1].LowPrice < _todaySar || _candles[_candles.Count - 2].LowPrice < _todaySar)) || (!_longPosition && (_candles[_candles.Count - 1].HighPrice > _todaySar || _candles[_candles.Count - 2].HighPrice > _todaySar))) { return new DecimalIndicatorValue(this, Reverse()); } if (_longPosition) { if (_prevBar != _candles.Count || _candles[_candles.Count - 1].LowPrice < _prevSar) { value = _todaySar; _prevSar = _todaySar; } else value = _prevSar; if (_candles[_candles.Count - 1].HighPrice > _xp) { _xp = _candles[_candles.Count - 1].HighPrice; AfIncrease(); } } else if (!_longPosition) { if (_prevBar != _candles.Count || _candles[_candles.Count - 1].HighPrice > _prevSar) { value = _todaySar; _prevSar = _todaySar; } else value = _prevSar; if (_candles[_candles.Count - 1].LowPrice < _xp) { _xp = _candles[_candles.Count - 1].LowPrice; AfIncrease(); } } } else { if (_longPosition && _candles[_candles.Count - 1].HighPrice > _xp) _xp = _candles[_candles.Count - 1].HighPrice; else if (!_longPosition && _candles[_candles.Count - 1].LowPrice < _xp) _xp = _candles[_candles.Count - 1].LowPrice; value = _prevSar; _todaySar = TodaySar(_longPosition ? Math.Min(_reverseValue, _candles[_candles.Count - 1].LowPrice) : Math.Max(_reverseValue, _candles[_candles.Count - 1].HighPrice)); } _prevBar = _candles.Count; return new DecimalIndicatorValue(this, value); } private decimal TodaySar(decimal todaySar) { if (_longPosition) { var lowestSar = Math.Min(Math.Min(todaySar, _candles[_candles.Count - 1].LowPrice), _candles[_candles.Count - 2].LowPrice); todaySar = _candles[_candles.Count - 1].LowPrice > lowestSar ? lowestSar : Reverse(); } else { var highestSar = Math.Max(Math.Max(todaySar, _candles[_candles.Count - 1].HighPrice), _candles[_candles.Count - 2].HighPrice); todaySar = _candles[_candles.Count - 1].HighPrice < highestSar ? highestSar : Reverse(); } return todaySar; } private decimal Reverse() { var todaySar = _xp; if ((_longPosition && _prevSar > _candles[_candles.Count - 1].LowPrice) || (!_longPosition && _prevSar < _candles[_candles.Count - 1].HighPrice) || _prevBar != _candles.Count) { _longPosition = !_longPosition; _reverseBar = _candles.Count; _reverseValue = _xp; _af = Acceleration; _xp = _longPosition ? _candles[_candles.Count - 1].HighPrice : _candles[_candles.Count - 1].LowPrice; _prevSar = todaySar; } else todaySar = _prevSar; return todaySar; } private void AfIncrease() { if (_afIncreased) return; _af = Math.Min(AccelerationMax, _af + AccelerationStep); _afIncreased = true; } /// <summary> /// Load settings. /// </summary> /// <param name="settings">Settings storage.</param> public override void Load(SettingsStorage settings) { base.Load(settings); Acceleration = settings.GetValue(nameof(Acceleration), 0.02M); AccelerationMax = settings.GetValue(nameof(AccelerationMax), 0.2M); AccelerationStep = settings.GetValue(nameof(AccelerationStep), 0.02M); } /// <summary> /// Save settings. /// </summary> /// <param name="settings">Settings storage.</param> public override void Save(SettingsStorage settings) { base.Save(settings); settings.SetValue(nameof(Acceleration), Acceleration); settings.SetValue(nameof(AccelerationMax), AccelerationMax); settings.SetValue(nameof(AccelerationStep), AccelerationStep); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Validation; using Xunit; using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>; namespace System.Collections.Immutable.Test { public abstract class ImmutableSetTest : ImmutablesTestBase { [Fact] public void AddTest() { this.AddTestHelper(this.Empty<int>(), 3, 5, 4, 3); } [Fact] public void AddDuplicatesTest() { var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray(); this.AddTestHelper(this.Empty<int>(), arrayWithDuplicates); } [Fact] public void RemoveTest() { this.RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3); } [Fact] public void AddRemoveLoadTest() { var data = this.GenerateDummyFillData(); this.AddRemoveLoadTestHelper(Empty<double>(), data); } [Fact] public void RemoveNonExistingTest() { this.RemoveNonExistingTest(this.Empty<int>()); } [Fact] public void AddBulkFromImmutableToEmpty() { var set = this.Empty<int>().Add(5); var empty2 = this.Empty<int>(); Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set." } [Fact] public void ExceptTest() { this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7); } [Fact] public void SymmetricExceptTest() { this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray()); this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray()); } [Fact] public void EnumeratorTest() { IComparer<double> comparer = null; var set = this.Empty<double>(); var sortedSet = set as ISortKeyCollection<double>; if (sortedSet != null) { comparer = sortedSet.KeyComparer; } this.EnumeratorTestHelper(set, comparer, 3, 5, 1); double[] data = this.GenerateDummyFillData(); this.EnumeratorTestHelper(set, comparer, data); } [Fact] public void IntersectTest() { this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5); } [Fact] public void UnionTest() { this.UnionTestHelper(this.Empty<int>(), new[] { 1, 3, 5, 7 }); this.UnionTestHelper(this.Empty<int>().Union(new[] { 2, 4, 6 }), new[] { 1, 3, 5, 7 }); this.UnionTestHelper(this.Empty<int>().Union(new[] { 1, 2, 3 }), new int[0] { }); this.UnionTestHelper(this.Empty<int>().Union(new[] { 2 }), Enumerable.Range(0, 1000).ToArray()); } [Fact] public void SetEqualsTest() { this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios()); } [Fact] public void IsProperSubsetOfTest() { this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, this.GetIsProperSubsetOfScenarios()); } [Fact] public void IsProperSupersetOfTest() { this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, this.GetIsProperSubsetOfScenarios().Select(Flip)); } [Fact] public void IsSubsetOfTest() { this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, this.GetIsSubsetOfScenarios()); } [Fact] public void IsSupersetOfTest() { this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, this.GetIsSubsetOfScenarios().Select(Flip)); } [Fact] public void OverlapsTest() { this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, this.GetOverlapsScenarios()); } [Fact] public void EqualsTest() { Assert.False(Empty<int>().Equals(null)); Assert.False(Empty<int>().Equals("hi")); Assert.True(Empty<int>().Equals(Empty<int>())); Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3))); Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3))); Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3))); Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5))); } [Fact] public void GetHashCodeTest() { // verify that get hash code is the default address based one. Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode()); } [Fact] public void ClearTest() { var originalSet = this.Empty<int>(); var nonEmptySet = originalSet.Add(5); var clearedSet = nonEmptySet.Clear(); Assert.Same(originalSet, clearedSet); } [Fact] public void ISetMutationMethods() { var set = (ISet<int>)this.Empty<int>(); Assert.Throws<NotSupportedException>(() => set.Add(0)); Assert.Throws<NotSupportedException>(() => set.ExceptWith(null)); Assert.Throws<NotSupportedException>(() => set.UnionWith(null)); Assert.Throws<NotSupportedException>(() => set.IntersectWith(null)); Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null)); } [Fact] public void ICollectionOfTMembers() { var set = (ICollection<int>)this.Empty<int>(); Assert.Throws<NotSupportedException>(() => set.Add(1)); Assert.Throws<NotSupportedException>(() => set.Clear()); Assert.Throws<NotSupportedException>(() => set.Remove(1)); Assert.True(set.IsReadOnly); } [Fact] public void ICollectionMethods() { ICollection builder = (ICollection)this.Empty<string>(); string[] array = new string[0]; builder.CopyTo(array, 0); builder = (ICollection)this.Empty<string>().Add("a"); array = new string[builder.Count + 1]; builder.CopyTo(array, 1); Assert.Equal(new[] { null, "a" }, array); Assert.True(builder.IsSynchronized); Assert.NotNull(builder.SyncRoot); Assert.Same(builder.SyncRoot, builder.SyncRoot); } protected abstract bool IncludesGetHashCodeDerivative { get; } internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence) { Contract.Requires(sequence != null); var list = new List<T>(); var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { list.Add((T)enumerator.Current); } return list; } protected abstract IImmutableSet<T> Empty<T>(); protected abstract ISet<T> EmptyMutable<T>(); protected void TryGetValueTestHelper(IImmutableSet<string> set) { Requires.NotNull(set, "set"); string expected = "egg"; set = set.Add(expected); string actual; string lookupValue = expected.ToUpperInvariant(); Assert.True(set.TryGetValue(lookupValue, out actual)); Assert.Same(expected, actual); Assert.False(set.TryGetValue("foo", out actual)); Assert.Equal("foo", actual); Assert.False(set.Clear().TryGetValue("nonexistent", out actual)); Assert.Equal("nonexistent", actual); } protected IImmutableSet<T> SetWith<T>(params T[] items) { return this.Empty<T>().Union(items); } protected void CustomSortTestHelper<T>(IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues) { Contract.Requires(emptySet != null); Contract.Requires(injectedValues != null); Contract.Requires(expectedValues != null); var set = emptySet; foreach (T value in injectedValues) { set = set.Add(value); } Assert.Equal(expectedValues.Length, set.Count); if (matchOrder) { Assert.Equal<T>(expectedValues, set.ToList()); } else { CollectionAssertAreEquivalent(expectedValues, set.ToList()); } } /// <summary> /// Tests various aspects of a set. This should be called only from the unordered or sorted overloads of this method. /// </summary> /// <typeparam name="T">The type of element stored in the set.</typeparam> /// <param name="emptySet">The empty set.</param> protected void EmptyTestHelper<T>(IImmutableSet<T> emptySet) { Contract.Requires(emptySet != null); Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0"); Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements."); Assert.Same(emptySet, emptySet.Clear()); } private IEnumerable<SetTriad> GetSetEqualsScenarios() { return new List<SetTriad> { new SetTriad(SetWith<int>(), new int[] { }, true), new SetTriad(SetWith<int>(5), new int[] { 5 }, true), new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true), new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false), new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false), new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true), new SetTriad(SetWith<int>(5), new int[] { }, false), new SetTriad(SetWith<int>(), new int[] { 5 }, false), new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false), new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false), }; } private IEnumerable<SetTriad> GetIsProperSubsetOfScenarios() { return new List<SetTriad> { new SetTriad(new int[] { }, new int[] { }, false), new SetTriad(new int[] { 1 }, new int[] { }, false), new SetTriad(new int[] { 1 }, new int[] { 2 }, false), new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false), new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true), new SetTriad(new int[] { }, new int[] { 1 }, true), }; } private IEnumerable<SetTriad> GetIsSubsetOfScenarios() { var results = new List<SetTriad> { new SetTriad(new int[] { }, new int[] { }, true), new SetTriad(new int[] { 1 }, new int[] { 1 }, true), new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true), new SetTriad(new int[] { 1 }, new int[] { }, false), new SetTriad(new int[] { 1 }, new int[] { 2 }, false), new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false), }; // By definition, any proper subset is also a subset. // But because a subset may not be a proper subset, we filter the proper- scenarios. results.AddRange(this.GetIsProperSubsetOfScenarios().Where(s => s.Item3)); return results; } private IEnumerable<SetTriad> GetOverlapsScenarios() { return new List<SetTriad> { new SetTriad(new int[] { }, new int[] { }, false), new SetTriad(new int[] { }, new int[] { 1 }, false), new SetTriad(new int[] { 1 }, new int[] { 2 }, false), new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false), new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false), new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true), new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true), new SetTriad(new int[] { 1 }, new int[] { 1 }, true), new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true), }; } private void SetCompareTestHelper<T>(Func<IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios) { //const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}"; int iteration = 0; foreach (var scenario in scenarios) { iteration++; // Figure out the response expected based on the BCL mutable collections. var baselineSet = this.EmptyMutable<T>(); baselineSet.UnionWith(scenario.Item1); var expectedFunc = baselineOperation(baselineSet); bool expected = expectedFunc(scenario.Item2); Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior."); var actualFunc = operation(this.SetWith(scenario.Item1.ToArray())); var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) }; Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args); Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args); } } private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario) { return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3); } private void RemoveTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); Assert.Same(set, set.Except(Enumerable.Empty<T>())); int initialCount = set.Count; int removedCount = 0; foreach (T value in values) { var nextSet = set.Remove(value); Assert.NotSame(set, nextSet); Assert.Equal(initialCount - removedCount, set.Count); Assert.Equal(initialCount - removedCount - 1, nextSet.Count); Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference."); removedCount++; set = nextSet; } Assert.Equal(initialCount - removedCount, set.Count); } private void RemoveNonExistingTest(IImmutableSet<int> emptySet) { Assert.Same(emptySet, emptySet.Remove(5)); // Also fill up a set with many elements to build up the tree, then remove from various places in the tree. const int Size = 200; var set = emptySet; for (int i = 0; i < Size; i += 2) { // only even numbers! set = set.Add(i); } // Verify that removing odd numbers doesn't change anything. for (int i = 1; i < Size; i += 2) { var setAfterRemoval = set.Remove(i); Assert.Same(set, setAfterRemoval); } } private void AddRemoveLoadTestHelper<T>(IImmutableSet<T> set, T[] data) { Contract.Requires(set != null); Contract.Requires(data != null); foreach (T value in data) { var newSet = set.Add(value); Assert.NotSame(set, newSet); set = newSet; } foreach (T value in data) { Assert.True(set.Contains(value)); } foreach (T value in data) { var newSet = set.Remove(value); Assert.NotSame(set, newSet); set = newSet; } } protected void EnumeratorTestHelper<T>(IImmutableSet<T> emptySet, IComparer<T> comparer, params T[] values) { var set = emptySet; foreach (T value in values) { set = set.Add(value); } var nonGenericEnumerableList = ToListNonGeneric<T>(set); CollectionAssertAreEquivalent(nonGenericEnumerableList, values); var list = set.ToList(); CollectionAssertAreEquivalent(list, values); if (comparer != null) { Array.Sort(values, comparer); Assert.Equal<T>(values, list); } // Apply some less common uses to the enumerator to test its metal. IEnumerator<T> enumerator; using (enumerator = set.GetEnumerator()) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); // reset isn't usually called before MoveNext Assert.Throws<InvalidOperationException>(() => enumerator.Current); ManuallyEnumerateTest(list, enumerator); Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); ManuallyEnumerateTest(list, enumerator); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); } private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove) { Contract.Requires(set != null); Contract.Requires(valuesToRemove != null); var expectedSet = new HashSet<T>(set); expectedSet.ExceptWith(valuesToRemove); var actualSet = set.Except(valuesToRemove); CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList()); } private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection) { Contract.Requires(set != null); Contract.Requires(otherCollection != null); var expectedSet = new HashSet<T>(set); expectedSet.SymmetricExceptWith(otherCollection); var actualSet = set.SymmetricExcept(otherCollection); CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList()); } private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0); var expected = new HashSet<T>(set); expected.IntersectWith(values); var actual = set.Intersect(values); CollectionAssertAreEquivalent(expected.ToList(), actual.ToList()); } private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); var expected = new HashSet<T>(set); expected.UnionWith(values); var actual = set.Union(values); CollectionAssertAreEquivalent(expected.ToList(), actual.ToList()); } private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values) { Contract.Requires(set != null); Contract.Requires(values != null); Assert.Same(set, set.Union(Enumerable.Empty<T>())); int initialCount = set.Count; var uniqueValues = new HashSet<T>(values); var enumerateAddSet = set.Union(values); Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count); foreach (T value in values) { Assert.True(enumerateAddSet.Contains(value)); } int addedCount = 0; foreach (T value in values) { bool duplicate = set.Contains(value); var nextSet = set.Add(value); Assert.True(nextSet.Count > 0); Assert.Equal(initialCount + addedCount, set.Count); int expectedCount = initialCount + addedCount; if (!duplicate) { expectedCount++; } Assert.Equal(expectedCount, nextSet.Count); Assert.Equal(duplicate, set.Contains(value)); Assert.True(nextSet.Contains(value)); if (!duplicate) { addedCount++; } // Next assert temporarily disabled because Roslyn's set doesn't follow this rule. Assert.Same(nextSet, nextSet.Add(value)); //, "Adding duplicate value {0} should keep the original reference.", value); set = nextSet; } } } }
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif using UnityEngine; using UnityEditor; using Pathfinding; using System.Collections; using Pathfinding.Serialization.JsonFx; namespace Pathfinding { /* #if !AstarRelease [CustomGraphEditor (typeof(CustomGridGraph),"CustomGrid Graph")] //[CustomGraphEditor (typeof(LineTraceGraph),"Grid Tracing Graph")] #endif */ [CustomGraphEditor (typeof(GridGraph),"Grid Graph")] public class GridGraphEditor : GraphEditor { [JsonMember] public bool locked = true; float newNodeSize; [JsonMember] public bool showExtra = false; /** Should textures be allowed to be used. * This can be set to false by inheriting graphs not implemeting that feature */ [JsonMember] public bool textureVisible = true; Matrix4x4 savedMatrix; Vector3 savedCenter; public bool isMouseDown = false; [JsonMember] public GridPivot pivot; GraphNode node1; /** Rounds a vector's components to whole numbers if very close to them */ public static Vector3 RoundVector3 ( Vector3 v ) { if (Mathf.Abs ( v.x - Mathf.Round(v.x)) < 0.001f ) v.x = Mathf.Round ( v.x ); if (Mathf.Abs ( v.y - Mathf.Round(v.y)) < 0.001f ) v.y = Mathf.Round ( v.y ); if (Mathf.Abs ( v.z - Mathf.Round(v.z)) < 0.001f ) v.z = Mathf.Round ( v.z ); return v; } #if UNITY_LE_4_3 /** Draws an integer field */ public int IntField (string label, int value, int offset, int adjust, out Rect r) { return IntField (new GUIContent (label),value,offset,adjust,out r); } /** Draws an integer field */ public int IntField (GUIContent label, int value, int offset, int adjust, out Rect r) { GUIStyle intStyle = EditorStyles.numberField; EditorGUILayoutx.BeginIndent (); Rect r1 = GUILayoutUtility.GetRect (label,intStyle); Rect r2 = GUILayoutUtility.GetRect (new GUIContent (value.ToString ()),intStyle); EditorGUILayoutx.EndIndent(); r2.width += (r2.x-r1.x); r2.x = r1.x+offset; r2.width -= offset+offset+adjust; r = new Rect (); r.x = r2.x+r2.width; r.y = r1.y; r.width = offset; r.height = r1.height; GUI.SetNextControlName ("IntField_"+label.text); value = EditorGUI.IntField (r2,"",value); bool on = GUI.GetNameOfFocusedControl () == "IntField_"+label.text; if (Event.current.type == EventType.Repaint) { intStyle.Draw (r1,label,false,false,false,on); } return value; } #endif public override void OnInspectorGUI (NavGraph target) { GridGraph graph = target as GridGraph; //GUILayout.BeginHorizontal (); //GUILayout.BeginVertical (); Rect lockRect; GUIStyle lockStyle = AstarPathEditor.astarSkin.FindStyle ("GridSizeLock"); if (lockStyle == null) { lockStyle = new GUIStyle (); } #if !UNITY_LE_4_3 || true GUILayout.BeginHorizontal (); GUILayout.BeginVertical (); int newWidth = EditorGUILayout.IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"), graph.width); int newDepth = EditorGUILayout.IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"), graph.depth); GUILayout.EndVertical (); lockRect = GUILayoutUtility.GetRect (lockStyle.fixedWidth,lockStyle.fixedHeight); // Add a small offset to make it better centred around the controls lockRect.y += 3; GUILayout.EndHorizontal (); // All the layouts mess up the margin to the next control, so add it manually GUILayout.Space (2); #elif UNITY_4 Rect tmpLockRect; int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,100,0, out lockRect, out sizeSelected1); int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,100,0, out tmpLockRect, out sizeSelected2); #else Rect tmpLockRect; int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,50,0, out lockRect, out sizeSelected1); int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,50,0, out tmpLockRect, out sizeSelected2); #endif lockRect.width = lockStyle.fixedWidth; lockRect.height = lockStyle.fixedHeight; lockRect.x += lockStyle.margin.left; lockRect.y += lockStyle.margin.top; locked = GUI.Toggle (lockRect,locked,new GUIContent ("","If the width and depth values are locked, changing the node size will scale the grid which keeping the number of nodes consistent instead of keeping the size the same and changing the number of nodes in the graph"),lockStyle); //GUILayout.EndHorizontal (); if (newWidth != graph.width || newDepth != graph.depth) { SnapSizeToNodes (newWidth,newDepth,graph); } GUI.SetNextControlName ("NodeSize"); newNodeSize = EditorGUILayout.FloatField (new GUIContent ("Node size","The size of a single node. The size is the side of the node square in world units"),graph.nodeSize); newNodeSize = newNodeSize <= 0.01F ? 0.01F : newNodeSize; float prevRatio = graph.aspectRatio; graph.aspectRatio = EditorGUILayout.FloatField (new GUIContent ("Aspect Ratio","Scaling of the nodes width/depth ratio. Good for isometric games"),graph.aspectRatio); graph.isometricAngle = EditorGUILayout.FloatField (new GUIContent ("Isometric Angle", "For an isometric 2D game, you can use this parameter to scale the graph correctly."), graph.isometricAngle); if (graph.nodeSize != newNodeSize || prevRatio != graph.aspectRatio) { if (!locked) { graph.nodeSize = newNodeSize; Matrix4x4 oldMatrix = graph.matrix; graph.GenerateMatrix (); if (graph.matrix != oldMatrix) { //Rescann the graphs //AstarPath.active.AutoScan (); GUI.changed = true; } } else { float delta = newNodeSize / graph.nodeSize; graph.nodeSize = newNodeSize; graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize); Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 ((newWidth/2F)*delta,0,(newDepth/2F)*delta)); graph.center = newCenter; graph.GenerateMatrix (); //Make sure the width & depths stay the same graph.width = newWidth; graph.depth = newDepth; AutoScan (); } } Vector3 pivotPoint; Vector3 diff; #if UNITY_LE_4_3 EditorGUIUtility.LookLikeControls (); #endif #if !UNITY_4 EditorGUILayoutx.BeginIndent (); #else GUILayout.BeginHorizontal (); #endif switch (pivot) { case GridPivot.Center: graph.center = RoundVector3 ( graph.center ); graph.center = EditorGUILayout.Vector3Field ("Center",graph.center); break; case GridPivot.TopLeft: pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,graph.depth)); pivotPoint = RoundVector3 ( pivotPoint ); diff = pivotPoint-graph.center; pivotPoint = EditorGUILayout.Vector3Field ("Top-Left",pivotPoint); graph.center = pivotPoint-diff; break; case GridPivot.TopRight: pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,graph.depth)); pivotPoint = RoundVector3 ( pivotPoint ); diff = pivotPoint-graph.center; pivotPoint = EditorGUILayout.Vector3Field ("Top-Right",pivotPoint); graph.center = pivotPoint-diff; break; case GridPivot.BottomLeft: pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,0)); pivotPoint = RoundVector3 ( pivotPoint ); diff = pivotPoint-graph.center; pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Left",pivotPoint); graph.center = pivotPoint-diff; break; case GridPivot.BottomRight: pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,0)); pivotPoint = RoundVector3 ( pivotPoint ); diff = pivotPoint-graph.center; pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Right",pivotPoint); graph.center = pivotPoint-diff; break; } graph.GenerateMatrix (); pivot = PivotPointSelector (pivot); #if !UNITY_4 EditorGUILayoutx.EndIndent (); EditorGUILayoutx.BeginIndent (); #else GUILayout.EndHorizontal (); #endif graph.rotation = EditorGUILayout.Vector3Field ("Rotation",graph.rotation); #if UNITY_LE_4_3 //Add some space to make the Rotation and postion fields be better aligned (instead of the pivot point selector) //GUILayout.Space (19+7); #endif //GUILayout.EndHorizontal (); #if !UNITY_4 EditorGUILayoutx.EndIndent (); #endif #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector (); #endif if (GUILayout.Button (new GUIContent ("Snap Size","Snap the size to exactly fit nodes"),GUILayout.MaxWidth (100),GUILayout.MaxHeight (16))) { SnapSizeToNodes (newWidth,newDepth,graph); } Separator (); graph.cutCorners = EditorGUILayout.Toggle (new GUIContent ("Cut Corners","Enables or disables cutting corners. See docs for image example"),graph.cutCorners); graph.neighbours = (NumNeighbours)EditorGUILayout.EnumPopup (new GUIContent ("Connections","Sets how many connections a node should have to it's neighbour nodes."),graph.neighbours); //GUILayout.BeginHorizontal (); //EditorGUILayout.PrefixLabel ("Max Climb"); graph.maxClimb = EditorGUILayout.FloatField (new GUIContent ("Max Climb","How high, relative to the graph, should a climbable level be. A zero (0) indicates infinity"),graph.maxClimb); if ( graph.maxClimb < 0 ) graph.maxClimb = 0; EditorGUI.indentLevel++; graph.maxClimbAxis = EditorGUILayout.IntPopup (new GUIContent ("Climb Axis","Determines which axis the above setting should test on"),graph.maxClimbAxis,new GUIContent[3] {new GUIContent ("X"),new GUIContent ("Y"),new GUIContent ("Z")},new int[3] {0,1,2}); EditorGUI.indentLevel--; if ( graph.maxClimb > 0 && Mathf.Abs((Quaternion.Euler (graph.rotation) * new Vector3 (graph.nodeSize,0,graph.nodeSize))[graph.maxClimbAxis]) > graph.maxClimb ) { EditorGUILayout.HelpBox ("Nodes are spaced further apart than this in the grid. You might want to increase this value or change the axis", MessageType.Warning ); } //GUILayout.EndHorizontal (); graph.maxSlope = EditorGUILayout.Slider (new GUIContent ("Max Slope","Sets the max slope in degrees for a point to be walkable. Only enabled if Height Testing is enabled."),graph.maxSlope,0,90F); graph.erodeIterations = EditorGUILayout.IntField (new GUIContent ("Erosion iterations","Sets how many times the graph should be eroded. This adds extra margin to objects. This will not work when using Graph Updates, so if you can, use the Diameter setting in collision settings instead"),graph.erodeIterations); graph.erodeIterations = graph.erodeIterations < 0 ? 0 : (graph.erodeIterations > 16 ? 16 : graph.erodeIterations); //Clamp iterations to [0,16] if ( graph.erodeIterations > 0 ) { EditorGUI.indentLevel++; graph.erosionUseTags = EditorGUILayout.Toggle (new GUIContent ("Erosion Uses Tags","Instead of making nodes unwalkable, " + "nodes will have their tag set to a value corresponding to their erosion level, " + "which is a quite good measurement of their distance to the closest wall.\nSee online documentation for more info."), graph.erosionUseTags); if (graph.erosionUseTags) { EditorGUI.indentLevel++; graph.erosionFirstTag = EditorGUILayoutx.SingleTagField ("First Tag",graph.erosionFirstTag); EditorGUI.indentLevel--; } EditorGUI.indentLevel--; } DrawCollisionEditor (graph.collision); if ( graph.collision.use2D ) { if ( Mathf.Abs ( Vector3.Dot ( Vector3.forward, Quaternion.Euler (graph.rotation) * Vector3.up ) ) < 0.9f ) { EditorGUILayout.HelpBox ("When using 2D it is recommended to rotate the graph so that it aligns with the 2D plane.", MessageType.Warning ); } } Separator (); showExtra = EditorGUILayout.Foldout (showExtra, "Extra"); if (showExtra) { EditorGUI.indentLevel+=2; graph.penaltyAngle = ToggleGroup (new GUIContent ("Angle Penalty","Adds a penalty based on the slope of the node"),graph.penaltyAngle); //bool preGUI = GUI.enabled; //GUI.enabled = graph.penaltyAngle && GUI.enabled; if (graph.penaltyAngle) { EditorGUI.indentLevel++; graph.penaltyAngleFactor = EditorGUILayout.FloatField (new GUIContent ("Factor","Scale of the penalty. A negative value should not be used"),graph.penaltyAngleFactor); //GUI.enabled = preGUI; HelpBox ("Applies penalty to nodes based on the angle of the hit surface during the Height Testing"); EditorGUI.indentLevel--; } graph.penaltyPosition = ToggleGroup ("Position Penalty",graph.penaltyPosition); //EditorGUILayout.Toggle ("Position Penalty",graph.penaltyPosition); //preGUI = GUI.enabled; //GUI.enabled = graph.penaltyPosition && GUI.enabled; if (graph.penaltyPosition) { EditorGUI.indentLevel++; graph.penaltyPositionOffset = EditorGUILayout.FloatField ("Offset",graph.penaltyPositionOffset); graph.penaltyPositionFactor = EditorGUILayout.FloatField ("Factor",graph.penaltyPositionFactor); HelpBox ("Applies penalty to nodes based on their Y coordinate\nSampled in Int3 space, i.e it is multiplied with Int3.Precision first ("+Int3.Precision+")\n" + "Be very careful when using negative values since a negative penalty will underflow and instead get really high"); //GUI.enabled = preGUI; EditorGUI.indentLevel--; } GUI.enabled = false; ToggleGroup (new GUIContent ("Use Texture",AstarPathEditor.AstarProTooltip),false); GUI.enabled = true; EditorGUI.indentLevel-=2; } } /** Displays an object field for objects which must be in the 'Resources' folder. * If the selected object is not in the resources folder, a warning message with a Fix button will be shown */ [System.Obsolete("Use ObjectField instead")] public UnityEngine.Object ResourcesField (string label, UnityEngine.Object obj, System.Type type) { #if UNITY_3_3 obj = EditorGUILayout.ObjectField (label,obj,type); #else obj = EditorGUILayout.ObjectField (label,obj,type,false); #endif if (obj != null) { string path = AssetDatabase.GetAssetPath (obj); if (!path.Contains ("Resources/")) { if (FixLabel ("Object must be in the 'Resources' folder")) { if (!System.IO.Directory.Exists (Application.dataPath+"/Resources")) { System.IO.Directory.CreateDirectory (Application.dataPath+"/Resources"); AssetDatabase.Refresh (); } string ext = System.IO.Path.GetExtension(path); string error = AssetDatabase.MoveAsset (path,"Assets/Resources/"+obj.name+ext); if (error == "") { //Debug.Log ("Successful move"); } else { Debug.LogError ("Couldn't move asset - "+error); } } } } return obj; } public void SnapSizeToNodes (int newWidth, int newDepth, GridGraph graph) { //Vector2 preSize = graph.unclampedSize; /*if (locked) { graph.unclampedSize = new Vector2 (newWidth*newNodeSize,newDepth*newNodeSize); graph.nodeSize = newNodeSize; graph.GenerateMatrix (); Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 (newWidth/2F,0,newDepth/2F)); graph.center = newCenter; AstarPath.active.AutoScan (); } else {*/ graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize); Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 (newWidth/2F,0,newDepth/2F)); graph.center = newCenter; graph.GenerateMatrix (); AutoScan (); //} GUI.changed = true; } public static GridPivot PivotPointSelector (GridPivot pivot) { GUISkin skin = AstarPathEditor.astarSkin; GUIStyle background = skin.FindStyle ("GridPivotSelectBackground"); Rect r = GUILayoutUtility.GetRect (19,19,background); #if !UNITY_LE_4_3 // I have no idea... but it is required for it to work well r.y -= 14; #endif r.width = 19; r.height = 19; if (background == null) { return pivot; } if (Event.current.type == EventType.Repaint) { background.Draw (r,false,false,false,false); } if (GUI.Toggle (new Rect (r.x,r.y,7,7),pivot == GridPivot.TopLeft, "",skin.FindStyle ("GridPivotSelectButton"))) pivot = GridPivot.TopLeft; if (GUI.Toggle (new Rect (r.x+12,r.y,7,7),pivot == GridPivot.TopRight,"",skin.FindStyle ("GridPivotSelectButton"))) pivot = GridPivot.TopRight; if (GUI.Toggle (new Rect (r.x+12,r.y+12,7,7),pivot == GridPivot.BottomRight,"",skin.FindStyle ("GridPivotSelectButton"))) pivot = GridPivot.BottomRight; if (GUI.Toggle (new Rect (r.x,r.y+12,7,7),pivot == GridPivot.BottomLeft,"",skin.FindStyle ("GridPivotSelectButton"))) pivot = GridPivot.BottomLeft; if (GUI.Toggle (new Rect (r.x+6,r.y+6,7,7),pivot == GridPivot.Center,"",skin.FindStyle ("GridPivotSelectButton"))) pivot = GridPivot.Center; return pivot; } //GraphUndo undoState; //byte[] savedBytes; public override void OnSceneGUI (NavGraph target) { Event e = Event.current; GridGraph graph = target as GridGraph; Matrix4x4 matrixPre = graph.matrix; graph.GenerateMatrix (); if (e.type == EventType.MouseDown) { isMouseDown = true; } else if (e.type == EventType.MouseUp) { isMouseDown = false; } if (!isMouseDown) { savedMatrix = graph.boundsMatrix; } Handles.matrix = savedMatrix; if ((graph.GetType() == typeof(GridGraph) && graph.nodes == null) || (graph.uniformWidthDepthGrid && graph.depth*graph.width != graph.nodes.Length) || graph.matrix != matrixPre) { //Rescan the graphs if (AutoScan ()) { GUI.changed = true; } } Matrix4x4 inversed = savedMatrix.inverse; Handles.color = AstarColor.BoundsHandles; Handles.DrawCapFunction cap = Handles.CylinderCap; Vector2 extents = graph.unclampedSize*0.5F; Vector3 center = inversed.MultiplyPoint3x4 (graph.center); #if UNITY_3_3 if (Tools.current == 3) { #else if (Tools.current == Tool.Scale) { #endif Vector3 p1 = Handles.Slider (center+new Vector3 (extents.x,0,0), Vector3.right, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (extents.x,0,0)),cap,0); Vector3 p2 = Handles.Slider (center+new Vector3 (0,0,extents.y), Vector3.forward, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,extents.y)),cap,0); //Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0), Vector3.up, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0); Vector3 p4 = Handles.Slider (center+new Vector3 (-extents.x,0,0), -Vector3.right, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (-extents.x,0,0)),cap,0); Vector3 p5 = Handles.Slider (center+new Vector3 (0,0,-extents.y), -Vector3.forward, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,-extents.y)),cap,0); Vector3 p6 = Handles.Slider (center, Vector3.up, 0.1F*HandleUtility.GetHandleSize (center),cap,0); Vector3 r1 = new Vector3 (p1.x,p6.y,p2.z); Vector3 r2 = new Vector3 (p4.x,p6.y,p5.z); //Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one)); //if (Tools.viewTool != ViewTool.Orbit) { graph.center = savedMatrix.MultiplyPoint3x4 ((r1+r2)/2F); Vector3 tmp = r1-r2; graph.unclampedSize = new Vector2(tmp.x,tmp.z); //} #if UNITY_3_3 } else if (Tools.current == 1) { #else } else if (Tools.current == Tool.Move) { #endif if (Tools.pivotRotation == PivotRotation.Local) { center = Handles.PositionHandle (center,Quaternion.identity); if (Tools.viewTool != ViewTool.Orbit) { graph.center = savedMatrix.MultiplyPoint3x4 (center); } } else { Handles.matrix = Matrix4x4.identity; center = Handles.PositionHandle (graph.center,Quaternion.identity); if (Tools.viewTool != ViewTool.Orbit) { graph.center = center; } } #if UNITY_3_3 } else if (Tools.current == 2) { #else } else if (Tools.current == Tool.Rotate) { #endif //The rotation handle doesn't seem to be able to handle different matrixes of some reason Handles.matrix = Matrix4x4.identity; Quaternion rot = Handles.RotationHandle (Quaternion.Euler (graph.rotation),graph.center); if (Tools.viewTool != ViewTool.Orbit) { graph.rotation = rot.eulerAngles; } } //graph.size.x = Mathf.Max (graph.size.x,1); //graph.size.y = Mathf.Max (graph.size.y,1); //graph.size.z = Mathf.Max (graph.size.z,1); Handles.matrix = Matrix4x4.identity; } public enum GridPivot { Center, TopLeft, TopRight, BottomLeft, BottomRight } } }
using System; /* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SharpNEAT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using SharpNeat.Core; using SharpNeat.Phenomes; namespace SharpNeat.Domains.BoxesVisualDiscrimination { /// <summary> /// Boxes Visual Discrimination Task. /// </summary> public class BoxesVisualDiscriminationEvaluator : IPhenomeEvaluator<IBlackBox> { /// <summary> /// Width and length of the visual field in the 'real' coordinate system that /// substrate nodes are located within (and therefore sensor and output pixels). /// </summary> public const double VisualFieldEdgeLength = 2.0; /// <summary> /// The root mean square distance (rmsd) between two random points in the unit square. /// An agent that attempts this problem domain by selecting random points will produce this value as a score /// when the size of the visual field is 1x1 (the unit square). For other visual field sizes we can obtain the /// random agent's score by simply multiplying this value by the edge length of the visual field (the score scales /// linearly with the edge length). /// /// This value can be derived starting with the function for the mean length of a line between two random points /// in the unit square, as given in: http://mathworld.wolfram.com/SquareLinePicking.html /// /// Alternatively the value can be experimentally determined/approximated. The value here was found computationally. /// </summary> const double MeanLineInSquareRootMeanSquareLength = 0.5773; /// <summary> /// Maximum fitness for this evaulator. Problem domain is considered perfectly 'solved' if this score is achieved. /// </summary> const double MaxFitness = 110.0; /// <summary> /// The resoltion of the visual and output fields. /// </summary> int _visualFieldResolution; /// <summary> /// The width and height of a visual field pixel in the real coordinate system. /// </summary> double _visualPixelSize; /// <summary> /// The X and Y position of the visual field's origin pixel in the real coordinate system (the center position of the origin pixel). /// </summary> double _visualOriginPixelXY; /// <summary> /// Number of evaluations. /// </summary> ulong _evalCount; /// <summary> /// Indicates if some stop condition has been achieved. /// </summary> bool _stopConditionSatisfied; #region Public Static Methods /// <summary> /// Apply the provided test case to the provided black box's inputs (visual input field). /// </summary> public static void ApplyVisualFieldToBlackBox(TestCaseField testCaseField, IBlackBox box, int visualFieldResolution, double visualOriginPixelXY, double visualPixelSize) { int inputIdx = 0; double yReal = visualOriginPixelXY; for(int y=0; y<visualFieldResolution; y++, yReal += visualPixelSize) { double xReal = visualOriginPixelXY; for(int x=0; x<visualFieldResolution; x++, xReal += visualPixelSize, inputIdx++) { box.InputSignalArray[inputIdx] = testCaseField.GetPixel(xReal, yReal); } } } /// <summary> /// Determine the coordinate of the pixel with the highest activation. /// </summary> public static IntPoint FindMaxActivationOutput(IBlackBox box, int visualFieldResolution, out double minActivation, out double maxActivation) { minActivation = maxActivation = box.OutputSignalArray[0]; int maxOutputIdx = 0; int len = box.OutputSignalArray.Length; for(int i=1; i<len; i++) { double val = box.OutputSignalArray[i]; if(val > maxActivation) { maxActivation = val; maxOutputIdx = i; } else if(val < minActivation) { minActivation = val; } } int y = maxOutputIdx / visualFieldResolution; int x = maxOutputIdx - (y * visualFieldResolution); return new IntPoint(x, y); } #endregion #region Constructor /// <summary> /// Construct with the specified sensor and output pixel array resolution. /// </summary> /// <param name="visualFieldResolution"></param> public BoxesVisualDiscriminationEvaluator(int visualFieldResolution) { _visualFieldResolution = visualFieldResolution; _visualPixelSize = VisualFieldEdgeLength / _visualFieldResolution; _visualOriginPixelXY = -1.0 + (_visualPixelSize/2.0); } #endregion #region IPhenomeEvaluator<IBlackBox> Members /// <summary> /// Gets the total number of evaluations that have been performed. /// </summary> public ulong EvaluationCount { get { return _evalCount; } } /// <summary> /// Gets a value indicating whether some goal fitness has been achieved and that /// the the evolutionary algorithm/search should stop. This property's value can remain false /// to allow the algorithm to run indefinitely. /// </summary> public bool StopConditionSatisfied { get { return _stopConditionSatisfied; } } /// <summary> /// Evaluate the provided IBlackBox against the XOR problem domain and return its fitness score. /// /// Fitness value explanation. /// 1) Max distance from target position in each trial is sqrt(2)*VisualFieldEdgeLength (target in one corner and selected target in /// opposite corner). /// /// 2) An agents is scored by squaring the distance of its selected target from the actual target, squaring the value, /// taking the average over all test cases and then taking the square root. This is referred to as the root mean squared distance (RMSD) /// and is effectively an implementation of least squares (least squared error). The square root term converts values back into units /// of distance (rather than squared distance) /// /// 3) An agent selecting points at random will score VisualFieldEdgeLength * MeanLineInSquareRootMeanSquareLength. Any agent scoring /// this amount or less is assigned a fitness of zero. All other scores are scaled and translated into the range 0-100 where 0 is no better /// or worse than a random agent, and 100 is perfectly selecting the correct target for all test cases (distance of zero between target and /// selected target). /// /// 4) In addition to this the range of output values is scaled to 0-10 and added to the final score, this encourages solutions with a wide /// output range between the highest activation (the selected pixel) and the lowest activation (this encourages prominent/clear selection). /// /// An alternative scheme is fitness = 1/RMSD (separately handling the special case where RMSD==0). /// However, this gives a non-linear increase in fitness as RMSD decreases linearly, which in turns produces a 'spikier' fitness landscape /// which is more likely to cause genomes and species to get caught in a local maximum. /// </summary> public FitnessInfo Evaluate(IBlackBox box) { _evalCount++; // Accumulate square distance from each test case. double acc = 0.0; double activationRangeAcc = 0.0; TestCaseField testCaseField = new TestCaseField(); for(int i=0; i<3; i++) { for(int j=0; j<25; j++) { double activationRange; acc += RunTrial(box, testCaseField, i, out activationRange); activationRangeAcc += activationRange; } } // Calc root mean squared distance (RMSD) and calculate fitness based comparison to the random agent. const double threshold = VisualFieldEdgeLength * 0.5772; double rmsd = Math.Sqrt(acc / 75.0); double fitness; if(rmsd > threshold) { fitness = 0.0; } else { fitness = (((threshold-rmsd) * 100.0) / threshold) + (activationRangeAcc / 7.5); } // Set stop flag when max fitness is attained. if(!_stopConditionSatisfied && fitness == MaxFitness) { _stopConditionSatisfied = true; } return new FitnessInfo(fitness, rmsd); } /// <summary> /// Reset the internal state of the evaluation scheme if any exists. /// Note. The XOR problem domain has no internal state. This method does nothing. /// </summary> public void Reset() { } #endregion #region Private Methods /// <summary> /// Run a single trial /// 1) Generate random test case with the box orientation specified by largeBoxRelativePos. /// 2) Apply test case visual field to black box inputs. /// 3) Activate black box. /// 4) Determine black box output with highest output, this is the selected pixel. /// /// Returns square of distance between target pixel (center of large box) and pixel selected by the black box. /// </summary> private double RunTrial(IBlackBox box, TestCaseField testCaseField, int largeBoxRelativePos, out double activationRange) { // Generate random test case. Also gets the center position of the large box. IntPoint targetPos = testCaseField.InitTestCase(0); // Apply test case visual field to black box inputs. ApplyVisualFieldToBlackBox(testCaseField, box, _visualFieldResolution, _visualOriginPixelXY, _visualPixelSize); // Clear any pre-existign state and activate. box.ResetState(); box.Activate(); if(!box.IsStateValid) { // Any black box that gets itself into an invalid state is unlikely to be // any good, so lets just bail out here. activationRange = 0.0; return 0.0; } // Find output pixel with highest activation. double minActivation, maxActivation; IntPoint highestActivationPoint = FindMaxActivationOutput(box, _visualFieldResolution, out minActivation, out maxActivation); activationRange = Math.Max(0.0, maxActivation - minActivation); // Get the distance between the target and activated pixels, in the real coordinate space. // We actually want squared distance (not distance) thus we can skip taking the square root (expensive CPU operation). return CalcRealDistanceSquared(targetPos, highestActivationPoint); } private double CalcRealDistanceSquared(IntPoint a, IntPoint b) { // We can skip calculating abs(val) because we square the values. double xdelta = (a._x - b._x) * _visualPixelSize; double ydelta = (a._y - b._y) * _visualPixelSize; return xdelta*xdelta + ydelta*ydelta; } #endregion } }
/*************************************************************************** * PodcastFeedPropertiesDialog.cs * * Written by Mike Urbanski <michael.c.urbanski@gmail.com> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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 Mono.Unix; using Gtk; using Pango; using Migo.Syndication; using Banshee.Base; using Banshee.Collection; using Banshee.Podcasting.Data; using Banshee.Gui.TrackEditor; using Banshee.Collection.Gui; using Banshee.ServiceStack; namespace Banshee.Podcasting.Gui { internal class PodcastFeedPropertiesDialog : Dialog { PodcastSource source; Feed feed; Entry name_entry; Frame header_image_frame; Image header_image; FakeTrackInfo fake_track = new FakeTrackInfo (); CheckButton subscribed_check, download_check, archive_check; public PodcastFeedPropertiesDialog (PodcastSource source, Feed feed) { this.source = source; this.feed = feed; fake_track.Feed = feed; Title = feed.Title; BorderWidth = 12; WidthRequest = 525; //IconThemeUtils.SetWindowIcon (this); BuildWindow (); DefaultResponse = Gtk.ResponseType.Cancel; ActionArea.Layout = Gtk.ButtonBoxStyle.End; Response += OnResponse; ShowAll (); } private FeedAutoDownload DownloadPref { get { return download_check.Active ? FeedAutoDownload.All : FeedAutoDownload.None; } set { download_check.Active = value != FeedAutoDownload.None; } } private int MaxItemCount { get { return archive_check.Active ? 1 : 0; } set { archive_check.Active = value > 0; } } private void BuildWindow() { ContentArea.Spacing = 12; var save_button = new Button ("gtk-save") { CanDefault = true }; name_entry = new Entry (); name_entry.Text = feed.Title; name_entry.Changed += delegate { save_button.Sensitive = !String.IsNullOrEmpty (name_entry.Text); }; subscribed_check = new CheckButton (Catalog.GetString ("Check periodically for new episodes")) { TooltipText = Catalog.GetString ("If checked, Banshee will check every hour to see if this podcast has new episodes") }; download_check = new CheckButton (Catalog.GetString ("Download new episodes")); DownloadPref = feed.AutoDownload; archive_check = new CheckButton (Catalog.GetString ("Archive all episodes except the newest one")); MaxItemCount = (int)feed.MaxItemCount; subscribed_check.Toggled += delegate { download_check.Sensitive = archive_check.Sensitive = subscribed_check.Active; }; subscribed_check.Active = feed.IsSubscribed; download_check.Sensitive = archive_check.Sensitive = subscribed_check.Active; var last_updated_text = new Label (feed.LastDownloadTime.ToString ("f")) { Justify = Justification.Left, Xalign = 0f }; var feed_url_text = new Label () { Text = feed.Url.ToString (), Wrap = false, Selectable = true, Xalign = 0f, Justify = Justification.Left, Ellipsize = Pango.EllipsizeMode.End }; string description_string = String.IsNullOrEmpty (feed.Description) ? Catalog.GetString ("No description available") : feed.Description; var header_box = new HBox () { Spacing = 6 }; header_image_frame = new Frame (); header_image = new Image (); LoadCoverArt (fake_track); header_image_frame.Add ( CoverArtEditor.For (header_image, (x, y) => true, () => fake_track, () => LoadCoverArt (fake_track) ) ); header_box.PackStart (header_image_frame, false, false, 0); var table = new Hyena.Widgets.SimpleTable<int> (); table.XOptions[0] = AttachOptions.Fill; table.XOptions[1] = AttachOptions.Expand | AttachOptions.Fill; table.AddRow (0, HeaderLabel (Catalog.GetString ("Name:")), name_entry); table.AddRow (1, HeaderLabel (Catalog.GetString ("Website:")), new Gtk.Alignment (0f, 0f, 0f, 0f) { Child = new LinkButton (feed.Link, Catalog.GetString ("Visit")) { Image = new Gtk.Image (Gtk.Stock.JumpTo, Gtk.IconSize.Button) } }); header_box.PackStart (table, true, true, 0); ContentArea.PackStart (header_box, false, false, 0); Add (Catalog.GetString ("Subscription Options"), subscribed_check, download_check, archive_check); var details = new Banshee.Gui.TrackEditor.StatisticsPage (); details.AddItem (Catalog.GetString ("Feed URL:"), feed_url_text.Text); details.AddItem (Catalog.GetString ("Last Refreshed:"), last_updated_text.Text); details.AddItem (Catalog.GetString ("Description:"), description_string, true); details.AddItem (Catalog.GetString ("Category:"), feed.Category); details.AddItem (Catalog.GetString ("Keywords:"), feed.Keywords); details.AddItem (Catalog.GetString ("Copyright:"), feed.Copyright); details.HeightRequest = 120; Add (true, Catalog.GetString ("Details"), details); AddActionWidget (new Button ("gtk-cancel") { CanDefault = true }, ResponseType.Cancel); AddActionWidget (save_button, ResponseType.Ok); } private void Add (string header_txt, params Widget [] widgets) { Add (false, header_txt, widgets); } private Label HeaderLabel (string str) { return new Label () { Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (str)), Xalign = 0f }; } private void Add (bool filled, string header_txt, params Widget [] widgets) { var vbox = new VBox () { Spacing = 3 }; vbox.PackStart (HeaderLabel (header_txt), false, false, 0); foreach (var child in widgets) { var align = new Gtk.Alignment (0, 0, 1, 1) { LeftPadding = 12, Child = child }; vbox.PackStart (align, filled, filled, 0); } ContentArea.PackStart (vbox, filled, filled, 0); } private void OnResponse (object sender, ResponseArgs args) { if (args.ResponseId == Gtk.ResponseType.Ok) { bool changed = false; if (feed.IsSubscribed != subscribed_check.Active) { feed.IsSubscribed = subscribed_check.Active; changed = true; } if (feed.IsSubscribed) { if (feed.AutoDownload != DownloadPref) { feed.AutoDownload = DownloadPref; changed = true; } if (feed.MaxItemCount != MaxItemCount) { feed.MaxItemCount = MaxItemCount; changed = true; } } if (feed.Title != name_entry.Text) { feed.Title = name_entry.Text; source.Reload (); changed = true; } if (changed) { feed.Save (); } } (sender as Dialog).Response -= OnResponse; (sender as Dialog).Destroy(); } void LoadCoverArt (TrackInfo current_track) { if (current_track == null || current_track.ArtworkId == null) { SetDefaultCoverArt (); return; } var artwork = ServiceManager.Get<ArtworkManager> (); var cover_art = artwork.LookupScalePixbuf (current_track.ArtworkId, 64); header_image.Clear (); header_image.Pixbuf = cover_art; if (cover_art == null) { SetDefaultCoverArt (); } else { header_image_frame.ShadowType = ShadowType.In; header_image.QueueDraw (); } } void SetDefaultCoverArt () { header_image.IconName = "podcast"; header_image.PixelSize = 64; header_image_frame.ShadowType = ShadowType.In; header_image.QueueDraw (); } class FakeTrackInfo : TrackInfo { public Feed Feed { get; set; } public override string ArtworkId { get { return Feed == null ? null : PodcastService.ArtworkIdFor (Feed); } } } } }
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Reports. /// </summary> internal partial class ReportsOperations : IServiceOperations<ApiManagementClient>, IReportsOperations { /// <summary> /// Initializes a new instance of the ReportsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ReportsOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Lists report records. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='aggregation'> /// Required. Report aggregation. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='interval'> /// Optional. By time interval. This value is only applicable to ByTime /// aggregation. Interval must be multiple of 15 minutes and may not /// be zero. The value should be in ISO 8601 format /// (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can be /// used to convert TimSpan to a valid interval string: /// XmlConvert.ToString(new TimeSpan(hours, minutes, secconds)) /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Report records operation response details. /// </returns> public async Task<ReportListResponse> ListAsync(string resourceGroupName, string serviceName, ReportsAggregation aggregation, QueryParameters query, string interval, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); tracingParameters.Add("aggregation", aggregation); tracingParameters.Add("query", query); tracingParameters.Add("interval", interval); 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.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/reports/"; url = url + Uri.EscapeDataString(ApiManagementClient.ReportsAggregationToString(aggregation)); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString())); } if (interval != null) { queryParameters.Add("interval=" + Uri.EscapeDataString(interval)); } 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 ReportListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ReportListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ReportPaged resultInstance = new ReportPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ReportRecordContract reportRecordContractInstance = new ReportRecordContract(); resultInstance.Values.Add(reportRecordContractInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); reportRecordContractInstance.Name = nameInstance; } JToken timestampValue = valueValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); reportRecordContractInstance.Timestamp = timestampInstance; } JToken intervalValue = valueValue["interval"]; if (intervalValue != null && intervalValue.Type != JTokenType.Null) { TimeSpan intervalInstance = TimeSpan.Parse(((string)intervalValue), CultureInfo.InvariantCulture); reportRecordContractInstance.Interval = intervalInstance; } JToken countryValue = valueValue["country"]; if (countryValue != null && countryValue.Type != JTokenType.Null) { string countryInstance = ((string)countryValue); reportRecordContractInstance.Country = countryInstance; } JToken regionValue = valueValue["region"]; if (regionValue != null && regionValue.Type != JTokenType.Null) { string regionInstance = ((string)regionValue); reportRecordContractInstance.Region = regionInstance; } JToken zipValue = valueValue["zip"]; if (zipValue != null && zipValue.Type != JTokenType.Null) { string zipInstance = ((string)zipValue); reportRecordContractInstance.Zip = zipInstance; } JToken userIdValue = valueValue["userId"]; if (userIdValue != null && userIdValue.Type != JTokenType.Null) { string userIdInstance = ((string)userIdValue); reportRecordContractInstance.UserIdPath = userIdInstance; } JToken productIdValue = valueValue["productId"]; if (productIdValue != null && productIdValue.Type != JTokenType.Null) { string productIdInstance = ((string)productIdValue); reportRecordContractInstance.ProductIdPath = productIdInstance; } JToken apiIdValue = valueValue["apiId"]; if (apiIdValue != null && apiIdValue.Type != JTokenType.Null) { string apiIdInstance = ((string)apiIdValue); reportRecordContractInstance.ApiIdPath = apiIdInstance; } JToken operationIdValue = valueValue["operationId"]; if (operationIdValue != null && operationIdValue.Type != JTokenType.Null) { string operationIdInstance = ((string)operationIdValue); reportRecordContractInstance.OperationIdPath = operationIdInstance; } JToken apiRegionValue = valueValue["apiRegion"]; if (apiRegionValue != null && apiRegionValue.Type != JTokenType.Null) { string apiRegionInstance = ((string)apiRegionValue); reportRecordContractInstance.ApiRegion = apiRegionInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); reportRecordContractInstance.SubscriptionIdPath = subscriptionIdInstance; } JToken callCountSuccessValue = valueValue["callCountSuccess"]; if (callCountSuccessValue != null && callCountSuccessValue.Type != JTokenType.Null) { int callCountSuccessInstance = ((int)callCountSuccessValue); reportRecordContractInstance.CallCountSuccess = callCountSuccessInstance; } JToken callCountBlockedValue = valueValue["callCountBlocked"]; if (callCountBlockedValue != null && callCountBlockedValue.Type != JTokenType.Null) { int callCountBlockedInstance = ((int)callCountBlockedValue); reportRecordContractInstance.CallCountBlocked = callCountBlockedInstance; } JToken callCountFailedValue = valueValue["callCountFailed"]; if (callCountFailedValue != null && callCountFailedValue.Type != JTokenType.Null) { int callCountFailedInstance = ((int)callCountFailedValue); reportRecordContractInstance.CallCountFailed = callCountFailedInstance; } JToken callCountOtherValue = valueValue["callCountOther"]; if (callCountOtherValue != null && callCountOtherValue.Type != JTokenType.Null) { int callCountOtherInstance = ((int)callCountOtherValue); reportRecordContractInstance.CallCountOther = callCountOtherInstance; } JToken callCountTotalValue = valueValue["callCountTotal"]; if (callCountTotalValue != null && callCountTotalValue.Type != JTokenType.Null) { int callCountTotalInstance = ((int)callCountTotalValue); reportRecordContractInstance.CallCountTotal = callCountTotalInstance; } JToken bandwidthValue = valueValue["bandwidth"]; if (bandwidthValue != null && bandwidthValue.Type != JTokenType.Null) { long bandwidthInstance = ((long)bandwidthValue); reportRecordContractInstance.Bandwidth = bandwidthInstance; } JToken cacheHitCountValue = valueValue["cacheHitCount"]; if (cacheHitCountValue != null && cacheHitCountValue.Type != JTokenType.Null) { int cacheHitCountInstance = ((int)cacheHitCountValue); reportRecordContractInstance.CacheHitCount = cacheHitCountInstance; } JToken cacheMissCountValue = valueValue["cacheMissCount"]; if (cacheMissCountValue != null && cacheMissCountValue.Type != JTokenType.Null) { int cacheMissCountInstance = ((int)cacheMissCountValue); reportRecordContractInstance.CacheMissCount = cacheMissCountInstance; } JToken apiTimeAvgValue = valueValue["apiTimeAvg"]; if (apiTimeAvgValue != null && apiTimeAvgValue.Type != JTokenType.Null) { double apiTimeAvgInstance = ((double)apiTimeAvgValue); reportRecordContractInstance.ApiTimeAvg = apiTimeAvgInstance; } JToken apiTimeMinValue = valueValue["apiTimeMin"]; if (apiTimeMinValue != null && apiTimeMinValue.Type != JTokenType.Null) { double apiTimeMinInstance = ((double)apiTimeMinValue); reportRecordContractInstance.ApiTimeMin = apiTimeMinInstance; } JToken apiTimeMaxValue = valueValue["apiTimeMax"]; if (apiTimeMaxValue != null && apiTimeMaxValue.Type != JTokenType.Null) { double apiTimeMaxInstance = ((double)apiTimeMaxValue); reportRecordContractInstance.ApiTimeMax = apiTimeMaxInstance; } JToken serviceTimeAvgValue = valueValue["serviceTimeAvg"]; if (serviceTimeAvgValue != null && serviceTimeAvgValue.Type != JTokenType.Null) { double serviceTimeAvgInstance = ((double)serviceTimeAvgValue); reportRecordContractInstance.ServiceTimeAvg = serviceTimeAvgInstance; } JToken serviceTimeMinValue = valueValue["serviceTimeMin"]; if (serviceTimeMinValue != null && serviceTimeMinValue.Type != JTokenType.Null) { double serviceTimeMinInstance = ((double)serviceTimeMinValue); reportRecordContractInstance.ServiceTimeMin = serviceTimeMinInstance; } JToken serviceTimeMaxValue = valueValue["serviceTimeMax"]; if (serviceTimeMaxValue != null && serviceTimeMaxValue.Type != JTokenType.Null) { double serviceTimeMaxInstance = ((double)serviceTimeMaxValue); reportRecordContractInstance.ServiceTimeMax = serviceTimeMaxInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } 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> /// List report records. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Report records operation response details. /// </returns> public async Task<ReportListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; 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 ReportListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ReportListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ReportPaged resultInstance = new ReportPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ReportRecordContract reportRecordContractInstance = new ReportRecordContract(); resultInstance.Values.Add(reportRecordContractInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); reportRecordContractInstance.Name = nameInstance; } JToken timestampValue = valueValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); reportRecordContractInstance.Timestamp = timestampInstance; } JToken intervalValue = valueValue["interval"]; if (intervalValue != null && intervalValue.Type != JTokenType.Null) { TimeSpan intervalInstance = TimeSpan.Parse(((string)intervalValue), CultureInfo.InvariantCulture); reportRecordContractInstance.Interval = intervalInstance; } JToken countryValue = valueValue["country"]; if (countryValue != null && countryValue.Type != JTokenType.Null) { string countryInstance = ((string)countryValue); reportRecordContractInstance.Country = countryInstance; } JToken regionValue = valueValue["region"]; if (regionValue != null && regionValue.Type != JTokenType.Null) { string regionInstance = ((string)regionValue); reportRecordContractInstance.Region = regionInstance; } JToken zipValue = valueValue["zip"]; if (zipValue != null && zipValue.Type != JTokenType.Null) { string zipInstance = ((string)zipValue); reportRecordContractInstance.Zip = zipInstance; } JToken userIdValue = valueValue["userId"]; if (userIdValue != null && userIdValue.Type != JTokenType.Null) { string userIdInstance = ((string)userIdValue); reportRecordContractInstance.UserIdPath = userIdInstance; } JToken productIdValue = valueValue["productId"]; if (productIdValue != null && productIdValue.Type != JTokenType.Null) { string productIdInstance = ((string)productIdValue); reportRecordContractInstance.ProductIdPath = productIdInstance; } JToken apiIdValue = valueValue["apiId"]; if (apiIdValue != null && apiIdValue.Type != JTokenType.Null) { string apiIdInstance = ((string)apiIdValue); reportRecordContractInstance.ApiIdPath = apiIdInstance; } JToken operationIdValue = valueValue["operationId"]; if (operationIdValue != null && operationIdValue.Type != JTokenType.Null) { string operationIdInstance = ((string)operationIdValue); reportRecordContractInstance.OperationIdPath = operationIdInstance; } JToken apiRegionValue = valueValue["apiRegion"]; if (apiRegionValue != null && apiRegionValue.Type != JTokenType.Null) { string apiRegionInstance = ((string)apiRegionValue); reportRecordContractInstance.ApiRegion = apiRegionInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); reportRecordContractInstance.SubscriptionIdPath = subscriptionIdInstance; } JToken callCountSuccessValue = valueValue["callCountSuccess"]; if (callCountSuccessValue != null && callCountSuccessValue.Type != JTokenType.Null) { int callCountSuccessInstance = ((int)callCountSuccessValue); reportRecordContractInstance.CallCountSuccess = callCountSuccessInstance; } JToken callCountBlockedValue = valueValue["callCountBlocked"]; if (callCountBlockedValue != null && callCountBlockedValue.Type != JTokenType.Null) { int callCountBlockedInstance = ((int)callCountBlockedValue); reportRecordContractInstance.CallCountBlocked = callCountBlockedInstance; } JToken callCountFailedValue = valueValue["callCountFailed"]; if (callCountFailedValue != null && callCountFailedValue.Type != JTokenType.Null) { int callCountFailedInstance = ((int)callCountFailedValue); reportRecordContractInstance.CallCountFailed = callCountFailedInstance; } JToken callCountOtherValue = valueValue["callCountOther"]; if (callCountOtherValue != null && callCountOtherValue.Type != JTokenType.Null) { int callCountOtherInstance = ((int)callCountOtherValue); reportRecordContractInstance.CallCountOther = callCountOtherInstance; } JToken callCountTotalValue = valueValue["callCountTotal"]; if (callCountTotalValue != null && callCountTotalValue.Type != JTokenType.Null) { int callCountTotalInstance = ((int)callCountTotalValue); reportRecordContractInstance.CallCountTotal = callCountTotalInstance; } JToken bandwidthValue = valueValue["bandwidth"]; if (bandwidthValue != null && bandwidthValue.Type != JTokenType.Null) { long bandwidthInstance = ((long)bandwidthValue); reportRecordContractInstance.Bandwidth = bandwidthInstance; } JToken cacheHitCountValue = valueValue["cacheHitCount"]; if (cacheHitCountValue != null && cacheHitCountValue.Type != JTokenType.Null) { int cacheHitCountInstance = ((int)cacheHitCountValue); reportRecordContractInstance.CacheHitCount = cacheHitCountInstance; } JToken cacheMissCountValue = valueValue["cacheMissCount"]; if (cacheMissCountValue != null && cacheMissCountValue.Type != JTokenType.Null) { int cacheMissCountInstance = ((int)cacheMissCountValue); reportRecordContractInstance.CacheMissCount = cacheMissCountInstance; } JToken apiTimeAvgValue = valueValue["apiTimeAvg"]; if (apiTimeAvgValue != null && apiTimeAvgValue.Type != JTokenType.Null) { double apiTimeAvgInstance = ((double)apiTimeAvgValue); reportRecordContractInstance.ApiTimeAvg = apiTimeAvgInstance; } JToken apiTimeMinValue = valueValue["apiTimeMin"]; if (apiTimeMinValue != null && apiTimeMinValue.Type != JTokenType.Null) { double apiTimeMinInstance = ((double)apiTimeMinValue); reportRecordContractInstance.ApiTimeMin = apiTimeMinInstance; } JToken apiTimeMaxValue = valueValue["apiTimeMax"]; if (apiTimeMaxValue != null && apiTimeMaxValue.Type != JTokenType.Null) { double apiTimeMaxInstance = ((double)apiTimeMaxValue); reportRecordContractInstance.ApiTimeMax = apiTimeMaxInstance; } JToken serviceTimeAvgValue = valueValue["serviceTimeAvg"]; if (serviceTimeAvgValue != null && serviceTimeAvgValue.Type != JTokenType.Null) { double serviceTimeAvgInstance = ((double)serviceTimeAvgValue); reportRecordContractInstance.ServiceTimeAvg = serviceTimeAvgInstance; } JToken serviceTimeMinValue = valueValue["serviceTimeMin"]; if (serviceTimeMinValue != null && serviceTimeMinValue.Type != JTokenType.Null) { double serviceTimeMinInstance = ((double)serviceTimeMinValue); reportRecordContractInstance.ServiceTimeMin = serviceTimeMinInstance; } JToken serviceTimeMaxValue = valueValue["serviceTimeMax"]; if (serviceTimeMaxValue != null && serviceTimeMaxValue.Type != JTokenType.Null) { double serviceTimeMaxInstance = ((double)serviceTimeMaxValue); reportRecordContractInstance.ServiceTimeMax = serviceTimeMaxInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } 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(); } } } } }
// 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.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.JSInterop; namespace BasicTestApp.InteropTest { public class JavaScriptInterop { public static ConcurrentDictionary<string, object[]> Invocations = new ConcurrentDictionary<string, object[]>(); [JSInvokable] public static void ThrowException() => throw new InvalidOperationException("Threw an exception!"); [JSInvokable] public static Task AsyncThrowSyncException() => throw new InvalidOperationException("Threw a sync exception!"); [JSInvokable] public static async Task AsyncThrowAsyncException() { await Task.Yield(); throw new InvalidOperationException("Threw an async exception!"); } [JSInvokable] public static void VoidParameterless() { Invocations[nameof(VoidParameterless)] = new object[0]; } [JSInvokable] public static void VoidWithOneParameter(ComplexParameter parameter1) { Invocations[nameof(VoidWithOneParameter)] = new object[] { parameter1 }; } [JSInvokable] public static void VoidWithTwoParameters( ComplexParameter parameter1, byte parameter2) { Invocations[nameof(VoidWithTwoParameters)] = new object[] { parameter1, parameter2 }; } [JSInvokable] public static void VoidWithThreeParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3) { Invocations[nameof(VoidWithThreeParameters)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue() }; } [JSInvokable] public static void VoidWithFourParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4) { Invocations[nameof(VoidWithFourParameters)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4 }; } [JSInvokable] public static void VoidWithFiveParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5) { Invocations[nameof(VoidWithFiveParameters)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5 }; } [JSInvokable] public static void VoidWithSixParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6) { Invocations[nameof(VoidWithSixParameters)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6 }; } [JSInvokable] public static void VoidWithSevenParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7) { Invocations[nameof(VoidWithSevenParameters)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7 }; } [JSInvokable] public static void VoidWithEightParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7, Segment parameter8) { Invocations[nameof(VoidWithEightParameters)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7, parameter8 }; } [JSInvokable] public static decimal[] ReturnArray() { return new decimal[] { 0.1M, 0.2M }; } [JSInvokable] public static object[] EchoOneParameter(ComplexParameter parameter1) { return new object[] { parameter1 }; } [JSInvokable] public static object[] EchoTwoParameters( ComplexParameter parameter1, byte parameter2) { return new object[] { parameter1, parameter2 }; } [JSInvokable] public static object[] EchoThreeParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3) { return new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue() }; } [JSInvokable] public static object[] EchoFourParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4) { return new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4 }; } [JSInvokable] public static object[] EchoFiveParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5) { return new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5 }; } [JSInvokable] public static object[] EchoSixParameters(ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6) { return new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6 }; } [JSInvokable] public static object[] EchoSevenParameters(ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7) { return new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7 }; } [JSInvokable] public static object[] EchoEightParameters( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7, Segment parameter8) { return new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7, parameter8 }; } [JSInvokable] public static Task VoidParameterlessAsync() { Invocations[nameof(VoidParameterlessAsync)] = new object[0]; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithOneParameterAsync(ComplexParameter parameter1) { Invocations[nameof(VoidWithOneParameterAsync)] = new object[] { parameter1 }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithTwoParametersAsync( ComplexParameter parameter1, byte parameter2) { Invocations[nameof(VoidWithTwoParametersAsync)] = new object[] { parameter1, parameter2 }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithThreeParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3) { Invocations[nameof(VoidWithThreeParametersAsync)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue() }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithFourParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4) { Invocations[nameof(VoidWithFourParametersAsync)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4 }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithFiveParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5) { Invocations[nameof(VoidWithFiveParametersAsync)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5 }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithSixParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6) { Invocations[nameof(VoidWithSixParametersAsync)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6 }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithSevenParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7) { Invocations[nameof(VoidWithSevenParametersAsync)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7 }; return Task.CompletedTask; } [JSInvokable] public static Task VoidWithEightParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7, Segment parameter8) { Invocations[nameof(VoidWithEightParametersAsync)] = new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7, parameter8 }; return Task.CompletedTask; } [JSInvokable] public static Task<decimal[]> ReturnArrayAsync() { return Task.FromResult(new decimal[] { 0.1M, 0.2M }); } [JSInvokable] public static Task<object[]> EchoOneParameterAsync(ComplexParameter parameter1) { return Task.FromResult(new object[] { parameter1 }); } [JSInvokable] public static Task<object[]> EchoTwoParametersAsync( ComplexParameter parameter1, byte parameter2) { return Task.FromResult(new object[] { parameter1, parameter2 }); } [JSInvokable] public static Task<object[]> EchoThreeParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3) { return Task.FromResult(new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue() }); } [JSInvokable] public static Task<object[]> EchoFourParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4) { return Task.FromResult(new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4 }); } [JSInvokable] public static Task<object[]> EchoFiveParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5) { return Task.FromResult(new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5 }); } [JSInvokable] public static Task<object[]> EchoSixParametersAsync(ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6) { return Task.FromResult(new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6 }); } [JSInvokable] public static Task<object[]> EchoSevenParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7) { return Task.FromResult(new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7 }); } [JSInvokable] public static Task<object[]> EchoEightParametersAsync( ComplexParameter parameter1, byte parameter2, DotNetObjectReference<TestDTO> parameter3, int parameter4, long parameter5, float parameter6, List<double> parameter7, Segment parameter8) { return Task.FromResult(new object[] { parameter1, parameter2, parameter3.Value.GetNonSerializedValue(), parameter4, parameter5, parameter6, parameter7, parameter8 }); } [JSInvokable] public static Dictionary<string, DotNetObjectReference<TestDTO>> ReturnDotNetObjectByRef() { return new Dictionary<string, DotNetObjectReference<TestDTO>> { { "Some sync instance", DotNetObjectReference.Create(new TestDTO(1000)) } }; } [JSInvokable] public static async Task<Dictionary<string, DotNetObjectReference<TestDTO>>> ReturnDotNetObjectByRefAsync() { await Task.Yield(); return new Dictionary<string, DotNetObjectReference<TestDTO>> { { "Some async instance", DotNetObjectReference.Create(new TestDTO(1001)) } }; } [JSInvokable] public static int ExtractNonSerializedValue(DotNetObjectReference<TestDTO> objectByRef) { return objectByRef.Value.GetNonSerializedValue(); } [JSInvokable] public static IJSObjectReference RoundTripJSObjectReference(IJSObjectReference jsObjectReference) { return jsObjectReference; } [JSInvokable] public static async Task<IJSObjectReference> RoundTripJSObjectReferenceAsync(IJSObjectReference jSObjectReference) { await Task.Yield(); return jSObjectReference; } [JSInvokable] public static string InvokeDisposedJSObjectReferenceException(IJSInProcessObjectReference jsObjectReference) { try { jsObjectReference.Invoke<object>("noop"); return "No exception thrown"; } catch (JSException e) { return e.Message; } } [JSInvokable] public static async Task<string> InvokeDisposedJSObjectReferenceExceptionAsync(IJSObjectReference jsObjectReference) { try { await jsObjectReference.InvokeVoidAsync("noop"); return "No exception thrown"; } catch (JSException e) { return e.Message; } } [JSInvokable] public InstanceMethodOutput InstanceMethod(InstanceMethodInput input) { // This method shows we can pass in values marshalled both as JSON (the dict itself) // and by ref (the incoming dtoByRef), plus that we can return values marshalled as // JSON (the returned dictionary) and by ref (the outgoingByRef value) return new InstanceMethodOutput { ThisTypeName = GetType().Name, StringValueUpper = input.StringValue.ToUpperInvariant(), IncomingByRef = input.DTOByRef.Value.GetNonSerializedValue(), OutgoingByRef = DotNetObjectReference.Create(new TestDTO(1234)), }; } [JSInvokable] public async Task<InstanceMethodOutput> InstanceMethodAsync(InstanceMethodInput input) { // This method shows we can pass in values marshalled both as JSON // and by ref (the incoming dtoByRef), plus that we can return values marshalled as // JSON (the returned dictionary) and by ref (the outgoingByRef value) await Task.Yield(); return new InstanceMethodOutput { ThisTypeName = GetType().Name, StringValueUpper = input.StringValue.ToUpperInvariant(), IncomingByRef = input.DTOByRef.Value.GetNonSerializedValue(), OutgoingByRef = DotNetObjectReference.Create(new TestDTO(1234)), }; } public class InstanceMethodInput { public string StringValue { get; set; } public DotNetObjectReference<TestDTO> DTOByRef { get; set; } } public class InstanceMethodOutput { public string ThisTypeName { get; set; } public string StringValueUpper { get; set; } public int IncomingByRef { get; set; } public DotNetObjectReference<TestDTO> OutgoingByRef { get; set; } } public class GenericType<TValue> { public TValue Value { get; set; } [JSInvokable] public TValue Update(TValue newValue) { var oldValue = Value; Value = newValue; return oldValue; } [JSInvokable] public async Task<TValue> UpdateAsync(TValue newValue) { await Task.Yield(); return Update(newValue); } } } }
/* GNU gettext for C# * Copyright (C) 2003 Free Software Foundation, Inc. * Written by Bruno Haible <bruno@clisp.org>, 2003. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * Using the GNU gettext approach, compiled message catalogs are assemblies * containing just one class, a subclass of GettextResourceSet. They are thus * interoperable with standard ResourceManager based code. * * The main differences between the common .NET resources approach and the * GNU gettext approach are: * - In the .NET resource approach, the keys are abstract textual shortcuts. * In the GNU gettext approach, the keys are the English/ASCII version * of the messages. * - In the .NET resource approach, the translation files are called * "Resource.locale.resx" and are UTF-8 encoded XML files. In the GNU gettext * approach, the translation files are called "Resource.locale.po" and are * in the encoding the translator has chosen. There are at least three GUI * translating tools (Emacs PO mode, KDE KBabel, GNOME gtranslator). * - In the .NET resource approach, the function ResourceManager.GetString * returns an empty string or throws an InvalidOperationException when no * translation is found. In the GNU gettext approach, the GetString function * returns the (English) message key in that case. * - In the .NET resource approach, there is no support for plural handling. * In the GNU gettext approach, we have the GetPluralString function. * * To compile GNU gettext message catalogs into C# assemblies, the msgfmt * program can be used. */ using System; /* String, InvalidOperationException, Console */ using System.Globalization; /* CultureInfo */ using System.Resources; /* ResourceManager, ResourceSet, IResourceReader */ using System.Reflection; /* Assembly, ConstructorInfo */ using System.Collections; /* Hashtable, ICollection, IEnumerator, IDictionaryEnumerator */ using System.IO; /* Path, FileNotFoundException, Stream */ using System.Text; /* StringBuilder */ namespace GNU.Gettext { /// <summary> /// Each instance of this class can be used to lookup translations for a /// given resource name. For each <c>CultureInfo</c>, it performs the lookup /// in several assemblies, from most specific over territory-neutral to /// language-neutral. /// </summary> public class GettextResourceManager : ResourceManager { // ======================== Public Constructors ======================== /// <summary> /// Constructor. /// </summary> /// <param name="baseName">the resource name, also the assembly base /// name</param> public GettextResourceManager (String baseName) : base (baseName, Assembly.GetCallingAssembly(), typeof (GettextResourceSet)) { } /// <summary> /// Constructor. /// </summary> /// <param name="baseName">the resource name, also the assembly base /// name</param> public GettextResourceManager (String baseName, Assembly assembly) : base (baseName, assembly, typeof (GettextResourceSet)) { } // ======================== Implementation ======================== /// <summary> /// Loads and returns a satellite assembly. /// </summary> // This is like Assembly.GetSatelliteAssembly, but uses resourceName // instead of assembly.GetName().Name, and works around a bug in // mono-0.28. private static Assembly GetSatelliteAssembly (Assembly assembly, String resourceName, CultureInfo culture) { String satelliteExpectedLocation = Path.GetDirectoryName(assembly.Location) + Path.DirectorySeparatorChar + culture.Name + Path.DirectorySeparatorChar + resourceName + ".resources.dll"; return Assembly.LoadFrom(satelliteExpectedLocation); } /// <summary> /// Loads and returns the satellite assembly for a given culture. /// </summary> private Assembly MySatelliteAssembly (CultureInfo culture) { return GetSatelliteAssembly(MainAssembly, BaseName, culture); } /// <summary> /// Converts a resource name to a class name. /// </summary> /// <returns>a nonempty string consisting of alphanumerics and underscores /// and starting with a letter or underscore</returns> private static String ConstructClassName (String resourceName) { // We could just return an arbitrary fixed class name, like "Messages", // assuming that every assembly will only ever contain one // GettextResourceSet subclass, but this assumption would break the day // we want to support multi-domain PO files in the same format... bool valid = (resourceName.Length > 0); for (int i = 0; valid && i < resourceName.Length; i++) { char c = resourceName[i]; if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_') || (i > 0 && c >= '0' && c <= '9'))) valid = false; } if (valid) return resourceName; else { // Use hexadecimal escapes, using the underscore as escape character. String hexdigit = "0123456789abcdef"; StringBuilder b = new StringBuilder(); b.Append("__UESCAPED__"); for (int i = 0; i < resourceName.Length; i++) { char c = resourceName[i]; if (c >= 0xd800 && c < 0xdc00 && i+1 < resourceName.Length && resourceName[i+1] >= 0xdc00 && resourceName[i+1] < 0xe000) { // Combine two UTF-16 words to a character. char c2 = resourceName[i+1]; int uc = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); b.Append('_'); b.Append('U'); b.Append(hexdigit[(uc >> 28) & 0x0f]); b.Append(hexdigit[(uc >> 24) & 0x0f]); b.Append(hexdigit[(uc >> 20) & 0x0f]); b.Append(hexdigit[(uc >> 16) & 0x0f]); b.Append(hexdigit[(uc >> 12) & 0x0f]); b.Append(hexdigit[(uc >> 8) & 0x0f]); b.Append(hexdigit[(uc >> 4) & 0x0f]); b.Append(hexdigit[uc & 0x0f]); i++; } else if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) { int uc = c; b.Append('_'); b.Append('u'); b.Append(hexdigit[(uc >> 12) & 0x0f]); b.Append(hexdigit[(uc >> 8) & 0x0f]); b.Append(hexdigit[(uc >> 4) & 0x0f]); b.Append(hexdigit[uc & 0x0f]); } else b.Append(c); } return b.ToString(); } } /// <summary> /// Instantiates a resource set for a given culture. /// </summary> /// <exception cref="ArgumentException"> /// The expected type name is not valid. /// </exception> /// <exception cref="ReflectionTypeLoadException"> /// satelliteAssembly does not contain the expected type. /// </exception> /// <exception cref="NullReferenceException"> /// The type has no no-arguments constructor. /// </exception> private static GettextResourceSet InstantiateResourceSet (Assembly satelliteAssembly, String resourceName, CultureInfo culture) { // We expect a class with a culture dependent class name. Type clazz = satelliteAssembly.GetType(ConstructClassName(resourceName)+"_"+culture.Name.Replace('-','_')); // We expect it has a no-argument constructor, and invoke it. ConstructorInfo constructor = clazz.GetConstructor(Type.EmptyTypes); return constructor.Invoke(null) as GettextResourceSet; } private static GettextResourceSet[] EmptyResourceSetArray = new GettextResourceSet[0]; // Cache for already loaded GettextResourceSet cascades. private Hashtable /* CultureInfo -> GettextResourceSet[] */ Loaded = new Hashtable(); /// <summary> /// Returns the array of <c>GettextResourceSet</c>s for a given culture, /// loading them if necessary, and maintaining the cache. /// </summary> private GettextResourceSet[] GetResourceSetsFor (CultureInfo culture) { //Console.WriteLine(">> GetResourceSetsFor "+culture); // Look up in the cache. GettextResourceSet[] result = Loaded[culture] as GettextResourceSet[]; if (result == null) { lock(this) { // Look up again - maybe another thread has filled in the entry // while we slept waiting for the lock. result = Loaded[culture] as GettextResourceSet[]; if (result == null) { // Determine the GettextResourceSets for the given culture. if (culture.Parent == null || culture.Equals(CultureInfo.InvariantCulture)) // Invariant culture. result = EmptyResourceSetArray; else { // Use a satellite assembly as primary GettextResourceSet, and // the result for the parent culture as fallback. GettextResourceSet[] parentResult = GetResourceSetsFor(culture.Parent); Assembly satelliteAssembly; try { satelliteAssembly = MySatelliteAssembly(culture); } catch (FileNotFoundException e) { satelliteAssembly = null; } if (satelliteAssembly != null) { GettextResourceSet satelliteResourceSet; try { satelliteResourceSet = InstantiateResourceSet(satelliteAssembly, BaseName, culture); } catch (Exception e) { Console.Error.WriteLine(e); Console.Error.WriteLine(e.StackTrace); satelliteResourceSet = null; } if (satelliteResourceSet != null) { result = new GettextResourceSet[1+parentResult.Length]; result[0] = satelliteResourceSet; Array.Copy(parentResult, 0, result, 1, parentResult.Length); } else result = parentResult; } else result = parentResult; } // Put the result into the cache. Loaded.Add(culture, result); } } } //Console.WriteLine("<< GetResourceSetsFor "+culture); return result; } /* /// <summary> /// Releases all loaded <c>GettextResourceSet</c>s and their assemblies. /// </summary> // TODO: No way to release an Assembly? public override void ReleaseAllResources () { ... } */ /// <summary> /// Returns the translation of <paramref name="msgid"/> in a given culture. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <returns>the translation of <paramref name="msgid"/>, or /// <paramref name="msgid"/> if none is found</returns> public override String GetString (String msgid, CultureInfo culture) { foreach (GettextResourceSet rs in GetResourceSetsFor(culture)) { String translation = rs.GetString(msgid); if (translation != null) return translation; } // Fallback. return msgid; } /// <summary> /// Returns the translation of <paramref name="msgid"/> and /// <paramref name="msgidPlural"/> in a given culture, choosing the right /// plural form depending on the number <paramref name="n"/>. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <param name="msgidPlural">the English plural of <paramref name="msgid"/>, /// an ASCII string</param> /// <param name="n">the number, should be &gt;= 0</param> /// <returns>the translation, or <paramref name="msgid"/> or /// <paramref name="msgidPlural"/> if none is found</returns> public virtual String GetPluralString (String msgid, String msgidPlural, long n, CultureInfo culture) { foreach (GettextResourceSet rs in GetResourceSetsFor(culture)) { String translation = rs.GetPluralString(msgid, msgidPlural, n); if (translation != null) return translation; } // Fallback: Germanic plural form. return (n == 1 ? msgid : msgidPlural); } // ======================== Public Methods ======================== /// <summary> /// Returns the translation of <paramref name="msgid"/> in the current /// culture. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <returns>the translation of <paramref name="msgid"/>, or /// <paramref name="msgid"/> if none is found</returns> public override String GetString (String msgid) { return GetString(msgid, CultureInfo.CurrentUICulture); } /// <summary> /// Returns the translation of <paramref name="msgid"/> and /// <paramref name="msgidPlural"/> in the current culture, choosing the /// right plural form depending on the number <paramref name="n"/>. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <param name="msgidPlural">the English plural of <paramref name="msgid"/>, /// an ASCII string</param> /// <param name="n">the number, should be &gt;= 0</param> /// <returns>the translation, or <paramref name="msgid"/> or /// <paramref name="msgidPlural"/> if none is found</returns> public virtual String GetPluralString (String msgid, String msgidPlural, long n) { return GetPluralString(msgid, msgidPlural, n, CultureInfo.CurrentUICulture); } } /// <summary> /// <para> /// Each instance of this class encapsulates a single PO file. /// </para> /// <para> /// This API of this class is not meant to be used directly; use /// <c>GettextResourceManager</c> instead. /// </para> /// </summary> // We need this subclass of ResourceSet, because the plural formula must come // from the same ResourceSet as the object containing the plural forms. public class GettextResourceSet : ResourceSet { /// <summary> /// Creates a new message catalog. When using this constructor, you /// must override the <c>ReadResources</c> method, in order to initialize /// the <c>Table</c> property. The message catalog will support plural /// forms only if the <c>ReadResources</c> method installs values of type /// <c>String[]</c> and if the <c>PluralEval</c> method is overridden. /// </summary> protected GettextResourceSet () : base (DummyResourceReader) { } /// <summary> /// Creates a new message catalog, by reading the string/value pairs from /// the given <paramref name="reader"/>. The message catalog will support /// plural forms only if the reader can produce values of type /// <c>String[]</c> and if the <c>PluralEval</c> method is overridden. /// </summary> public GettextResourceSet (IResourceReader reader) : base (reader) { } /// <summary> /// Creates a new message catalog, by reading the string/value pairs from /// the given <paramref name="stream"/>, which should have the format of /// a <c>.resources</c> file. The message catalog will not support plural /// forms. /// </summary> public GettextResourceSet (Stream stream) : base (stream) { } /// <summary> /// Creates a new message catalog, by reading the string/value pairs from /// the file with the given <paramref name="fileName"/>. The file should /// be in the format of a <c>.resources</c> file. The message catalog will /// not support plural forms. /// </summary> public GettextResourceSet (String fileName) : base (fileName) { } /// <summary> /// Returns the translation of <paramref name="msgid"/>. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <returns>the translation of <paramref name="msgid"/>, or <c>null</c> if /// none is found</returns> // The default implementation essentially does (String)Table[msgid]. // Here we also catch the plural form case. public override String GetString (String msgid) { Object value = GetObject(msgid); if (value == null || value is String) return (String)value; else if (value is String[]) // A plural form, but no number is given. // Like the C implementation, return the first plural form. return (value as String[])[0]; else throw new InvalidOperationException("resource for \""+msgid+"\" in "+GetType().FullName+" is not a string"); } /// <summary> /// Returns the translation of <paramref name="msgid"/>, with possibly /// case-insensitive lookup. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <returns>the translation of <paramref name="msgid"/>, or <c>null</c> if /// none is found</returns> // The default implementation essentially does (String)Table[msgid]. // Here we also catch the plural form case. public override String GetString (String msgid, bool ignoreCase) { Object value = GetObject(msgid, ignoreCase); if (value == null || value is String) return (String)value; else if (value is String[]) // A plural form, but no number is given. // Like the C implementation, return the first plural form. return (value as String[])[0]; else throw new InvalidOperationException("resource for \""+msgid+"\" in "+GetType().FullName+" is not a string"); } /// <summary> /// Returns the translation of <paramref name="msgid"/> and /// <paramref name="msgidPlural"/>, choosing the right plural form /// depending on the number <paramref name="n"/>. /// </summary> /// <param name="msgid">the key string to be translated, an ASCII /// string</param> /// <param name="msgidPlural">the English plural of <paramref name="msgid"/>, /// an ASCII string</param> /// <param name="n">the number, should be &gt;= 0</param> /// <returns>the translation, or <c>null</c> if none is found</returns> public virtual String GetPluralString (String msgid, String msgidPlural, long n) { Object value = GetObject(msgid); if (value == null || value is String) return (String)value; else if (value is String[]) { String[] choices = value as String[]; long index = PluralEval(n); return choices[index >= 0 && index < choices.Length ? index : 0]; } else throw new InvalidOperationException("resource for \""+msgid+"\" in "+GetType().FullName+" is not a string"); } /// <summary> /// Returns the index of the plural form to be chosen for a given number. /// The default implementation is the Germanic plural formula: /// zero for <paramref name="n"/> == 1, one for <paramref name="n"/> != 1. /// </summary> protected virtual long PluralEval (long n) { return (n == 1 ? 0 : 1); } /// <summary> /// Returns the keys of this resource set, i.e. the strings for which /// <c>GetObject()</c> can return a non-null value. /// </summary> public virtual ICollection Keys { get { return Table.Keys; } } /// <summary> /// A trivial instance of <c>IResourceReader</c> that does nothing. /// </summary> // Needed by the no-arguments constructor. private static IResourceReader DummyResourceReader = new DummyIResourceReader(); } /// <summary> /// A trivial <c>IResourceReader</c> implementation. /// </summary> class DummyIResourceReader : IResourceReader { // Implementation of IDisposable. void System.IDisposable.Dispose () { } // Implementation of IEnumerable. IEnumerator System.Collections.IEnumerable.GetEnumerator () { return null; } // Implementation of IResourceReader. void System.Resources.IResourceReader.Close () { } IDictionaryEnumerator System.Resources.IResourceReader.GetEnumerator () { return null; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using FluentAssertions; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using NuGet.Versioning; using Xunit; namespace Microsoft.DotNet.Cli.Utils.Tests { public class GivenAProjectToolsCommandResolver { private static readonly NuGetFramework s_toolPackageFramework = FrameworkConstants.CommonFrameworks.NetCoreApp10; private static readonly string s_liveProjectDirectory = Path.Combine(AppContext.BaseDirectory, "TestAssets/TestProjects/AppWithToolDependency"); [Fact] public void It_returns_null_when_CommandName_is_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] { "" }, ProjectDirectory = "/some/directory" }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_ProjectDirectory_is_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = null }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_CommandName_does_not_exist_in_ProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_a_CommandSpec_with_DOTNET_as_FileName_and_CommandName_in_Args_when_CommandName_exists_in_ProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void It_escapes_CommandArguments_when_returning_a_CommandSpec() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = new[] { "arg with space" }, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void It_returns_a_CommandSpec_with_Args_containing_CommandPath_when_returning_a_CommandSpec_and_CommandArguments_are_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-portable.dll"); } [Fact] public void It_writes_a_deps_json_file_next_to_the_lockfile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var context = ProjectContext.Create(Path.Combine(s_liveProjectDirectory, "project.json"), s_toolPackageFramework); var nugetPackagesRoot = context.PackagesDirectory; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var directory = Path.GetDirectoryName(lockFilePath); var depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); if (depsJsonFile != null) { File.Delete(depsJsonFile); } var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); depsJsonFile.Should().NotBeNull(); } [Fact] public void Generate_deps_json_method_doesnt_overwrite_when_deps_file_already_exists() { var context = ProjectContext.Create(Path.Combine(s_liveProjectDirectory, "project.json"), s_toolPackageFramework); var nugetPackagesRoot = context.PackagesDirectory; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var lockFile = LockFileReader.Read(lockFilePath, designTime: false); var depsJsonFile = Path.Combine( Path.GetDirectoryName(lockFilePath), "dotnet-portable.deps.json"); if (File.Exists(depsJsonFile)) { File.Delete(depsJsonFile); } File.WriteAllText(depsJsonFile, "temp"); var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); projectToolsCommandResolver.GenerateDepsJsonFile(lockFile, depsJsonFile); File.ReadAllText(depsJsonFile).Should().Be("temp"); File.Delete(depsJsonFile); } private ProjectToolsCommandResolver SetupProjectToolsCommandResolver( IPackagedCommandSpecFactory packagedCommandSpecFactory = null) { packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory(); var projectToolsCommandResolver = new ProjectToolsCommandResolver(packagedCommandSpecFactory); return projectToolsCommandResolver; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Minimalism { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; ExtendedSpriteBatch spriteBatch; //I/O private KeyboardState _currentKeyboardState; private KeyboardState _previousKeyboardState; //Player private Player _player; //Paint private Lines _lines; private List<PaintedRectangle> _rectangles; private List<Paint> _paints; private int _level; private int _score; private bool _levelStart; private bool _levelEnd; private Song _themeSong; private SpriteFont _spriteFont; private SpriteFont _newLevelFont; private SoundEffect collisionSound; private SoundEffect _paintSound; public static SoundEffect MoveSound; private SoundEffect _blendedColorSound; private SoundEffect _filledRect; private bool _titleScreen; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { Globals.XMin = 20; Globals.XMax = GraphicsDevice.Viewport.Width - 20; Globals.YMin = 20; Globals.YMax = GraphicsDevice.Viewport.Height - 100; _rectangles = new List<PaintedRectangle>(); _player = new Player(); _lines = new Lines(); _player.Initialize(Globals.XMin, Globals.YMin); _lines.Initialize(); _paints = new List<Paint>(); _level = 0; _score = 0; _levelStart = true; _levelEnd = false; _titleScreen = true; for (var n = 0; n < 6; n++) { var newPaint = new Paint(); newPaint.Initialize((Globals.XMax + Globals.XMin) / 2 + Globals.Rng.Next(-25, 25), (Globals.YMax + Globals.YMin) / 2 + Globals.Rng.Next(-25, 25)); _paints.Add(newPaint); } base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new ExtendedSpriteBatch(GraphicsDevice); _spriteFont = Content.Load<SpriteFont>("PlaqueFont"); _newLevelFont = Content.Load<SpriteFont>("NewLevelFont"); collisionSound = Content.Load<SoundEffect>("Collision"); _paintSound = Content.Load<SoundEffect>("PaintSound"); MoveSound = Content.Load<SoundEffect>("Move"); _themeSong = Content.Load<Song>("Minimalist2"); _blendedColorSound = Content.Load<SoundEffect>("BlendedColorSound"); _filledRect = Content.Load<SoundEffect>("FilledRect"); MediaPlayer.Play(_themeSong); MediaPlayer.IsRepeating = true; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); _previousKeyboardState = _currentKeyboardState; _currentKeyboardState = Keyboard.GetState(); if (_levelStart) { for (var n = _paints.Count - 1; n >= 0; n--) { _paints[n].Update(_rectangles); MathHelper.Clamp(_paints[n].Position.X, Globals.XMin, Globals.XMax); MathHelper.Clamp(_paints[n].Position.X, Globals.XMin, Globals.XMax); if (!_paints[n].Active) _paints.Remove(_paints[n]); } if (_currentKeyboardState.IsKeyDown(Keys.Enter)) { _levelStart = false; _titleScreen = false; _level++; InitializeLevel(); } } else if (_levelEnd) { if (_currentKeyboardState.IsKeyDown(Keys.Enter)) { _levelEnd = false; InitializeLevel(); } } else { UpdatePlayer(); UpdateRectangles(); CollisionDetection(); _lines.Update(_player.Position); for (var n = _paints.Count - 1; n >= 0; n--) { _paints[n].Update(_rectangles); MathHelper.Clamp(_paints[n].Position.X, Globals.XMin, Globals.XMax); MathHelper.Clamp(_paints[n].Position.X, Globals.XMin, Globals.XMax); if (!_paints[n].Active) _paints.Remove(_paints[n]); } if (_paints.Count == 0) { if (_level*50000 > _score) { _levelEnd = true; } else { _levelStart = true; } } } base.Update(gameTime); } private void InitializeLevel() { _rectangles = new List<PaintedRectangle>(); _player = new Player(); _lines = new Lines(); _player.Initialize(Globals.XMin, Globals.YMin); _lines.Initialize(); _paints = new List<Paint>(); _score = 0; for (var n = 0; n < _level; n++) { var newPaint = new Paint(); newPaint.Initialize((Globals.XMax + Globals.XMin) / 2 + Globals.Rng.Next(-125, 125), (Globals.YMax + Globals.YMin) / 2 + Globals.Rng.Next(-125, 125)); _paints.Add(newPaint); } } /// <summary> /// Check if paint hits the line /// </summary> private void CollisionDetection() { foreach (var paint in _paints) { foreach (var spot in _lines.FilledRects) { if (spot.Intersects(paint.Rect) && spot.X+2 != Globals.XMax && spot.X+2 != Globals.XMin && spot.Y+2 != Globals.YMax && spot.Y+2 != Globals.YMin) { bool collision = true; foreach (var rect in _rectangles) { if (spot.Intersects(rect.Rect)) { collision = false; } } if (collision) { _score -= 1000; collisionSound.Play(); } } } } } /// <summary> /// If there is a new rectangle, draw it and capture any paints it got /// </summary> private void UpdateRectangles() { if (_player.HasNewRectangle) { var color = Color.White; _filledRect.Play(); //Check if any paints intersect the new rectangle foreach (var paint in _paints) { if (paint.Rect.Intersects(_player.NewRectangle)) { paint.Active = false; if (color == Color.White) { color = paint.PaintColor; _score += paint.Score; _paintSound.Play(); } else { _blendedColorSound.Play(); } } } _rectangles.Add(new PaintedRectangle(_player.NewRectangle, color)); _player.HasNewRectangle = false; } } public static Color Blend(Color color, Color backColor, double amount) { byte r = (byte)((color.R * amount) + backColor.R * (1 - amount)); byte g = (byte)((color.G * amount) + backColor.G * (1 - amount)); byte b = (byte)((color.B * amount) + backColor.B * (1 - amount)); return new Color(r, g, b); } private void UpdatePlayer() { _player.Update(_currentKeyboardState, _previousKeyboardState); _player.Position.X = MathHelper.Clamp(_player.Position.X, Globals.XMin, Globals.XMax); _player.Position.Y = MathHelper.Clamp(_player.Position.Y, Globals.YMin, Globals.YMax); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.DarkGray); spriteBatch.Begin(); if (_titleScreen) { spriteBatch.FillRectangle(new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White); spriteBatch.DrawString(_spriteFont, "You are Piet Mondrian, minimalist extrodinaire, \n and today you will paint your masterpiece! Your \n goal is to create a painting worth " + "$1,000,000. \n To do this, you have prepared a series of beautiful \n and carefully crafted colors. You must separate \n each of these colors into a separate " + "compartment \n on your canvas. Each time you mix multiple colors \n in a box, you lose potential value. Be careful! \n As you improve, " + "you can create more and more \n complex paintings. Good luck!", new Vector2(220, 100), Color.Black); spriteBatch.DrawString(_newLevelFont, "Press <ENTER> to begin", new Vector2(180, GraphicsDevice.Viewport.Height/3*2), Color.Black); foreach (var paint in _paints) { paint.Draw(spriteBatch); } } else { DrawScore(); spriteBatch.FillRectangle( new Rectangle(Globals.XMin, Globals.YMin, (Globals.XMax - Globals.XMin), (Globals.YMax - Globals.YMin)), Color.LightGray); spriteBatch.DrawLine(new Vector2(Globals.XMin, Globals.YMin), new Vector2(Globals.XMin, Globals.YMax), Color.Black); spriteBatch.DrawLine(new Vector2(Globals.XMin, Globals.YMin), new Vector2(Globals.XMax, Globals.YMin), Color.Black); spriteBatch.DrawLine(new Vector2(Globals.XMax, Globals.YMin), new Vector2(Globals.XMax, Globals.YMax), Color.Black); spriteBatch.DrawLine(new Vector2(Globals.XMin, Globals.YMax), new Vector2(Globals.XMax, Globals.YMax), Color.Black); DrawRectangles(spriteBatch); _lines.Draw(spriteBatch); foreach (var paint in _paints) { paint.Draw(spriteBatch); } _player.Draw(spriteBatch); if (_levelEnd) { // spriteBatch.FillRectangle(new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White); spriteBatch.DrawString(_newLevelFont, "No good!", new Vector2(GraphicsDevice.Viewport.Width/2 - 100, GraphicsDevice.Viewport.Height/2 - 50), Color.Black); spriteBatch.DrawString(_newLevelFont, "You need to separate out more colors.", new Vector2(GraphicsDevice.Viewport.Width / 2 - 380, GraphicsDevice.Viewport.Height / 2 - 10), Color.Black); spriteBatch.DrawString(_newLevelFont, "Press <ENTER> to retry", new Vector2(GraphicsDevice.Viewport.Width/2 - 250, GraphicsDevice.Viewport.Height/2 + 30), Color.Black); } if (_levelStart) { // spriteBatch.FillRectangle(new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White); if (_score > 1000000) { spriteBatch.DrawString(_newLevelFont, "Congratulations!", new Vector2(GraphicsDevice.Viewport.Width/2 - 180, GraphicsDevice.Viewport.Height/2 - 150), Color.Black); spriteBatch.DrawString(_newLevelFont, "You made a painting worth $" + (_score.ToString("#,##0")), new Vector2(30, GraphicsDevice.Viewport.Height/2 - 100), Color.Black); } spriteBatch.DrawString(_newLevelFont, "Opus #" + (_level + 1), new Vector2(GraphicsDevice.Viewport.Width/2 - 80, GraphicsDevice.Viewport.Height/2 - 50), Color.Black); spriteBatch.DrawString(_newLevelFont, "Press <ENTER> to begin", new Vector2(GraphicsDevice.Viewport.Width/2 - 250, GraphicsDevice.Viewport.Height/2 + 30), Color.Black); } } spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// Draw the score and level on a plaque beneath the painting /// </summary> private void DrawScore() { spriteBatch.FillRectangle( new Rectangle(GraphicsDevice.Viewport.Width/2 - 75, GraphicsDevice.Viewport.Height - 75, 150, 60), Color.Gold); spriteBatch.DrawRectangle( new Rectangle(GraphicsDevice.Viewport.Width/2 - 75, GraphicsDevice.Viewport.Height - 75, 150, 60), Color.RosyBrown); spriteBatch.DrawString(_spriteFont, "Opus #" + _level.ToString(), new Vector2(GraphicsDevice.Viewport.Width/2-30, GraphicsDevice.Viewport.Height-70), Color.Black); var score = _score.ToString("#,##0"); spriteBatch.DrawString(_spriteFont, "$" + score, new Vector2(GraphicsDevice.Viewport.Width / 2 - 35, GraphicsDevice.Viewport.Height - 45), Color.Black); } private void DrawRectangles(ExtendedSpriteBatch spriteBatch) { foreach (var rect in _rectangles.Reverse<PaintedRectangle>()) { spriteBatch.FillRectangle(rect.Rect, rect.RectColor); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using System.Numerics; namespace IronPython.Runtime { /// <summary> /// bytearray(string, encoding[, errors]) -> bytearray /// bytearray(iterable) -> bytearray /// /// Construct a mutable bytearray object from: /// - an iterable yielding values in range(256), including: /// + a list of integer values /// + a bytes, bytearray, buffer, or array object /// - a text string encoded using the specified encoding /// /// bytearray([int]) -> bytearray /// /// Construct a zero-ititialized bytearray of the specified length. /// (default=0) /// </summary> [PythonType("bytearray")] public class ByteArray : IList<byte>, ICodeFormattable, IBufferProtocol { internal List<byte>/*!*/ _bytes; public ByteArray() { _bytes = new List<byte>(0); } internal ByteArray(List<byte> bytes) { _bytes = bytes; } internal ByteArray (byte[] bytes) { _bytes = new List<byte>(bytes); } public void __init__() { _bytes = new List<byte>(); } public void __init__(int source) { _bytes = new List<byte>(source); for (int i = 0; i < source; i++) { _bytes.Add(0); } } public void __init__(BigInteger source) { __init__((int)source); } public void __init__([NotNull]IList<byte>/*!*/ source) { _bytes = new List<byte>(source); } public void __init__(object source) { __init__(GetBytes(source)); } public void __init__(CodeContext/*!*/ context, string source, string encoding, [DefaultParameterValue("strict")]string errors) { _bytes = new List<byte>(StringOps.encode(context, source, encoding, errors).MakeByteArray()); } #region Public Mutable Sequence API public void append(int item) { lock (this) { _bytes.Add(item.ToByteChecked()); } } public void append(object item) { lock(this) { _bytes.Add(GetByte(item)); } } public void extend([NotNull]IEnumerable<byte>/*!*/ seq) { using (new OrderedLocker(this, seq)) { // use the original count for if we're extending this w/ this _bytes.AddRange(seq); } } public void extend(object seq) { extend(GetBytes(seq)); } public void insert(int index, int value) { lock (this) { if (index >= Count) { append(value); return; } index = PythonOps.FixSliceIndex(index, Count); _bytes.Insert(index, value.ToByteChecked()); } } public void insert(int index, object value) { insert(index, Converter.ConvertToIndex(value)); } public int pop() { lock (this) { if (Count == 0) { throw PythonOps.IndexError("pop off of empty bytearray"); } int res = _bytes[_bytes.Count - 1]; _bytes.RemoveAt(_bytes.Count - 1); return res; } } public int pop(int index) { lock (this) { if (Count == 0) { throw PythonOps.IndexError("pop off of empty bytearray"); } index = PythonOps.FixIndex(index, Count); int ret = _bytes[index]; _bytes.RemoveAt(index); return ret; } } public void remove(int value) { lock (this) { _bytes.RemoveAt(_bytes.IndexOfByte(value.ToByteChecked(), 0, _bytes.Count)); } } public void remove(object value) { lock (this) { if (value is ByteArray) { throw PythonOps.TypeError("an integer or string of size 1 is required"); } _bytes.RemoveAt(_bytes.IndexOfByte(GetByte(value), 0, _bytes.Count)); } } public void reverse() { lock (this) { List<byte> reversed = new List<byte>(); for (int i = _bytes.Count - 1; i >= 0; i--) { reversed.Add(_bytes[i]); } _bytes = reversed; } } [SpecialName] public ByteArray InPlaceAdd(ByteArray other) { using (new OrderedLocker(this, other)) { _bytes.AddRange(other._bytes); return this; } } [SpecialName] public ByteArray InPlaceAdd(Bytes other) { lock (this) { _bytes.AddRange(other); return this; } } [SpecialName] public ByteArray InPlaceAdd(MemoryView other) { lock (this) { _bytes.AddRange(other.tobytes()); return this; } } [SpecialName] public ByteArray InPlaceMultiply(int len) { lock (this) { _bytes = (this * len)._bytes; return this; } } #endregion #region Public Python API surface public ByteArray/*!*/ capitalize() { lock (this) { return new ByteArray(_bytes.Capitalize()); } } public ByteArray/*!*/ center(int width) { return center(width, " "); } public ByteArray/*!*/ center(int width, [NotNull]string fillchar) { lock (this) { List<byte> res = _bytes.TryCenter(width, fillchar.ToByte("center", 2)); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public ByteArray/*!*/ center(int width, [BytesConversion]IList<byte> fillchar) { lock (this) { List<byte> res = _bytes.TryCenter(width, fillchar.ToByte("center", 2)); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public int count([BytesConversion]IList<byte>/*!*/ sub) { return count(sub, 0, _bytes.Count); } public int count([BytesConversion]IList<byte>/*!*/ sub, int start) { return count(sub, start, _bytes.Count); } public int count([BytesConversion]IList<byte>/*!*/ ssub, int start, int end) { lock (this) { return _bytes.CountOf(ssub, start, end); } } public string decode(CodeContext/*!*/ context, [Optional]object encoding, [DefaultParameterValue("strict")][NotNull]string errors) { return StringOps.decode(context, _bytes.MakeString(), encoding, errors); } public bool endswith([BytesConversion]IList<byte>/*!*/ suffix) { lock (this) { return _bytes.EndsWith(suffix); } } public bool endswith([BytesConversion]IList<byte>/*!*/ suffix, int start) { lock (this) { return _bytes.EndsWith(suffix, start); } } public bool endswith([BytesConversion]IList<byte>/*!*/ suffix, int start, int end) { lock (this) { return _bytes.EndsWith(suffix, start, end); } } public bool endswith(PythonTuple/*!*/ suffix) { lock (this) { return _bytes.EndsWith(suffix); } } public bool endswith(PythonTuple/*!*/ suffix, int start) { lock (this) { return _bytes.EndsWith(suffix, start); } } public bool endswith(PythonTuple/*!*/ suffix, int start, int end) { lock (this) { return _bytes.EndsWith(suffix, start, end); } } public ByteArray/*!*/ expandtabs() { return expandtabs(8); } public ByteArray/*!*/ expandtabs(int tabsize) { lock (this) { return new ByteArray(_bytes.ExpandTabs(tabsize)); } } public int find([BytesConversion]IList<byte>/*!*/ sub) { lock (this) { return _bytes.Find(sub); } } public int find([BytesConversion]IList<byte>/*!*/ sub, int start) { lock (this) { return _bytes.Find(sub, start); } } public int find([BytesConversion]IList<byte>/*!*/ sub, int start, int end) { lock (this) { return _bytes.Find(sub, start, end); } } public static ByteArray/*!*/ fromhex(string/*!*/ @string) { return new ByteArray(IListOfByteOps.FromHex(@string)); } public int index([BytesConversion]IList<byte>/*!*/ item) { return index(item, 0, _bytes.Count); } public int index([BytesConversion]IList<byte>/*!*/ item, int start) { return index(item, start, _bytes.Count); } public int index([BytesConversion]IList<byte>/*!*/ item, int start, int stop) { lock (this) { int res = find(item, start, stop); if (res == -1) { throw PythonOps.ValueError("bytearray.index(item): item not in bytearray"); } return res; } } public bool isalnum() { lock (this) { return _bytes.IsAlphaNumeric(); } } public bool isalpha() { lock (this) { return _bytes.IsLetter(); } } public bool isdigit() { lock (this) { return _bytes.IsDigit(); } } public bool islower() { lock (this) { return _bytes.IsLower(); } } public bool isspace() { lock (this) { return _bytes.IsWhiteSpace(); } } /// <summary> /// return true if self is a titlecased string and there is at least one /// character in self; also, uppercase characters may only follow uncased /// characters (e.g. whitespace) and lowercase characters only cased ones. /// return false otherwise. /// </summary> public bool istitle() { lock (this) { return _bytes.IsTitle(); } } public bool isupper() { lock (this) { return _bytes.IsUpper(); } } /// <summary> /// Return a string which is the concatenation of the strings /// in the sequence seq. The separator between elements is the /// string providing this method /// </summary> public ByteArray/*!*/ join(object/*!*/ sequence) { IEnumerator seq = PythonOps.GetEnumerator(sequence); if (!seq.MoveNext()) { return new ByteArray(); } // check if we have just a sequnce of just one value - if so just // return that value. object curVal = seq.Current; if (!seq.MoveNext()) { return JoinOne(curVal); } List<byte> ret = new List<byte>(); ByteOps.AppendJoin(curVal, 0, ret); int index = 1; do { ret.AddRange(this); ByteOps.AppendJoin(seq.Current, index, ret); index++; } while (seq.MoveNext()); return new ByteArray(ret); } public ByteArray/*!*/ join([NotNull]List/*!*/ sequence) { if (sequence.__len__() == 0) { return new ByteArray(); } lock (this) { if (sequence.__len__() == 1) { return JoinOne(sequence[0]); } List<byte> ret = new List<byte>(); ByteOps.AppendJoin(sequence._data[0], 0, ret); for (int i = 1; i < sequence._size; i++) { ret.AddRange(this); ByteOps.AppendJoin(sequence._data[i], i, ret); } return new ByteArray(ret); } } public ByteArray/*!*/ ljust(int width) { return ljust(width, (byte)' '); } public ByteArray/*!*/ ljust(int width, [NotNull]string/*!*/ fillchar) { return ljust(width, fillchar.ToByte("ljust", 2)); } public ByteArray/*!*/ ljust(int width, IList<byte>/*!*/ fillchar) { return ljust(width, fillchar.ToByte("ljust", 2)); } private ByteArray/*!*/ ljust(int width, byte fillchar) { lock (this) { int spaces = width - _bytes.Count; List<byte> ret = new List<byte>(width); ret.AddRange(_bytes); for (int i = 0; i < spaces; i++) { ret.Add(fillchar); } return new ByteArray(ret); } } public ByteArray/*!*/ lower() { lock (this) { return new ByteArray(_bytes.ToLower()); } } public ByteArray/*!*/ lstrip() { lock (this) { List<byte> res = _bytes.LeftStrip(); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public ByteArray/*!*/ lstrip([BytesConversionNoString]IList<byte> bytes) { lock (this) { List<byte> res = _bytes.LeftStrip(bytes); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public PythonTuple/*!*/ partition(IList<byte>/*!*/ sep) { if (sep == null) { throw PythonOps.TypeError("expected string, got NoneType"); } else if (sep.Count == 0) { throw PythonOps.ValueError("empty separator"); } object[] obj = new object[3] { new ByteArray(), new ByteArray(), new ByteArray() }; if (_bytes.Count != 0) { int index = find(sep); if (index == -1) { obj[0] = CopyThis(); } else { obj[0] = new ByteArray(_bytes.Substring(0, index)); obj[1] = sep; obj[2] = new ByteArray(_bytes.Substring(index + sep.Count, _bytes.Count - index - sep.Count)); } } return new PythonTuple(obj); } public PythonTuple/*!*/ partition([NotNull]List/*!*/ sep) { return partition(GetBytes(sep)); } public ByteArray/*!*/ replace([BytesConversion]IList<byte>/*!*/ old, [BytesConversion]IList<byte> @new) { if (old == null) { throw PythonOps.TypeError("expected bytes or bytearray, got NoneType"); } return replace(old, @new, _bytes.Count); } public ByteArray/*!*/ replace([BytesConversion]IList<byte>/*!*/ old, [BytesConversion]IList<byte>/*!*/ @new, int count) { if (old == null) { throw PythonOps.TypeError("expected bytes or bytearray, got NoneType"); } else if (count == 0) { return CopyThis(); } return new ByteArray(_bytes.Replace(old, @new, count)); } public int rfind([BytesConversion]IList<byte>/*!*/ sub) { return rfind(sub, 0, _bytes.Count); } public int rfind([BytesConversion]IList<byte>/*!*/ sub, int start) { return rfind(sub, start, _bytes.Count); } public int rfind([BytesConversion]IList<byte>/*!*/ sub, int start, int end) { lock (this) { return _bytes.ReverseFind(sub, start, end); } } public int rindex([BytesConversion]IList<byte>/*!*/ sub) { return rindex(sub, 0, _bytes.Count); } public int rindex([BytesConversion]IList<byte>/*!*/ sub, int start) { return rindex(sub, start, _bytes.Count); } public int rindex([BytesConversion]IList<byte>/*!*/ sub, int start, int end) { int ret = rfind(sub, start, end); if (ret == -1) { throw PythonOps.ValueError("substring {0} not found in {1}", sub, this); } return ret; } public ByteArray/*!*/ rjust(int width) { return rjust(width, (byte)' '); } public ByteArray/*!*/ rjust(int width, [NotNull]string/*!*/ fillchar) { return rjust(width, fillchar.ToByte("rjust", 2)); } public ByteArray/*!*/ rjust(int width, [BytesConversion]IList<byte>/*!*/ fillchar) { return rjust(width, fillchar.ToByte("rjust", 2)); } private ByteArray/*!*/ rjust(int width, int fillchar) { byte fill = fillchar.ToByteChecked(); lock (this) { int spaces = width - _bytes.Count; if (spaces <= 0) { return CopyThis(); } List<byte> ret = new List<byte>(width); for (int i = 0; i < spaces; i++) { ret.Add(fill); } ret.AddRange(_bytes); return new ByteArray(ret); } } public PythonTuple/*!*/ rpartition(IList<byte>/*!*/ sep) { if (sep == null) { throw PythonOps.TypeError("expected string, got NoneType"); } else if (sep.Count == 0) { throw PythonOps.ValueError("empty separator"); } lock (this) { object[] obj = new object[3] { new ByteArray(), new ByteArray(), new ByteArray() }; if (_bytes.Count != 0) { int index = rfind(sep); if (index == -1) { obj[2] = CopyThis(); } else { obj[0] = new ByteArray(_bytes.Substring(0, index)); obj[1] = new ByteArray(new List<byte>(sep)); obj[2] = new ByteArray(_bytes.Substring(index + sep.Count, Count - index - sep.Count)); } } return new PythonTuple(obj); } } public PythonTuple/*!*/ rpartition([NotNull]List/*!*/ sep) { return rpartition(GetBytes(sep)); } public List/*!*/ rsplit() { lock (this) { return _bytes.SplitInternal((byte[])null, -1, x => new ByteArray(x)); } } public List/*!*/ rsplit([BytesConversionNoString]IList<byte>/*!*/ sep) { return rsplit(sep, -1); } public List/*!*/ rsplit([BytesConversionNoString]IList<byte>/*!*/ sep, int maxsplit) { return _bytes.RightSplit(sep, maxsplit, x => new ByteArray(new List<byte>(x))); } public ByteArray/*!*/ rstrip() { lock (this) { List<byte> res = _bytes.RightStrip(); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public ByteArray/*!*/ rstrip([BytesConversionNoString]IList<byte> bytes) { lock (this) { List<byte> res = _bytes.RightStrip(bytes); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public List/*!*/ split() { lock (this) { return _bytes.SplitInternal((byte[])null, -1, x => new ByteArray(x)); } } public List/*!*/ split([BytesConversionNoString]IList<byte> sep) { return split(sep, -1); } public List/*!*/ split([BytesConversionNoString]IList<byte> sep, int maxsplit) { lock (this) { return _bytes.Split(sep, maxsplit, x => new ByteArray(x)); } } public List/*!*/ splitlines() { return splitlines(false); } public List/*!*/ splitlines(bool keepends) { lock (this) { return _bytes.SplitLines(keepends, x => new ByteArray(x)); } } public bool startswith([BytesConversion]IList<byte>/*!*/ prefix) { lock (this) { return _bytes.StartsWith(prefix); } } public bool startswith([BytesConversion]IList<byte>/*!*/ prefix, int start) { lock (this) { int len = Count; if (start > len) { return false; } else if (start < 0) { start += len; if (start < 0) start = 0; } return _bytes.Substring(start).StartsWith(prefix); } } public bool startswith([BytesConversion]IList<byte>/*!*/ prefix, int start, int end) { lock (this) { return _bytes.StartsWith(prefix, start, end); } } public bool startswith(PythonTuple/*!*/ prefix) { lock (this) { return _bytes.StartsWith(prefix); } } public bool startswith(PythonTuple/*!*/ prefix, int start) { lock (this) { return _bytes.StartsWith(prefix, start); } } public bool startswith(PythonTuple/*!*/ prefix, int start, int end) { lock (this) { return _bytes.StartsWith(prefix, start, end); } } public ByteArray/*!*/ strip() { lock (this) { List<byte> res = _bytes.Strip(); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public ByteArray/*!*/ strip([BytesConversionNoString]IList<byte> chars) { lock (this) { List<byte> res = _bytes.Strip(chars); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public ByteArray/*!*/ swapcase() { lock (this) { return new ByteArray(_bytes.SwapCase()); } } public ByteArray/*!*/ title() { lock (this) { List<byte> res = _bytes.Title(); if (res == null) { return CopyThis(); } return new ByteArray(res); } } public ByteArray/*!*/ translate([BytesConversion]IList<byte>/*!*/ table) { lock (this) { if (table != null) { if (table.Count != 256) { throw PythonOps.ValueError("translation table must be 256 characters long"); } else if (Count == 0) { return CopyThis(); } } return new ByteArray(_bytes.Translate(table, null)); } } public ByteArray/*!*/ translate([BytesConversion]IList<byte>/*!*/ table, [BytesConversion]IList<byte>/*!*/ deletechars) { if (table == null && deletechars == null) { throw PythonOps.TypeError("expected bytearray or bytes, got NoneType"); } else if (deletechars == null) { throw PythonOps.TypeError("expected bytes or bytearray, got None"); } lock (this) { return new ByteArray(_bytes.Translate(table, deletechars)); } } public ByteArray/*!*/ upper() { lock (this) { return new ByteArray(_bytes.ToUpper()); } } public ByteArray/*!*/ zfill(int width) { lock (this) { int spaces = width - Count; if (spaces <= 0) { return CopyThis(); } return new ByteArray(_bytes.ZeroFill(width, spaces)); } } public int __alloc__() { if (_bytes.Count == 0) { return 0; } return _bytes.Count + 1; } public bool __contains__([BytesConversionNoString]IList<byte> bytes) { return this.IndexOf(bytes, 0) != -1; } public bool __contains__(int value) { return IndexOf(value.ToByteChecked()) != -1; } public bool __contains__(CodeContext/*!*/ context, object value) { if (value is Extensible<int>) { return IndexOf(((Extensible<int>)value).Value.ToByteChecked()) != -1; } else if (value is BigInteger) { return IndexOf(((BigInteger)value).ToByteChecked()) != -1; } else if (value is Extensible<BigInteger>) { return IndexOf(((Extensible<BigInteger>)value).Value.ToByteChecked()) != -1; } throw PythonOps.TypeError("Type {0} doesn't support the buffer API", context.LanguageContext.PythonOptions.Python30 ? PythonTypeOps.GetOldName(value) : PythonTypeOps.GetName(value)); } public PythonTuple __reduce__(CodeContext/*!*/ context) { return PythonTuple.MakeTuple( DynamicHelpers.GetPythonType(this), PythonTuple.MakeTuple( PythonOps.MakeString(this), "latin-1" ), GetType() == typeof(ByteArray) ? null : ObjectOps.ReduceProtocol0(context, this)[2] ); } public virtual string/*!*/ __repr__(CodeContext/*!*/ context) { lock (this) { return "bytearray(" + _bytes.BytesRepr() + ")"; } } public static ByteArray operator +(ByteArray self, ByteArray other) { if (self == null) { throw PythonOps.TypeError("expected ByteArray, got None"); } List<byte> bytes; lock (self) { bytes = new List<byte>(self._bytes); } lock (other) { bytes.AddRange(other._bytes); } return new ByteArray(bytes); } public static ByteArray operator +(ByteArray self, Bytes other) { List<byte> bytes; lock (self) { bytes = new List<byte>(self._bytes); } bytes.AddRange(other); return new ByteArray(bytes); } public static ByteArray operator +(ByteArray self, MemoryView other) { List<byte> bytes; lock (self) { bytes = new List<byte>(self._bytes); } bytes.AddRange(other.tobytes()); return new ByteArray(bytes); } /// <summary> /// This overload is specifically implemented because in IronPython strings are unicode /// </summary> public static ByteArray operator +(ByteArray self, string other) { List<byte> bytes; lock(self) { bytes = new List<byte>(self._bytes); } if(!other.TryMakeByteArray(out byte[] data)) { throw PythonOps.TypeError("can't concat unicode to bytearray"); } bytes.AddRange(data); return new ByteArray(bytes); } public static ByteArray operator *(ByteArray x, int y) { lock (x) { if (y == 1) { return x.CopyThis(); } return new ByteArray(x._bytes.Multiply(y)); } } public static ByteArray operator *(int x, ByteArray y) { return y * x; } public static bool operator >(ByteArray/*!*/ x, ByteArray y) { if (y == null) { return true; } using (new OrderedLocker(x, y)) { return x._bytes.Compare(y._bytes) > 0; } } public static bool operator <(ByteArray/*!*/ x, ByteArray y) { if (y == null) { return false; } using (new OrderedLocker(x, y)) { return x._bytes.Compare(y._bytes) < 0; } } public static bool operator >=(ByteArray/*!*/ x, ByteArray y) { if (y == null) { return true; } using (new OrderedLocker(x, y)) { return x._bytes.Compare(y._bytes) >= 0; } } public static bool operator <=(ByteArray/*!*/ x, ByteArray y) { if (y == null) { return false; } using (new OrderedLocker(x, y)) { return x._bytes.Compare(y._bytes) <= 0; } } public static bool operator >(ByteArray/*!*/ x, Bytes y) { if (y == null) { return true; } lock (x) { return x._bytes.Compare(y) > 0; } } public static bool operator <(ByteArray/*!*/ x, Bytes y) { if (y == null) { return false; } lock (x) { return x._bytes.Compare(y) < 0; } } public static bool operator >=(ByteArray/*!*/ x, Bytes y) { if (y == null) { return true; } lock (x) { return x._bytes.Compare(y) >= 0; } } public static bool operator <=(ByteArray/*!*/ x, Bytes y) { if (y == null) { return false; } lock (x) { return x._bytes.Compare(y) <= 0; } } public object this[int index] { get { lock (this) { return ScriptingRuntimeHelpers.Int32ToObject((int)_bytes[PythonOps.FixIndex(index, _bytes.Count)]); } } set { lock (this) { _bytes[PythonOps.FixIndex(index, _bytes.Count)] = GetByte(value); } } } public object this[BigInteger index] { get { int iVal; if (index.AsInt32(out iVal)) { return this[iVal]; } throw PythonOps.IndexError("cannot fit long in index"); } set { int iVal; if (index.AsInt32(out iVal)) { this[iVal] = value; return; } throw PythonOps.IndexError("cannot fit long in index"); } } public object this[Slice/*!*/ slice] { get { lock (this) { List<byte> res = _bytes.Slice(slice); if (res == null) { return new ByteArray(); } return new ByteArray(res); } } set { if (slice == null) { throw PythonOps.TypeError("bytearray indices must be integer or slice, not None"); } // get a list of the bytes we're going to assign into the slice. We accept: // integers, longs, etc... - fill in an array of 0 bytes // list of bytes, indexables, etc... if (!(value is IList<byte> list)) { int? iVal = null; if (value is int) { iVal = (int)value; } else if (value is Extensible<int>) { iVal = ((Extensible<int>)value).Value; } else if (value is BigInteger) { int intval; if (((BigInteger)value).AsInt32(out intval)) { iVal = intval; } } if (iVal != null) { List<byte> newlist = new List<byte>(); newlist.Capacity = iVal.Value; for (int i = 0; i < iVal; i++) { newlist.Add(0); } list = newlist; } else { IEnumerator ie = PythonOps.GetEnumerator(value); list = new List<byte>(); while (ie.MoveNext()) { list.Add(GetByte(ie.Current)); } } } lock (this) { if (slice.step != null) { // try to assign back to self: make a copy first if (this == list) { value = CopyThis(); } else if (list.Count == 0) { DeleteItem(slice); return; } IList<byte> castedVal = GetBytes(value); int start, stop, step; slice.indices(_bytes.Count, out start, out stop, out step); int n = (step > 0 ? (stop - start + step - 1) : (stop - start + step + 1)) / step; // we don't use slice.Assign* helpers here because bytearray has different assignment semantics. if (list.Count < n) { throw PythonOps.ValueError("too few items in the enumerator. need {0} have {1}", n, castedVal.Count); } for (int i = 0, index = start; i < castedVal.Count; i++, index += step) { if (i >= n) { if (index == _bytes.Count) { _bytes.Add(castedVal[i]); } else { _bytes.Insert(index, castedVal[i]); } } else { _bytes[index] = castedVal[i]; } } } else { int start, stop, step; slice.indices(_bytes.Count, out start, out stop, out step); SliceNoStep(start, stop, list); } } } } [SpecialName] public void DeleteItem(int index) { _bytes.RemoveAt(PythonOps.FixIndex(index, _bytes.Count)); } [SpecialName] public void DeleteItem(Slice/*!*/ slice) { if (slice == null) { throw PythonOps.TypeError("list indices must be integers or slices"); } lock (this) { int start, stop, step; // slice is sealed, indices can't be user code... slice.indices(_bytes.Count, out start, out stop, out step); if (step > 0 && (start >= stop)) return; if (step < 0 && (start <= stop)) return; if (step == 1) { int i = start; for (int j = stop; j < _bytes.Count; j++, i++) { _bytes[i] = _bytes[j]; } _bytes.RemoveRange(i, stop - start); return; } else if (step == -1) { int i = stop + 1; for (int j = start + 1; j < _bytes.Count; j++, i++) { _bytes[i] = _bytes[j]; } _bytes.RemoveRange(i, start - stop); return; } else if (step < 0) { // find "start" we will skip in the 1,2,3,... order int i = start; while (i > stop) { i += step; } i -= step; // swap start/stop, make step positive stop = start + 1; start = i; step = -step; } int curr, skip, move; // skip: the next position we should skip // curr: the next position we should fill in data // move: the next position we will check curr = skip = move = start; while (curr < stop && move < stop) { if (move != skip) { _bytes[curr++] = _bytes[move]; } else skip += step; move++; } while (stop < _bytes.Count) { _bytes[curr++] = _bytes[stop++]; } _bytes.RemoveRange(curr, _bytes.Count - curr); } } #endregion #region Implementation Details private static ByteArray/*!*/ JoinOne(object/*!*/ curVal) { if (!(curVal is IList<byte>)) { throw PythonOps.TypeError("can only join an iterable of bytes"); } return new ByteArray(new List<byte>(curVal as IList<byte>)); } private ByteArray/*!*/ CopyThis() { return new ByteArray(new List<byte>(_bytes)); } private void SliceNoStep(int start, int stop, IList<byte>/*!*/ value) { // always copy from a List object, even if it's a copy of some user defined enumerator. This // makes it easy to hold the lock for the duration fo the copy. IList<byte> other = GetBytes(value); lock (this) { if (start > stop) { int newSize = Count + other.Count; List<byte> newData = new List<byte>(newSize); int reading = 0; for (reading = 0; reading < start; reading++) { newData.Add(_bytes[reading]); } for (int i = 0; i < other.Count; i++) { newData.Add(other[i]); } for (; reading < Count; reading++) { newData.Add(_bytes[reading]); } _bytes = newData; } else if ((stop - start) == other.Count) { // we are simply replacing values, this is fast... for (int i = 0; i < other.Count; i++) { _bytes[i + start] = other[i]; } } else { // we are resizing the array (either bigger or smaller), we // will copy the data array and replace it all at once. int newSize = Count - (stop - start) + other.Count; List<byte> newData = new List<byte>(newSize); for (int i = 0; i < start; i++) { newData.Add(_bytes[i]); } for (int i = 0; i < other.Count; i++) { newData.Add(other[i]); } for (int i = stop; i < Count; i++) { newData.Add(_bytes[i]); } _bytes = newData; } } } private static byte GetByte(object/*!*/ value) { if (value is double || value is Extensible<double> || value is float) { throw PythonOps.TypeError("an integer or string of size 1 is required"); } return ByteOps.GetByteListOk(value); } private static IList<byte>/*!*/ GetBytes(object/*!*/ value) { if (!(value is ListGenericWrapper<byte> genWrapper) && value is IList<byte>) { return (IList<byte>)value; } if (value is string strValue) { return strValue.MakeByteArray(); } if (value is Extensible<string> esValue) { return esValue.Value.MakeByteArray(); } if (value is IBufferProtocol buffer) { return buffer.ToBytes(0, null); } List<byte> ret = new List<byte>(); IEnumerator ie = PythonOps.GetEnumerator(value); while (ie.MoveNext()) { ret.Add(GetByte(ie.Current)); } return ret; } #endregion #region IList<byte> Members [PythonHidden] public int IndexOf(byte item) { lock (this) { return _bytes.IndexOf(item); } } [PythonHidden] public void Insert(int index, byte item) { _bytes.Insert(index, item); } [PythonHidden] public void RemoveAt(int index) { _bytes.RemoveAt(index); } byte IList<byte>.this[int index] { get { return _bytes[index]; } set { _bytes[index] = value; } } #endregion #region ICollection<byte> Members [PythonHidden] public void Add(byte item) { lock (this) { _bytes.Add(item); } } [PythonHidden] public void Clear() { lock (this) { _bytes.Clear(); } } [PythonHidden] public bool Contains(byte item) { lock (this) { return _bytes.Contains(item); } } [PythonHidden] public void CopyTo(byte[]/*!*/ array, int arrayIndex) { lock (this) { _bytes.CopyTo(array, arrayIndex); } } public int Count { [PythonHidden] get { lock (this) { return _bytes.Count; } } } public bool IsReadOnly { [PythonHidden] get { return false; } } [PythonHidden] public bool Remove(byte item) { lock (this) { return _bytes.Remove(item); } } #endregion public IEnumerator __iter__() { return PythonOps.BytesIntEnumerator(this).Key; } #region IEnumerable<byte> Members [PythonHidden] public IEnumerator<byte>/*!*/ GetEnumerator() { return _bytes.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator/*!*/ System.Collections.IEnumerable.GetEnumerator() { foreach (var _byte in _bytes) { yield return (int)_byte; } } #endregion public const object __hash__ = null; public override int GetHashCode() { return (PythonTuple.MakeTuple(_bytes.ToArray())).GetHashCode(); } public override bool Equals(object other) { IList<byte> bytes ; if (other is string) bytes = PythonOps.MakeBytes(((string)other).MakeByteArray()); else if (other is Extensible<string>) bytes = PythonOps.MakeBytes(((Extensible<string>)other).Value.MakeByteArray()); else bytes = other as IList<byte>; if (bytes == null || Count != bytes.Count) { return false; } else if (Count == 0) { // 2 empty ByteArrays are equal return true; } using (new OrderedLocker(this, other)) { for (int i = 0; i < Count; i++) { if (_bytes[i] != bytes[i]) { return false; } } } return true; } public override string ToString() { return _bytes.MakeString(); } #region IBufferProtocol Members Bytes IBufferProtocol.GetItem(int index) { lock (this) { return new Bytes(new[] { _bytes[PythonOps.FixIndex(index, _bytes.Count)] }); } } void IBufferProtocol.SetItem(int index, object value) { this[index] = value; } void IBufferProtocol.SetSlice(Slice index, object value) { this[index] = value; } int IBufferProtocol.ItemCount { get { return _bytes.Count; } } string IBufferProtocol.Format { get { return "B"; } } BigInteger IBufferProtocol.ItemSize { get { return 1; } } BigInteger IBufferProtocol.NumberDimensions { get { return 1; } } bool IBufferProtocol.ReadOnly { get { return false; } } IList<BigInteger> IBufferProtocol.GetShape(int start, int? end) { if (end != null) { return new[] { (BigInteger)end - start }; } return new[] { (BigInteger)this._bytes.Count - start }; } PythonTuple IBufferProtocol.Strides { get { return PythonTuple.MakeTuple(1); } } object IBufferProtocol.SubOffsets { get { return null; } } Bytes IBufferProtocol.ToBytes(int start, int? end) { if (start == 0 && end == null) { return new Bytes(this); } return new Bytes((ByteArray)this[new Slice(start, end)]); } List IBufferProtocol.ToList(int start, int? end) { List<byte> res = _bytes.Slice(new Slice(start, end)); if (res == null) { return new List(); } return new List(res.ToArray()); } #endregion } }
//#define COSMOSDEBUG using System; using System.Runtime.CompilerServices; using Cosmos.Core; using Cosmos.Core_Asm.MemoryOperations; using IL2CPU.API; using IL2CPU.API.Attribs; //using Cosmos.Core.MemoryOperations; namespace Cosmos.Core_Plugs.MemoryOperations { [Plug(Target = typeof(Cosmos.Core.MemoryOperations))] public unsafe class MemoryOperationsImpl { [PlugMethod(Assembler = typeof(MemoryOperationsFill16BlocksAsm))] private static unsafe void Fill16Blocks(byte* dest, int value, int BlocksNum) { throw new NotImplementedException(); } unsafe public static void Fill(byte* dest, int value, int size) { //Console.WriteLine("Filling array of size " + size + " with value 0x" + value.ToString("X")); //Global.mDebugger.SendInternal("Filling array of size " + size + " with value " + value); /* For very little sizes (until 15 bytes) we hand unroll the loop */ switch (size) { case 0: return; case 1: *dest = (byte)value; return; case 2: *(short*)dest = (short)value; return; case 3: *(short*)dest = (short)value; *(dest + 2) = (byte)value; return; case 4: *(int*)dest = value; return; case 5: *(int*)dest = value; *(dest + 4) = (byte)value; return; case 6: *(int*)dest = value; *(short*)(dest + 4) = (short)value; return; case 7: *(int*)dest = value; *(short*)(dest + 4) = (short)value; *(dest + 6) = (byte)value; return; case 8: *(int*)dest = value; *(int*)(dest + 4) = value; return; case 9: *(int*)dest = value; *(int*)(dest + 4) = value; *(dest + 8) = (byte)value; return; case 10: *(int*)dest = value; *(int*)(dest + 4) = value; *(short*)(dest + 8) = (short)value; return; case 11: *(int*)dest = value; *(int*)(dest + 4) = value; *(short*)(dest + 8) = (short)value; *(dest + 10) = (byte)value; return; case 12: *(int*)dest = value; *(int*)(dest + 4) = value; *(int*)(dest + 8) = value; return; case 13: *(int*)dest = value; *(int*)(dest + 4) = value; *(int*)(dest + 8) = value; *(dest + 12) = (byte)value; return; case 14: *(int*)dest = value; *(int*)(dest + 4) = value; *(int*)(dest + 8) = value; *(short*)(dest + 12) = (byte)value; return; case 15: *(int*)dest = value; *(int*)(dest + 4) = value; *(int*)(dest + 8) = value; *(short*)(dest + 12) = (short)value; *(dest + 14) = (byte)value; return; } /* * OK size is >= 16 it does not make any sense to do it with primitive types as C# * has not a Int128 type, the Int128 operations will be done in assembler but we can * do yet in the Managed world the two things: * 1. Check of how many blocks of 16 bytes size is composed * 2. If there are reaming bytes (that is size is not a perfect multiple of size) * we do the Fill() using a simple managed for() loop of bytes */ int xBlocksNum; int xByteRemaining; #if NETSTANDARD1_5 xBlocksNum = size / 16; xByteRemaining = size % 16; #else xBlocksNum = Math.DivRem(size, 16, out xByteRemaining); #endif //Global.mDebugger.SendInternal("size " + size + " is composed of " + BlocksNum + " block of 16 bytes with " + ByteRemaining + " remainder"); for (int i = 0; i < xByteRemaining; i++) { *(dest + i) = (byte)value; } /* Let's call the assembler version now to do the 16 byte block copies */ //Cosmos.Core.MemoryOperations.Fill16Blocks(dest + xByteRemaining, value, xBlocksNum); Fill16Blocks(dest + xByteRemaining, value, xBlocksNum); /* * If needed there is yet space of optimization here for example: * - you can check if size is a multiple of 64 and if yes use an yet more faster Fill64Blocks * - or if it is not so try to see if it is a multiple of 32 * at that point probably it would be better to move a lot of the logic to assembler */ } [PlugMethod(Assembler = typeof(MemoryOperationsCopy16BytesAsm))] private static unsafe void Copy16Bytes(byte* dest, byte* src) { throw new NotImplementedException(); } [PlugMethod(Assembler = typeof(MemoryOperationsCopy32BytesAsm))] private static unsafe void Copy32Bytes(byte* dest, byte* src) { throw new NotImplementedException(); } [PlugMethod(Assembler = typeof(MemoryOperationsCopy64BytesAsm))] private static unsafe void Copy64Bytes(byte* dest, byte* src) { throw new NotImplementedException(); } [PlugMethod(Assembler = typeof(MemoryOperationsCopy128BytesAsm))] private static unsafe void Copy128Bytes(byte* dest, byte* src) { throw new NotImplementedException(); } [PlugMethod(Assembler = typeof(MemoryOperationsCopy128BlocksAsm))] private static unsafe void Copy128Blocks(byte* dest, byte* src, int blockNums) { throw new NotImplementedException(); } /* * Tiny memory copy with jump table optimized */ unsafe private static void CopyTiny(byte* dest, byte* src, int size) { /* We do copy in reverse */ byte* dd = dest + size; byte* ss = src + size; switch (size) { case 64: Copy64Bytes(dd - 64, ss - 64); goto case 0; case 0: break; case 65: Copy64Bytes(dd - 65, ss - 65); goto case 1; case 1: dd[-1] = ss[-1]; break; case 66: Copy64Bytes(dd - 66, ss - 66); goto case 2; case 2: *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 67: Copy64Bytes(dd - 67, ss - 67); goto case 3; case 3: *((ushort*)(dd - 3)) = *((ushort*)(ss - 3)); dd[-1] = ss[-1]; break; case 68: Copy64Bytes(dd - 68, ss - 68); goto case 4; case 4: *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 69: Copy64Bytes(dd - 68, ss - 68); goto case 5; case 5: *((uint*)(dd - 5)) = *((uint*)(ss - 5)); dd[-1] = ss[-1]; break; case 70: Copy64Bytes(dd - 70, ss - 70); goto case 6; case 6: *((uint*)(dd - 6)) = *((uint*)(ss - 6)); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 71: Copy64Bytes(dd - 71, ss - 71); goto case 7; case 7: *((uint*)(dd - 7)) = *((uint*)(ss - 7)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 72: Copy64Bytes(dd - 72, ss - 72); goto case 8; case 8: *((ulong*)(dd - 8)) = *((ulong*)(ss - 8)); break; case 73: Copy64Bytes(dd - 73, ss - 73); goto case 9; case 9: *((ulong*)(dd - 9)) = *((ulong*)(ss - 9)); dd[-1] = ss[-1]; break; case 74: Copy64Bytes(dd - 74, ss - 74); goto case 10; case 10: *((ulong*)(dd - 10)) = *((ulong*)(ss - 10)); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 75: Copy64Bytes(dd - 75, ss - 75); goto case 11; case 11: *((ulong*)(dd - 11)) = *((ulong*)(ss - 11)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 76: Copy64Bytes(dd - 76, ss - 76); goto case 12; case 12: *((ulong*)(dd - 12)) = *((ulong*)(ss - 12)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 77: Copy64Bytes(dd - 77, ss - 77); goto case 13; case 13: *((ulong*)(dd - 13)) = *((ulong*)(ss - 13)); *((uint*)(dd - 5)) = *((uint*)(ss - 5)); dd[-1] = ss[-1]; break; case 78: Copy64Bytes(dd - 78, ss - 78); goto case 14; case 14: *((ulong*)(dd - 14)) = *((ulong*)(ss - 14)); *((ulong*)(dd - 8)) = *((ulong*)(ss - 8)); break; case 79: Copy64Bytes(dd - 79, ss - 79); goto case 15; case 15: *((ulong*)(dd - 15)) = *((ulong*)(ss - 15)); *((ulong*)(dd - 8)) = *((ulong*)(ss - 8)); break; case 80: Copy64Bytes(dd - 80, ss - 80); goto case 16; case 16: Copy16Bytes(dd - 16, ss - 16); break; case 81: Copy64Bytes(dd - 81, ss - 81); goto case 17; case 17: Copy16Bytes(dd - 17, ss - 17); dd[-1] = ss[-1]; break; case 82: Copy64Bytes(dd - 82, ss - 82); goto case 18; case 18: Copy16Bytes(dd - 18, ss - 18); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 83: Copy64Bytes(dd - 83, ss - 83); goto case 19; case 19: Copy16Bytes(dd - 19, ss - 19); *((ushort*)(dd - 3)) = *((ushort*)(ss - 3)); dd[-1] = ss[-1]; break; case 84: Copy64Bytes(dd - 84, ss - 84); goto case 20; case 20: Copy16Bytes(dd - 20, ss - 20); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 85: Copy64Bytes(dd - 85, ss - 85); goto case 21; case 21: Copy16Bytes(dd - 21, ss - 21); *((uint*)(dd - 5)) = *((uint*)(ss - 5)); dd[-1] = ss[-1]; break; case 86: Copy64Bytes(dd - 86, ss - 86); goto case 22; case 22: Copy16Bytes(dd - 22, ss - 22); *((uint*)(dd - 6)) = *((uint*)(ss - 6)); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 87: Copy64Bytes(dd - 87, ss - 87); goto case 23; case 23: Copy16Bytes(dd - 23, ss - 23); *((uint*)(dd - 7)) = *((uint*)(ss - 7)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 88: Copy64Bytes(dd - 88, ss - 88); goto case 24; case 24: Copy16Bytes(dd - 24, ss - 24); Copy16Bytes(dd - 16, ss - 16); break; case 89: Copy64Bytes(dd - 89, ss - 89); goto case 25; case 25: Copy16Bytes(dd - 25, ss - 25); Copy16Bytes(dd - 16, ss - 16); break; case 90: Copy64Bytes(dd - 90, ss - 90); goto case 26; case 26: Copy16Bytes(dd - 26, ss - 26); Copy16Bytes(dd - 16, ss - 16); break; case 91: Copy64Bytes(dd - 91, ss - 91); goto case 27; case 27: Copy16Bytes(dd - 27, ss - 27); Copy16Bytes(dd - 16, ss - 16); break; case 92: Copy64Bytes(dd - 92, ss - 92); goto case 28; case 28: Copy16Bytes(dd - 28, ss - 28); Copy16Bytes(dd - 16, ss - 16); break; case 93: Copy64Bytes(dd - 93, ss - 93); goto case 29; case 29: Copy16Bytes(dd - 29, ss - 29); Copy16Bytes(dd - 16, ss - 16); break; case 94: Copy64Bytes(dd - 94, ss - 94); goto case 30; case 30: Copy16Bytes(dd - 30, ss - 30); Copy16Bytes(dd - 16, ss - 16); break; case 95: Copy64Bytes(dd - 95, ss - 95); goto case 31; case 31: Copy16Bytes(dd - 31, ss - 31); Copy16Bytes(dd - 16, ss - 16); break; case 96: Copy64Bytes(dd - 96, ss - 96); goto case 32; case 32: Copy32Bytes(dd - 32, ss - 32); break; case 97: Copy64Bytes(dd - 97, ss - 97); goto case 33; case 33: Copy32Bytes(dd - 33, ss - 33); dd[-1] = ss[-1]; break; case 98: Copy64Bytes(dd - 98, ss - 98); goto case 34; case 34: Copy32Bytes(dd - 34, ss - 34); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 99: Copy64Bytes(dd - 99, ss - 99); goto case 35; case 35: Copy32Bytes(dd - 35, ss - 35); *((ushort*)(dd - 3)) = *((ushort*)(ss - 3)); dd[-1] = ss[-1]; break; case 100: Copy64Bytes(dd - 100, ss - 100); goto case 36; case 36: Copy32Bytes(dd - 36, ss - 36); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 101: Copy64Bytes(dd - 101, ss - 101); goto case 37; case 37: Copy32Bytes(dd - 37, ss - 37); *((uint*)(dd - 5)) = *((uint*)(ss - 5)); dd[-1] = ss[-1]; break; case 102: Copy64Bytes(dd - 102, ss - 102); goto case 38; case 38: Copy32Bytes(dd - 38, ss - 38); *((uint*)(dd - 6)) = *((uint*)(ss - 6)); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 103: Copy64Bytes(dd - 103, ss - 103); goto case 39; case 39: Copy32Bytes(dd - 39, ss - 39); *((uint*)(dd - 7)) = *((uint*)(ss - 7)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 104: Copy64Bytes(dd - 104, ss - 104); goto case 40; case 40: Copy32Bytes(dd - 40, ss - 40); *((ulong*)(dd - 8)) = *((ulong*)(ss - 8)); break; case 105: Copy64Bytes(dd - 105, ss - 105); goto case 41; case 41: Copy32Bytes(dd - 41, ss - 41); *((ulong*)(dd - 9)) = *((ulong*)(ss - 9)); dd[-1] = ss[-1]; break; case 106: Copy64Bytes(dd - 106, ss - 106); goto case 42; case 42: Copy32Bytes(dd - 42, ss - 42); *((ulong*)(dd - 10)) = *((ulong*)(ss - 10)); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 107: Copy64Bytes(dd - 107, ss - 107); goto case 43; case 43: Copy32Bytes(dd - 43, ss - 43); *((ulong*)(dd - 11)) = *((ulong*)(ss - 11)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 108: //Cosmos.Core.MemoryOperations.Copy64Bytes(dd - 108, ss - 108); Copy64Bytes(dd - 108, ss - 108); goto case 44; case 44: Copy32Bytes(dd - 44, ss - 44); *((ulong*)(dd - 12)) = *((ulong*)(ss - 12)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 109: Copy64Bytes(dd - 109, ss - 109); goto case 45; case 45: Copy32Bytes(dd - 45, ss - 45); *((ulong*)(dd - 13)) = *((ulong*)(ss - 13)); *((uint*)(dd - 5)) = *((uint*)(ss - 5)); dd[-1] = ss[-1]; break; case 110: Copy64Bytes(dd - 110, ss - 110); goto case 46; case 46: Copy32Bytes(dd - 46, ss - 46); *((ulong*)(dd - 14)) = *((ulong*)(ss - 14)); *((ulong*)(dd - 8)) = *((ulong*)(ss - 8)); break; case 111: Copy64Bytes(dd - 111, ss - 111); goto case 47; case 47: Copy32Bytes(dd - 47, ss - 47); *((ulong*)(dd - 15)) = *((ulong*)(ss - 15)); *((ulong*)(dd - 8)) = *((ulong*)(ss - 8)); break; case 112: Copy64Bytes(dd - 112, ss - 112); goto case 48; case 48: Copy32Bytes(dd - 48, ss - 48); Copy16Bytes(dd - 16, ss - 16); break; case 113: Copy64Bytes(dd - 113, ss - 113); goto case 49; case 49: Copy32Bytes(dd - 49, ss - 49); Copy16Bytes(dd - 17, ss - 17); dd[-1] = ss[-1]; break; case 114: Copy64Bytes(dd - 114, ss - 114); goto case 50; case 50: Copy32Bytes(dd - 50, ss - 50); Copy16Bytes(dd - 18, ss - 18); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 115: Copy64Bytes(dd - 115, ss - 115); goto case 51; case 51: Copy32Bytes(dd - 51, ss - 51); Copy16Bytes(dd - 19, ss - 19); *((ushort*)(dd - 3)) = *((ushort*)(ss - 3)); dd[-1] = ss[-1]; break; case 116: Copy64Bytes(dd - 116, ss - 116); goto case 52; case 52: Copy32Bytes(dd - 52, ss - 52); Copy16Bytes(dd - 20, ss - 20); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 117: Copy64Bytes(dd - 117, ss - 117); goto case 53; case 53: Copy32Bytes(dd - 53, ss - 53); Copy16Bytes(dd - 21, ss - 21); *((uint*)(dd - 5)) = *((uint*)(ss - 5)); dd[-1] = ss[-1]; break; case 118: Copy64Bytes(dd - 118, ss - 118); goto case 54; case 54: Copy32Bytes(dd - 54, ss - 54); Copy16Bytes(dd - 22, ss - 22); *((uint*)(dd - 6)) = *((uint*)(ss - 6)); *((ushort*)(dd - 2)) = *((ushort*)(ss - 2)); break; case 119: Copy64Bytes(dd - 119, ss - 119); goto case 55; case 55: Copy32Bytes(dd - 55, ss - 55); Copy16Bytes(dd - 23, ss - 23); *((uint*)(dd - 7)) = *((uint*)(ss - 7)); *((uint*)(dd - 4)) = *((uint*)(ss - 4)); break; case 120: Copy64Bytes(dd - 120, ss - 120); goto case 56; case 56: Copy32Bytes(dd - 56, ss - 56); Copy16Bytes(dd - 24, ss - 24); Copy16Bytes(dd - 16, ss - 16); break; case 121: Copy64Bytes(dd - 121, ss - 121); goto case 57; case 57: Copy32Bytes(dd - 57, ss - 57); Copy16Bytes(dd - 25, ss - 25); Copy16Bytes(dd - 16, ss - 16); break; case 122: Copy64Bytes(dd - 122, ss - 122); goto case 58; case 58: Copy32Bytes(dd - 58, ss - 58); Copy16Bytes(dd - 26, ss - 26); Copy16Bytes(dd - 16, ss - 16); break; case 123: Copy64Bytes(dd - 123, ss - 123); goto case 59; case 59: Copy32Bytes(dd - 59, ss - 59); Copy16Bytes(dd - 27, ss - 27); Copy16Bytes(dd - 16, ss - 16); break; case 124: Copy64Bytes(dd - 124, ss - 124); goto case 60; case 60: Copy32Bytes(dd - 60, ss - 60); Copy16Bytes(dd - 28, ss - 28); Copy16Bytes(dd - 16, ss - 16); break; case 125: Copy64Bytes(dd - 125, ss - 125); goto case 61; case 61: Copy32Bytes(dd - 61, ss - 61); Copy16Bytes(dd - 29, ss - 29); Copy16Bytes(dd - 16, ss - 16); break; case 126: Copy64Bytes(dd - 126, ss - 126); goto case 62; case 62: Copy32Bytes(dd - 62, ss - 62); Copy16Bytes(dd - 30, ss - 30); Copy16Bytes(dd - 16, ss - 16); break; case 127: Copy64Bytes(dd - 127, ss - 127); goto case 63; case 63: Copy32Bytes(dd - 63, ss - 63); Copy16Bytes(dd - 31, ss - 31); Copy16Bytes(dd - 16, ss - 16); break; case 128: Copy128Bytes(dd - 128, ss - 128); break; } } unsafe public static void Copy(byte* dest, byte* src, int size) { Global.mDebugger.SendInternal("Copying array of size " + size + " ..."); if (size < 129) { Global.mDebugger.SendInternal("Size less than 129 bytes Calling CopyTiny..."); CopyTiny(dest, src, size); Global.mDebugger.SendInternal("CopyTiny returned"); return; } int xBlocksNum; int xByteRemaining; const int xBlockSize = 128; #if NETSTANDARD1_5 xBlocksNum = size / xBlockSize; xByteRemaining = size % xBlockSize; #else xBlocksNum = Math.DivRem(size, xBlockSize, out xByteRemaining); #endif Global.mDebugger.SendInternal($"size {size} is composed of {xBlocksNum} blocks of {xBlockSize} bytes with {xByteRemaining} remainder"); // TODO call Copy128Blocks() for (int i = 0; i < xByteRemaining; i++) { *(dest + i) = *(src + i); } Global.mDebugger.SendInternal("Calling Copy128Blocks..."); /* Let's call the assembler version now to do the 128 byte block copies */ Copy128Blocks(dest + xByteRemaining, src + xByteRemaining, xBlocksNum); Global.mDebugger.SendInternal("Copy128Blocks returned"); } } }
//----------------------------------------------------------------------- // <copyright file="DrawingAttributes.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using MS.Utility; using System; using System.ComponentModel; using System.Windows; using System.Windows.Media; using System.Collections.Specialized; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using MS.Internal; using MS.Internal.Ink; using MS.Internal.Ink.InkSerializedFormat; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Ink { /// <summary> /// DrawingAttributes is the list of attributes applied to an ink stroke /// when it is drawn. The DrawingAttributes controls stroke color, width, /// transparency, and more. /// </summary> /// <remarks> /// Note that when saving the DrawingAttributes, the V1 AntiAlias attribute /// is always set, and on load the AntiAlias property is ignored. /// </remarks> public class DrawingAttributes : INotifyPropertyChanged { #region Constructors /// <summary> /// Creates a DrawingAttributes with default values /// </summary> public DrawingAttributes() { _extendedProperties = new ExtendedPropertyCollection(); Initialize(); } /// <summary> /// Internal only constructor that initializes a DA with an EPC /// </summary> /// <param name="extendedProperties"></param> internal DrawingAttributes(ExtendedPropertyCollection extendedProperties) { System.Diagnostics.Debug.Assert(extendedProperties != null); _extendedProperties = extendedProperties; Initialize(); } /// <summary> /// Common constructor call, also called by Clone /// </summary> private void Initialize() { System.Diagnostics.Debug.Assert(_extendedProperties != null); _extendedProperties.Changed += new ExtendedPropertiesChangedEventHandler(this.ExtendedPropertiesChanged_EventForwarder); } #endregion Constructors #region Public Properties /// <summary> /// The color of the Stroke /// </summary> public Color Color { get { //prevent boxing / unboxing if possible if (!_extendedProperties.Contains(KnownIds.Color)) { Debug.Assert(Colors.Black == (Color)GetDefaultDrawingAttributeValue(KnownIds.Color)); return Colors.Black; } return (Color)GetExtendedPropertyBackedProperty(KnownIds.Color); } set { //no need to raise change events, they will bubble up from the EPC //underneath us // Validation of value is done in EPC SetExtendedPropertyBackedProperty(KnownIds.Color, value); } } /// <summary> /// The StylusTip used to draw the stroke /// </summary> public StylusTip StylusTip { get { //prevent boxing / unboxing if possible if (!_extendedProperties.Contains(KnownIds.StylusTip)) { Debug.Assert(StylusTip.Ellipse == (StylusTip)GetDefaultDrawingAttributeValue(KnownIds.StylusTip)); return StylusTip.Ellipse; } else { //if we ever add to StylusTip enumeration, we need to just return GetExtendedPropertyBackedProperty Debug.Assert(StylusTip.Rectangle == (StylusTip)GetExtendedPropertyBackedProperty(KnownIds.StylusTip)); return StylusTip.Rectangle; } } set { //no need to raise change events, they will bubble up from the EPC //underneath us // Validation of value is done in EPC SetExtendedPropertyBackedProperty(KnownIds.StylusTip, value); } } /// <summary> /// The StylusTip used to draw the stroke /// </summary> public Matrix StylusTipTransform { get { //prevent boxing / unboxing if possible if (!_extendedProperties.Contains(KnownIds.StylusTipTransform)) { Debug.Assert(Matrix.Identity == (Matrix)GetDefaultDrawingAttributeValue(KnownIds.StylusTipTransform)); return Matrix.Identity; } return (Matrix)GetExtendedPropertyBackedProperty(KnownIds.StylusTipTransform); } set { Matrix m = (Matrix) value; if (m.OffsetX != 0 || m.OffsetY != 0) { throw new ArgumentException(SR.Get(SRID.InvalidSttValue), "value"); } //no need to raise change events, they will bubble up from the EPC //underneath us // Validation of value is done in EPC SetExtendedPropertyBackedProperty(KnownIds.StylusTipTransform, value); } } /// <summary> /// The height of the StylusTip /// </summary> public double Height { get { //prevent boxing / unboxing if possible if (!_extendedProperties.Contains(KnownIds.StylusHeight)) { Debug.Assert(DrawingAttributes.DefaultHeight == (double)GetDefaultDrawingAttributeValue(KnownIds.StylusHeight)); return DrawingAttributes.DefaultHeight; } return (double)GetExtendedPropertyBackedProperty(KnownIds.StylusHeight); } set { if (double.IsNaN(value) || value < MinHeight || value > MaxHeight) { throw new ArgumentOutOfRangeException("Height", SR.Get(SRID.InvalidDrawingAttributesHeight)); } //no need to raise change events, they will bubble up from the EPC //underneath us SetExtendedPropertyBackedProperty(KnownIds.StylusHeight, value); } } /// <summary> /// The width of the StylusTip /// </summary> public double Width { get { //prevent boxing / unboxing if possible if (!_extendedProperties.Contains(KnownIds.StylusWidth)) { Debug.Assert(DrawingAttributes.DefaultWidth == (double)GetDefaultDrawingAttributeValue(KnownIds.StylusWidth)); return DrawingAttributes.DefaultWidth; } return (double)GetExtendedPropertyBackedProperty(KnownIds.StylusWidth); } set { if (double.IsNaN(value) || value < MinWidth || value > MaxWidth) { throw new ArgumentOutOfRangeException("Width", SR.Get(SRID.InvalidDrawingAttributesWidth)); } //no need to raise change events, they will bubble up from the EPC //underneath us SetExtendedPropertyBackedProperty(KnownIds.StylusWidth, value); } } /// <summary> /// When true, ink will be rendered as a series of curves instead of as /// lines between Stylus sample points. This is useful for smoothing the ink, especially /// when the person writing the ink has jerky or shaky writing. /// This value is TRUE by default in the Avalon implementation /// </summary> public bool FitToCurve { get { DrawingFlags flags = (DrawingFlags)GetExtendedPropertyBackedProperty(KnownIds.DrawingFlags); return (0 != (flags & DrawingFlags.FitToCurve)); } set { //no need to raise change events, they will bubble up from the EPC //underneath us DrawingFlags flags = (DrawingFlags)GetExtendedPropertyBackedProperty(KnownIds.DrawingFlags); if (value) { //turn on the bit flags |= DrawingFlags.FitToCurve; } else { //turn off the bit flags &= ~DrawingFlags.FitToCurve; } SetExtendedPropertyBackedProperty(KnownIds.DrawingFlags, flags); } } /// <summary> /// When true, ink will be rendered with any available pressure information /// taken into account /// </summary> public bool IgnorePressure { get { DrawingFlags flags = (DrawingFlags)GetExtendedPropertyBackedProperty(KnownIds.DrawingFlags); return (0 != (flags & DrawingFlags.IgnorePressure)); } set { //no need to raise change events, they will bubble up from the EPC //underneath us DrawingFlags flags = (DrawingFlags)GetExtendedPropertyBackedProperty(KnownIds.DrawingFlags); if (value) { //turn on the bit flags |= DrawingFlags.IgnorePressure; } else { //turn off the bit flags &= ~DrawingFlags.IgnorePressure; } SetExtendedPropertyBackedProperty(KnownIds.DrawingFlags, flags); } } /// <summary> /// Determines if the stroke should be treated as a highlighter /// </summary> public bool IsHighlighter { get { //prevent boxing / unboxing if possible if (!_extendedProperties.Contains(KnownIds.IsHighlighter)) { Debug.Assert(false == (bool)GetDefaultDrawingAttributeValue(KnownIds.IsHighlighter)); return false; } else { Debug.Assert(true == (bool)GetExtendedPropertyBackedProperty(KnownIds.IsHighlighter)); return true; } } set { //no need to raise change events, they will bubble up from the EPC //underneath us SetExtendedPropertyBackedProperty(KnownIds.IsHighlighter, value); // // set RasterOp for V1 interop // if (value) { _v1RasterOperation = DrawingAttributeSerializer.RasterOperationMaskPen; } else { _v1RasterOperation = DrawingAttributeSerializer.RasterOperationDefaultV1; } } } #region Extended Properties /// <summary> /// Allows addition of objects to the EPC /// </summary> /// <param name="propertyDataId"></param> /// <param name="propertyData"></param> public void AddPropertyData(Guid propertyDataId, object propertyData) { DrawingAttributes.ValidateStylusTipTransform(propertyDataId, propertyData); SetExtendedPropertyBackedProperty(propertyDataId, propertyData); } /// <summary> /// Allows removal of objects from the EPC /// </summary> /// <param name="propertyDataId"></param> public void RemovePropertyData(Guid propertyDataId) { this.ExtendedProperties.Remove(propertyDataId); } /// <summary> /// Allows retrieval of objects from the EPC /// </summary> /// <param name="propertyDataId"></param> public object GetPropertyData(Guid propertyDataId) { return GetExtendedPropertyBackedProperty(propertyDataId); } /// <summary> /// Allows retrieval of a Array of guids that are contained in the EPC /// </summary> public Guid[] GetPropertyDataIds() { return this.ExtendedProperties.GetGuidArray(); } /// <summary> /// Allows check of containment of objects to the EPC /// </summary> /// <param name="propertyDataId"></param> public bool ContainsPropertyData(Guid propertyDataId) { return this.ExtendedProperties.Contains(propertyDataId); } /// <summary> /// ExtendedProperties /// </summary> internal ExtendedPropertyCollection ExtendedProperties { get { return _extendedProperties; } } /// <summary> /// Returns a copy of the EPC /// </summary> internal ExtendedPropertyCollection CopyPropertyData() { return this.ExtendedProperties.Clone(); } #endregion #endregion #region Internal Properties /// <summary> /// StylusShape /// </summary> internal StylusShape StylusShape { get { StylusShape s; if (this.StylusTip == StylusTip.Rectangle) { s = new RectangleStylusShape(this.Width, this.Height); } else { s = new EllipseStylusShape(this.Width, this.Height); } s.Transform = StylusTipTransform; return s; } } /// <summary> /// Sets the Fitting error for this drawing attributes /// </summary> internal int FittingError { get { if (!_extendedProperties.Contains(KnownIds.CurveFittingError)) { return 0; } else { return (int)_extendedProperties[KnownIds.CurveFittingError]; } } set { _extendedProperties[KnownIds.CurveFittingError] = value; } } /// <summary> /// Sets the Fitting error for this drawing attributes /// </summary> internal DrawingFlags DrawingFlags { get { return (DrawingFlags)GetExtendedPropertyBackedProperty(KnownIds.DrawingFlags); } set { //no need to raise change events, they will bubble up from the EPC //underneath us SetExtendedPropertyBackedProperty(KnownIds.DrawingFlags, value); } } /// <summary> /// we need to preserve this for round tripping /// </summary> /// <value></value> internal uint RasterOperation { get { return _v1RasterOperation; } set { _v1RasterOperation = value; } } /// <summary> /// When we load ISF from V1 if width is set and height is not /// and PenTip is Circle, we need to set height to the same as width /// or else we'll render different as an Ellipse. We use this flag to /// preserve state for round tripping. /// </summary> internal bool HeightChangedForCompatabity { get { return _heightChangedForCompatabity; } set { _heightChangedForCompatabity = value; } } #endregion //------------------------------------------------------ // // INotifyPropertyChanged Interface // //------------------------------------------------------ #region INotifyPropertyChanged Interface /// <summary> /// INotifyPropertyChanged.PropertyChanged event /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChanged += value; } remove { _propertyChanged -= value; } } #endregion INotifyPropertyChanged Interface #region Methods #region Object overrides // NTRAID#T2-23041-2003/10/01-[....]: SPECISSUE: What should ExtendedPropertyCollection.GetHashCode return? /// <summary>Retrieve an integer-based value for using ExtendedPropertyCollection /// objects in a hash table as keys</summary> public override int GetHashCode() { return base.GetHashCode(); } /// <summary>Overload of the Equals method which determines if two DrawingAttributes /// objects contain the same drawing attributes</summary> public override bool Equals(object o) { if (o == null || o.GetType() != this.GetType()) { return false; } //use as and check for null instead of casting to DA to make presharp happy DrawingAttributes that = o as DrawingAttributes; if (that == null) { return false; } return (this._extendedProperties == that._extendedProperties); } /// <summary>Overload of the equality operator which determines /// if two DrawingAttributes are equal</summary> public static bool operator ==(DrawingAttributes first, DrawingAttributes second) { // compare the GC ptrs for the obvious reference equality if (((object)first == null && (object)second == null) || ((object)first == (object)second)) { return true; } // otherwise, if one of the ptrs are null, but not the other then return false else if ((object)first == null || (object)second == null) { return false; } // finally use the full `blown value-style comparison against the collection contents return first.Equals(second); } /// <summary>Overload of the not equals operator to determine if two /// DrawingAttributes are different</summary> public static bool operator !=(DrawingAttributes first, DrawingAttributes second) { return !(first == second); } #endregion /// <summary> /// Copies the DrawingAttributes /// </summary> /// <returns>Deep copy of the DrawingAttributes</returns> /// <remarks></remarks> public virtual DrawingAttributes Clone() { // // use MemberwiseClone, which will instance the most derived type // We use this instead of Activator.CreateInstance because it does not // require ReflectionPermission. One thing to note, all references // are shared, including event delegates, so we need to set those to null // DrawingAttributes clone = (DrawingAttributes)this.MemberwiseClone(); // // null the delegates in the cloned DrawingAttributes // clone.AttributeChanged = null; clone.PropertyDataChanged = null; //make a copy of the epc , set up listeners clone._extendedProperties = _extendedProperties.Clone(); clone.Initialize(); //don't need to clone these, it is a value type //and is copied by MemberwiseClone //_v1RasterOperation //_heightChangedForCompatabity return clone; } #endregion #region Events /// <summary> /// Event fired whenever a DrawingAttribute is modified /// </summary> public event PropertyDataChangedEventHandler AttributeChanged; /// <summary> /// Method called when a change occurs to any DrawingAttribute /// </summary> /// <param name="e">The change information for the DrawingAttribute that was modified</param> protected virtual void OnAttributeChanged(PropertyDataChangedEventArgs e) { if (null == e) { throw new ArgumentNullException("e", SR.Get(SRID.EventArgIsNull)); } try { PrivateNotifyPropertyChanged(e); } finally { if ( this.AttributeChanged != null ) { this.AttributeChanged(this, e); } } } /// <summary> /// Event fired whenever a DrawingAttribute is modified /// </summary> public event PropertyDataChangedEventHandler PropertyDataChanged; /// <summary> /// Method called when a change occurs to any PropertyData /// </summary> /// <param name="e">The change information for the PropertyData that was modified</param> protected virtual void OnPropertyDataChanged(PropertyDataChangedEventArgs e) { if (null == e) { throw new ArgumentNullException("e", SR.Get(SRID.EventArgIsNull)); } if (this.PropertyDataChanged != null) { this.PropertyDataChanged(this, e); } } #endregion #region Protected Methods /// <summary> /// Method called when a property change occurs to DrawingAttribute /// </summary> /// <param name="e">The EventArgs specifying the name of the changed property.</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { if ( _propertyChanged != null ) { _propertyChanged(this, e); } } #endregion Protected Methods #region Private Methods /// <summary> /// Simple helper method used to determine if a guid /// from an ExtendedProperty is used as the backing store /// of a DrawingAttribute /// </summary> /// <param name="id"></param> /// <returns></returns> internal static object GetDefaultDrawingAttributeValue(Guid id) { if (KnownIds.Color == id) { return Colors.Black; } if (KnownIds.StylusWidth == id) { return DrawingAttributes.DefaultWidth; } if (KnownIds.StylusTip == id) { return StylusTip.Ellipse; } if (KnownIds.DrawingFlags == id) { //note that in this implementation, FitToCurve is false by default return DrawingFlags.AntiAliased; } if (KnownIds.StylusHeight == id) { return DrawingAttributes.DefaultHeight; } if (KnownIds.StylusTipTransform == id) { return Matrix.Identity; } if (KnownIds.IsHighlighter == id) { return false; } // this is a valid case // as this helper method is used not only to // get the default value, but also to see if // the Guid is a drawing attribute value return null; } internal static void ValidateStylusTipTransform(Guid propertyDataId, object propertyData) { // NTRAID#WINOS-1136720-2005/06/22-XIAOTU: // Calling AddPropertyData(KnownIds.StylusTipTransform, "d") does not throw an ArgumentException. // ExtendedPropertySerializer.Validate take a string as a valid type since StylusTipTransform // gets serialized as a String, but at runtime is a Matrix if (propertyData == null) { throw new ArgumentNullException("propertyData"); } else if (propertyDataId == KnownIds.StylusTipTransform) { // StylusTipTransform gets serialized as a String, but at runtime is a Matrix Type t = propertyData.GetType(); if (t == typeof(String)) { throw new ArgumentException(SR.Get(SRID.InvalidValueType, typeof(Matrix)), "propertyData"); } } } /// <summary> /// Simple helper method used to determine if a guid /// needs to be removed from the ExtendedPropertyCollection in ISF /// before serializing /// </summary> /// <param name="id"></param> /// <returns></returns> internal static bool RemoveIdFromExtendedProperties(Guid id) { if (KnownIds.Color == id || KnownIds.Transparency == id || KnownIds.StylusWidth == id || KnownIds.DrawingFlags == id || KnownIds.StylusHeight == id || KnownIds.CurveFittingError == id ) { return true; } return false; } /// <summary> /// Returns true if two DrawingAttributes lead to the same PathGeometry. /// </summary> internal static bool GeometricallyEqual(DrawingAttributes left, DrawingAttributes right) { // Optimization case: // must correspond to the same path geometry if they refer to the same instance. if (Object.ReferenceEquals(left, right)) { return true; } if (left.StylusTip == right.StylusTip && left.StylusTipTransform == right.StylusTipTransform && DoubleUtil.AreClose(left.Width, right.Width) && DoubleUtil.AreClose(left.Height, right.Height) && left.DrawingFlags == right.DrawingFlags /*contains IgnorePressure / FitToCurve*/) { return true; } return false; } /// <summary> /// Returns true if the guid passed in has impact on geometry of the stroke /// </summary> internal static bool IsGeometricalDaGuid(Guid guid) { // Assert it is a DA guid System.Diagnostics.Debug.Assert(null != DrawingAttributes.GetDefaultDrawingAttributeValue(guid)); if (guid == KnownIds.StylusHeight || guid == KnownIds.StylusWidth || guid == KnownIds.StylusTipTransform || guid == KnownIds.StylusTip || guid == KnownIds.DrawingFlags) { return true; } return false; } /// <summary> /// Whenever the base class fires the generic ExtendedPropertiesChanged /// event, we need to fire the DrawingAttributesChanged event also. /// </summary> /// <param name="sender">Should be 'this' object</param> /// <param name="args">The custom attributes that changed</param> private void ExtendedPropertiesChanged_EventForwarder(object sender, ExtendedPropertiesChangedEventArgs args) { System.Diagnostics.Debug.Assert(sender != null); System.Diagnostics.Debug.Assert(args != null); //see if the EP that changed is a drawingattribute if (args.NewProperty == null) { //a property was removed, see if it is a drawing attribute property object defaultValueIfDrawingAttribute = DrawingAttributes.GetDefaultDrawingAttributeValue(args.OldProperty.Id); if (defaultValueIfDrawingAttribute != null) { ExtendedProperty newProperty = new ExtendedProperty( args.OldProperty.Id, defaultValueIfDrawingAttribute); //this is a da guid PropertyDataChangedEventArgs dargs = new PropertyDataChangedEventArgs( args.OldProperty.Id, newProperty.Value, //the property args.OldProperty.Value);//previous value this.OnAttributeChanged(dargs); } else { PropertyDataChangedEventArgs dargs = new PropertyDataChangedEventArgs( args.OldProperty.Id, null, //the property args.OldProperty.Value);//previous value this.OnPropertyDataChanged(dargs); } } else if (args.OldProperty == null) { //a property was added, see if it is a drawing attribute property object defaultValueIfDrawingAttribute = DrawingAttributes.GetDefaultDrawingAttributeValue(args.NewProperty.Id); if (defaultValueIfDrawingAttribute != null) { if (!defaultValueIfDrawingAttribute.Equals(args.NewProperty.Value)) { //this is a da guid PropertyDataChangedEventArgs dargs = new PropertyDataChangedEventArgs( args.NewProperty.Id, args.NewProperty.Value, //the property defaultValueIfDrawingAttribute); //previous value this.OnAttributeChanged(dargs); } } else { PropertyDataChangedEventArgs dargs = new PropertyDataChangedEventArgs(args.NewProperty.Id, args.NewProperty.Value, //the property null); //previous value this.OnPropertyDataChanged(dargs); } } else { //something was modified, see if it is a drawing attribute property object defaultValueIfDrawingAttribute = DrawingAttributes.GetDefaultDrawingAttributeValue(args.NewProperty.Id); if (defaultValueIfDrawingAttribute != null) { // // we only raise DA changed when the value actually changes // if (!args.NewProperty.Value.Equals(args.OldProperty.Value)) { //this is a da guid PropertyDataChangedEventArgs dargs = new PropertyDataChangedEventArgs( args.NewProperty.Id, args.NewProperty.Value, //the da args.OldProperty.Value);//old value this.OnAttributeChanged(dargs); } } else { if (!args.NewProperty.Value.Equals(args.OldProperty.Value)) { PropertyDataChangedEventArgs dargs = new PropertyDataChangedEventArgs( args.NewProperty.Id, args.NewProperty.Value, args.OldProperty.Value);//old value this.OnPropertyDataChanged(dargs); } } } } /// <summary> /// All DrawingAttributes are backed by an ExtendedProperty /// this is a simple helper to set a property /// </summary> /// <param name="id">id</param> /// <param name="value">value</param> private void SetExtendedPropertyBackedProperty(Guid id, object value) { if (_extendedProperties.Contains(id)) { // // check to see if we're setting the property back // to a default value. If we are we should remove it from // the EPC // object defaultValue = DrawingAttributes.GetDefaultDrawingAttributeValue(id); if (defaultValue != null) { if (defaultValue.Equals(value)) { _extendedProperties.Remove(id); return; } } // // we're setting a non-default value on a EP that // already exists, check for equality before we do // so we don't raise unnecessary EPC changed events // object o = GetExtendedPropertyBackedProperty(id); if (!o.Equals(value)) { _extendedProperties[id] = value; } } else { // // make sure we're not setting a default value of the guid // there is no need to do this // object defaultValue = DrawingAttributes.GetDefaultDrawingAttributeValue(id); if (defaultValue == null || !defaultValue.Equals(value)) { _extendedProperties[id] = value; } } } /// <summary> /// All DrawingAttributes are backed by an ExtendedProperty /// this is a simple helper to set a property /// </summary> /// <param name="id">id</param> /// <returns></returns> private object GetExtendedPropertyBackedProperty(Guid id) { if (!_extendedProperties.Contains(id)) { if (null != DrawingAttributes.GetDefaultDrawingAttributeValue(id)) { return DrawingAttributes.GetDefaultDrawingAttributeValue(id); } throw new ArgumentException(SR.Get(SRID.EPGuidNotFound), "id"); } else { return _extendedProperties[id]; } } /// <summary> /// A help method which fires INotifyPropertyChanged.PropertyChanged event /// </summary> /// <param name="e"></param> private void PrivateNotifyPropertyChanged(PropertyDataChangedEventArgs e) { if ( e.PropertyGuid == KnownIds.Color) { OnPropertyChanged("Color"); } else if ( e.PropertyGuid == KnownIds.StylusTip) { OnPropertyChanged("StylusTip"); } else if ( e.PropertyGuid == KnownIds.StylusTipTransform) { OnPropertyChanged("StylusTipTransform"); } else if ( e.PropertyGuid == KnownIds.StylusHeight) { OnPropertyChanged("Height"); } else if ( e.PropertyGuid == KnownIds.StylusWidth) { OnPropertyChanged("Width"); } else if ( e.PropertyGuid == KnownIds.IsHighlighter) { OnPropertyChanged("IsHighlighter"); } else if ( e.PropertyGuid == KnownIds.DrawingFlags ) { DrawingFlags changedBits = ( ( (DrawingFlags)e.PreviousValue ) ^ ( (DrawingFlags)e.NewValue ) ); // NOTICE-2006/01/20-WAYNEZEN, // If someone changes FitToCurve and IgnorePressure simultaneously via AddPropertyData/RemovePropertyData, // we will fire both OnPropertyChangeds in advance the order of the values. if ( (changedBits & DrawingFlags.FitToCurve) != 0 ) { OnPropertyChanged("FitToCurve"); } if ( (changedBits & DrawingFlags.IgnorePressure) != 0 ) { OnPropertyChanged("IgnorePressure"); } } } private void OnPropertyChanged(string propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } #endregion #region Private Fields // The private PropertyChanged event private PropertyChangedEventHandler _propertyChanged; private ExtendedPropertyCollection _extendedProperties; private uint _v1RasterOperation = DrawingAttributeSerializer.RasterOperationDefaultV1; private bool _heightChangedForCompatabity = false; /// <summary> /// Statics /// </summary> internal static readonly float StylusPrecision = 1000.0f; internal static readonly double DefaultWidth = 2.0031496062992127; internal static readonly double DefaultHeight = 2.0031496062992127; #endregion /// <summary> /// Mininum acceptable stylus tip height, corresponds to 0.001 in V1 /// </summary> /// <remarks>corresponds to 0.001 in V1 (0.001 / (2540/96))</remarks> public static readonly double MinHeight = 0.00003779527559055120; /// <summary> /// Minimum acceptable stylus tip width /// </summary> /// <remarks>corresponds to 0.001 in V1 (0.001 / (2540/96))</remarks> public static readonly double MinWidth = 0.00003779527559055120; /// <summary> /// Maximum acceptable stylus tip height. /// </summary> /// <remarks>corresponds to 4294967 in V1 (4294967 / (2540/96))</remarks> public static readonly double MaxHeight = 162329.4614173230; /// <summary> /// Maximum acceptable stylus tip width. /// </summary> /// <remarks>corresponds to 4294967 in V1 (4294967 / (2540/96))</remarks> public static readonly double MaxWidth = 162329.4614173230; } }
using System; using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Cli.CommandParsing; using Microsoft.TemplateEngine.Cli.UnitTests.CliMocks; using Microsoft.TemplateEngine.Edge.Settings; using Microsoft.TemplateEngine.Edge.Template; using Xunit; using static Microsoft.TemplateEngine.Cli.TemplateListResolutionResult; namespace Microsoft.TemplateEngine.Cli.UnitTests.TemplateResolutionTests { public class SingularInvokableMatchTests { [Fact(DisplayName = nameof(MultipleTemplatesInGroupHavingSingleStartsWithOnSameParamIsAmbiguous))] public void MultipleTemplatesInGroupHavingSingleStartsWithOnSameParamIsAmbiguous() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_1"}) } }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_2", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_2"}) } }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", "value_" } } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(2, unambiguousGroup.Count); Assert.Equal(2, matchResult.GetBestTemplateMatchList().Count); Assert.False(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Equal(SingularInvokableMatchCheckStatus.AmbiguousChoice, resultStatus); Assert.Null(singularInvokableMatch); } [Fact(DisplayName = nameof(MultipleTemplatesInGroupParamPartiaMatch_TheOneHavingSingleStartsWithIsTheSingularInvokableMatch))] public void MultipleTemplatesInGroupParamPartiaMatch_TheOneHavingSingleStartsWithIsTheSingularInvokableMatch() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_1"}) } }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_2", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_2", "value_3"}) } }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", "value_" } } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(2, unambiguousGroup.Count); Assert.Equal(2, matchResult.GetBestTemplateMatchList().Count); Assert.True(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Equal(SingularInvokableMatchCheckStatus.SingleMatch, resultStatus); Assert.Equal("foo.test_1", singularInvokableMatch.Info.Identity); } [Fact(DisplayName = nameof(MultipleTemplatesInGroupHavingAmbiguousParamMatchOnSameParamIsAmbiguous))] public void MultipleTemplatesInGroupHavingAmbiguousParamMatchOnSameParamIsAmbiguous() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_1", "value_2"}) } }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_2", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_3", "value_4"}) } }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", "value_" } } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(2, unambiguousGroup.Count); Assert.Equal(2, matchResult.GetBestTemplateMatchList().Count); Assert.False(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Equal(SingularInvokableMatchCheckStatus.NoMatch, resultStatus); Assert.Null(singularInvokableMatch); } [Fact(DisplayName = nameof(MultipleTemplatesInGroupHavingSingularStartMatchesOnDifferentParams_HighPrecedenceIsChosen))] public void MultipleTemplatesInGroupHavingSingularStartMatchesOnDifferentParams_HighPrecedenceIsChosen() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_1", "other_value"}) }, // single starts with { "OtherChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "foo_" }) } // exact }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_2", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "value_" }) }, // exact { "OtherChoice", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "foo_", "bar_1"}) } // single starts with }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "MyChoice", "value_" }, { "OtherChoice", "foo_" } } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(2, unambiguousGroup.Count); Assert.Equal(2, matchResult.GetBestTemplateMatchList().Count); Assert.True(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Equal(SingularInvokableMatchCheckStatus.SingleMatch, resultStatus); Assert.Equal("foo.test_2", singularInvokableMatch.Info.Identity); } [Fact(DisplayName = nameof(GivenOneInvokableTemplateWithNonDefaultLanguage_ItIsChosen))] public void GivenOneInvokableTemplateWithNonDefaultLanguage_ItIsChosen() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "F#" }) }, }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(1, unambiguousGroup.Count); Assert.Equal(1, matchResult.GetBestTemplateMatchList().Count); Assert.True(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Equal(SingularInvokableMatchCheckStatus.SingleMatch, resultStatus); Assert.Equal("foo.test_1", singularInvokableMatch.Info.Identity); } [Fact(DisplayName = nameof(GivenTwoInvokableTemplatesNonDefaultLanguage_HighPrecedenceIsChosen))] public void GivenTwoInvokableTemplatesNonDefaultLanguage_HighPrecedenceIsChosen() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1.FSharp", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "F#" }) }, }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1.VB", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "VB" }) }, }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(2, unambiguousGroup.Count); Assert.Equal(2, matchResult.GetBestTemplateMatchList().Count); Assert.True(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Equal(SingularInvokableMatchCheckStatus.SingleMatch, resultStatus); Assert.Equal("foo.test_1.VB", singularInvokableMatch.Info.Identity); } [Fact(DisplayName = nameof(GivenMultipleHighestPrecedenceTemplates_ResultIsAmbiguous))] public void GivenMultipleHighestPrecedenceTemplates_ResultIsAmbiguous() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1.FSharp", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "F#" }) }, }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test_1.VB", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", ResolutionTestHelper.CreateTestCacheTag(new List<string>() { "VB" }) }, }, CacheParameters = new Dictionary<string, ICacheParameter>(), }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.GetTemplateResolutionResult(templatesToSearch, hostSpecificDataLoader, userInputs, null); // make sure there's an unambiguous group, otherwise the singular match check is meaningless Assert.True(matchResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousGroup)); Assert.Equal(2, unambiguousGroup.Count); Assert.Equal(2, matchResult.GetBestTemplateMatchList().Count); Assert.False(matchResult.TryGetSingularInvokableMatch(out ITemplateMatchInfo singularInvokableMatch, out SingularInvokableMatchCheckStatus resultStatus)); Assert.Null(singularInvokableMatch); Assert.Equal(SingularInvokableMatchCheckStatus.AmbiguousPrecedence, resultStatus); } } }
namespace NPascalCoin.Crypto { /* This class is property of the BouncyCastle Cryptographic Library Project and was borrowed from <a href="https://github.com/bcgit/bc-csharp/blob/master/crypto/src/crypto/util/Pack.cs">https://github.com/bcgit/bc-csharp/blob/master/crypto/src/crypto/util/Pack.cs</a> for internal use. */ internal sealed class Pack { private Pack() { } internal static void UInt16_To_BE(ushort n, byte[] bs) { bs[0] = (byte) (n >> 8); bs[1] = (byte) (n); } internal static void UInt16_To_BE(ushort n, byte[] bs, int off) { bs[off] = (byte) (n >> 8); bs[off + 1] = (byte) (n); } internal static ushort BE_To_UInt16(byte[] bs) { uint n = (uint) bs[0] << 8 | (uint) bs[1]; return (ushort) n; } internal static ushort BE_To_UInt16(byte[] bs, int off) { uint n = (uint) bs[off] << 8 | (uint) bs[off + 1]; return (ushort) n; } internal static byte[] UInt32_To_BE(uint n) { byte[] bs = new byte[4]; UInt32_To_BE(n, bs, 0); return bs; } internal static void UInt32_To_BE(uint n, byte[] bs) { bs[0] = (byte) (n >> 24); bs[1] = (byte) (n >> 16); bs[2] = (byte) (n >> 8); bs[3] = (byte) (n); } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { bs[off] = (byte) (n >> 24); bs[off + 1] = (byte) (n >> 16); bs[off + 2] = (byte) (n >> 8); bs[off + 3] = (byte) (n); } internal static byte[] UInt32_To_BE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_BE(ns, bs, 0); return bs; } internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_BE(ns[i], bs, off); off += 4; } } internal static uint BE_To_UInt32(byte[] bs) { return (uint) bs[0] << 24 | (uint) bs[1] << 16 | (uint) bs[2] << 8 | (uint) bs[3]; } internal static uint BE_To_UInt32(byte[] bs, int off) { return (uint) bs[off] << 24 | (uint) bs[off + 1] << 16 | (uint) bs[off + 2] << 8 | (uint) bs[off + 3]; } internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt32(bs, off); off += 4; } } internal static byte[] UInt64_To_BE(ulong n) { byte[] bs = new byte[8]; UInt64_To_BE(n, bs, 0); return bs; } internal static void UInt64_To_BE(ulong n, byte[] bs) { UInt32_To_BE((uint) (n >> 32), bs); UInt32_To_BE((uint) (n), bs, 4); } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { UInt32_To_BE((uint) (n >> 32), bs, off); UInt32_To_BE((uint) (n), bs, off + 4); } internal static byte[] UInt64_To_BE(ulong[] ns) { byte[] bs = new byte[8 * ns.Length]; UInt64_To_BE(ns, bs, 0); return bs; } internal static void UInt64_To_BE(ulong[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt64_To_BE(ns[i], bs, off); off += 8; } } internal static ulong BE_To_UInt64(byte[] bs) { uint hi = BE_To_UInt32(bs); uint lo = BE_To_UInt32(bs, 4); return ((ulong) hi << 32) | (ulong) lo; } internal static ulong BE_To_UInt64(byte[] bs, int off) { uint hi = BE_To_UInt32(bs, off); uint lo = BE_To_UInt32(bs, off + 4); return ((ulong) hi << 32) | (ulong) lo; } internal static void BE_To_UInt64(byte[] bs, int off, ulong[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt64(bs, off); off += 8; } } internal static void UInt16_To_LE(ushort n, byte[] bs) { bs[0] = (byte) (n); bs[1] = (byte) (n >> 8); } internal static void UInt16_To_LE(ushort n, byte[] bs, int off) { bs[off] = (byte) (n); bs[off + 1] = (byte) (n >> 8); } internal static ushort LE_To_UInt16(byte[] bs) { uint n = (uint) bs[0] | (uint) bs[1] << 8; return (ushort) n; } internal static ushort LE_To_UInt16(byte[] bs, int off) { uint n = (uint) bs[off] | (uint) bs[off + 1] << 8; return (ushort) n; } internal static byte[] UInt32_To_LE(uint n) { byte[] bs = new byte[4]; UInt32_To_LE(n, bs, 0); return bs; } internal static void UInt32_To_LE(uint n, byte[] bs) { bs[0] = (byte) (n); bs[1] = (byte) (n >> 8); bs[2] = (byte) (n >> 16); bs[3] = (byte) (n >> 24); } internal static void UInt32_To_LE(uint n, byte[] bs, int off) { bs[off] = (byte) (n); bs[off + 1] = (byte) (n >> 8); bs[off + 2] = (byte) (n >> 16); bs[off + 3] = (byte) (n >> 24); } internal static byte[] UInt32_To_LE(uint[] ns) { byte[] bs = new byte[4 * ns.Length]; UInt32_To_LE(ns, bs, 0); return bs; } internal static void UInt32_To_LE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_LE(ns[i], bs, off); off += 4; } } internal static uint LE_To_UInt32(byte[] bs) { return (uint) bs[0] | (uint) bs[1] << 8 | (uint) bs[2] << 16 | (uint) bs[3] << 24; } internal static uint LE_To_UInt32(byte[] bs, int off) { return (uint) bs[off] | (uint) bs[off + 1] << 8 | (uint) bs[off + 2] << 16 | (uint) bs[off + 3] << 24; } internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } } internal static void LE_To_UInt32(byte[] bs, int bOff, uint[] ns, int nOff, int count) { for (int i = 0; i < count; ++i) { ns[nOff + i] = LE_To_UInt32(bs, bOff); bOff += 4; } } internal static uint[] LE_To_UInt32(byte[] bs, int off, int count) { uint[] ns = new uint[count]; for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } return ns; } internal static byte[] UInt64_To_LE(ulong n) { byte[] bs = new byte[8]; UInt64_To_LE(n, bs, 0); return bs; } internal static void UInt64_To_LE(ulong n, byte[] bs) { UInt32_To_LE((uint) (n), bs); UInt32_To_LE((uint) (n >> 32), bs, 4); } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { UInt32_To_LE((uint) (n), bs, off); UInt32_To_LE((uint) (n >> 32), bs, off + 4); } internal static byte[] UInt64_To_LE(ulong[] ns) { byte[] bs = new byte[8 * ns.Length]; UInt64_To_LE(ns, bs, 0); return bs; } internal static void UInt64_To_LE(ulong[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt64_To_LE(ns[i], bs, off); off += 8; } } internal static void UInt64_To_LE(ulong[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { for (int i = 0; i < nsLen; ++i) { UInt64_To_LE(ns[nsOff + i], bs, bsOff); bsOff += 8; } } internal static ulong LE_To_UInt64(byte[] bs) { uint lo = LE_To_UInt32(bs); uint hi = LE_To_UInt32(bs, 4); return ((ulong) hi << 32) | (ulong) lo; } internal static ulong LE_To_UInt64(byte[] bs, int off) { uint lo = LE_To_UInt32(bs, off); uint hi = LE_To_UInt32(bs, off + 4); return ((ulong) hi << 32) | (ulong) lo; } internal static void LE_To_UInt64(byte[] bs, int off, ulong[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt64(bs, off); off += 8; } } internal static void LE_To_UInt64(byte[] bs, int bsOff, ulong[] ns, int nsOff, int nsLen) { for (int i = 0; i < nsLen; ++i) { ns[nsOff + i] = LE_To_UInt64(bs, bsOff); bsOff += 8; } } } }
using System; using System.Collections.Generic; using System.IO; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Analysis { /* * 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 CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /// <summary> /// Analyzer for testing /// <p> /// this analyzer is a replacement for Whitespace/Simple/KeywordAnalyzers /// for unit tests. If you are testing a custom component such as a queryparser /// or analyzer-wrapper that consumes analysis streams, its a great idea to test /// it with this analyzer instead. MockAnalyzer has the following behavior: /// <ul> /// <li>By default, the assertions in <seealso cref="MockTokenizer"/> are turned on for extra /// checks that the consumer is consuming properly. These checks can be disabled /// with <seealso cref="#setEnableChecks(boolean)"/>. /// <li>Payload data is randomly injected into the stream for more thorough testing /// of payloads. /// </ul> </summary> /// <seealso cref= MockTokenizer </seealso> public sealed class MockAnalyzer : Analyzer { private readonly CharacterRunAutomaton RunAutomaton; private readonly bool LowerCase; private readonly CharacterRunAutomaton Filter; private int PositionIncrementGap_Renamed; private int? OffsetGap_Renamed; private readonly Random Random; private IDictionary<string, int?> PreviousMappings = new Dictionary<string, int?>(); private bool EnableChecks_Renamed = true; private int MaxTokenLength_Renamed = MockTokenizer.DEFAULT_MAX_TOKEN_LENGTH; /// <summary> /// Creates a new MockAnalyzer. /// </summary> /// <param name="random"> Random for payloads behavior </param> /// <param name="runAutomaton"> DFA describing how tokenization should happen (e.g. [a-zA-Z]+) </param> /// <param name="lowerCase"> true if the tokenizer should lowercase terms </param> /// <param name="filter"> DFA describing how terms should be filtered (set of stopwords, etc) </param> public MockAnalyzer(Random random, CharacterRunAutomaton runAutomaton, bool lowerCase, CharacterRunAutomaton filter) : base(PER_FIELD_REUSE_STRATEGY) { // TODO: this should be solved in a different way; Random should not be shared (!). this.Random = new Random(random.Next()); this.RunAutomaton = runAutomaton; this.LowerCase = lowerCase; this.Filter = filter; } /// <summary> /// Calls <c>MockAnalyzer(random, runAutomaton, lowerCase, MockTokenFilter.EMPTY_STOPSET, false)</c>. /// </summary> public MockAnalyzer(Random random, CharacterRunAutomaton runAutomaton, bool lowerCase) : this(random, runAutomaton, lowerCase, MockTokenFilter.EMPTY_STOPSET) { } /// <summary> /// Create a Whitespace-lowercasing analyzer with no stopwords removal. /// <para/> /// Calls <c>MockAnalyzer(random, MockTokenizer.WHITESPACE, true, MockTokenFilter.EMPTY_STOPSET, false)</c>. /// </summary> public MockAnalyzer(Random random) : this(random, MockTokenizer.WHITESPACE, true) { } protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { MockTokenizer tokenizer = new MockTokenizer(reader, RunAutomaton, LowerCase, MaxTokenLength_Renamed); tokenizer.EnableChecks = EnableChecks_Renamed; MockTokenFilter filt = new MockTokenFilter(tokenizer, Filter); return new TokenStreamComponents(tokenizer, MaybePayload(filt, fieldName)); } private TokenFilter MaybePayload(TokenFilter stream, string fieldName) { lock (this) { int? val; PreviousMappings.TryGetValue(fieldName, out val); if (val == null) { val = -1; // no payloads if (LuceneTestCase.Rarely(Random)) { switch (Random.Next(3)) { case 0: // no payloads val = -1; break; case 1: // variable length payload val = int.MaxValue; break; case 2: // fixed length payload val = Random.Next(12); break; } } if (LuceneTestCase.VERBOSE) { if (val == int.MaxValue) { Console.WriteLine("MockAnalyzer: field=" + fieldName + " gets variable length payloads"); } else if (val != -1) { Console.WriteLine("MockAnalyzer: field=" + fieldName + " gets fixed length=" + val + " payloads"); } } PreviousMappings[fieldName] = val; // save it so we are consistent for this field } if (val == -1) { return stream; } else if (val == int.MaxValue) { return new MockVariableLengthPayloadFilter(Random, stream); } else { return new MockFixedLengthPayloadFilter(Random, stream, (int)val); } } } public int PositionIncrementGap { set { this.PositionIncrementGap_Renamed = value; } } public override int GetPositionIncrementGap(string fieldName) { return PositionIncrementGap_Renamed; } /// <summary> /// Set a new offset gap which will then be added to the offset when several fields with the same name are indexed </summary> /// <param name="offsetGap"> The offset gap that should be used. </param> public int OffsetGap { set { this.OffsetGap_Renamed = value; } } /// <summary> /// Get the offset gap between tokens in fields if several fields with the same name were added. </summary> /// <param name="fieldName"> Currently not used, the same offset gap is returned for each field. </param> public override int GetOffsetGap(string fieldName) { return OffsetGap_Renamed == null ? base.GetOffsetGap(fieldName) : OffsetGap_Renamed.Value; } /// <summary> /// Toggle consumer workflow checking: if your test consumes tokenstreams normally you /// should leave this enabled. /// </summary> public bool EnableChecks { set { this.EnableChecks_Renamed = value; } } /// <summary> /// Toggle maxTokenLength for MockTokenizer /// </summary> public int MaxTokenLength { set { this.MaxTokenLength_Renamed = value; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Dynamic; using System.IO; using System.Linq; using HandlebarsDotNet.Collections; using HandlebarsDotNet.Helpers; using HandlebarsDotNet.PathStructure; using HandlebarsDotNet.Runtime; using HandlebarsDotNet.StringUtils; using HandlebarsDotNet.ValueProviders; using Xunit; namespace HandlebarsDotNet.Test { public class IssueTests { // Issue https://github.com/zjklee/Handlebars.CSharp/issues/7 [Fact] public void ValueVariableShouldNotBeAccessibleFromContext() { var handlebars = Handlebars.Create(); var render = handlebars.Compile("{{value}}"); var output = render(new { anotherValue = "Test" }); Assert.Equal("", output); } // Issue https://github.com/rexm/Handlebars.Net/issues/351 [Fact] public void PerhapsNull() { var handlebars = Handlebars.Create(); var render = handlebars.Compile("{{#if PerhapsNull}}It's not null{{else}}It's null{{/if}}"); dynamic data = new ExpandoObject(); data.PerhapsNull = null; var actual = render(data); Assert.Equal("It's null", actual); } // Issue https://github.com/rexm/Handlebars.Net/issues/350 // the helper has priority // https://handlebarsjs.com/guide/expressions.html#disambiguating-helpers-calls-and-property-lookup [Fact] public void HelperWithSameNameVariable() { var handlebars = Handlebars.Create(); var expected = "Helper"; handlebars.RegisterHelper("foo", (context, arguments) => expected); var template = handlebars.Compile("{{foo}}"); var data = new {foo = "Variable"}; var actual = template(data); Assert.Equal(expected, actual); } // Issue https://github.com/rexm/Handlebars.Net/issues/350 [Fact] public void LateBoundHelperWithSameNameVariable() { var handlebars = Handlebars.Create(); var template = handlebars.Compile("{{amoeba}}"); Assert.Equal("Variable", template(new {amoeba = "Variable"})); handlebars.RegisterHelper("amoeba", (writer, context, arguments) => { writer.Write("Helper"); }); Assert.Equal("Helper", template(new {amoeba = "Variable"})); } // Issue https://github.com/rexm/Handlebars.Net/issues/350 [Fact] public void LateBoundHelperWithSameNameVariablePath() { var handlebars = Handlebars.Create(); var expected = "Variable"; var template = handlebars.Compile("{{amoeba.a}}"); var data = new {amoeba = new {a = expected}}; var actual = template(data); Assert.Equal(expected, actual); handlebars.RegisterHelper("amoeba", (context, arguments) => "Helper"); actual = template(data); Assert.Equal(expected, actual); } // Issue https://github.com/rexm/Handlebars.Net/issues/354 [Fact] public void BlockHelperWithInversion() { string source = "{{^test input}}empty{{else}}not empty{{/test}}"; var handlebars = Handlebars.Create(); handlebars.RegisterHelper("test", (output, options, context, arguments) => { if (HandlebarsUtils.IsTruthy(arguments[0])) { options.Template(output, context); } else { options.Inverse(output, context); } }); var template = handlebars.Compile(source); Assert.Equal("empty", template(null)); Assert.Equal("empty", template(new { otherInput = 1 })); Assert.Equal("not empty", template(new { input = 1 })); } // Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/383 [Fact] public void TestNestedPartials() { var innerPartial = @"{{#>outer-partial}}<br /> Begin inner partial<br /> Begin inner partial block<br /> {{>@partial-block}} End inner partial block<br /> End inner partial<br /> {{/outer-partial}}"; var outerPartial = @"Begin outer partial<br /> Begin outer partial block {{>@partial-block}} End outer partial block<br /> End outer partial"; var view = @"{{#>inner-partial}} View<br /> {{/inner-partial}}"; var handlebars = Handlebars.Create(); handlebars.RegisterTemplate("outer-partial", outerPartial); handlebars.RegisterTemplate("inner-partial", innerPartial); var callback = handlebars.Compile(view); string result = callback(new object()); const string expected = @"Begin outer partial<br /> Begin outer partial block <br /> Begin inner partial<br /> Begin inner partial block<br /> View<br /> End inner partial block<br /> End inner partial<br /> End outer partial block<br /> End outer partial"; Assert.Equal(expected, result); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/395 [Fact] public void RenderingWithUnusedPartial() { var handlebars = Handlebars.Create(); var mainTemplate = @" {{>Navigation}} "; var navPartial = @" <div> {{#each MenuItems}} <div>Menu Item: {{Name}}</div> {{/each}} </div>"; // Remove the {{#if First}} section, and the test will pass var unusedPartial = @" {{#each Results}} Result {{#if HasSinglePackage}} HasSinglePackage {{#if First}} First {{/if}} {{/if}} {{/each}}"; var navTemplate = handlebars.Compile(mainTemplate); using (var reader = new StringReader(navPartial)) { handlebars.RegisterTemplate("Navigation", handlebars.Compile(reader)); } // Comment this section out and the test will succeed using (var reader = new StringReader(unusedPartial)) { handlebars.RegisterTemplate("Unused", handlebars.Compile(reader)); } // Attempted with concrete classes, still fails var context = new { MenuItems = new[] { new { Name = "Getting Started"} } }; var transformed = navTemplate(context).Trim(); Assert.Equal(@"<div> <div>Menu Item: Getting Started</div> </div>", transformed); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/394 [Fact] public void SlashesInTemplateKey() { var handlebars = Handlebars.Create(); handlebars.RegisterTemplate("Foo/bar", "hello world"); var compiled = handlebars.Compile("{{#>Foo/bar }} {{/Foo/bar}}"); var result = compiled(null); Assert.Equal("hello world", result); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/399 [Fact] public void PassesWhenMemberAccessorIsNull() { var template = "{{Join ['a', \"b \", 42] ':'}}"; var handlebars = Handlebars.Create(); handlebars.RegisterHelper(new JoinHelper()); var handlebarsTemplate = handlebars.Compile(template); var actual = handlebarsTemplate(""); Assert.Equal("a:b :42", actual); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/387 [Fact] public void ReverseIfCondition() { const string template = "{{^if false}}false{{/if}}"; var handlebars = Handlebars.Create(); var handlebarsTemplate = handlebars.Compile(template); var actual = handlebarsTemplate(null); Assert.Equal("false", actual); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/387 [Fact] public void ReverseUnlessCondition() { const string template = "{{^unless true}}false{{/unless}}"; var handlebars = Handlebars.Create(); var handlebarsTemplate = handlebars.Compile(template); var actual = handlebarsTemplate(null); Assert.Equal("false", actual); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/387 [Fact] public void ReverseEach() { const string template = "{{^each this}}false{{else}}{{@value}}{{/each}}"; var handlebars = Handlebars.Create(); var handlebarsTemplate = handlebars.Compile(template); var actual = handlebarsTemplate(new[]{ 1, 2 }); Assert.Equal("12", actual); actual = handlebarsTemplate(null); Assert.Equal("false", actual); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/402 [Fact] public void NestedObjectIteration() { const string template = @" {{#with test}} {{#if complexItems}} <ul> {{#each complexItems}} <li>{{name}} {{value}} {{evenMoreComplex.name}} {{evenMoreComplex.abbr}}</li> {{/each}} </ul> {{/if}} {{/with}}"; var data = new { test = new { complexItems = new[] { new { name = "a", value = 1, evenMoreComplex = new { name = "zzz", abbr = "z" } }, new { name = "b", value = 2, evenMoreComplex = new { name = "yyy", abbr = "y" } }, new { name = "c", value = 3, evenMoreComplex = new { name = "xxx", abbr = "x" } } }, } }; var handlebars = Handlebars.Create(); var handlebarsTemplate = handlebars.Compile(template); var result = handlebarsTemplate(data); const string expected = "<ul><li>a 1 zzz z</li><li>b 2 yyy y</li><li>c 3 xxx x</li></ul>"; var actual = result .Replace("\n", string.Empty) .Replace("\r", string.Empty) .Replace("\t", string.Empty); Assert.Equal(expected, actual); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/422 [Fact] public void CallPartialInEach() { var handlebars = Handlebars.Create(); handlebars.RegisterTemplate("testPartial", " 42 "); var source = "{{#each Fruits}}{{> testPartial aPartialParameter=\"couldBeAnything\"}}{{/each}}"; var template = handlebars.Compile(source); var data = new { Fruits = new[] {"apple", "banana" } }; var actual = template(data); var expected = " 42 42 "; Assert.Equal(expected, actual); } private class JoinHelper : IHelperDescriptor<HelperOptions> { public PathInfo Name { get; } = "join"; public object Invoke(in HelperOptions options, in Context context, in Arguments arguments) { return this.ReturnInvoke(options, context, arguments); } public void Invoke(in EncodedTextWriter output, in HelperOptions options, in Context context, in Arguments arguments) { var undefinedBindingResult = arguments.At<UndefinedBindingResult>(0); var separator = arguments.At<string>(1); var values = Substring.TrimStart(undefinedBindingResult.Value, '['); values = Substring.TrimEnd(values, ']'); var substrings = Substring.Split(values, ','); var extendedEnumerator = ExtendedEnumerator<Substring>.Create(substrings); while (extendedEnumerator.MoveNext()) { var substring = extendedEnumerator.Current.Value; substring = Substring.Trim(substring, ' '); substring = Substring.Trim(substring, '"'); substring = Substring.Trim(substring, '\''); output.Write(substring); if (!extendedEnumerator.Current.IsLast) { output.Write(separator); } } } } // discussion: https://github.com/Handlebars-Net/Handlebars.Net/discussions/404 [Fact] public void SwitchCaseTest() { const string template = @" {{~#switch propertyValue}} {{~#case 'a'}}a == {{@switchValue}}{{/case~}} {{~#case 'b'}}b == {{@switchValue}}{{/case~}} {{~#default}}the value is not provided{{/default~}} {{/switch~}}"; var handlebars = Handlebars.Create(); handlebars.RegisterHelper(new CaseHelper()); handlebars.RegisterHelper(new SwitchHelper()); handlebars.RegisterHelper(new DefaultCaseHelper()); var handlebarsTemplate = handlebars.Compile(template); var a = handlebarsTemplate(new {propertyValue = "a"}); var b = handlebarsTemplate(new {propertyValue = "b"}); var c = handlebarsTemplate(new {propertyValue = "c"}); Assert.Equal("a == a", a); Assert.Equal("b == b", b); Assert.Equal("the value is not provided", c); } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/300 [Fact] public void PartialLayoutAndInlineBlock() { string layout = "{{#>body}}{{fallback}}{{/body}}"; string page = @"{{#>layout}}{{#*inline ""body""}}{{truebody}}{{/inline}}{{/body}}{{/layout}}"; var handlebars = Handlebars.Create(); var template = handlebars.Compile(page); var data = new { fallback = "aaa", truebody = "Hello world" }; using (var reader = new StringReader(layout)) { var partialTemplate = handlebars.Compile(reader); handlebars.RegisterTemplate("layout", partialTemplate); } var result = template(data); Assert.Equal("Hello world", result); } private class SwitchHelper : IHelperDescriptor<BlockHelperOptions> { public PathInfo Name { get; } = "switch"; public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments) { return this.ReturnInvoke(options, context, arguments); } public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments) { var switchFrame = options.CreateFrame(); var data = new DataValues(switchFrame); data["switchValue"] = arguments[0]; data["__switchBlock"] = BoxedValues.True; data["__switchCaseMatched"] = BoxedValues.False; options.Template(output, switchFrame); } } private class CaseHelper : IHelperDescriptor<BlockHelperOptions> { public PathInfo Name { get; } = "case"; public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments) { return this.ReturnInvoke(options, context, arguments); } public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments) { if (!(bool) options.Data["__switchBlock"]) throw new InvalidOperationException(); if((bool) options.Data["__switchCaseMatched"]) return; var value = options.Data["switchValue"]; if(!Equals(value, arguments[0])) return; var data = new DataValues(options.Frame); data["__switchCaseMatched"] = BoxedValues.True; options.Template(output, options.Frame); // execute `case` in switch context } } private class DefaultCaseHelper : IHelperDescriptor<BlockHelperOptions> { public PathInfo Name { get; } = "default"; public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments) { return this.ReturnInvoke(options, context, arguments); } public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments) { if (!(bool) options.Data["__switchBlock"]) throw new InvalidOperationException(); if((bool) options.Data["__switchCaseMatched"]) return; options.Template(output, options.Frame); // execute `default` in switch context } } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/408 [Theory] [ClassData(typeof(CollectionsOutOfRangeGenerator))] public void Empty_string_if_index_is_out_of_range(IEnumerable input) { var handlebars = Handlebars.Create(); var render = handlebars.Compile("{{input.[1]}}"); object data = new { input }; var actual = render(data); Assert.Equal("", actual); } private class EscapeExpressionGenerator : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { const string OKAY = "OKAY"; var chars = " !\"#%&'()*+,./;<=>@[\\]^`{|}~".ToCharArray(); var words = new[] { "true", "false","null", "undefined", "foo" }; var testList = new List<string>(); var theContext = new Dictionary<string, object>(); foreach (var word in words) { foreach (var @char in chars) { //You can't use the same identifier you use for literal notation. if (@char == '[' || @char == ']') continue; var theKeyWord = $"{word}{@char}{word}"; var testSegment = $"[{theKeyWord}]"; testList.Add(testSegment); theContext[theKeyWord]=OKAY; } } for (var index = 0; index < testList.Count; index++) { yield return new object[] { $"{{{{ { testList[index] } }}}}", OKAY, theContext }; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } private class CollectionsOutOfRangeGenerator : IEnumerable<object[]> { private readonly List<IEnumerable> _data = new List<IEnumerable> { new[] { "one" }, new List<string>{ "one" }, new HashSet<string>{ "one" }, new CustomReadOnlyList(new[] { "one" }), Enumerable.Range(0, 1).Select(i => "one") }; public IEnumerator<object[]> GetEnumerator() => _data.Select(o => new object[] { o }).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private class CustomReadOnlyList : IReadOnlyList<string> { private readonly IReadOnlyList<string> _readOnlyListImplementation; public CustomReadOnlyList(IReadOnlyList<string> readOnlyListImplementation) { _readOnlyListImplementation = readOnlyListImplementation; } public IEnumerator<string> GetEnumerator() { return _readOnlyListImplementation.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _readOnlyListImplementation).GetEnumerator(); } public int Count => _readOnlyListImplementation.Count; public string this[int index] => _readOnlyListImplementation[index]; } } // issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/412 [Fact] public void StructReflectionAccessor() { const string template = "{{Name}}"; var handlebars = Handlebars.Create(); var handlebarsTemplate = handlebars.Compile(template); var actual = handlebarsTemplate(new CustomStruct { Name = "Foo" }); Assert.Equal("Foo", actual); } private struct CustomStruct { public string Name { get; set; } } // Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/432 [Fact] public void WeirdBehaviour() { var handlebars = Handlebars.Create(); handlebars.RegisterTemplate("displayListItem", "{{this}},"); handlebars.RegisterTemplate("displayList", "{{#each this}}{{> displayListItem}}{{/each}}"); var template = handlebars.Compile("{{> displayList TheList}}"); var actual1 = template(new ClassWithAList()); var actual2 = template(new ClassWithAListAndOtherMembers()); var expected = ""; Assert.Equal(expected, actual1); Assert.Equal(expected, actual2); } // Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/470 [Theory] [ClassData(typeof(EscapeExpressionGenerator))] public void SegmentLiteralNotationTest(string template, string expected, Dictionary<string, object> context) { var handlebars = Handlebars.Create(); var renderer = handlebars.Compile(template); var actual = renderer(context); Assert.Equal(expected, actual); } private class ClassWithAList { public IEnumerable<string> TheList { get; set; } } private class ClassWithAListAndOtherMembers { public IEnumerable<string> TheList { get; set; } public bool SomeBool { get; set; } public string SomeString { get; set; } = "I shouldn't show up!"; } // Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/468 // Issue refers to chinese characters, bug tested here affects any // html char and any non-ascii character. [Theory] [InlineData(true, "<", "<")] [InlineData(false, "<", "&lt;")] public void ConfigNoEscapeHtmlCharsShouldNotBeEscapedAfterWritingTripleCurlyValue(bool noEscape, string inputChar, string expectedChar) { // Affects any value written after execution of expression built in // class UnencodedStatementVisitor when config NoEscape is true. // Using triple curly brackets to trigger this case. var template = "{{{ArbitraryText}}} {{HtmlSymbol}}"; var value = new { ArbitraryText = "text", HtmlSymbol = inputChar }; var expected = $"text {expectedChar}"; var config = new HandlebarsConfiguration { NoEscape = noEscape }; var actual = Handlebars.Create(config).Compile(template).Invoke(value); Assert.Equal(expected, actual); } // Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/500 // Issue refers to the last letter being cut off when using // keys set in context [Fact] public void LastLetterCutOff() { var context = ImmutableDictionary<string, object>.Empty .Add("Name", "abcd"); var template = "{{.Name}}"; var compiledTemplate = Handlebars.Compile(template); string templateOutput = compiledTemplate(context); Assert.Equal("abcd", templateOutput); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Management.Automation.Runspaces.Internal; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace System.Management.Automation { internal class RemotePipeline : Pipeline { #region Private Members private PowerShell _powershell; private readonly bool _addToHistory; private bool _isNested; private bool _isSteppable; private readonly Runspace _runspace; private readonly object _syncRoot = new object(); private bool _disposed = false; private string _historyString; private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted); private readonly CommandCollection _commands = new CommandCollection(); private readonly string _computerName; private readonly Guid _runspaceId; private readonly ConnectCommandInfo _connectCmdInfo = null; /// <summary> /// This is queue of all the state change event which have occured for /// this pipeline. RaisePipelineStateEvents raises event for each /// item in this queue. We don't raise the event with in SetPipelineState /// because often SetPipelineState is called with in a lock. /// Raising event in lock introduces chances of deadlock in GUI applications. /// </summary> private Queue<ExecutionEventQueueItem> _executionEventQueue = new Queue<ExecutionEventQueueItem>(); private sealed class ExecutionEventQueueItem { public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability) { this.PipelineStateInfo = pipelineStateInfo; this.CurrentRunspaceAvailability = currentAvailability; this.NewRunspaceAvailability = newAvailability; } public PipelineStateInfo PipelineStateInfo; public RunspaceAvailability CurrentRunspaceAvailability; public RunspaceAvailability NewRunspaceAvailability; } private readonly bool _performNestedCheck = true; #endregion Private Members #region Constructors /// <summary> /// Private constructor that does most of the work constructing a remote pipeline object. /// </summary> /// <param name="runspace">RemoteRunspace object.</param> /// <param name="addToHistory">AddToHistory.</param> /// <param name="isNested">IsNested.</param> private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested) : base(runspace) { _addToHistory = addToHistory; _isNested = isNested; _isSteppable = false; _runspace = runspace; _computerName = ((RemoteRunspace)_runspace).ConnectionInfo.ComputerName; _runspaceId = _runspace.InstanceId; // Initialize streams _inputCollection = new PSDataCollection<object>(); _inputCollection.ReleaseOnEnumeration = true; _inputStream = new PSDataCollectionStream<object>(Guid.Empty, _inputCollection); _outputCollection = new PSDataCollection<PSObject>(); _outputStream = new PSDataCollectionStream<PSObject>(Guid.Empty, _outputCollection); _errorCollection = new PSDataCollection<ErrorRecord>(); _errorStream = new PSDataCollectionStream<ErrorRecord>(Guid.Empty, _errorCollection); // Create object stream for method executor objects. MethodExecutorStream = new ObjectStream(); IsMethodExecutorStreamEnabled = false; SetCommandCollection(_commands); // Create event which will be signalled when pipeline execution // is completed/failed/stoped. // Note:Runspace.Close waits for all the running pipeline // to finish. This Event must be created before pipeline is // added to list of running pipelines. This avoids the race condition // where Close is called after pipeline is added to list of // running pipeline but before event is created. PipelineFinishedEvent = new ManualResetEvent(false); } /// <summary> /// Constructs a remote pipeline for the specified runspace and /// specified command. /// </summary> /// <param name="runspace">Runspace in which to create the pipeline.</param> /// <param name="command">Command as a string, to be used in pipeline creation.</param> /// <param name="addToHistory">Whether to add the command to the runspaces history.</param> /// <param name="isNested">Whether this pipeline is nested.</param> internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHistory, bool isNested) : this(runspace, addToHistory, isNested) { if (command != null) { _commands.Add(new Command(command, true)); } // initialize the underlying powershell object _powershell = new PowerShell(_inputStream, _outputStream, _errorStream, ((RemoteRunspace)_runspace).RunspacePool); _powershell.SetIsNested(isNested); _powershell.InvocationStateChanged += HandleInvocationStateChanged; } /// <summary> /// Constructs a remote pipeline object associated with a remote running /// command but in a disconnected state. /// </summary> /// <param name="runspace">Remote runspace associated with running command.</param> internal RemotePipeline(RemoteRunspace runspace) : this(runspace, false, false) { if (runspace.RemoteCommand == null) { throw new InvalidOperationException(PipelineStrings.InvalidRemoteCommand); } _connectCmdInfo = runspace.RemoteCommand; _commands.Add(_connectCmdInfo.Command); // Beginning state will be disconnected. SetPipelineState(PipelineState.Disconnected, null); // Create the underlying powershell object. _powershell = new PowerShell(_connectCmdInfo, _inputStream, _outputStream, _errorStream, ((RemoteRunspace)_runspace).RunspacePool); _powershell.InvocationStateChanged += HandleInvocationStateChanged; } /// <summary> /// Creates a cloned pipeline from the specified one. /// </summary> /// <param name="pipeline">Pipeline to clone from.</param> /// <remarks>This constructor is private because this will /// only be called from the copy method</remarks> private RemotePipeline(RemotePipeline pipeline) : this( (RemoteRunspace)pipeline.Runspace, command: null, addToHistory: false, pipeline.IsNested) { _isSteppable = pipeline._isSteppable; // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 // the above comment copied from RemotePipelineBase which // originally copied it from PipelineBase if (pipeline == null) { throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } if (pipeline._disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); } _addToHistory = pipeline._addToHistory; _historyString = pipeline._historyString; foreach (Command command in pipeline.Commands) { Command clone = command.Clone(); // Attach the cloned Command to this pipeline. Commands.Add(clone); } } /// <summary> /// Override for creating a copy of pipeline. /// </summary> /// <returns> /// Pipeline object which is copy of this pipeline /// </returns> public override Pipeline Copy() { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); } return (Pipeline)new RemotePipeline(this); } #endregion Constructors #region Properties /// <summary> /// Access the runspace this pipeline is created on. /// </summary> public override Runspace Runspace { get { #pragma warning disable 56503 // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); } #pragma warning restore 56503 return _runspace; } } /// <summary> /// This internal method doesn't do the _disposed check. /// </summary> /// <returns></returns> internal Runspace GetRunspace() { return _runspace; } /// <summary> /// Is this pipeline nested. /// </summary> public override bool IsNested { get { return _isNested; } } /// <summary> /// Internal method to set the value of IsNested. This is called /// by serializer. /// </summary> internal void SetIsNested(bool isNested) { _isNested = isNested; _powershell.SetIsNested(isNested); } /// <summary> /// Internal method to set the value of IsSteppable. This is called /// during DoConcurrentCheck. /// </summary> internal void SetIsSteppable(bool isSteppable) { _isSteppable = isSteppable; } /// <summary> /// Info about current state of the pipeline. /// </summary> /// <remarks> /// This value indicates the state of the pipeline after the change. /// </remarks> public override PipelineStateInfo PipelineStateInfo { get { lock (_syncRoot) { // Note:We do not return internal state. return _pipelineStateInfo.Clone(); } } } /// <summary> /// Access the input writer for this pipeline. /// </summary> public override PipelineWriter Input { get { return _inputStream.ObjectWriter; } } /// <summary> /// Access the output reader for this pipeline. /// </summary> public override PipelineReader<PSObject> Output { get { return _outputStream.GetPSObjectReaderForPipeline(_computerName, _runspaceId); } } /// <summary> /// Access the error output reader for this pipeline. /// </summary> /// <remarks> /// This is the non-terminating error stream from the command. /// In this release, the objects read from this PipelineReader /// are PSObjects wrapping ErrorRecords. /// </remarks> public override PipelineReader<object> Error { get { return _errorStream.GetObjectReaderForPipeline(_computerName, _runspaceId); } } /// <summary> /// String which is added in the history. /// </summary> /// <remarks>This needs to be internal so that it can be replaced /// by invoke-cmd to place correct string in history.</remarks> internal string HistoryString { get { return _historyString; } set { _historyString = value; } } /// <summary> /// Whether the pipeline needs to be added to history of the runspace. /// </summary> public bool AddToHistory { get { return _addToHistory; } } #endregion Properties #region streams // Stream and Collection go together...a stream wraps // a corresponding collection to support // streaming behavior of the pipeline. private readonly PSDataCollection<PSObject> _outputCollection; private readonly PSDataCollectionStream<PSObject> _outputStream; private readonly PSDataCollection<ErrorRecord> _errorCollection; private readonly PSDataCollectionStream<ErrorRecord> _errorStream; private readonly PSDataCollection<object> _inputCollection; private readonly PSDataCollectionStream<object> _inputStream; /// <summary> /// Stream for providing input to PipelineProcessor. Host will write on /// ObjectWriter of this stream. PipelineProcessor will read from /// ObjectReader of this stream. /// </summary> protected PSDataCollectionStream<object> InputStream { get { return _inputStream; } } #endregion streams #region Invoke /// <summary> /// Invoke the pipeline asynchronously. /// </summary> /// <remarks> /// Results are returned through the <see cref="Pipeline.Output"/> reader. /// </remarks> public override void InvokeAsync() { InitPowerShell(false); CoreInvokeAsync(); } /// <summary> /// Invokes a remote command and immediately disconnects if /// transport layer supports it. /// </summary> internal override void InvokeAsyncAndDisconnect() { // Initialize PowerShell invocation with "InvokeAndDisconnect" setting. InitPowerShell(false, true); CoreInvokeAsync(); } /// <summary> /// Invoke the pipeline, synchronously, returning the results as an /// array of objects. /// </summary> /// <param name="input">an array of input objects to pass to the pipeline. /// Array may be empty but may not be null</param> /// <returns>An array of zero or more result objects.</returns> /// <remarks>Caller of synchronous exectute should not close /// input objectWriter. Synchronous invoke will always close the input /// objectWriter. /// /// On Synchronous Invoke if output is throttled and no one is reading from /// output pipe, Execution will block after buffer is full. /// </remarks> public override Collection<PSObject> Invoke(System.Collections.IEnumerable input) { if (input == null) { this.InputStream.Close(); } InitPowerShell(true); Collection<PSObject> results; try { results = _powershell.Invoke(input); } catch (InvalidRunspacePoolStateException) { InvalidRunspaceStateException e = new InvalidRunspaceStateException ( StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, _runspace.RunspaceStateInfo.State.ToString()), _runspace.RunspaceStateInfo.State, RunspaceState.Opened ); throw e; } return results; } #endregion Invoke #region Connect /// <summary> /// Connects synchronously to a running command on a remote server. /// The pipeline object must be in the disconnected state. /// </summary> /// <returns>A collection of result objects.</returns> public override Collection<PSObject> Connect() { InitPowerShellForConnect(true); Collection<PSObject> results; try { results = _powershell.Connect(); } catch (InvalidRunspacePoolStateException) { InvalidRunspaceStateException e = new InvalidRunspaceStateException ( StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipelineConnect, _runspace.RunspaceStateInfo.State.ToString()), _runspace.RunspaceStateInfo.State, RunspaceState.Opened ); throw e; } // PowerShell object will return empty results if it was provided an alternative object to // collect output in. Check to see if the output was collected in a member variable. if (results.Count == 0) { if (_outputCollection != null && _outputCollection.Count > 0) { results = new Collection<PSObject>(_outputCollection); } } return results; } /// <summary> /// Connects asynchronously to a running command on a remote server. /// </summary> public override void ConnectAsync() { InitPowerShellForConnect(false); try { _powershell.ConnectAsync(); } catch (InvalidRunspacePoolStateException) { InvalidRunspaceStateException e = new InvalidRunspaceStateException ( StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipelineConnect, _runspace.RunspaceStateInfo.State.ToString()), _runspace.RunspaceStateInfo.State, RunspaceState.Opened ); throw e; } } #endregion #region Stop /// <summary> /// Stop the pipeline synchronously. /// </summary> public override void Stop() { bool isAlreadyStopping = false; if (CanStopPipeline(out isAlreadyStopping)) { // A pipeline can be stopped before it is started.so protecting against that if (_powershell != null) { IAsyncResult asyncresult = null; try { asyncresult = _powershell.BeginStop(null, null); } catch (ObjectDisposedException) { throw PSTraceSource.NewObjectDisposedException("Pipeline"); } asyncresult.AsyncWaitHandle.WaitOne(); } } // Waits until pipeline completes stop as this is a sync call. PipelineFinishedEvent.WaitOne(); } /// <summary> /// Stop the pipeline asynchronously. /// This method calls the BeginStop on the underlying /// powershell and so any exception will be /// thrown on the same thread. /// </summary> public override void StopAsync() { bool isAlreadyStopping; if (CanStopPipeline(out isAlreadyStopping)) { try { _powershell.BeginStop(null, null); } catch (ObjectDisposedException) { throw PSTraceSource.NewObjectDisposedException("Pipeline"); } } } /// <summary> /// Verifies if the pipeline is in a state where it can be stopped. /// </summary> private bool CanStopPipeline(out bool isAlreadyStopping) { bool returnResult = false; isAlreadyStopping = false; lock (_syncRoot) { // SetPipelineState does not raise events.. // so locking is ok here. switch (_pipelineStateInfo.State) { case PipelineState.NotStarted: SetPipelineState(PipelineState.Stopping, null); SetPipelineState(PipelineState.Stopped, null); returnResult = false; break; // If pipeline execution has failed or completed or // stoped, return silently. case PipelineState.Stopped: case PipelineState.Completed: case PipelineState.Failed: return false; // If pipeline is in Stopping state, ignore the second // stop. case PipelineState.Stopping: isAlreadyStopping = true; return false; case PipelineState.Running: case PipelineState.Disconnected: SetPipelineState(PipelineState.Stopping, null); returnResult = true; break; } } RaisePipelineStateEvents(); return returnResult; } #endregion Stop #region Events /// <summary> /// Event raised when Pipeline's state changes. /// </summary> public override event EventHandler<PipelineStateEventArgs> StateChanged = null; #endregion Events #region Dispose /// <summary> /// Disposes the pipeline. /// </summary> /// <param name="disposing">True, when called on Dispose().</param> protected override void Dispose(bool disposing) { try { if (_disposed) { return; } lock (_syncRoot) { if (_disposed) { return; } _disposed = true; } if (disposing) { // wait for the pipeline to stop..this will block // if the pipeline is already stopping. Stop(); // _pipelineFinishedEvent.Close(); if (_powershell != null) { _powershell.Dispose(); _powershell = null; } _inputCollection.Dispose(); _inputStream.Dispose(); _outputCollection.Dispose(); _outputStream.Dispose(); _errorCollection.Dispose(); _errorStream.Dispose(); MethodExecutorStream.Dispose(); PipelineFinishedEvent.Dispose(); } } finally { base.Dispose(disposing); } } #endregion Dispose #region Private Methods private void CoreInvokeAsync() { try { _powershell.BeginInvoke(); } catch (InvalidRunspacePoolStateException) { InvalidRunspaceStateException e = new InvalidRunspaceStateException ( StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, _runspace.RunspaceStateInfo.State.ToString()), _runspace.RunspaceStateInfo.State, RunspaceState.Opened ); throw e; } } private void HandleInvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e) { SetPipelineState((PipelineState)e.InvocationStateInfo.State, e.InvocationStateInfo.Reason); RaisePipelineStateEvents(); } /// <summary> /// Sets the new execution state. /// </summary> /// <param name="state">The new state.</param> /// <param name="reason"> /// An exception indicating that state change is the result of an error, /// otherwise; null. /// </param> /// <remarks> /// Sets the internal execution state information member variable. It /// also adds PipelineStateInfo to a queue. RaisePipelineStateEvents /// raises event for each item in this queue. /// </remarks> private void SetPipelineState(PipelineState state, Exception reason) { PipelineState copyState = state; PipelineStateInfo copyStateInfo = null; lock (_syncRoot) { switch (_pipelineStateInfo.State) { case PipelineState.Completed: case PipelineState.Failed: case PipelineState.Stopped: return; case PipelineState.Running: { if (state == PipelineState.Running) { return; } } break; case PipelineState.Stopping: { if (state == PipelineState.Running || state == PipelineState.Stopping) { return; } else { copyState = PipelineState.Stopped; } } break; } _pipelineStateInfo = new PipelineStateInfo(copyState, reason); copyStateInfo = _pipelineStateInfo; // Add _pipelineStateInfo to _executionEventQueue. // RaisePipelineStateEvents will raise event for each item // in this queue. // Note:We are doing clone here instead of passing the member // _pipelineStateInfo because we donot want outside // to change pipeline state. RunspaceAvailability previousAvailability = _runspace.RunspaceAvailability; Guid? cmdInstanceId = (_powershell != null) ? _powershell.InstanceId : (Guid?)null; _runspace.UpdateRunspaceAvailability(_pipelineStateInfo.State, false, cmdInstanceId); _executionEventQueue.Enqueue( new ExecutionEventQueueItem( _pipelineStateInfo.Clone(), previousAvailability, _runspace.RunspaceAvailability)); } // using the copyStateInfo here as this piece of code is // outside of lock and _pipelineStateInfo might get changed // by two threads running concurrently..so its value is // not guaranteed to be the same for this entire method call. // copyStateInfo is a local variable. if (copyStateInfo.State == PipelineState.Completed || copyStateInfo.State == PipelineState.Failed || copyStateInfo.State == PipelineState.Stopped) { Cleanup(); } } /// <summary> /// Raises events for changes in execution state. /// </summary> protected void RaisePipelineStateEvents() { Queue<ExecutionEventQueueItem> tempEventQueue = null; EventHandler<PipelineStateEventArgs> stateChanged = null; bool runspaceHasAvailabilityChangedSubscribers = false; lock (_syncRoot) { stateChanged = this.StateChanged; runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers; if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers) { tempEventQueue = _executionEventQueue; _executionEventQueue = new Queue<ExecutionEventQueueItem>(); } else { // Clear the events if there are no EventHandlers. This // ensures that events do not get called for state // changes prior to their registration. _executionEventQueue.Clear(); } } if (tempEventQueue != null) { while (tempEventQueue.Count > 0) { ExecutionEventQueueItem queueItem = tempEventQueue.Dequeue(); if (runspaceHasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability) { _runspace.RaiseAvailabilityChangedEvent(queueItem.NewRunspaceAvailability); } // Exception raised in the eventhandler are not error in pipeline. // silently ignore them. if (stateChanged != null) { try { stateChanged(this, new PipelineStateEventArgs(queueItem.PipelineStateInfo)); } catch (Exception) { } } } } } /// <summary> /// Initializes the underlying PowerShell object after verifying /// if the pipeline is in a state where it can be invoked. /// If invokeAndDisconnect is true then the remote PowerShell /// command will be immediately disconnected after it begins /// running. /// </summary> /// <param name="syncCall">True if called from a sync call.</param> /// <param name="invokeAndDisconnect">Invoke and Disconnect.</param> private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { if (_commands == null || _commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NoCommandInPipeline); } if (_pipelineStateInfo.State != PipelineState.NotStarted) { InvalidPipelineStateException e = new InvalidPipelineStateException ( StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed), _pipelineStateInfo.State, PipelineState.NotStarted ); throw e; } ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; settings.InvokeAndDisconnect = invokeAndDisconnect; _powershell.InitForRemotePipeline(_commands, _inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); _powershell.RemotePowerShell.HostCallReceived += HandleHostCallReceived; } /// <summary> /// Initializes the underlying PowerShell object after verifying that it is /// in a state where it can connect to the remote command. /// </summary> /// <param name="syncCall"></param> private void InitPowerShellForConnect(bool syncCall) { if (_pipelineStateInfo.State != PipelineState.Disconnected) { throw new InvalidPipelineStateException(StringUtil.Format(PipelineStrings.PipelineNotDisconnected), _pipelineStateInfo.State, PipelineState.Disconnected); } // The connect may be from the same Pipeline that disconnected and in this case // the Pipeline state already exists. Or this could be a new Pipeline object // (connect reconstruction case) and new state is created. // Check to see if this pipeline already exists in the runspace. RemotePipeline currentPipeline = (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline(); if (!ReferenceEquals(currentPipeline, this)) { ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); } // Initialize the PowerShell object if it hasn't been initialized before. if ((_powershell.RemotePowerShell) == null || !_powershell.RemotePowerShell.Initialized) { PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; _powershell.InitForRemotePipelineConnect(_inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); _powershell.RemotePowerShell.HostCallReceived += HandleHostCallReceived; } } /// <summary> /// Handle host call received. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Arguments describing the host call to invoke.</param> private void HandleHostCallReceived(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs) { ClientMethodExecutor.Dispatch( _powershell.RemotePowerShell.DataStructureHandler.TransportManager, ((RemoteRunspace)_runspace).RunspacePool.RemoteRunspacePoolInternal.Host, _errorStream, MethodExecutorStream, IsMethodExecutorStreamEnabled, ((RemoteRunspace)_runspace).RunspacePool.RemoteRunspacePoolInternal, _powershell.InstanceId, eventArgs.Data); } /// <summary> /// Does the cleanup necessary on pipeline completion. /// </summary> private void Cleanup() { // Close the output stream if it is not closed. if (_outputStream.IsOpen) { try { _outputCollection.Complete(); _outputStream.Close(); } catch (ObjectDisposedException) { } } // Close the error stream if it is not closed. if (_errorStream.IsOpen) { try { _errorCollection.Complete(); _errorStream.Close(); } catch (ObjectDisposedException) { } } // Close the input stream if it is not closed. if (_inputStream.IsOpen) { try { _inputCollection.Complete(); _inputStream.Close(); } catch (ObjectDisposedException) { } } try { // Runspace object maintains a list of pipelines in execution. // Remove this pipeline from the list. This method also calls the // pipeline finished event. ((RemoteRunspace)_runspace).RemoveFromRunningPipelineList(this); PipelineFinishedEvent.Set(); } catch (ObjectDisposedException) { } } #endregion Private Methods #region Internal Methods/Properties /// <summary> /// ManualResetEvent which is signaled when pipeline execution is /// completed/failed/stoped. /// </summary> internal ManualResetEvent PipelineFinishedEvent { get; } /// <summary> /// Is method executor stream enabled. /// </summary> internal bool IsMethodExecutorStreamEnabled { get; set; } /// <summary> /// Method executor stream. /// </summary> internal ObjectStream MethodExecutorStream { get; } /// <summary> /// Check if anyother pipeline is executing. /// In case of nested pipeline, checks that it is called /// from currently executing pipeline's thread. /// </summary> /// <param name="syncCall">True if method is called from Invoke, false /// if called from InvokeAsync</param> /// <exception cref="InvalidOperationException"> /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) InvokeAsync is called on nested pipeline. Nested pipeline /// cannot be executed Asynchronously. /// 3) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// </exception> internal void DoConcurrentCheck(bool syncCall) { RemotePipeline currentPipeline = (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline(); if (!_isNested) { if (currentPipeline == null && ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.Busy && ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.RemoteDebug) { // We can add a new pipeline to the runspace only if it is // available (not busy). return; } if (currentPipeline == null && ((RemoteRunspace)_runspace).RemoteCommand != null && _connectCmdInfo != null && Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId)) { // Connect case. We can add a pipeline to a busy runspace when // that pipeline represents the same command as is currently // running. return; } if (currentPipeline != null && ReferenceEquals(currentPipeline, this)) { // Reconnect case. We can add a pipeline to a busy runspace when the // pipeline is the same (reconnecting). return; } if (!_isSteppable) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.ConcurrentInvokeNotAllowed); } } else { if (_performNestedCheck) { if (_isSteppable) { return; } if (!syncCall) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NestedPipelineInvokeAsync); } if (currentPipeline == null) { if (!_isSteppable) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NestedPipelineNoParentPipeline); } } } } } /// <summary> /// The underlying powershell object on which this remote pipeline /// is created. /// </summary> internal PowerShell PowerShell { get { return _powershell; } } /// <summary> /// Sets the history string to the specified string. /// </summary> /// <param name="historyString">New history string to set to.</param> internal override void SetHistoryString(string historyString) { _powershell.HistoryString = historyString; } #endregion Internal Methods/Properties #region Remote data drain/block methods /// <summary> /// Blocks data arriving from remote session. /// </summary> internal override void SuspendIncomingData() { _powershell.SuspendIncomingData(); } /// <summary> /// Resumes data arrive from remote session. /// </summary> internal override void ResumeIncomingData() { _powershell.ResumeIncomingData(); } /// <summary> /// Blocking call that waits until the current remote data /// queue is empty. /// </summary> internal override void DrainIncomingData() { _powershell.WaitForServicingComplete(); } #endregion } }
/* PlayStation(R)Mobile SDK 2.00.00 * Copyright (C) 2014 Sony Computer Entertainment Inc. * All Rights Reserved. */ using System; using System.IO; using System.Reflection; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Imaging; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Input; namespace Sample { /** * SampleDraw class */ public static class SampleDraw { private static GraphicsContext graphics; private static ShaderProgram textureShaderProgram; private static ShaderProgram colorShaderProgram; private static Matrix4 projectionMatrix; private static Matrix4 viewMatrix; private static VertexBuffer rectVertices; private static VertexBuffer circleVertices; private static Dictionary<string, SampleSprite> spriteDict; private static int spriteNamelessCount; private static Font defaultFont; private static Font currentFont; public static bool Init(GraphicsContext graphicsContext, Stopwatch swInit = null) { graphics = graphicsContext; textureShaderProgram = createSimpleTextureShader(); colorShaderProgram = createSimpleColorShader(); projectionMatrix = Matrix4.Ortho(0, Width, 0, Height, 0.0f, 32768.0f); viewMatrix = Matrix4.LookAt(new Vector3(0, Height, 0), new Vector3(0, Height, 1), new Vector3(0, -1, 0)); rectVertices = new VertexBuffer(4, VertexFormat.Float3); rectVertices.SetVertices(0, new float[]{0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0}); circleVertices = new VertexBuffer(36, VertexFormat.Float3); float[] circleVertex = new float[3 * 36]; for (int i = 0; i < 36; i++) { float radian = ((i * 10) / 180.0f * FMath.PI); circleVertex[3 * i + 0] = FMath.Cos(radian); circleVertex[3 * i + 1] = FMath.Sin(radian); circleVertex[3 * i + 2] = 0.0f; } circleVertices.SetVertices(0, circleVertex); defaultFont = new Font(FontAlias.System, 24, FontStyle.Regular); SetDefaultFont(); spriteDict = new Dictionary<string, SampleSprite>(); spriteNamelessCount = 0; return true; } /// Terminate public static void Term() { ClearSprite(); defaultFont.Dispose(); circleVertices.Dispose(); rectVertices.Dispose(); colorShaderProgram.Dispose(); textureShaderProgram.Dispose(); graphics = null; } public static int Width { get {return graphics.GetFrameBuffer().Width;} } public static int Height { get {return graphics.GetFrameBuffer().Height;} } /// Touch coordinates -> screen coordinates conversion : X public static int TouchPixelX(TouchData touchData) { return (int)((touchData.X + 0.5f) * Width); } /// Touch coordinates -> screen coordinates conversion : Y public static int TouchPixelY(TouchData touchData) { return (int)((touchData.Y + 0.5f) * Height); } public static void AddSprite(SampleSprite sprite) { AddSprite("[nameless]:" + spriteNamelessCount, sprite); spriteNamelessCount++; } public static void AddSprite(string key, SampleSprite sprite) { if (spriteDict.ContainsKey(key) == false) { spriteDict.Add(key, sprite); } } /// Register a sprite that draws text public static void AddSprite(string key, string text, uint argb, Font font, int positionX, int positionY) { if (spriteDict.ContainsKey(key) == false) { AddSprite(key, new SampleSprite(text, argb, font, positionX, positionY)); } } /// Register a sprite that draws text public static void AddSprite(string text, uint argb, int positionX, int positionY) { AddSprite(text, text, argb, currentFont, positionX, positionY); } public static void RemoveSprite(string key) { if (spriteDict.ContainsKey(key)) { spriteDict[key].Dispose(); spriteDict.Remove(key); } } public static void ClearSprite() { foreach (string key in spriteDict.Keys) { spriteDict[key].Dispose(); } spriteDict.Clear(); spriteNamelessCount = 0; } // if use SampleDraw's method, please call this method. public static void Update() { int keyNo = 0; string[] removeKey = new string[spriteDict.Count]; foreach (var key in spriteDict.Keys) { if(false == spriteDict[key].CheckLifeTimer()) { removeKey[keyNo] = key; keyNo++; } } for(int i = 0; i < keyNo; i++) { if(removeKey[i] != null) { RemoveSprite(removeKey[i]); } } } public static void DrawSprite(string key) { if (spriteDict.ContainsKey(key)) { DrawSprite(spriteDict[key]); } } public static void DrawSprite(SampleSprite sprite) { var modelMatrix = sprite.CreateModelMatrix(); var worldViewProj = projectionMatrix * viewMatrix * modelMatrix; textureShaderProgram.SetUniformValue(0, ref worldViewProj); graphics.SetShaderProgram(textureShaderProgram); graphics.SetVertexBuffer(0, sprite.Vertices); graphics.SetTexture(0, sprite.Texture); graphics.Enable(EnableMode.Blend); graphics.SetBlendFunc(BlendFuncMode.Add, BlendFuncFactor.SrcAlpha, BlendFuncFactor.OneMinusSrcAlpha); graphics.DrawArrays(DrawMode.TriangleFan, 0, 4); sprite.SetLifeTimer(); } public static Font CurrentFont { get {return currentFont;} } public static Font SetDefaultFont() { return SetFont(defaultFont); } public static Font SetFont(Font font) { Font previousFont = currentFont; currentFont = font; return previousFont; } public static void DrawText(string text, uint argb, Font font, int positionX, int positionY) { var key = string.Format("{0:X8}{1:X8}{2}", font.GetHashCode(), argb, text); if (!spriteDict.ContainsKey(key)) { AddSprite(key, new SampleSprite(text, argb, font, positionX, positionY)); } else { var sprite = spriteDict[key]; sprite.PositionX = positionX; sprite.PositionY = positionY; } DrawSprite(key); } public static void DrawText(string text, uint argb, int positionX, int positionY) { DrawText(text, argb, currentFont, positionX, positionY); } public static void FillRect(uint argb, int positionX, int positionY, int rectW, int rectH) { FillVertices(rectVertices, argb, positionX, positionY, rectW, rectH); } public static void FillCircle(uint argb, int positionX, int positionY, int radius) { FillVertices(circleVertices, argb, positionX, positionY, radius, radius); } public static void FillVertices(VertexBuffer vertices, uint argb, float positionX, float positionY, float scaleX, float scaleY) { var transMatrix = Matrix4.Translation(new Vector3(positionX, positionY, 0.0f)); var scaleMatrix = Matrix4.Scale(new Vector3(scaleX, scaleY, 1.0f)); var modelMatrix = transMatrix * scaleMatrix; var worldViewProj = projectionMatrix * viewMatrix * modelMatrix; colorShaderProgram.SetUniformValue(0, ref worldViewProj); Vector4 color = new Vector4((float)((argb >> 16) & 0xff) / 0xff, (float)((argb >> 8) & 0xff) / 0xff, (float)((argb >> 0) & 0xff) / 0xff, (float)((argb >> 24) & 0xff) / 0xff); colorShaderProgram.SetUniformValue(colorShaderProgram.FindUniform("MaterialColor"), ref color); graphics.SetShaderProgram(colorShaderProgram); graphics.SetVertexBuffer(0, vertices); graphics.DrawArrays(DrawMode.TriangleFan, 0, vertices.VertexCount); } private static ShaderProgram createSimpleTextureShader() { string ResourceName = "PSMMassParticle.shaders.Texture.cgx"; Assembly resourceAssembly = Assembly.GetExecutingAssembly(); if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null) { throw new FileNotFoundException("File not found.", ResourceName); } Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName); Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length]; fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length); var shaderProgram = new ShaderProgram(dataBufferVertex); // var shaderProgram = new ShaderProgram("/Application/shaders/Texture.cgx"); shaderProgram.SetAttributeBinding(0, "a_Position"); shaderProgram.SetAttributeBinding(1, "a_TexCoord"); shaderProgram.SetUniformBinding(0, "WorldViewProj"); return shaderProgram; } private static ShaderProgram createSimpleColorShader() { string ResourceName = "PSMMassParticle.shaders.Simple.cgx"; Assembly resourceAssembly = Assembly.GetExecutingAssembly(); if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null) { throw new FileNotFoundException("File not found.", ResourceName); } Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName); Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length]; fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length); var shaderProgram = new ShaderProgram(dataBufferVertex); // var shaderProgram = new ShaderProgram("/Application/shaders/Simple.cgx"); shaderProgram.SetAttributeBinding(0, "a_Position"); //shaderProgram.SetAttributeBinding(1, "a_Color0"); shaderProgram.SetUniformBinding(0, "WorldViewProj"); return shaderProgram; } } } // Sample
escape: not used UrlArg: <?cs var:UrlArg ?> BlahJs: <?cs var:BlahJs ?> Title: <?cs var:Title ?> <?cs escape: "none" ?> escape: none UrlArg: <?cs var:UrlArg ?> BlahJs: <?cs var:BlahJs ?> Title: <?cs var:Title ?> <?cs /escape ?> <?cs escape: "html" ?> escape: html UrlArg: <?cs var:UrlArg ?> BlahJs: <?cs var:BlahJs ?> Title: <?cs var:Title ?> <?cs /escape ?> <?cs escape: "js" ?> escape: js UrlArg: <?cs var:UrlArg ?> BlahJs: <?cs var:BlahJs ?> Title: <?cs var:Title ?> <?cs /escape ?> <?cs escape: "url" ?> escape: url UrlArg: <?cs var:UrlArg ?> BlahJs: <?cs var:BlahJs ?> Title: <?cs var:Title ?> <?cs /escape ?> <?cs escape: "html" ?> Nested escaping: html The internal calls should take precedence <?cs escape: "url" ?>url -> UrlArg: <?cs var:UrlArg ?><?cs /escape ?> <?cs escape: "js" ?>js -> BlahJs: <?cs var:BlahJs ?><?cs /escape ?> <?cs escape: "html" ?>html -> Title: <?cs var:Title ?><?cs /escape ?> <?cs /escape ?> Defining the macro echo_all inside of a "html" escape. <?cs escape: "html" ?><?cs def:echo_all(e) ?> not used: <?cs var:e ?> none: <?cs escape: "none" ?><?cs var:e ?><?cs /escape ?> url: <?cs escape: "url" ?><?cs var:e ?><?cs /escape ?> js: <?cs escape: "js" ?><?cs var:e ?><?cs /escape ?> html: <?cs escape: "html" ?><?cs var:e ?><?cs /escape ?> <?cs /def ?><?cs /escape ?> Calling echo_all() macro: <?cs call:echo_all(Title + UrlArh + BlahJs) ?> <?cs escape: "html" ?> Calling echo_all() macro from within "html": <?cs call:echo_all(Title + UrlArh + BlahJs) ?> <?cs /escape ?> <?cs escape: "js" ?> Calling echo_all() macro from within "js": <?cs call:echo_all(Title + UrlArh + BlahJs) ?> <?cs /escape ?> <?cs escape: "url" ?> Calling echo_all() macro from within "url": <?cs call:echo_all(Title + UrlArh + BlahJs) ?> <?cs /escape ?> <?cs escape: "html" ?> Nested if escaping: Should be: <?cs var:Title ?> <?cs if: 1 ?> If: <?cs var:Title ?> IfAlt: <?cs alt:Title ?>Not me<?cs /alt ?> <?cs /if ?> <?cs if: 0 ?> If: <?cs var:Title ?> IfAlt: <?cs alt:Title ?>Not me<?cs /alt ?> <?cs else ?> Else: <?cs var:Title ?> <?cs /if ?> <?cs if: 0 ?> If: <?cs var:Title ?> IfAlt: <?cs alt:Title ?>Not me<?cs /alt ?> <?cs elif: 1 ?> Elif: <?cs var:Title ?> If: <?cs alt:Title ?>Not me<?cs /alt ?> <?cs /if ?> <?cs if: 1 ?> <?cs if: 1 ?> Nested If: <?cs var:Title ?> <?cs /if ?> <?cs /if ?> <?cs if: 1 ?> Calling echo_all() macro inside escape, within if: <?cs call:echo_all(Title + UrlArh + BlahJs) ?> Defining show_title() inside escape, within if <?cs def:show_title(t) ?> No escaping: <?cs var:t ?> none: <?cs escape: "none" ?><?cs var:t ?><?cs /escape ?> html: <?cs escape: "html" ?><?cs var:t ?><?cs /escape ?> <?cs /def ?> <?cs /if ?> <?cs /escape ?> Calling show_title() outside escape:<?cs call:show_title(Title) ?> Now a series of tests testing the interaction between 'escape' and various control flows <?cs escape: "html" ?> Title: <?cs var:Title ?> <?cs def:some_func(t) ?>Inside def: <?cs var:t ?><?cs /def ?> After def: <?cs var:Title ?> <?cs if: 1 ?> Inside if: <?cs var:Title ?> <?cs /if ?> After if: <?cs var:Title ?> <?cs call:some_func(Title) ?> After call: <?cs var:Title ?> <?cs loop:x = #1, #5, #2 ?> Inside loop: <?cs var:Title ?> <?cs /loop ?> After loop: <?cs var:Title ?> <?cs each:sub = Numbers ?> Inside each: <?cs var:Title ?> <?cs /each ?> After each: <?cs var:Title ?> <?cs with:sub = Title ?> Inside with: <?cs var: sub ?> <?cs /with ?> After with: <?cs var:Title ?> <?cs /escape ?> Now a series of tests wrapping various control flows in 'escape' <?cs escape: "html" ?> Title: <?cs var:Title ?> <?cs /escape ?> After var: <?cs var: Title ?> <?cs escape: "html" ?> <?cs def:sec_some_func(t) ?>Inside call: <?cs var:t ?><?cs /def ?> <?cs /escape ?> After def: <?cs var:Title ?> <?cs escape: "html" ?> <?cs if: 1 ?> Inside if: <?cs var:Title ?> <?cs /if ?> <?cs /escape ?> After if: <?cs var:Title ?> <?cs escape: "html" ?> <?cs call:sec_some_func(Title) ?> <?cs /escape ?> After call: <?cs var:Title ?> <?cs escape: "html" ?> <?cs loop:x = #1, #5, #2 ?> Inside loop: <?cs var:Title ?> <?cs /loop ?> <?cs /escape ?> After loop: <?cs var:Title ?> <?cs escape: "html" ?> <?cs each:sub = Numbers ?> Inside each: <?cs var:Title ?> <?cs /each ?> <?cs /escape ?> After each: <?cs var:Title ?> <?cs escape: "html" ?> <?cs with:sub = Title ?> Inside with: <?cs var: sub ?> <?cs /with ?> <?cs /escape ?> After with: <?cs var:Title ?> Now test escape with nested calls <?cs def:first() ?> <?cs var: Title ?> <?cs /def ?> <?cs def:second() ?> <?cs escape: "html" ?> Should be html escaped :local: <?cs var: Title ?> Macro: <?cs call:first() ?> <?cs /escape ?> Should not be html escaped:local: <?cs var: Title ?> <?cs /def ?> <?cs call:second() ?> Now test escape with nested defs <?cs escape: "html" ?> <?cs def:outer_def(t) ?> Inside def: <?cs var:t ?> <?cs def:inner_def(y) ?>Inside inner def: <?cs var: y ?><?cs /def ?> <?cs call:inner_def(t) ?> <?cs /def ?> Calling defs from inside escape:<?cs call:outer_def(Title) ?> <?cs /escape ?> Calling defs from outside escape:<?cs call:outer_def(Title) ?> Now test escape inside def <?cs def:escaped_func(t) ?> Before escape: <?cs var: t ?> <?cs escape: "html" ?> Inside escape: <?cs var: t ?> <?cs /escape ?> After escape: <?cs var: t ?> <?cs /def ?> <?cs call:escaped_func(Title) ?> Now test escape with name <?cs escape: "html" ?> <?cs set: "A.<EvilName>" = "something" ?> <?cs with: evilname = A["<EvilName>"] ?> <?cs name: evilname ?> <?cs /with ?> <?cs /escape ?> <?cs with: evilname = A["<EvilName>"] ?> <?cs escape: "html" ?> <?cs name: evilname ?> <?cs /escape ?> <?cs /with ?> Include:<?cs escape: "html" ?> <?cs include: "test_include.cs" ?> <?cs /escape ?> Linclude:<?cs escape: "html" ?> <?cs linclude: "test_include.cs" ?> <?cs /escape ?> Evar:<?cs escape: "html" ?> <?cs evar: csvar ?> <?cs /escape ?> Lvar:<?cs escape: "html" ?> <?cs lvar: csvar ?> <?cs /escape ?> Nested include:<?cs escape: "html" ?> <?cs linclude: "test_escape_include.cs" ?> <?cs /escape ?> End Nested include
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace LogIndexer.Analysis.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region license // Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Linq; using System.Collections.Generic; using Boo.Lang.Compiler.TypeSystem.Generics; namespace Boo.Lang.Compiler.TypeSystem.Generics { /// <summary> /// Maps entities onto their constructed counterparts, substituting type arguments for generic parameters. /// </summary> public abstract class GenericMapping : TypeMapper { IDictionary<IGenericParameter, IType> _map = new Dictionary<IGenericParameter, IType>(); IDictionary<IMember, IMember> _memberCache = new Dictionary<IMember, IMember>(); IEntity _constructedOwner = null; IEntity _genericSource = null; /// <summary> /// Constructs a new generic mapping between a generic type and one of its constructed types. /// </summary> public GenericMapping(IType constructedType, IType[] arguments) : this(constructedType.ConstructedInfo.GenericDefinition.GenericInfo.GenericParameters, arguments) { _constructedOwner = constructedType; _genericSource = constructedType.ConstructedInfo.GenericDefinition; } /// <summary> /// Constructs a new generic mapping between a generic method and one of its constructed methods. /// </summary> public GenericMapping(IMethod constructedMethod, IType[] arguments) : this(constructedMethod.ConstructedInfo.GenericDefinition.GenericInfo.GenericParameters, arguments) { _constructedOwner = constructedMethod; _genericSource = constructedMethod.ConstructedInfo.GenericDefinition; } /// <summary> /// Constrcuts a new GenericMapping for a specific mapping of generic parameters to type arguments. /// </summary> /// <param name="parameters">The generic parameters that should be mapped.</param> /// <param name="arguments">The type arguments to map generic parameters to.</param> protected GenericMapping(IGenericParameter[] parameters, IType[] arguments) { for (int i = 0; i < parameters.Length; i++) { _map.Add(parameters[i], arguments[i]); } } /// <summary> /// Maps a type involving generic parameters to the corresponding type after substituting concrete /// arguments for generic parameters. /// </summary> /// <remarks> /// If the source type is a generic parameter, it is mapped to the corresponding argument. /// If the source type is an open generic type using any of the specified generic parameters, it /// is mapped to a closed constructed type based on the specified arguments. /// </remarks> override public IType MapType(IType sourceType) { if (sourceType == _genericSource) return _constructedOwner as IType; IGenericParameter gp = sourceType as IGenericParameter; if (gp != null) { // Map type parameters declared on our source if (_map.ContainsKey(gp)) return _map[gp]; // Map type parameters declared on members of our source (methods / nested types) return GenericsServices.GetGenericParameters(Map(gp.DeclaringEntity))[gp.GenericParameterPosition]; } // TODO: Map nested types // GenericType[of T].NestedType => GenericType[of int].NestedType return base.MapType(sourceType); } /// <summary> /// Maps a type member involving generic arguments to its constructed counterpart, after substituting /// concrete types for generic arguments. /// </summary> public IEntity Map(IEntity source) { if (source == null) return null; // Map generic source to the constructed owner of this mapping if (source == _genericSource) return _constructedOwner; Ambiguous ambiguous = source as Ambiguous; if (ambiguous != null) return MapAmbiguousEntity(ambiguous); IMember member = source as IMember; if (member != null) return MapMember(member); IType type = source as IType; if (type != null) return MapType(type); return source; } private IMember MapMember(IMember source) { // Use cached mapped member if available if (_memberCache.ContainsKey(source)) return _memberCache[source]; // Map members declared on our source if (source.DeclaringType == _genericSource) { return CacheMember(source, CreateMappedMember(source)); } IType[] genArgs = null; // If member is declared on a basetype of our source, that is itself constructed, let its own mapper map it IType declaringType = source.DeclaringType; if (declaringType.ConstructedInfo != null) { var genMethod = source as IConstructedMethodInfo; if (genMethod != null) { genArgs = genMethod.GenericArguments; source = genMethod.GenericDefinition; } source = declaringType.ConstructedInfo.UnMap(source); } IType mappedDeclaringType = MapType(declaringType); if (mappedDeclaringType.ConstructedInfo != null) { source = mappedDeclaringType.ConstructedInfo.Map(source); } if (genArgs != null) source = ((IMethod)source).GenericInfo.ConstructMethod(genArgs.Select(MapType).ToArray()); return source; } abstract protected IMember CreateMappedMember(IMember source); public IConstructor Map(IConstructor source) { return (IConstructor)Map((IEntity)source); } public IMethod Map(IMethod source) { return (IMethod)Map((IEntity)source); } public IField Map(IField source) { return (IField)Map((IEntity)source); } public IProperty Map(IProperty source) { return (IProperty)Map((IEntity)source); } public IEvent Map(IEvent source) { return (IEvent)Map((IEntity)source); } internal IGenericParameter MapGenericParameter(IGenericParameter source) { return Cache<IGenericParameter>(source, new GenericMappedTypeParameter(TypeSystemServices, source, this)); } private IEntity MapAmbiguousEntity(Ambiguous source) { // Map each individual entity in the ambiguous list return new Ambiguous(Array.ConvertAll<IEntity, IEntity>(source.Entities, Map)); } /// <summary> /// Gets the method from which the specified method was mapped. /// </summary> public virtual IMember UnMap(IMember mapped) { foreach (KeyValuePair<IMember, IMember> kvp in _memberCache) { if (kvp.Value == mapped) return kvp.Key; } return null; } private IMember CacheMember(IMember source, IMember mapped) { _memberCache[source] = mapped; return mapped; } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using GzsTool.Core.Common; using GzsTool.Core.Common.Interfaces; using GzsTool.Core.Utility; namespace GzsTool.Core.Qar { [XmlType("Entry", Namespace = "Qar")] public class QarEntry { [XmlAttribute("Hash")] public ulong Hash { get; set; } [XmlAttribute("Key")] public uint Key { get; set; } [XmlAttribute("FilePath")] public string FilePath { get; set; } [XmlAttribute("Compressed")] public bool Compressed { get; set; } [XmlAttribute("MetaFlag")] public bool MetaFlag { get; set; } [XmlIgnore] public bool FileNameFound { get; set; } [XmlIgnore] public uint UncompressedSize { get; private set; } [XmlIgnore] public uint CompressedSize { get; private set; } [XmlIgnore] public long DataOffset { get; set; } public bool ShouldSerializeHash() { return FileNameFound == false; } public bool ShouldSerializeKey() { return Key != 0; } public bool ShouldSerializeMetaFlag() { return MetaFlag; } public void CalculateHash() { if (Hash == 0) { Hash = Hashing.HashFileNameWithExtension(FilePath); } else { DebugAssertHashMatches(); } if (MetaFlag) { Hash = Hash | Hashing.MetaFlag; } } [Conditional("DEBUG")] private void DebugAssertHashMatches() { ulong newHash = Hashing.HashFileNameWithExtension(FilePath); if (Hash != newHash) { Debug.WriteLine("Hash mismatch '{0}' {1:x}!={2:x}", FilePath, newHash, Hash); } } public void Read(BinaryReader reader) { const uint xorMask1 = 0x41441043; const uint xorMask2 = 0x11C22050; const uint xorMask3 = 0xD05608C3; const uint xorMask4 = 0x532C7319; uint hashLow = reader.ReadUInt32() ^ xorMask1; uint hashHigh = reader.ReadUInt32() ^ xorMask1; Hash = (ulong)hashHigh << 32 | hashLow; MetaFlag = (Hash & Hashing.MetaFlag) > 0; UncompressedSize = reader.ReadUInt32() ^ xorMask2; CompressedSize = reader.ReadUInt32() ^ xorMask3; Compressed = UncompressedSize != CompressedSize; uint md51 = reader.ReadUInt32() ^ xorMask4; uint md52 = reader.ReadUInt32() ^ xorMask1; uint md53 = reader.ReadUInt32() ^ xorMask1; uint md54 = reader.ReadUInt32() ^ xorMask2; string filePath; FileNameFound = Hashing.TryGetFileNameFromHash(Hash, out filePath); FilePath = filePath; DataOffset = reader.BaseStream.Position; } public FileDataStreamContainer Export(Stream input) { FileDataStreamContainer fileDataStreamContainer = new FileDataStreamContainer { DataStream = ReadDataLazy(input), FileName = Hashing.NormalizeFilePath(FilePath) }; return fileDataStreamContainer; } private Func<Stream> ReadDataLazy(Stream input) { return () => { lock (input) { return ReadData(input); } }; } private Stream ReadData(Stream input) { input.Position = DataOffset; BinaryReader reader = new BinaryReader(input, Encoding.Default, true); byte[] data = reader.ReadBytes((int)UncompressedSize); Decrypt1(data, hashLow: (uint) (Hash & 0xFFFFFFFF)); uint magicEntry = BitConverter.ToUInt32(data, 0); if (magicEntry == 0xA0F8EFE6) { const int headerSize = 8; Key = BitConverter.ToUInt32(data, 4); UncompressedSize -= headerSize; byte[] newData = new byte[UncompressedSize]; Array.Copy(data, headerSize, newData, 0, UncompressedSize); Decrypt2(newData, Key); data = newData; } else if (magicEntry == 0xE3F8EFE6) { const int headerSize = 16; Key = BitConverter.ToUInt32(data, 4); UncompressedSize -= headerSize; byte[] newData = new byte[UncompressedSize]; Array.Copy(data, headerSize, newData, 0, UncompressedSize); Decrypt2(newData, Key); data = newData; } if (Compressed) { data = Compression.Uncompress(data); } return new MemoryStream(data); } private void Decrypt1(byte[] sectionData, uint hashLow) { // TODO: Use a ulong array instead. uint[] decryptionTable = { 0xBB8ADEDB, 0x65229958, 0x08453206, 0x88121302, 0x4C344955, 0x2C02F10C, 0x4887F823, 0xF3818583, //0x40C90FDB, //0x3FC90FDB, //0x3F490FDB, //0x3EA2F983, //0x3C8EFA35, //0x42652EE0, //0x40C90FDB, //0x3FC90FDB, //0x3F490FDB, //0x3EA2F983, //0x3C8EFA35, //0x42652EE0 }; int blocks = sectionData.Length / sizeof(ulong); for (int i = 0; i < blocks; i++) { int offset1 = i * sizeof(ulong); int offset2 = i * sizeof(ulong) + sizeof(uint); int index = (int)(2 * ((hashLow + offset1 / 11) % 4)); uint u1 = BitConverter.ToUInt32(sectionData, offset1) ^ decryptionTable[index]; uint u2 = BitConverter.ToUInt32(sectionData, offset2) ^ decryptionTable[index + 1]; Buffer.BlockCopy(BitConverter.GetBytes(u1), 0, sectionData, offset1, sizeof(uint)); Buffer.BlockCopy(BitConverter.GetBytes(u2), 0, sectionData, offset2, sizeof(uint)); } int remaining = sectionData.Length % sizeof(ulong); for (int i = 0; i < remaining; i++) { int offset = blocks * sizeof(long) + i * sizeof(byte); int index = (int)(2 * ((hashLow + (offset - (offset % sizeof(long))) / 11) % 4)); int decryptionIndex = offset % sizeof(long); uint xorMask = decryptionIndex < 4 ? decryptionTable[index] : decryptionTable[index + 1]; byte xorMaskByte = (byte)((xorMask >> (8 * decryptionIndex)) & 0xff); byte b1 = (byte)(sectionData[offset] ^ xorMaskByte); sectionData[offset] = b1; } } private unsafe void Decrypt2(byte[] input, uint key) { int size = input.Length; uint currentKey = key | ((key ^ 25974) << 16); byte[] output = input.ToArray(); fixed (byte* pDestBase = output, pSrcBase = input) { uint* pDest = (uint*)pDestBase; uint* pSrc = (uint*)pSrcBase; uint i = 278 * key; for (; size >= 64; size -= 64) { uint j = 16; do { *pDest = currentKey ^ *pSrc; currentKey = i + 48828125 * currentKey; --j; pDest++; pSrc++; } while (j > 0); } for (; size >= 16; pSrc += 4) { *pDest = currentKey ^ *pSrc; uint v7 = i + 48828125 * currentKey; *(pDest + 1) = v7 ^ *(pSrc + 1); uint v8 = i + 48828125 * v7; *(pDest + 2) = v8 ^ *(pSrc + 2); uint v9 = i + 48828125 * v8; *(pDest + 3) = v9 ^ *(pSrc + 3); currentKey = i + 48828125 * v9; size -= 16; pDest += 4; } for (; size >= 4; pSrc++) { *pDest = currentKey ^ *pSrc; currentKey = i + 48828125 * currentKey; size -= 4; pDest++; } } Buffer.BlockCopy(output, 0, input, 0, input.Length); } public void Write(Stream output, IDirectory inputDirectory) { const ulong xorMask1Long = 0x4144104341441043; const uint xorMask1 = 0x41441043; const uint xorMask2 = 0x11C22050; const uint xorMask3 = 0xD05608C3; const uint xorMask4 = 0x532C7319; byte[] data = inputDirectory.ReadFile(Hashing.NormalizeFilePath(FilePath)); byte[] hash = Hashing.Md5Hash(data); uint uncompressedSize = (uint)data.Length; uint compressedSize; if (Compressed) { data = Compression.Compress(data); compressedSize = (uint) data.Length; } else { compressedSize = uncompressedSize; } Decrypt1(data, hashLow: (uint)(Hash & 0xFFFFFFFF)); BinaryWriter writer = new BinaryWriter(output, Encoding.Default, true); writer.Write(Hash ^ xorMask1Long); writer.Write(compressedSize ^ xorMask2); writer.Write(uncompressedSize ^ xorMask3); writer.Write(BitConverter.ToUInt32(hash, 0) ^ xorMask4); writer.Write(BitConverter.ToUInt32(hash, 4) ^ xorMask1); writer.Write(BitConverter.ToUInt32(hash, 8) ^ xorMask1); writer.Write(BitConverter.ToUInt32(hash, 12) ^ xorMask2); // TODO: Maybe reencrypt the lua files. writer.Write(data); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PolymorphismOperations operations. /// </summary> internal partial class PolymorphismOperations : IServiceOperations<AzureCompositeModel>, IPolymorphismOperations { /// <summary> /// Initializes a new instance of the PolymorphismOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PolymorphismOperations(AzureCompositeModel client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<FishInner>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<FishInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<FishInner>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(FishInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } if (complexBody != null) { complexBody.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(FishInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } if (complexBody != null) { complexBody.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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.Text; using Xunit; namespace System.Diagnostics.Tests { public partial class FileVersionInfoTest : FileCleanupTestBase { private const string TestAssemblyFileName = "System.Diagnostics.FileVersionInfo.TestAssembly.dll"; private const string TestCsFileName = "Assembly1.cs"; private const string TestNotFoundFileName = "notfound.dll"; [Fact] public void FileVersionInfo_CustomManagedAssembly() { // Assembly1.dll VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), new MyFVI() { Comments = "Have you played a Contoso amusement device today?", CompanyName = "The name of the company.", FileBuildPart = 2, FileDescription = "My File", FileMajorPart = 4, FileMinorPart = 3, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), FilePrivatePart = 1, FileVersion = "4.3.2.1", InternalName = TestAssemblyFileName, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = GetFileVersionLanguage(0x0000), LegalCopyright = "Copyright, you betcha!", LegalTrademarks = "TM", OriginalFilename = TestAssemblyFileName, PrivateBuild = "", ProductBuildPart = 3, ProductMajorPart = 1, ProductMinorPart = 2, ProductName = "The greatest product EVER", ProductPrivatePart = 0, ProductVersion = "1.2.3-beta.4", SpecialBuild = "", }); } [Fact] public void FileVersionInfo_EmptyFVI() { // Assembly1.cs VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), new MyFVI() { Comments = null, CompanyName = null, FileBuildPart = 0, FileDescription = null, FileMajorPart = 0, FileMinorPart = 0, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), FilePrivatePart = 0, FileVersion = null, InternalName = null, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = null, LegalCopyright = null, LegalTrademarks = null, OriginalFilename = null, PrivateBuild = null, ProductBuildPart = 0, ProductMajorPart = 0, ProductMinorPart = 0, ProductName = null, ProductPrivatePart = 0, ProductVersion = null, SpecialBuild = null, }); } [Fact] public void FileVersionInfo_CurrentDirectory_FileNotFound() { Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(Directory.GetCurrentDirectory())); } [Fact] public void FileVersionInfo_NonExistentFile_FileNotFound() { Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestNotFoundFileName))); } // Additional Tests Wanted: // [] File exists but we don't have permission to read it // [] DLL has unknown codepage info // [] DLL language/codepage is 8-hex-digits (locale > 0x999) (different codepath) private void VerifyVersionInfo(string filePath, MyFVI expected) { FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(filePath); Assert.Equal(expected.Comments, fvi.Comments); Assert.Equal(expected.CompanyName, fvi.CompanyName); Assert.Equal(expected.FileBuildPart, fvi.FileBuildPart); Assert.Equal(expected.FileDescription, fvi.FileDescription); Assert.Equal(expected.FileMajorPart, fvi.FileMajorPart); Assert.Equal(expected.FileMinorPart, fvi.FileMinorPart); Assert.Equal(expected.FileName, fvi.FileName); Assert.Equal(expected.FilePrivatePart, fvi.FilePrivatePart); Assert.Equal(expected.FileVersion, fvi.FileVersion); Assert.Equal(expected.InternalName, fvi.InternalName); Assert.Equal(expected.IsDebug, fvi.IsDebug); Assert.Equal(expected.IsPatched, fvi.IsPatched); Assert.Equal(expected.IsPrivateBuild, fvi.IsPrivateBuild); Assert.Equal(expected.IsPreRelease, fvi.IsPreRelease); Assert.Equal(expected.IsSpecialBuild, fvi.IsSpecialBuild); Assert.Contains(fvi.Language, new[] { expected.Language, expected.Language2 }); Assert.Equal(expected.LegalCopyright, fvi.LegalCopyright); Assert.Equal(expected.LegalTrademarks, fvi.LegalTrademarks); Assert.Equal(expected.OriginalFilename, fvi.OriginalFilename); Assert.Equal(expected.PrivateBuild, fvi.PrivateBuild); Assert.Equal(expected.ProductBuildPart, fvi.ProductBuildPart); Assert.Equal(expected.ProductMajorPart, fvi.ProductMajorPart); Assert.Equal(expected.ProductMinorPart, fvi.ProductMinorPart); Assert.Equal(expected.ProductName, fvi.ProductName); Assert.Equal(expected.ProductPrivatePart, fvi.ProductPrivatePart); Assert.Equal(expected.ProductVersion, fvi.ProductVersion); Assert.Equal(expected.SpecialBuild, fvi.SpecialBuild); //ToString string nl = Environment.NewLine; Assert.Equal("File: " + fvi.FileName + nl + "InternalName: " + fvi.InternalName + nl + "OriginalFilename: " + fvi.OriginalFilename + nl + "FileVersion: " + fvi.FileVersion + nl + "FileDescription: " + fvi.FileDescription + nl + "Product: " + fvi.ProductName + nl + "ProductVersion: " + fvi.ProductVersion + nl + "Debug: " + fvi.IsDebug.ToString() + nl + "Patched: " + fvi.IsPatched.ToString() + nl + "PreRelease: " + fvi.IsPreRelease.ToString() + nl + "PrivateBuild: " + fvi.IsPrivateBuild.ToString() + nl + "SpecialBuild: " + fvi.IsSpecialBuild.ToString() + nl + "Language: " + fvi.Language + nl, fvi.ToString()); } internal class MyFVI { public string Comments; public string CompanyName; public int FileBuildPart; public string FileDescription; public int FileMajorPart; public int FileMinorPart; public string FileName; public int FilePrivatePart; public string FileVersion; public string InternalName; public bool IsDebug; public bool IsPatched; public bool IsPrivateBuild; public bool IsPreRelease; public bool IsSpecialBuild; public string Language; public string Language2; public string LegalCopyright; public string LegalTrademarks; public string OriginalFilename; public string PrivateBuild; public int ProductBuildPart; public int ProductMajorPart; public int ProductMinorPart; public string ProductName; public int ProductPrivatePart; public string ProductVersion; public string SpecialBuild; } static string GetUnicodeString(String str) { if (str == null) return "<null>"; StringBuilder buffer = new StringBuilder(); buffer.Append("\""); for (int i = 0; i < str.Length; i++) { char ch = str[i]; if (ch == '\r') { buffer.Append("\\r"); } else if (ch == '\n') { buffer.Append("\\n"); } else if (ch == '\\') { buffer.Append("\\"); } else if (ch == '\"') { buffer.Append("\\\""); } else if (ch == '\'') { buffer.Append("\\\'"); } else if (ch < 0x20 || ch >= 0x7f) { buffer.Append("\\u"); buffer.Append(((int)ch).ToString("x4")); } else { buffer.Append(ch); } } buffer.Append("\""); return (buffer.ToString()); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.IO; using System.Reflection; using System.Xml; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.LayoutRenderers; using NLog.Time; using System.Collections.ObjectModel; #if SILVERLIGHT // ReSharper disable once RedundantUsingDirective using System.Windows; #endif /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// </summary> ///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks> public class XmlLoggingConfiguration : LoggingConfiguration { #region private fields private readonly Dictionary<string, bool> fileMustAutoReloadLookup = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private string originalFileName; private ConfigurationItemFactory ConfigurationItemFactory { get { return ConfigurationItemFactory.Default; } } #endregion #region contructors /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration(string fileName) { using (XmlReader reader = CreateFileReader(fileName)) { this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(string fileName, bool ignoreErrors) { using (XmlReader reader = CreateFileReader(fileName)) { this.Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Create XML reader for (xml config) file. /// </summary> /// <param name="fileName">filepath</param> /// <returns>reader or <c>null</c> if filename is empty.</returns> private static XmlReader CreateFileReader(string fileName) { if (!string.IsNullOrEmpty(fileName)) { fileName = fileName.Trim(); #if __ANDROID__ //suport loading config from special assets folder in nlog.config const string assetsPrefix = "assets/"; if (fileName.StartsWith(assetsPrefix, StringComparison.OrdinalIgnoreCase)) { //remove prefix fileName = fileName.Substring(assetsPrefix.Length); Stream stream = Android.App.Application.Context.Assets.Open(fileName); return XmlReader.Create(stream); } #endif return XmlReader.Create(fileName); } return null; } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> public XmlLoggingConfiguration(XmlReader reader, string fileName) { this.Initialize(reader, fileName, false); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors) { this.Initialize(reader, fileName, ignoreErrors); } #if !SILVERLIGHT /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, ignoreErrors); } } #endif #endregion #region public properties #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet. /// </summary> public bool? InitializeSucceeded { get; private set; } /// <summary> /// Gets or sets a value indicating whether all of the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get { return this.fileMustAutoReloadLookup.Values.All(mustAutoReload => mustAutoReload); } set { var autoReloadFiles = this.fileMustAutoReloadLookup.Keys.ToList(); foreach (string nextFile in autoReloadFiles) this.fileMustAutoReloadLookup[nextFile] = value; } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { return this.fileMustAutoReloadLookup.Where(entry => entry.Value).Select(entry => entry.Key); } } #endregion #region public methods /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { return new XmlLoggingConfiguration(this.originalFileName); } #endregion private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Remove all spaces, also in between text. /// </summary> /// <param name="s">text</param> /// <returns>text without spaces</returns> /// <remarks>Tabs and other whitespace is not removed!</remarks> private static string CleanSpaces(string s) { s = s.Replace(" ", string.Empty); // get rid of the whitespace return s; } /// <summary> /// Remove the namespace (before :) /// </summary> /// <example> /// x:a, will be a /// </example> /// <param name="attributeValue"></param> /// <returns></returns> private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue == null) { return null; } int p = attributeValue.IndexOf(':'); if (p < 0) { return attributeValue; } return attributeValue.Substring(p + 1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")] private static Target WrapWithAsyncTargetWrapper(Target target) { var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize(XmlReader reader, string fileName, bool ignoreErrors) { try { InitializeSucceeded = null; reader.MoveToContent(); var content = new NLogXmlElement(reader); if (fileName != null) { this.originalFileName = fileName; this.ParseTopLevel(content, fileName, autoReloadDefault: false); InternalLogger.Info("Configured from an XML element in {0}...", fileName); } else { this.ParseTopLevel(content, null, autoReloadDefault: false); } InitializeSucceeded = true; this.CheckUnusedTargets(); } catch (Exception exception) { InitializeSucceeded = false; if (exception.MustBeRethrownImmediately()) { throw; } var configurationException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception); InternalLogger.Error(configurationException, "Error in Parsing Configuration File."); if (!ignoreErrors) { if (exception.MustBeRethrown()) { throw configurationException; } } } } /// <summary> /// Checks whether unused targets exist. If found any, just write an internal log at Warn level. /// <remarks>If initializing not started or failed, then checking process will be canceled</remarks> /// </summary> private void CheckUnusedTargets() { if (this.InitializeSucceeded == null) { InternalLogger.Warn("Unused target checking is canceled -> initialize not started yet."); return; } if (!this.InitializeSucceeded.Value) { InternalLogger.Warn("Unused target checking is canceled -> initialize not succeeded."); return; } ReadOnlyCollection<Target> configuredNamedTargets = this.ConfiguredNamedTargets; //assign to variable because `ConfiguredNamedTargets` computes a new list every time. InternalLogger.Debug("Unused target checking is started... Rule Count: {0}, Target Count: {1}", this.LoggingRules.Count, configuredNamedTargets.Count); HashSet<string> targetNamesAtRules = new HashSet<string>(this.LoggingRules.SelectMany(r => r.Targets).Select(t => t.Name)); int unusedCount = 0; configuredNamedTargets.ToList().ForEach((target) => { if (!targetNamesAtRules.Contains(target.Name)) { InternalLogger.Warn("Unused target detected. Add a rule for this target to the configuration. TargetName: {0}", target.Name); unusedCount++; } }); InternalLogger.Debug("Unused target checking is completed. Total Rule Count: {0}, Total Target Count: {1}, Unused Target Count: {2}", this.LoggingRules.Count, configuredNamedTargets.Count, unusedCount); } private void ConfigureFromFile(string fileName, bool autoReloadDefault) { if (!this.fileMustAutoReloadLookup.ContainsKey(GetFileLookupKey(fileName))) this.ParseTopLevel(new NLogXmlElement(fileName), fileName, autoReloadDefault); } #region parse methods /// <summary> /// Parse the root /// </summary> /// <param name="content"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseTopLevel(NLogXmlElement content, string filePath, bool autoReloadDefault) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "CONFIGURATION": this.ParseConfigurationElement(content, filePath, autoReloadDefault); break; case "NLOG": this.ParseNLogElement(content, filePath, autoReloadDefault); break; } } /// <summary> /// Parse {configuration} xml element. /// </summary> /// <param name="configurationElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseConfigurationElement(NLogXmlElement configurationElement, string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); var nlogElements = configurationElement.Elements("nlog").ToList(); foreach (var nlogElement in nlogElements) { this.ParseNLogElement(nlogElement, filePath, autoReloadDefault); } } /// <summary> /// Parse {NLog} xml element. /// </summary> /// <param name="nlogElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseNLogElement(NLogXmlElement nlogElement, string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false)) { this.DefaultCultureInfo = CultureInfo.InvariantCulture; } #pragma warning disable 618 this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false); #pragma warning restore 618 bool autoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", autoReloadDefault); if (filePath != null) this.fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload; LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions); InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole); InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError); InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile); InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name)); LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name)); var children = nlogElement.Children.ToList(); //first load the extensions, as the can be used in other elements (targets etc) var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase)).ToList(); foreach (var extensionsChild in extensionsChilds) { this.ParseExtensionsElement(extensionsChild, Path.GetDirectoryName(filePath)); } //parse all other direct elements foreach (var child in children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "EXTENSIONS": //already parsed break; case "INCLUDE": this.ParseIncludeElement(child, Path.GetDirectoryName(filePath), autoReloadDefault: autoReload); break; case "APPENDERS": case "TARGETS": this.ParseTargetsElement(child); break; case "VARIABLE": this.ParseVariableElement(child); break; case "RULES": this.ParseRulesElement(child, this.LoggingRules); break; case "TIME": this.ParseTimeElement(child); break; default: InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName); break; } } } /// <summary> /// Parse {Rules} xml element /// </summary> /// <param name="rulesElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); var loggerElements = rulesElement.Elements("logger").ToList(); foreach (var loggerElement in loggerElements) { this.ParseLoggerElement(loggerElement, rulesCollection); } } /// <summary> /// Parse {Logger} xml element /// </summary> /// <param name="loggerElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection) { loggerElement.AssertName("logger"); var namePattern = loggerElement.GetOptionalAttribute("name", "*"); var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true); if (!enabled) { InternalLogger.Debug("The logger named '{0}' are disabled"); return; } var rule = new LoggingRule(); string appendTo = loggerElement.GetOptionalAttribute("appendTo", null); if (appendTo == null) { appendTo = loggerElement.GetOptionalAttribute("writeTo", null); } rule.LoggerNamePattern = namePattern; if (appendTo != null) { foreach (string t in appendTo.Split(',')) { string targetName = t.Trim(); Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { throw new NLogConfigurationException("Target " + targetName + " not found."); } } } rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false); string levelString; if (loggerElement.AttributeValues.TryGetValue("level", out levelString)) { LogLevel level = LogLevel.FromString(levelString); rule.EnableLoggingForLevel(level); } else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString)) { levelString = CleanSpaces(levelString); string[] tokens = levelString.Split(','); foreach (string token in tokens) { if (!string.IsNullOrEmpty(token)) { LogLevel level = LogLevel.FromString(token); rule.EnableLoggingForLevel(level); } } } else { int minLevel = 0; int maxLevel = LogLevel.MaxLevel.Ordinal; string minLevelString; string maxLevelString; if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString)) { minLevel = LogLevel.FromString(minLevelString).Ordinal; } if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString)) { maxLevel = LogLevel.FromString(maxLevelString).Ordinal; } for (int i = minLevel; i <= maxLevel; ++i) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } var children = loggerElement.Children.ToList(); foreach (var child in children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "FILTERS": this.ParseFilters(rule, child); break; case "LOGGER": this.ParseLoggerElement(child, rule.ChildRules); break; } } rulesCollection.Add(rule); } private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement) { filtersElement.AssertName("filters"); var children = filtersElement.Children.ToList(); foreach (var filterElement in children) { string name = filterElement.LocalName; Filter filter = this.ConfigurationItemFactory.Filters.CreateInstance(name); this.ConfigureObjectFromAttributes(filter, filterElement, false); rule.Filters.Add(filter); } } private void ParseVariableElement(NLogXmlElement variableElement) { variableElement.AssertName("variable"); string name = variableElement.GetRequiredAttribute("name"); string value = this.ExpandSimpleVariables(variableElement.GetRequiredAttribute("value")); this.Variables[name] = value; } private void ParseTargetsElement(NLogXmlElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false); NLogXmlElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>(); var children = targetsElement.Children.ToList(); foreach (var targetElement in children) { string name = targetElement.LocalName; string typeAttributeVal = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null)); switch (name.ToUpper(CultureInfo.InvariantCulture)) { case "DEFAULT-WRAPPER": defaultWrapperElement = targetElement; break; case "DEFAULT-TARGET-PARAMETERS": if (typeAttributeVal == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } typeNameToDefaultTargetParameters[typeAttributeVal] = targetElement; break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (typeAttributeVal == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(typeAttributeVal); NLogXmlElement defaults; if (typeNameToDefaultTargetParameters.TryGetValue(typeAttributeVal, out defaults)) { this.ParseTargetElement(newTarget, defaults); } this.ParseTargetElement(newTarget, targetElement); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}", newTarget); AddTarget(newTarget.Name, newTarget); break; } } } private void ParseTargetElement(Target target, NLogXmlElement targetElement) { var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; this.ConfigureObjectFromAttributes(target, targetElement, true); var children = targetElement.Children.ToList(); foreach (var childElement in children) { string name = childElement.LocalName; if (compound != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } continue; } } if (wrapper != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } wrapper.WrappedTarget = newTarget; continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } if (wrapper.WrappedTarget != null) { throw new NLogConfigurationException("Wrapped target already defined."); } wrapper.WrappedTarget = newTarget; } continue; } } this.SetPropertyFromElement(target, childElement); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")] private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); var addElements = extensionsElement.Elements("add").ToList(); foreach (var addElement in addElements) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if SILVERLIGHT && !WINDOWS_PHONE var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Error(exception, "Error loading extensions."); if (exception.MustBeRethrown()) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if SILVERLIGHT && !WINDOWS_PHONE var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Error(exception, "Error loading extensions."); if (exception.MustBeRethrown()) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } } } } private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory, bool autoReloadDefault) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredAttribute("file"); try { newFileName = this.ExpandSimpleVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); if (baseDirectory != null) { newFileName = Path.Combine(baseDirectory, newFileName); } #if SILVERLIGHT newFileName = newFileName.Replace("\\", "/"); if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null) #else if (File.Exists(newFileName)) #endif { InternalLogger.Debug("Including file '{0}'", newFileName); this.ConfigureFromFile(newFileName, autoReloadDefault); } else { throw new FileNotFoundException("Included file not found: " + newFileName); } } catch (Exception exception) { InternalLogger.Error(exception, "Error when including '{0}'.", newFileName); if (exception.MustBeRethrown()) { throw; } if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false)) { return; } throw new NLogConfigurationException("Error when including: " + newFileName, exception); } } private void ParseTimeElement(NLogXmlElement timeElement) { timeElement.AssertName("time"); string type = timeElement.GetRequiredAttribute("type"); TimeSource newTimeSource = this.ConfigurationItemFactory.TimeSources.CreateInstance(type); this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true); InternalLogger.Info("Selecting time source {0}", newTimeSource); TimeSource.Current = newTimeSource; } #endregion private static string GetFileLookupKey(string fileName) { #if SILVERLIGHT // file names are relative to XAP return fileName; #else return Path.GetFullPath(fileName); #endif } private void SetPropertyFromElement(object o, NLogXmlElement element) { if (this.AddArrayItemFromElement(o, element)) { return; } if (this.SetLayoutFromElement(o, element)) { return; } PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandSimpleVariables(element.Value), this.ConfigurationItemFactory); } private bool AddArrayItemFromElement(object o, NLogXmlElement element) { string name = element.LocalName; PropertyInfo propInfo; if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo)) { return false; } Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); object arrayItem = FactoryHelper.CreateInstance(elementType); this.ConfigureObjectFromAttributes(arrayItem, element, true); this.ConfigureObjectFromElement(arrayItem, element); propertyValue.Add(arrayItem); return true; } return false; } private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType) { var attributeValues = element.AttributeValues.ToList(); foreach (var kvp in attributeValues) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase)) { continue; } PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandSimpleVariables(childValue), this.ConfigurationItemFactory); } } private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement) { PropertyInfo targetPropertyInfo; string name = layoutElement.LocalName; // if property exists if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo)) { // and is a Layout if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType)) { string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null)); // and 'type' attribute has been specified if (layoutTypeName != null) { // configure it from current element Layout layout = this.ConfigurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName)); this.ConfigureObjectFromAttributes(layout, layoutElement, true); this.ConfigureObjectFromElement(layout, layoutElement); targetPropertyInfo.SetValue(o, layout, null); return true; } } } return false; } private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element) { var children = element.Children.ToList(); foreach (var child in children) { this.SetPropertyFromElement(targetObject, child); } } private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters) { string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type")); Target wrapperTargetInstance = this.ConfigurationItemFactory.Targets.CreateInstance(wrapperType); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } this.ParseTargetElement(wrapperTargetInstance, defaultParameters); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper."); } } wtb.WrappedTarget = t; wrapperTargetInstance.Name = t.Name; t.Name = t.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name); return wrapperTargetInstance; } /// <summary> /// Replace a simple variable with a value. The orginal value is removed and thus we cannot redo this in a later stage. /// /// Use for that: <see cref="VariableLayoutRenderer"/> /// </summary> /// <param name="input"></param> /// <returns></returns> private string ExpandSimpleVariables(string input) { string output = input; // TODO - make this case-insensitive, will probably require a different approach var variables = this.Variables.ToList(); foreach (var kvp in variables) { var layout = kvp.Value; //this value is set from xml and that's a string. Because of that, we can use SimpleLayout here. if (layout != null) output = output.Replace("${" + kvp.Key + "}", layout.OriginalText); } return output; } } }
// ------------------------------------------------------------------------ // <copyright file="PrintHelper.cs" company="Mark Pitman"> // Copyright 2007 - 2013 Mark Pitman // // 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> // ------------------------------------------------------------------------ // namespace Pitman.Printing { using System; using System.Drawing; using System.Drawing.Printing; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Forms; public class PrintHelper { #region Fields private readonly PrintDocument printDoc; private Image controlImage; private PrintDirection currentDir; private Point lastPrintPosition; private int nodeHeight; private int pageNumber; private int scrollBarHeight; private int scrollBarWidth; private string title = string.Empty; #endregion #region Constructors and Destructors public PrintHelper() { this.lastPrintPosition = new Point(0, 0); this.printDoc = new PrintDocument(); this.printDoc.BeginPrint += this.PrintDocBeginPrint; this.printDoc.PrintPage += this.PrintDocPrintPage; this.printDoc.EndPrint += this.PrintDocEndPrint; } #endregion #region Enums private enum PrintDirection { Horizontal, Vertical } #endregion #region Public Methods and Operators /// <summary> /// Shows a PrintPreview dialog displaying the Tree control passed in. /// </summary> /// <param name="tree">TreeView to print preview</param> /// <param name="reportTitle"></param> public void PrintPreviewTree(TreeView tree, string reportTitle) { this.title = reportTitle; this.PrepareTreeImage(tree); var pp = new PrintPreviewDialog { Document = this.printDoc }; pp.Show(); } /// <summary> /// Prints a tree /// </summary> /// <param name="tree">TreeView to print</param> /// <param name="reportTitle"></param> public void PrintTree(TreeView tree, string reportTitle) { this.title = reportTitle; this.PrepareTreeImage(tree); var pd = new PrintDialog { Document = this.printDoc }; if (pd.ShowDialog() == DialogResult.OK) { this.printDoc.Print(); } } #endregion #region Methods [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int width, int height); [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam); // Returns an image of the specified width and height, of a control represented by handle. private Image GetImage(IntPtr handle, int width, int height) { IntPtr screenDC = GetDC(IntPtr.Zero); IntPtr hbm = CreateCompatibleBitmap(screenDC, width, height); Image image = Image.FromHbitmap(hbm); Graphics g = Graphics.FromImage(image); IntPtr hdc = g.GetHdc(); SendMessage(handle, 0x0318 /*WM_PRINTCLIENT*/, hdc, (0x00000010 | 0x00000004 | 0x00000002)); g.ReleaseHdc(hdc); ReleaseDC(IntPtr.Zero, screenDC); return image; } /// <summary> /// Gets an image that shows the entire tree, not just what is visible on the form /// </summary> /// <param name="tree"></param> private void PrepareTreeImage(TreeView tree) { this.scrollBarWidth = tree.Width - tree.ClientSize.Width; this.scrollBarHeight = tree.Height - tree.ClientSize.Height; tree.Nodes[0].EnsureVisible(); int height = tree.Nodes[0].Bounds.Height; this.nodeHeight = height; int width = tree.Nodes[0].Bounds.Right; TreeNode node = tree.Nodes[0].NextVisibleNode; while (node != null) { height += node.Bounds.Height; if (node.Bounds.Right > width) { width = node.Bounds.Right; } node = node.NextVisibleNode; } //keep track of the original tree settings int tempHeight = tree.Height; int tempWidth = tree.Width; BorderStyle tempBorder = tree.BorderStyle; bool tempScrollable = tree.Scrollable; TreeNode selectedNode = tree.SelectedNode; //setup the tree to take the snapshot tree.SelectedNode = null; DockStyle tempDock = tree.Dock; tree.Height = height + this.scrollBarHeight; tree.Width = width + this.scrollBarWidth; tree.BorderStyle = BorderStyle.None; tree.Dock = DockStyle.None; //get the image of the tree // .Net 2.0 supports drawing controls onto bitmaps natively now // However, the full tree didn't get drawn when I tried it, so I am // sticking with the P/Invoke calls //_controlImage = new Bitmap(height, width); //Bitmap bmp = _controlImage as Bitmap; //tree.DrawToBitmap(bmp, tree.Bounds); this.controlImage = this.GetImage(tree.Handle, tree.Width, tree.Height); //reset the tree to its original settings tree.BorderStyle = tempBorder; tree.Width = tempWidth; tree.Height = tempHeight; tree.Dock = tempDock; tree.Scrollable = tempScrollable; tree.SelectedNode = selectedNode; //give the window time to update Application.DoEvents(); } private void PrintDocEndPrint(object sender, PrintEventArgs e) { this.controlImage.Dispose(); } private void PrintDocBeginPrint(object sender, PrintEventArgs e) { this.lastPrintPosition = new Point(0, 0); this.currentDir = PrintDirection.Horizontal; this.pageNumber = 0; } private void PrintDocPrintPage(object sender, PrintPageEventArgs e) { this.pageNumber++; Graphics g = e.Graphics; var sourceRect = new Rectangle(this.lastPrintPosition, e.MarginBounds.Size); Rectangle destRect = e.MarginBounds; if ((sourceRect.Height % this.nodeHeight) > 0) { sourceRect.Height -= (sourceRect.Height % this.nodeHeight); } g.DrawImage(this.controlImage, destRect, sourceRect, GraphicsUnit.Pixel); //check to see if we need more pages if ((this.controlImage.Height - this.scrollBarHeight) > sourceRect.Bottom || (this.controlImage.Width - this.scrollBarWidth) > sourceRect.Right) { //need more pages e.HasMorePages = true; } if (this.currentDir == PrintDirection.Horizontal) { if (sourceRect.Right < (this.controlImage.Width - this.scrollBarWidth)) { //still need to print horizontally this.lastPrintPosition.X += (sourceRect.Width + 1); } else { this.lastPrintPosition.X = 0; this.lastPrintPosition.Y += (sourceRect.Height + 1); this.currentDir = PrintDirection.Vertical; } } else if (this.currentDir == PrintDirection.Vertical && sourceRect.Right < (this.controlImage.Width - this.scrollBarWidth)) { this.currentDir = PrintDirection.Horizontal; this.lastPrintPosition.X += (sourceRect.Width + 1); } else { this.lastPrintPosition.Y += (sourceRect.Height + 1); } //print footer Brush brush = new SolidBrush(Color.Black); string footer = this.pageNumber.ToString(NumberFormatInfo.CurrentInfo); var f = new Font(FontFamily.GenericSansSerif, 10f); SizeF footerSize = g.MeasureString(footer, f); var pageBottomCenter = new PointF(x: e.PageBounds.Width / 2, y: e.MarginBounds.Bottom + ((e.PageBounds.Bottom - e.MarginBounds.Bottom) / 2)); var footerLocation = new PointF( pageBottomCenter.X - (footerSize.Width / 2), pageBottomCenter.Y - (footerSize.Height / 2)); g.DrawString(footer, f, brush, footerLocation); //print header if (this.pageNumber == 1 && this.title.Length > 0) { var headerFont = new Font(FontFamily.GenericSansSerif, 24f, FontStyle.Bold, GraphicsUnit.Point); SizeF headerSize = g.MeasureString(this.title, headerFont); var headerLocation = new PointF(x: e.MarginBounds.Left, y: ((e.MarginBounds.Top - e.PageBounds.Top) / 2) - (headerSize.Height / 2)); g.DrawString(this.title, headerFont, brush, headerLocation); } } #endregion //External function declarations } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderCreateType6 { private const int MinAsmName = 1; private const int MaxAsmName = 260; private const int MinModName = 1; private const int MaxModName = 260; private const int MinTypName = 1; private const int MaxTypName = 1024; private const int NumLoops = 5; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private TypeAttributes[] _typesPos = new TypeAttributes[17] { TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.AnsiClass | TypeAttributes.NestedPublic, TypeAttributes.AutoClass | TypeAttributes.NestedPublic, TypeAttributes.AutoLayout | TypeAttributes.NestedPublic, TypeAttributes.BeforeFieldInit | TypeAttributes.NestedPublic, TypeAttributes.Class | TypeAttributes.NestedPublic, TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.ExplicitLayout | TypeAttributes.NestedPublic, TypeAttributes.Import | TypeAttributes.NestedPublic, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.Sealed | TypeAttributes.NestedPublic, TypeAttributes.SequentialLayout | TypeAttributes.NestedPublic, TypeAttributes.Serializable | TypeAttributes.NestedPublic, TypeAttributes.SpecialName | TypeAttributes.NestedPublic, TypeAttributes.StringFormatMask | TypeAttributes.NestedPublic, TypeAttributes.UnicodeClass | TypeAttributes.NestedPublic, TypeAttributes.VisibilityMask, }; [Fact] public void TestDefineNestedType() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName); for (int i = 0; i < NumLoops; i++) { nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (_generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestWithEmbeddedNullsInName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; for (int i = 0; i < NumLoops; i++) { modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + _generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + _generator.GetString(true, MinTypName, MaxTypName / 4); typeBuilder = modBuilder.DefineType(typeName); // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } } [Fact] public void TestWithTypeAttributes() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; TypeAttributes typeAttrib = (TypeAttributes)0; int i = 0; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName, typeAttrib); for (i = 0; i < _typesPos.Length; i++) { typeAttrib = _typesPos[i]; nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (_generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, _typesPos[i], typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, _typesPos[i], typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestWithNullparentType() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName); nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic, null, new Type[1] { typeof(IComparable) }); newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestThrowsExceptionForNullName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = null; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentNullException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class, typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); newType = typeBuilder.CreateTypeInfo().AsType(); }); } [Fact] public void TestThrowsExceptionForEmptyName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = string.Empty; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class, typeBuilder.GetType(), new Type[1] { typeof(IComparable) }); newType = typeBuilder.CreateTypeInfo().AsType(); }); } public ModuleBuilder CreateModule(string assemblyName, string modName) { AssemblyName asmName; AssemblyBuilder asmBuilder; ModuleBuilder modBuilder; // create the dynamic module asmName = new AssemblyName(assemblyName); asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, "Module1"); return modBuilder; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Management.Automation; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Text; using TaskScheduler; namespace Microsoft.PowerShell.ScheduledJob { /// <summary> /// Managed code class to provide Windows Task Scheduler functionality for /// scheduled jobs. /// </summary> internal sealed class ScheduledJobWTS : IDisposable { #region Private Members private ITaskService _taskScheduler; private ITaskFolder _iRootFolder; private const short WTSSunday = 0x01; private const short WTSMonday = 0x02; private const short WTSTuesday = 0x04; private const short WTSWednesday = 0x08; private const short WTSThursday = 0x10; private const short WTSFriday = 0x20; private const short WTSSaturday = 0x40; // Task Scheduler folders for PowerShell scheduled job tasks. private const string TaskSchedulerWindowsFolder = @"\Microsoft\Windows"; private const string ScheduledJobSubFolder = @"PowerShell\ScheduledJobs"; private const string ScheduledJobTasksRootFolder = @"\Microsoft\Windows\PowerShell\ScheduledJobs"; // Define a single Action Id since PowerShell Scheduled Job tasks will have only one action. private const string ScheduledJobTaskActionId = "StartPowerShellJob"; #endregion #region Constructors public ScheduledJobWTS() { // Create the Windows Task Scheduler object. _taskScheduler = (ITaskService)new TaskScheduler.TaskScheduler(); // Connect the task scheduler object to the local machine // using the current user security token. _taskScheduler.Connect(null, null, null, null); // Get or create the root folder in Task Scheduler for PowerShell scheduled jobs. _iRootFolder = GetRootFolder(); } #endregion #region Public Methods /// <summary> /// Retrieves job triggers from WTS with provided task Id. /// </summary> /// <param name="taskId">Task Id.</param> /// <exception cref="ScheduledJobException">Task not found.</exception> /// <returns>ScheduledJobTriggers.</returns> public Collection<ScheduledJobTrigger> GetJobTriggers( string taskId) { if (string.IsNullOrEmpty(taskId)) { throw new PSArgumentException("taskId"); } ITaskDefinition iTaskDefinition = FindTask(taskId); Collection<ScheduledJobTrigger> jobTriggers = new Collection<ScheduledJobTrigger>(); ITriggerCollection iTriggerCollection = iTaskDefinition.Triggers; if (iTriggerCollection != null) { foreach (ITrigger iTrigger in iTriggerCollection) { ScheduledJobTrigger jobTrigger = CreateJobTrigger(iTrigger); if (jobTrigger == null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.UnknownTriggerType, taskId, iTrigger.Id); throw new ScheduledJobException(msg); } jobTriggers.Add(jobTrigger); } } return jobTriggers; } /// <summary> /// Retrieves options for the provided task Id. /// </summary> /// <param name="taskId">Task Id.</param> /// <exception cref="ScheduledJobException">Task not found.</exception> /// <returns>ScheduledJobOptions.</returns> public ScheduledJobOptions GetJobOptions( string taskId) { if (string.IsNullOrEmpty(taskId)) { throw new PSArgumentException("taskId"); } ITaskDefinition iTaskDefinition = FindTask(taskId); return CreateJobOptions(iTaskDefinition); } /// <summary> /// Returns a boolean indicating whether the job/task is enabled /// in the Task Scheduler. /// </summary> /// <param name="taskId"></param> /// <returns></returns> public bool GetTaskEnabled( string taskId) { if (string.IsNullOrEmpty(taskId)) { throw new PSArgumentException("taskId"); } ITaskDefinition iTaskDefinition = FindTask(taskId); return iTaskDefinition.Settings.Enabled; } /// <summary> /// Creates a new task in WTS with information from ScheduledJobDefinition. /// </summary> /// <param name="definition">ScheduledJobDefinition.</param> public void CreateTask( ScheduledJobDefinition definition) { if (definition == null) { throw new PSArgumentNullException("definition"); } // Create task definition ITaskDefinition iTaskDefinition = _taskScheduler.NewTask(0); // Add task options. AddTaskOptions(iTaskDefinition, definition.Options); // Add task triggers. foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers) { AddTaskTrigger(iTaskDefinition, jobTrigger); } // Add task action. AddTaskAction(iTaskDefinition, definition); // Create a security descriptor for the current user so that only the user // (and Local System account) can see/access the registered task. string startSddl = "D:P(A;;GA;;;SY)(A;;GA;;;BA)"; // DACL Allow Generic Access to System and BUILTIN\Administrators. System.Security.Principal.SecurityIdentifier userSid = System.Security.Principal.WindowsIdentity.GetCurrent().User; CommonSecurityDescriptor SDesc = new CommonSecurityDescriptor(false, false, startSddl); SDesc.DiscretionaryAcl.AddAccess(AccessControlType.Allow, userSid, 0x10000000, InheritanceFlags.None, PropagationFlags.None); string sddl = SDesc.GetSddlForm(AccessControlSections.All); // Register this new task with the Task Scheduler. if (definition.Credential == null) { // Register task to run as currently logged on user. _iRootFolder.RegisterTaskDefinition( definition.Name, iTaskDefinition, (int)_TASK_CREATION.TASK_CREATE, null, // User name null, // Password _TASK_LOGON_TYPE.TASK_LOGON_S4U, sddl); } else { // Register task to run under provided user account/credentials. _iRootFolder.RegisterTaskDefinition( definition.Name, iTaskDefinition, (int)_TASK_CREATION.TASK_CREATE, definition.Credential.UserName, GetCredentialPassword(definition.Credential), _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD, sddl); } } /// <summary> /// Removes the WTS task for this ScheduledJobDefinition. /// Throws error if one or more instances of this task are running. /// Force parameter will stop all running instances and remove task. /// </summary> /// <param name="definition">ScheduledJobDefinition.</param> /// <param name="force">Force running instances to stop and remove task.</param> public void RemoveTask( ScheduledJobDefinition definition, bool force = false) { if (definition == null) { throw new PSArgumentNullException("definition"); } RemoveTaskByName(definition.Name, force, false); } /// <summary> /// Removes a Task Scheduler task from the PowerShell/ScheduledJobs folder /// based on a task name. /// </summary> /// <param name="taskName">Task Scheduler task name.</param> /// <param name="force">Force running instances to stop and remove task.</param> /// <param name="firstCheckForTask">First check for existence of task.</param> public void RemoveTaskByName( string taskName, bool force, bool firstCheckForTask) { // Get registered task. IRegisteredTask iRegisteredTask = null; try { iRegisteredTask = _iRootFolder.GetTask(taskName); } catch (System.IO.DirectoryNotFoundException) { if (!firstCheckForTask) { throw; } } catch (System.IO.FileNotFoundException) { if (!firstCheckForTask) { throw; } } if (iRegisteredTask == null) { return; } // Check to see if any instances of this job/task is running. IRunningTaskCollection iRunningTasks = iRegisteredTask.GetInstances(0); if (iRunningTasks.Count > 0) { if (!force) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CannotRemoveTaskRunningInstance, taskName); throw new ScheduledJobException(msg); } // Stop all running tasks. iRegisteredTask.Stop(0); } // Remove task. _iRootFolder.DeleteTask(taskName, 0); } /// <summary> /// Starts task running from Task Scheduler. /// </summary> /// <param name="definition">ScheduledJobDefinition.</param> /// <exception cref="System.IO.DirectoryNotFoundException"></exception> /// <exception cref="System.IO.FileNotFoundException"></exception> public void RunTask( ScheduledJobDefinition definition) { // Get registered task. IRegisteredTask iRegisteredTask = _iRootFolder.GetTask(definition.Name); // Run task. iRegisteredTask.Run(null); } /// <summary> /// Updates an existing task in WTS with information from /// ScheduledJobDefinition. /// </summary> /// <param name="definition">ScheduledJobDefinition.</param> public void UpdateTask( ScheduledJobDefinition definition) { if (definition == null) { throw new PSArgumentNullException("definition"); } // Get task to update. ITaskDefinition iTaskDefinition = FindTask(definition.Name); // Replace options. AddTaskOptions(iTaskDefinition, definition.Options); // Set enabled state. iTaskDefinition.Settings.Enabled = definition.Enabled; // Replace triggers. iTaskDefinition.Triggers.Clear(); foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers) { AddTaskTrigger(iTaskDefinition, jobTrigger); } // Replace action. iTaskDefinition.Actions.Clear(); AddTaskAction(iTaskDefinition, definition); // Register updated task. if (definition.Credential == null) { // Register task to run as currently logged on user. _iRootFolder.RegisterTaskDefinition( definition.Name, iTaskDefinition, (int)_TASK_CREATION.TASK_UPDATE, null, // User name null, // Password _TASK_LOGON_TYPE.TASK_LOGON_S4U, null); } else { // Register task to run under provided user account/credentials. _iRootFolder.RegisterTaskDefinition( definition.Name, iTaskDefinition, (int)_TASK_CREATION.TASK_UPDATE, definition.Credential.UserName, GetCredentialPassword(definition.Credential), _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD, null); } } #endregion #region Private Methods /// <summary> /// Creates a new WTS trigger based on the provided ScheduledJobTrigger object /// and adds it to the provided ITaskDefinition object. /// </summary> /// <param name="iTaskDefinition">ITaskDefinition.</param> /// <param name="jobTrigger">ScheduledJobTrigger.</param> private void AddTaskTrigger( ITaskDefinition iTaskDefinition, ScheduledJobTrigger jobTrigger) { ITrigger iTrigger = null; switch (jobTrigger.Frequency) { case TriggerFrequency.AtStartup: { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT); IBootTrigger iBootTrigger = iTrigger as IBootTrigger; Debug.Assert(iBootTrigger != null); iBootTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } break; case TriggerFrequency.AtLogon: { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); ILogonTrigger iLogonTrigger = iTrigger as ILogonTrigger; Debug.Assert(iLogonTrigger != null); iLogonTrigger.UserId = ScheduledJobTrigger.IsAllUsers(jobTrigger.User) ? null : jobTrigger.User; iLogonTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } break; case TriggerFrequency.Once: { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); ITimeTrigger iTimeTrigger = iTrigger as ITimeTrigger; Debug.Assert(iTimeTrigger != null); iTimeTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); // Time trigger repetition. if (jobTrigger.RepetitionInterval != null && jobTrigger.RepetitionDuration != null) { iTimeTrigger.Repetition.Interval = ConvertTimeSpanToWTSString(jobTrigger.RepetitionInterval.Value); if (jobTrigger.RepetitionDuration.Value == TimeSpan.MaxValue) { iTimeTrigger.Repetition.StopAtDurationEnd = false; } else { iTimeTrigger.Repetition.StopAtDurationEnd = true; iTimeTrigger.Repetition.Duration = ConvertTimeSpanToWTSString(jobTrigger.RepetitionDuration.Value); } } iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At); iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } break; case TriggerFrequency.Daily: { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); IDailyTrigger iDailyTrigger = iTrigger as IDailyTrigger; Debug.Assert(iDailyTrigger != null); iDailyTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); iDailyTrigger.DaysInterval = (short)jobTrigger.Interval; iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At); iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } break; case TriggerFrequency.Weekly: { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); IWeeklyTrigger iWeeklyTrigger = iTrigger as IWeeklyTrigger; Debug.Assert(iWeeklyTrigger != null); iWeeklyTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); iWeeklyTrigger.WeeksInterval = (short)jobTrigger.Interval; iWeeklyTrigger.DaysOfWeek = ConvertDaysOfWeekToMask(jobTrigger.DaysOfWeek); iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At); iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); iTrigger.Enabled = jobTrigger.Enabled; } break; } } /// <summary> /// Creates a ScheduledJobTrigger object based on a provided WTS ITrigger. /// </summary> /// <param name="iTrigger">ITrigger.</param> /// <returns>ScheduledJobTrigger.</returns> private ScheduledJobTrigger CreateJobTrigger( ITrigger iTrigger) { ScheduledJobTrigger rtnJobTrigger = null; if (iTrigger is IBootTrigger) { IBootTrigger iBootTrigger = (IBootTrigger)iTrigger; rtnJobTrigger = ScheduledJobTrigger.CreateAtStartupTrigger( ParseWTSTime(iBootTrigger.Delay), ConvertStringId(iBootTrigger.Id), iBootTrigger.Enabled); } else if (iTrigger is ILogonTrigger) { ILogonTrigger iLogonTrigger = (ILogonTrigger)iTrigger; rtnJobTrigger = ScheduledJobTrigger.CreateAtLogOnTrigger( iLogonTrigger.UserId, ParseWTSTime(iLogonTrigger.Delay), ConvertStringId(iLogonTrigger.Id), iLogonTrigger.Enabled); } else if (iTrigger is ITimeTrigger) { ITimeTrigger iTimeTrigger = (ITimeTrigger)iTrigger; TimeSpan repInterval = ParseWTSTime(iTimeTrigger.Repetition.Interval); TimeSpan repDuration = (repInterval != TimeSpan.Zero && iTimeTrigger.Repetition.StopAtDurationEnd == false) ? TimeSpan.MaxValue : ParseWTSTime(iTimeTrigger.Repetition.Duration); rtnJobTrigger = ScheduledJobTrigger.CreateOnceTrigger( DateTime.Parse(iTimeTrigger.StartBoundary, CultureInfo.InvariantCulture), ParseWTSTime(iTimeTrigger.RandomDelay), repInterval, repDuration, ConvertStringId(iTimeTrigger.Id), iTimeTrigger.Enabled); } else if (iTrigger is IDailyTrigger) { IDailyTrigger iDailyTrigger = (IDailyTrigger)iTrigger; rtnJobTrigger = ScheduledJobTrigger.CreateDailyTrigger( DateTime.Parse(iDailyTrigger.StartBoundary, CultureInfo.InvariantCulture), (Int32)iDailyTrigger.DaysInterval, ParseWTSTime(iDailyTrigger.RandomDelay), ConvertStringId(iDailyTrigger.Id), iDailyTrigger.Enabled); } else if (iTrigger is IWeeklyTrigger) { IWeeklyTrigger iWeeklyTrigger = (IWeeklyTrigger)iTrigger; rtnJobTrigger = ScheduledJobTrigger.CreateWeeklyTrigger( DateTime.Parse(iWeeklyTrigger.StartBoundary, CultureInfo.InvariantCulture), (Int32)iWeeklyTrigger.WeeksInterval, ConvertMaskToDaysOfWeekArray(iWeeklyTrigger.DaysOfWeek), ParseWTSTime(iWeeklyTrigger.RandomDelay), ConvertStringId(iWeeklyTrigger.Id), iWeeklyTrigger.Enabled); } return rtnJobTrigger; } private void AddTaskOptions( ITaskDefinition iTaskDefinition, ScheduledJobOptions jobOptions) { iTaskDefinition.Settings.DisallowStartIfOnBatteries = !jobOptions.StartIfOnBatteries; iTaskDefinition.Settings.StopIfGoingOnBatteries = jobOptions.StopIfGoingOnBatteries; iTaskDefinition.Settings.WakeToRun = jobOptions.WakeToRun; iTaskDefinition.Settings.RunOnlyIfIdle = !jobOptions.StartIfNotIdle; iTaskDefinition.Settings.IdleSettings.StopOnIdleEnd = jobOptions.StopIfGoingOffIdle; iTaskDefinition.Settings.IdleSettings.RestartOnIdle = jobOptions.RestartOnIdleResume; iTaskDefinition.Settings.IdleSettings.IdleDuration = ConvertTimeSpanToWTSString(jobOptions.IdleDuration); iTaskDefinition.Settings.IdleSettings.WaitTimeout = ConvertTimeSpanToWTSString(jobOptions.IdleTimeout); iTaskDefinition.Settings.Hidden = !jobOptions.ShowInTaskScheduler; iTaskDefinition.Settings.RunOnlyIfNetworkAvailable = !jobOptions.RunWithoutNetwork; iTaskDefinition.Settings.AllowDemandStart = !jobOptions.DoNotAllowDemandStart; iTaskDefinition.Settings.MultipleInstances = ConvertFromMultiInstances(jobOptions.MultipleInstancePolicy); iTaskDefinition.Principal.RunLevel = (jobOptions.RunElevated) ? _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST : _TASK_RUNLEVEL.TASK_RUNLEVEL_LUA; } private ScheduledJobOptions CreateJobOptions( ITaskDefinition iTaskDefinition) { ITaskSettings iTaskSettings = iTaskDefinition.Settings; IPrincipal iPrincipal = iTaskDefinition.Principal; return new ScheduledJobOptions( !iTaskSettings.DisallowStartIfOnBatteries, iTaskSettings.StopIfGoingOnBatteries, iTaskSettings.WakeToRun, !iTaskSettings.RunOnlyIfIdle, iTaskSettings.IdleSettings.StopOnIdleEnd, iTaskSettings.IdleSettings.RestartOnIdle, ParseWTSTime(iTaskSettings.IdleSettings.IdleDuration), ParseWTSTime(iTaskSettings.IdleSettings.WaitTimeout), !iTaskSettings.Hidden, iPrincipal.RunLevel == _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST, !iTaskSettings.RunOnlyIfNetworkAvailable, !iTaskSettings.AllowDemandStart, ConvertToMultiInstances(iTaskSettings)); } private void AddTaskAction( ITaskDefinition iTaskDefinition, ScheduledJobDefinition definition) { IExecAction iExecAction = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction; Debug.Assert(iExecAction != null); iExecAction.Id = ScheduledJobTaskActionId; iExecAction.Path = definition.PSExecutionPath; iExecAction.Arguments = definition.PSExecutionArgs; } /// <summary> /// Gets and returns the unsecured password for the provided /// PSCredential object. /// </summary> /// <param name="credential">PSCredential.</param> /// <returns>Unsecured password string.</returns> private string GetCredentialPassword(PSCredential credential) { if (credential == null) { return null; } IntPtr unmanagedString = IntPtr.Zero; try { unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(credential.Password); return Marshal.PtrToStringUni(unmanagedString); } finally { Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString); } } #endregion #region Private Utility Methods /// <summary> /// Gets the Task Scheduler root folder for Scheduled Jobs or /// creates it if it does not exist. /// </summary> /// <returns>Scheduled Jobs root folder.</returns> private ITaskFolder GetRootFolder() { ITaskFolder iTaskRootFolder = null; try { iTaskRootFolder = _taskScheduler.GetFolder(ScheduledJobTasksRootFolder); } catch (System.IO.DirectoryNotFoundException) { } catch (System.IO.FileNotFoundException) { // This can be thrown if COM interop tries to load the Microsoft.PowerShell.ScheduledJob // assembly again. } if (iTaskRootFolder == null) { // Create the PowerShell Scheduled Job root folder. ITaskFolder iTSWindowsFolder = _taskScheduler.GetFolder(TaskSchedulerWindowsFolder); iTaskRootFolder = iTSWindowsFolder.CreateFolder(ScheduledJobSubFolder); } return iTaskRootFolder; } /// <summary> /// Finds a task with the provided Task Id and returns it as /// a ITaskDefinition object. /// </summary> /// <param name="taskId">Task Id.</param> /// <returns>ITaskDefinition.</returns> private ITaskDefinition FindTask(string taskId) { try { ITaskFolder iTaskFolder = _taskScheduler.GetFolder(ScheduledJobTasksRootFolder); IRegisteredTask iRegisteredTask = iTaskFolder.GetTask(taskId); return iRegisteredTask.Definition; } catch (System.IO.DirectoryNotFoundException e) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CannotFindTaskId, taskId); throw new ScheduledJobException(msg, e); } } private Int32 ConvertStringId(string triggerId) { Int32 triggerIdVal = 0; try { triggerIdVal = Convert.ToInt32(triggerId); } catch (FormatException) { } catch (OverflowException) { } return triggerIdVal; } /// <summary> /// Helper method to parse a WTS time string and return /// a corresponding TimeSpan object. Note that the /// year and month values are ignored. /// Format: /// "PnYnMnDTnHnMnS" /// "P" - Date separator /// "nY" - year value. /// "nM" - month value. /// "nD" - day value. /// "T" - Time separator /// "nH" - hour value. /// "nM" - minute value. /// "nS" - second value. /// </summary> /// <param name="wtsTime">Formatted time string.</param> /// <returns>TimeSpan.</returns> private TimeSpan ParseWTSTime(string wtsTime) { if (string.IsNullOrEmpty(wtsTime)) { return new TimeSpan(0); } int days = 0; int hours = 0; int minutes = 0; int seconds = 0; int indx = 0; int length = wtsTime.Length; StringBuilder str = new StringBuilder(); try { while (indx != length) { char c = wtsTime[indx++]; switch (c) { case 'P': str.Clear(); while (indx != length && wtsTime[indx] != 'T') { char c2 = wtsTime[indx++]; if (c2 == 'Y') { // Ignore year value. str.Clear(); } else if (c2 == 'M') { // Ignore month value. str.Clear(); } else if (c2 == 'D') { days = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); str.Clear(); } else if (c2 >= '0' && c2 <= '9') { str.Append(c2); } } break; case 'T': str.Clear(); while (indx != length && wtsTime[indx] != 'P') { char c2 = wtsTime[indx++]; if (c2 == 'H') { hours = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); str.Clear(); } else if (c2 == 'M') { minutes = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); str.Clear(); } else if (c2 == 'S') { seconds = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); str.Clear(); } else if (c2 >= '0' && c2 <= '9') { str.Append(c2); } } break; } } } catch (FormatException) { } catch (OverflowException) { } return new TimeSpan(days, hours, minutes, seconds); } /// <summary> /// Creates WTS formatted time string based on TimeSpan parameter. /// </summary> /// <param name="time">TimeSpan.</param> /// <returns>WTS time string.</returns> internal static string ConvertTimeSpanToWTSString(TimeSpan time) { return string.Format( CultureInfo.InvariantCulture, "P{0}DT{1}H{2}M{3}S", time.Days, time.Hours, time.Minutes, time.Seconds); } /// <summary> /// Converts DateTime to string for WTS. /// </summary> /// <param name="dt">DateTime.</param> /// <returns>DateTime string.</returns> internal static string ConvertDateTimeToString(DateTime? dt) { if (dt == null) { return string.Empty; } else { return dt.Value.ToString("s", CultureInfo.InvariantCulture); } } /// <summary> /// Returns a bitmask representing days of week as /// required by Windows Task Scheduler API. /// </summary> /// <param name="daysOfWeek">Array of DayOfWeek.</param> /// <returns>WTS days of week mask.</returns> internal static short ConvertDaysOfWeekToMask(IEnumerable<DayOfWeek> daysOfWeek) { short rtnValue = 0; foreach (DayOfWeek day in daysOfWeek) { switch (day) { case DayOfWeek.Sunday: rtnValue |= WTSSunday; break; case DayOfWeek.Monday: rtnValue |= WTSMonday; break; case DayOfWeek.Tuesday: rtnValue |= WTSTuesday; break; case DayOfWeek.Wednesday: rtnValue |= WTSWednesday; break; case DayOfWeek.Thursday: rtnValue |= WTSThursday; break; case DayOfWeek.Friday: rtnValue |= WTSFriday; break; case DayOfWeek.Saturday: rtnValue |= WTSSaturday; break; } } return rtnValue; } /// <summary> /// Converts WTS days of week mask to an array of DayOfWeek type. /// </summary> /// <param name="mask">WTS days of week mask.</param> /// <returns>Days of week as List.</returns> private List<DayOfWeek> ConvertMaskToDaysOfWeekArray(short mask) { List<DayOfWeek> daysOfWeek = new List<DayOfWeek>(); if ((mask & WTSSunday) != 0) { daysOfWeek.Add(DayOfWeek.Sunday); } if ((mask & WTSMonday) != 0) { daysOfWeek.Add(DayOfWeek.Monday); } if ((mask & WTSTuesday) != 0) { daysOfWeek.Add(DayOfWeek.Tuesday); } if ((mask & WTSWednesday) != 0) { daysOfWeek.Add(DayOfWeek.Wednesday); } if ((mask & WTSThursday) != 0) { daysOfWeek.Add(DayOfWeek.Thursday); } if ((mask & WTSFriday) != 0) { daysOfWeek.Add(DayOfWeek.Friday); } if ((mask & WTSSaturday) != 0) { daysOfWeek.Add(DayOfWeek.Saturday); } return daysOfWeek; } private TaskMultipleInstancePolicy ConvertToMultiInstances( ITaskSettings iTaskSettings) { switch (iTaskSettings.MultipleInstances) { case _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW: return TaskMultipleInstancePolicy.IgnoreNew; case _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL: return TaskMultipleInstancePolicy.Parallel; case _TASK_INSTANCES_POLICY.TASK_INSTANCES_QUEUE: return TaskMultipleInstancePolicy.Queue; case _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING: return TaskMultipleInstancePolicy.StopExisting; } Debug.Assert(false); return TaskMultipleInstancePolicy.None; } private _TASK_INSTANCES_POLICY ConvertFromMultiInstances( TaskMultipleInstancePolicy jobPolicies) { switch (jobPolicies) { case TaskMultipleInstancePolicy.IgnoreNew: return _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; case TaskMultipleInstancePolicy.Parallel: return _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL; case TaskMultipleInstancePolicy.Queue: return _TASK_INSTANCES_POLICY.TASK_INSTANCES_QUEUE; case TaskMultipleInstancePolicy.StopExisting: return _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING; default: return _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; } } #endregion #region IDisposable /// <summary> /// Dispose. /// </summary> public void Dispose() { // Release reference to Task Scheduler object so that the COM // object can be released. _iRootFolder = null; _taskScheduler = null; GC.SuppressFinalize(this); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Util.Fst { /* * 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 DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; // TODO: merge with PagedBytes, except PagedBytes doesn't // let you read while writing which FST needs internal class BytesStore : DataOutput { private readonly List<byte[]> Blocks = new List<byte[]>(); private readonly int BlockSize; private readonly int blockBits; private readonly int BlockMask; private byte[] Current; private int NextWrite; public BytesStore(int blockBits) { this.blockBits = blockBits; BlockSize = 1 << blockBits; BlockMask = BlockSize - 1; NextWrite = BlockSize; } /// <summary> /// Pulls bytes from the provided IndexInput. </summary> public BytesStore(DataInput @in, long numBytes, int maxBlockSize) { int blockSize = 2; int blockBits = 1; while (blockSize < numBytes && blockSize < maxBlockSize) { blockSize *= 2; blockBits++; } this.blockBits = blockBits; this.BlockSize = blockSize; this.BlockMask = blockSize - 1; long left = numBytes; while (left > 0) { int chunk = (int)Math.Min(blockSize, left); byte[] block = new byte[chunk]; @in.ReadBytes(block, 0, block.Length); Blocks.Add(block); left -= chunk; } // So .getPosition still works NextWrite = Blocks[Blocks.Count - 1].Length; } /// <summary> /// Absolute write byte; you must ensure dest is < max /// position written so far. /// </summary> public virtual void WriteByte(int dest, byte b) { int blockIndex = dest >> blockBits; byte[] block = Blocks[blockIndex]; block[dest & BlockMask] = b; } public override void WriteByte(byte b) { if (NextWrite == BlockSize) { Current = new byte[BlockSize]; Blocks.Add(Current); NextWrite = 0; } Current[NextWrite++] = b; } public override void WriteBytes(byte[] b, int offset, int len) { while (len > 0) { int chunk = BlockSize - NextWrite; if (len <= chunk) { System.Buffer.BlockCopy(b, offset, Current, NextWrite, len); NextWrite += len; break; } else { if (chunk > 0) { Array.Copy(b, offset, Current, NextWrite, chunk); offset += chunk; len -= chunk; } Current = new byte[BlockSize]; Blocks.Add(Current); NextWrite = 0; } } } internal virtual int BlockBits { get { return blockBits; } } /// <summary> /// Absolute writeBytes without changing the current /// position. Note: this cannot "grow" the bytes, so you /// must only call it on already written parts. /// </summary> internal virtual void WriteBytes(long dest, byte[] b, int offset, int len) { //System.out.println(" BS.writeBytes dest=" + dest + " offset=" + offset + " len=" + len); Debug.Assert(dest + len <= Position, "dest=" + dest + " pos=" + Position + " len=" + len); // Note: weird: must go "backwards" because copyBytes // calls us with overlapping src/dest. If we // go forwards then we overwrite bytes before we can // copy them: /* int blockIndex = dest >> blockBits; int upto = dest & blockMask; byte[] block = blocks.get(blockIndex); while (len > 0) { int chunk = blockSize - upto; System.out.println(" cycle chunk=" + chunk + " len=" + len); if (len <= chunk) { System.arraycopy(b, offset, block, upto, len); break; } else { System.arraycopy(b, offset, block, upto, chunk); offset += chunk; len -= chunk; blockIndex++; block = blocks.get(blockIndex); upto = 0; } } */ long end = dest + len; int blockIndex = (int)(end >> blockBits); int downTo = (int)(end & BlockMask); if (downTo == 0) { blockIndex--; downTo = BlockSize; } byte[] block = Blocks[blockIndex]; while (len > 0) { //System.out.println(" cycle downTo=" + downTo + " len=" + len); if (len <= downTo) { //System.out.println(" final: offset=" + offset + " len=" + len + " dest=" + (downTo-len)); Array.Copy(b, offset, block, downTo - len, len); break; } else { len -= downTo; //System.out.println(" partial: offset=" + (offset + len) + " len=" + downTo + " dest=0"); Array.Copy(b, offset + len, block, 0, downTo); blockIndex--; block = Blocks[blockIndex]; downTo = BlockSize; } } } /// <summary> /// Absolute copy bytes self to self, without changing the /// position. Note: this cannot "grow" the bytes, so must /// only call it on already written parts. /// </summary> public virtual void CopyBytes(long src, long dest, int len) { //System.out.println("BS.copyBytes src=" + src + " dest=" + dest + " len=" + len); Debug.Assert(src < dest); // Note: weird: must go "backwards" because copyBytes // calls us with overlapping src/dest. If we // go forwards then we overwrite bytes before we can // copy them: /* int blockIndex = src >> blockBits; int upto = src & blockMask; byte[] block = blocks.get(blockIndex); while (len > 0) { int chunk = blockSize - upto; System.out.println(" cycle: chunk=" + chunk + " len=" + len); if (len <= chunk) { writeBytes(dest, block, upto, len); break; } else { writeBytes(dest, block, upto, chunk); blockIndex++; block = blocks.get(blockIndex); upto = 0; len -= chunk; dest += chunk; } } */ long end = src + len; int blockIndex = (int)(end >> blockBits); int downTo = (int)(end & BlockMask); if (downTo == 0) { blockIndex--; downTo = BlockSize; } byte[] block = Blocks[blockIndex]; while (len > 0) { //System.out.println(" cycle downTo=" + downTo); if (len <= downTo) { //System.out.println(" finish"); WriteBytes(dest, block, downTo - len, len); break; } else { //System.out.println(" partial"); len -= downTo; WriteBytes(dest + len, block, 0, downTo); blockIndex--; block = Blocks[blockIndex]; downTo = BlockSize; } } } /// <summary> /// Writes an int at the absolute position without /// changing the current pointer. /// </summary> public virtual void WriteInt(long pos, int value) { int blockIndex = (int)(pos >> blockBits); int upto = (int)(pos & BlockMask); byte[] block = Blocks[blockIndex]; int shift = 24; for (int i = 0; i < 4; i++) { block[upto++] = (byte)(value >> shift); shift -= 8; if (upto == BlockSize) { upto = 0; blockIndex++; block = Blocks[blockIndex]; } } } /// <summary> /// Reverse from srcPos, inclusive, to destPos, inclusive. </summary> public virtual void Reverse(long srcPos, long destPos) { Debug.Assert(srcPos < destPos); Debug.Assert(destPos < Position); //System.out.println("reverse src=" + srcPos + " dest=" + destPos); int srcBlockIndex = (int)(srcPos >> blockBits); int src = (int)(srcPos & BlockMask); byte[] srcBlock = Blocks[srcBlockIndex]; int destBlockIndex = (int)(destPos >> blockBits); int dest = (int)(destPos & BlockMask); byte[] destBlock = Blocks[destBlockIndex]; //System.out.println(" srcBlock=" + srcBlockIndex + " destBlock=" + destBlockIndex); int limit = (int)(destPos - srcPos + 1) / 2; for (int i = 0; i < limit; i++) { //System.out.println(" cycle src=" + src + " dest=" + dest); byte b = srcBlock[src]; srcBlock[src] = destBlock[dest]; destBlock[dest] = b; src++; if (src == BlockSize) { srcBlockIndex++; srcBlock = Blocks[srcBlockIndex]; //System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock); src = 0; } dest--; if (dest == -1) { destBlockIndex--; destBlock = Blocks[destBlockIndex]; //System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock); dest = BlockSize - 1; } } } public virtual void SkipBytes(int len) { while (len > 0) { int chunk = BlockSize - NextWrite; if (len <= chunk) { NextWrite += len; break; } else { len -= chunk; Current = new byte[BlockSize]; Blocks.Add(Current); NextWrite = 0; } } } public virtual long Position { get { return ((long)Blocks.Count - 1) * BlockSize + NextWrite; } } /// <summary> /// Pos must be less than the max position written so far! /// Ie, you cannot "grow" the file with this! /// </summary> public virtual void Truncate(long newLen) { Debug.Assert(newLen <= Position); Debug.Assert(newLen >= 0); int blockIndex = (int)(newLen >> blockBits); NextWrite = (int)(newLen & BlockMask); if (NextWrite == 0) { blockIndex--; NextWrite = BlockSize; } Blocks.GetRange(blockIndex + 1, Blocks.Count).Clear(); if (newLen == 0) { Current = null; } else { Current = Blocks[blockIndex]; } Debug.Assert(newLen == Position); } public virtual void Finish() { if (Current != null) { byte[] lastBuffer = new byte[NextWrite]; Array.Copy(Current, 0, lastBuffer, 0, NextWrite); Blocks[Blocks.Count - 1] = lastBuffer; Current = null; } } /// <summary> /// Writes all of our bytes to the target <seealso cref="DataOutput"/>. </summary> public virtual void WriteTo(DataOutput @out) { foreach (byte[] block in Blocks) { @out.WriteBytes(block, 0, block.Length); } } public virtual FST.BytesReader ForwardReader { get { if (Blocks.Count == 1) { return new ForwardBytesReader(Blocks[0]); } return new ForwardBytesReaderAnonymousInner(this); } } private class ForwardBytesReaderAnonymousInner : FST.BytesReader { private readonly BytesStore OuterInstance; public ForwardBytesReaderAnonymousInner(BytesStore outerInstance) { this.OuterInstance = outerInstance; nextRead = outerInstance.BlockSize; } private sbyte[] Current; private int nextBuffer; private int nextRead; public override byte ReadByte() { if (nextRead == OuterInstance.BlockSize) { OuterInstance.Current = OuterInstance.Blocks[nextBuffer++]; nextRead = 0; } return OuterInstance.Current[nextRead++]; } public override void SkipBytes(int count) { Position = OuterInstance.Position + count; } public override void ReadBytes(byte[] b, int offset, int len) { while (len > 0) { int chunkLeft = OuterInstance.BlockSize - nextRead; if (len <= chunkLeft) { Array.Copy(OuterInstance.Current, nextRead, b, offset, len); nextRead += len; break; } else { if (chunkLeft > 0) { Array.Copy(OuterInstance.Current, nextRead, b, offset, chunkLeft); offset += chunkLeft; len -= chunkLeft; } OuterInstance.Current = OuterInstance.Blocks[nextBuffer++]; nextRead = 0; } } } public override long Position { get { return ((long)nextBuffer - 1) * OuterInstance.BlockSize + nextRead; } set { int bufferIndex = (int)(value >> OuterInstance.blockBits); nextBuffer = bufferIndex + 1; OuterInstance.Current = OuterInstance.Blocks[bufferIndex]; nextRead = (int)(value & OuterInstance.BlockMask); Debug.Assert(this.Position == value, "pos=" + value + " getPos()=" + this.Position); } } public override bool Reversed() { return false; } } public virtual FST.BytesReader ReverseReader { get { return GetReverseReader(true); } } internal virtual FST.BytesReader GetReverseReader(bool allowSingle) { if (allowSingle && Blocks.Count == 1) { return new ReverseBytesReader(Blocks[0]); } return new ReverseBytesReaderAnonymousInner(this); } private class ReverseBytesReaderAnonymousInner : FST.BytesReader { private readonly BytesStore OuterInstance; public ReverseBytesReaderAnonymousInner(BytesStore outerInstance) { this.OuterInstance = outerInstance; Current = outerInstance.Blocks.Count == 0 ? null : outerInstance.Blocks[0]; nextBuffer = -1; nextRead = 0; } private byte[] Current; private int nextBuffer; private int nextRead; public override byte ReadByte() { if (nextRead == -1) { Current = OuterInstance.Blocks[nextBuffer--]; nextRead = OuterInstance.BlockSize - 1; } return Current[nextRead--]; } public override void SkipBytes(int count) { Position = Position - count; } public override void ReadBytes(byte[] b, int offset, int len) { for (int i = 0; i < len; i++) { b[offset + i] = ReadByte(); } } public override long Position { get { return ((long)nextBuffer + 1) * OuterInstance.BlockSize + nextRead; } set { // NOTE: a little weird because if you // setPosition(0), the next byte you read is // bytes[0] ... but I would expect bytes[-1] (ie, // EOF)...? int bufferIndex = (int)(value >> OuterInstance.blockBits); nextBuffer = bufferIndex - 1; Current = OuterInstance.Blocks[bufferIndex]; nextRead = (int)(value & OuterInstance.BlockMask); Debug.Assert(this.Position == value, "value=" + value + " this.Position=" + this.Position); } } public override bool Reversed() { return true; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Web.Security; using System.Security.Principal; using System.Web.Profile; namespace Appleseed.Framework.Providers.AppleseedMembershipProvider { /// <summary> /// Appleseed specific membership user class. /// </summary> public class AppleseedUser : MembershipUser, IIdentity { /// <summary> /// Initializes a new instance of the <see cref="AppleseedUser"/> class. /// </summary> /// <param name="providerName">Name of the provider.</param> /// <param name="name">The name.</param> /// <param name="providerUserKey">The provider user key.</param> /// <param name="email">The email.</param> /// <param name="passwordQuestion">The password question.</param> /// <param name="comment">The comment.</param> /// <param name="isApproved">if set to <c>true</c> [is approved].</param> /// <param name="isLockedOut">if set to <c>true</c> [is locked out].</param> /// <param name="creationDate">The creation date.</param> /// <param name="lastLoginDate">The last login date.</param> /// <param name="lastActivityDate">The last activity date.</param> /// <param name="lastPasswordChangeDate">The last password change date.</param> /// <param name="lastLockoutDate">The last lockout date.</param> public AppleseedUser( string providerName, string name, Guid providerUserKey, string email, string passwordQuestion, string comment, bool isApproved, bool isLockedOut, DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate, DateTime lastPasswordChangeDate, DateTime lastLockoutDate ) : base( providerName, name, providerUserKey, email, passwordQuestion, comment, isApproved, isLockedOut, creationDate, lastLoginDate, lastActivityDate, lastPasswordChangeDate, lastLockoutDate ) { } /// <summary> /// Initializes a new instance of the <see cref="AppleseedUser"/> class. /// </summary> /// <param name="name">The name.</param> public AppleseedUser( string name ) : base( Membership.Provider.Name, name, Guid.Empty, string.Empty, string.Empty, string.Empty, true, false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue ) { this.Name = name; } #region IIdentity Members /// <summary> /// Gets the type of authentication used. /// </summary> /// <value></value> /// <returns>The type of authentication used to identify the user.</returns> public string AuthenticationType { get { throw new Exception( "Appleseed." ); } } /// <summary> /// Gets a value that indicates whether the user has been authenticated. /// </summary> /// <value></value> /// <returns>true if the user was authenticated; otherwise, false.</returns> public bool IsAuthenticated { get { return IsOnline; } } #endregion /// <summary> /// Gets or sets application-specific information for the membership user. We hide this property, as it isn't used in Appleseed /// </summary> /// <value></value> /// <returns>Application-specific information for the membership user.</returns> protected new string Comment { get { return base.Comment; } set { base.Comment = value; } } /// <summary> /// Gets the profile. /// </summary> /// <value>The profile.</value> public ProfileBase Profile { get { return ProfileBase.Create( this.UserName ); } } #region Appleseed properties private string name; /// <summary> /// Gets the name of the current user. /// </summary> /// <value></value> /// <returns>The name of the user on whose behalf the code is running.</returns> public string Name { get { return name; } set { name = value; } } /// <summary> /// Gets the Password of the current user. /// </summary> /// <value></value> /// <returns>The name of the user on whose behalf the code is running.</returns> public string Password { get { return this.GetPassword(); } } private string phone; /// <summary> /// Gets or sets the phone. /// </summary> /// <value>The phone.</value> public string Phone { get { return phone; } set { phone = value; } } /// <summary> /// Gets the user identifier from the membership data source for the user. /// </summary> /// <value></value> /// <returns>The user identifier from the membership data source for the user.</returns> public new Guid ProviderUserKey { get { return ( Guid )base.ProviderUserKey; } } private string company; /// <summary> /// Gets or sets the company. /// </summary> /// <value>The company.</value> public string Company { get { return company; } set { company = value; } } private string address; /// <summary> /// Gets or sets the address. /// </summary> /// <value>The address.</value> public string Address { get { return address; } set { address = value; } } private string zip; /// <summary> /// Gets or sets the zip. /// </summary> /// <value>The zip.</value> public string Zip { get { return zip; } set { zip = value; } } private string city; /// <summary> /// Gets or sets the city. /// </summary> /// <value>The city.</value> public string City { get { return city; } set { city = value; } } private string countryID; /// <summary> /// Gets or sets the country ID. /// </summary> /// <value>The country ID.</value> public string CountryID { get { return countryID; } set { countryID = value; } } private int stateID; /// <summary> /// Gets or sets the state ID. /// </summary> /// <value>The state ID.</value> public int StateID { get { return stateID; } set { stateID = value; } } private string fax; /// <summary> /// Gets or sets the fax. /// </summary> /// <value>The fax.</value> public string Fax { get { return fax; } set { fax = value; } } private bool sendNewsletter; /// <summary> /// Gets or sets a value indicating whether the user receives newletters. /// </summary> /// <value><c>true</c> if the user receives newletters; otherwise, <c>false</c>.</value> public bool SendNewsletter { get { return sendNewsletter; } set { sendNewsletter = value; } } private int failedPasswordAttemptCount; /// <summary> /// Gets or sets the FailedPasswordAttemptCount. /// </summary> /// <value>The FailedPasswordAttemptCount.</value> public int FailedPasswordAttemptCount { get { return failedPasswordAttemptCount; } set { failedPasswordAttemptCount = value; } } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CrystalDecisions.Shared; namespace WebApplication2 { /// <summary> /// Summary description for Main. /// </summary> public partial class MainBMgr : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Button lblResME; protected System.Web.UI.WebControls.Button btnContactsReport; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Load_Main(); Session["MgrOption"] = "Budget"; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void Load_Main() { lblContent1.Text="Greetings. This menu enables you to establish and distribute budgets." + " Click on 'Start' to continue."; getProfile(); getBDS(); lblOrg.Text = Session["OrgName"].ToString(); } private void getBDS() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="ams_RetrieveOrgFlagsBDS"; cmd.Parameters.Add("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"BDS"); if (ds.Tables["BDS"].Rows[0][0].ToString() == "0") { Session["BDS"]= 0; } else { Session["BDS"]= 1; } } private void getProfile() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveOrgProfile"; cmd.Parameters.Add("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"OrgProfile"); if (ds.Tables["OrgProfile"].Rows.Count == 0) { setProfile(); } else { Session["ProfilesId"]=ds.Tables["OrgProfile"].Rows[0][0].ToString(); Session["ProfilesName"]=ds.Tables["OrgProfile"].Rows[0][1].ToString(); } } private void setProfile() { Session["CSProfilesAll"]="frmMainBMgr"; Session["Type"]="Producer"; Response.Redirect (strURL + "frmProfilesAll.aspx?"); } protected void btnExit_Click(object sender, System.EventArgs e) { Response.Redirect(strURL + "frmStart.aspx?"); } private void getPeopleId() { Object tmp = new object(); SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "eps_RetrieveUserIdName"; cmd.Parameters.Add ("@UserId",SqlDbType.NVarChar); cmd.Parameters["@UserId"].Value=Session["UserId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"UserPerson"); /*tmp = cmd.ExecuteScalar();*/ Session["PeopleId"] = ds.Tables["UserPerson"].Rows[0][0]; Session["LName"] = ds.Tables["UserPerson"].Rows[0][1]; Session["Fname"] = ds.Tables["UserPerson"].Rows[0][2]; Session["CellPhone"] = ds.Tables["UserPerson"].Rows[0][3]; Session["HomePhone"] = ds.Tables["UserPerson"].Rows[0][4]; Session["WorkPhone"] = ds.Tables["UserPerson"].Rows[0][5]; Session["Address"] = ds.Tables["UserPerson"].Rows[0][6]; Session["Email"] = ds.Tables["UserPerson"].Rows[0][7]; } private void btnPlanReport_Click(object sender, System.EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "OrgId"; discreteval.Value = Session["OrgId"].ToString(); paramField.CurrentValues.Add (discreteval); paramFields.Add (paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptHouseholdRes.rpt"; rpts(); } private void btnContactsReport_Click(object sender, System.EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "OrgId"; discreteval.Value = Session["OrgId"].ToString(); paramField.CurrentValues.Add (discreteval); paramFields.Add (paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptHouseholdContacts.rpt"; rpts(); } private void rpts() { Session["cRG"]="frmMainBMgr"; Response.Redirect (strURL + "frmReportGen.aspx?"); } /*private void getServiceId() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveServiceId"; cmd.Parameters.Add("@OrgId",SqlDbType.NVarChar); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"ServiceId"); if (ds.Tables["ServiceId"].Rows.Count != 0) { Session["ServiceId"]=ds.Tables["ServiceId"].Rows[0][0].ToString(); Session["ServiceName"]="Emergency Management"; } else { issueServiceId(); } } private void issueServiceId() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_AddServiceId"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value= "Emergency Management"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value= Session["OrgId"]; cmd.Parameters.Add ("@ResTypeId",SqlDbType.Int); cmd.Parameters["@ResTypeId"].Value= 51; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); SqlCommand cmd1=new SqlCommand(); cmd1.Connection=this.epsDbConn; cmd1.CommandType=CommandType.StoredProcedure; cmd1.CommandText="eps_RetrieveServiceId"; cmd1.Parameters.Add("@OrgId",SqlDbType.NVarChar); cmd1.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd1); da.Fill(ds,"ServiceId"); if (ds.Tables["ServiceId"].Rows.Count != 0) { Session["ServiceId"]=ds.Tables["ServiceId"].Rows[0][0].ToString(); Session["ServiceName"]="Emergency Management"; } else { lblOrg.Text="Unable to complete request. Please contact IT Support."; } }*/ protected void btnFYBudgets_Click(object sender, System.EventArgs e) { getBRSFlag(); Session["CBudgets"]="frmMainBMgr"; Response.Redirect (strURL + "frmBudgets.aspx?"); } private void getBRSFlag() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="ams_RetrieveOrgFlagsBRS"; cmd.Parameters.Add("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"BRS"); if (ds.Tables["BRS"].Rows[0][0].ToString() == "0") { Session["BRS"]= 0; } else { Session["BRS"]= 1; } } } }
// 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.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.IdentityModel.Selectors; using System.Runtime.Diagnostics; using System.Threading.Tasks; namespace System.ServiceModel.Security { internal class WrapperSecurityCommunicationObject : CommunicationObject { private ISecurityCommunicationObject _innerCommunicationObject; public WrapperSecurityCommunicationObject(ISecurityCommunicationObject innerCommunicationObject) : base() { if (innerCommunicationObject == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerCommunicationObject"); } _innerCommunicationObject = innerCommunicationObject; } protected override Type GetCommunicationObjectType() { return _innerCommunicationObject.GetType(); } protected override TimeSpan DefaultCloseTimeout { get { return _innerCommunicationObject.DefaultCloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return _innerCommunicationObject.DefaultOpenTimeout; } } protected override void OnAbort() { _innerCommunicationObject.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return _innerCommunicationObject.OnBeginClose(timeout, callback, state); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return _innerCommunicationObject.OnBeginOpen(timeout, callback, state); } protected override void OnClose(TimeSpan timeout) { _innerCommunicationObject.OnClose(timeout); } protected override void OnClosed() { _innerCommunicationObject.OnClosed(); base.OnClosed(); } protected override void OnClosing() { _innerCommunicationObject.OnClosing(); base.OnClosing(); } protected override void OnEndClose(IAsyncResult result) { _innerCommunicationObject.OnEndClose(result); } protected override void OnEndOpen(IAsyncResult result) { _innerCommunicationObject.OnEndOpen(result); } protected override void OnFaulted() { _innerCommunicationObject.OnFaulted(); base.OnFaulted(); } protected override void OnOpen(TimeSpan timeout) { _innerCommunicationObject.OnOpen(timeout); } protected override void OnOpened() { _innerCommunicationObject.OnOpened(); base.OnOpened(); } protected override void OnOpening() { _innerCommunicationObject.OnOpening(); base.OnOpening(); } new internal void ThrowIfDisposedOrImmutable() { base.ThrowIfDisposedOrImmutable(); } protected internal override async Task OnCloseAsync(TimeSpan timeout) { var asyncInnerCommunicationObject = _innerCommunicationObject as IAsyncCommunicationObject; if (asyncInnerCommunicationObject != null) { await asyncInnerCommunicationObject.CloseAsync(timeout); } else { this.OnClose(timeout); } } protected internal override async Task OnOpenAsync(TimeSpan timeout) { var asyncInnerCommunicationObject = _innerCommunicationObject as IAsyncCommunicationObject; if (asyncInnerCommunicationObject != null) { await asyncInnerCommunicationObject.OpenAsync(timeout); } else { this.OnOpen(timeout); } } } internal abstract class CommunicationObjectSecurityTokenProvider : SecurityTokenProvider, ICommunicationObject, ISecurityCommunicationObject { private EventTraceActivity _eventTraceActivity; private WrapperSecurityCommunicationObject _communicationObject; protected CommunicationObjectSecurityTokenProvider() { _communicationObject = new WrapperSecurityCommunicationObject(this); } internal EventTraceActivity EventTraceActivity { get { if (_eventTraceActivity == null) { _eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); } return _eventTraceActivity; } } protected WrapperSecurityCommunicationObject CommunicationObject { get { return _communicationObject; } } public event EventHandler Closed { add { _communicationObject.Closed += value; } remove { _communicationObject.Closed -= value; } } public event EventHandler Closing { add { _communicationObject.Closing += value; } remove { _communicationObject.Closing -= value; } } public event EventHandler Faulted { add { _communicationObject.Faulted += value; } remove { _communicationObject.Faulted -= value; } } public event EventHandler Opened { add { _communicationObject.Opened += value; } remove { _communicationObject.Opened -= value; } } public event EventHandler Opening { add { _communicationObject.Opening += value; } remove { _communicationObject.Opening -= value; } } public CommunicationState State { get { return _communicationObject.State; } } public virtual TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public virtual TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } // communication object public void Abort() { _communicationObject.Abort(); } public void Close() { _communicationObject.Close(); } public void Close(TimeSpan timeout) { _communicationObject.Close(timeout); } public IAsyncResult BeginClose(AsyncCallback callback, object state) { return _communicationObject.BeginClose(callback, state); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return _communicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { _communicationObject.EndClose(result); } public void Open() { _communicationObject.Open(); } public void Open(TimeSpan timeout) { _communicationObject.Open(timeout); } public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return _communicationObject.BeginOpen(callback, state); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return _communicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { _communicationObject.EndOpen(result); } public void Dispose() { this.Close(); } // ISecurityCommunicationObject methods public virtual void OnAbort() { } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state); } public virtual void OnClose(TimeSpan timeout) { } public virtual void OnClosed() { } public virtual void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public virtual void OnFaulted() { this.OnAbort(); } public virtual void OnOpen(TimeSpan timeout) { } public virtual void OnOpened() { } public virtual void OnOpening() { } } internal abstract class CommunicationObjectSecurityTokenAuthenticator : SecurityTokenAuthenticator, ICommunicationObject, ISecurityCommunicationObject { private WrapperSecurityCommunicationObject _communicationObject; protected CommunicationObjectSecurityTokenAuthenticator() { _communicationObject = new WrapperSecurityCommunicationObject(this); } protected WrapperSecurityCommunicationObject CommunicationObject { get { return _communicationObject; } } public event EventHandler Closed { add { _communicationObject.Closed += value; } remove { _communicationObject.Closed -= value; } } public event EventHandler Closing { add { _communicationObject.Closing += value; } remove { _communicationObject.Closing -= value; } } public event EventHandler Faulted { add { _communicationObject.Faulted += value; } remove { _communicationObject.Faulted -= value; } } public event EventHandler Opened { add { _communicationObject.Opened += value; } remove { _communicationObject.Opened -= value; } } public event EventHandler Opening { add { _communicationObject.Opening += value; } remove { _communicationObject.Opening -= value; } } public CommunicationState State { get { return _communicationObject.State; } } public virtual TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public virtual TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } // communication object public void Abort() { _communicationObject.Abort(); } public void Close() { _communicationObject.Close(); } public void Close(TimeSpan timeout) { _communicationObject.Close(timeout); } public IAsyncResult BeginClose(AsyncCallback callback, object state) { return _communicationObject.BeginClose(callback, state); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return _communicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { _communicationObject.EndClose(result); } public void Open() { _communicationObject.Open(); } public void Open(TimeSpan timeout) { _communicationObject.Open(timeout); } public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return _communicationObject.BeginOpen(callback, state); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return _communicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { _communicationObject.EndOpen(result); } public void Dispose() { this.Close(); } // ISecurityCommunicationObject methods public virtual void OnAbort() { } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state); } public virtual void OnClose(TimeSpan timeout) { } public virtual void OnClosed() { } public virtual void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public virtual void OnFaulted() { this.OnAbort(); } public virtual void OnOpen(TimeSpan timeout) { } public virtual void OnOpened() { } public virtual void OnOpening() { } } }
////////////////////////////////////////////////////////////////////////////////////// // Author : Shukri Adams // // Contact : shukri.adams@gmail.com // // // // vcFramework : A reuseable library of utility classes // // Copyright (C) // ////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; using vcFramework.Arrays; namespace vcFramework.IO.Streams { /// <summary> Static class for working with basic streams </summary> public class StreamsLib { public static byte[] StreamToByteArray(Stream s) { using (MemoryStream ms = new MemoryStream()) { s.CopyTo(ms); return ms.ToArray(); } } /// <summary> /// Takes a string and converts to an binary stream /// </summary> /// <param name="input"></param> /// <param name="blockSize"></param> /// <returns></returns> public static Stream StringToBinaryStream(string input,int blockSize) { char[] charBuffer = new char[blockSize]; byte[] byteBuffer = new byte[blockSize]; StringReader reader = null; Encoder encoder = Encoding.Default.GetEncoder(); try { Stream mem = new MemoryStream(); // puts string into string reader stream reader = new StringReader(input); // stores total length of string long totalLength = input.Length; while (totalLength > 0) { // sets normal transfer block size int bufferSize = blockSize; // actual used block size - is usually = intBlockSize, but can be less on final block // if this is the the final block transfer, transfer size is the // remainder of the total original size divided by intBlockSize if (totalLength < blockSize) { bufferSize = Convert.ToInt32(totalLength); // recreate arrays to accurately fit input charBuffer = new char[bufferSize]; byteBuffer = new byte[bufferSize]; } // writes block of string to char array reader.Read(charBuffer, 0, bufferSize); // converts char block to binary encoder.GetBytes(charBuffer, 0, bufferSize, byteBuffer, 0, true); // writes binary array to file mem.Write(byteBuffer, 0, bufferSize); totalLength = totalLength - blockSize; } // resets stream start position mem.Seek(0, SeekOrigin.Begin); return mem; } finally { // clean up if (reader != null) { reader.Close(); } } } /// <summary> /// Returns contents of binary stream as string /// </summary> /// <param name="stream"></param> /// <param name="blockSize"></param> /// <returns></returns> public static string BinaryStreamToString(Stream stream,int blockSize) { char[] charBuffer = new char[blockSize]; byte[] byteBuffer = new byte[blockSize]; Decoder decoder = Encoding.Default.GetDecoder(); StringBuilder s = new StringBuilder(); // rewinds stream stream.Seek(0, SeekOrigin.Begin); // stores total length of stream long totalLength = stream.Length; while (totalLength > 0) { // sets normal transfer block size int bufferSize = blockSize; // if this is the the final block transfer, transfer size is the // remainder of the total original size divided by intBlockSize if (totalLength < blockSize) { bufferSize = Convert.ToInt32(totalLength); // recreate arrays to accurately fit input charBuffer = new char[bufferSize]; byteBuffer = new byte[bufferSize]; } // writes block of to byte array stream.Read(byteBuffer, 0, bufferSize); // converts byte block to char decoder.GetChars(byteBuffer, 0, bufferSize, charBuffer, 0); // writes chars to stringbuilder s.Append(new string(charBuffer)); totalLength = totalLength - bufferSize; } return s.ToString(); } /// <summary> /// found at http://www.yoda.arachsys.com/csharp/readbinary.html /// </summary> /// <param name="stream"></param> /// <param name="initialLength"></param> /// <returns></returns> public static byte[] BinaryStreamToByteArray ( Stream stream, int initialLength ) { // If we've been passed an unhelpful initial length, just // use 32K. if (initialLength < 1) { initialLength = 32768; } byte[] buffer = new byte[initialLength]; int read=0; int chunk; while ( (chunk = stream.Read(buffer, read, buffer.Length-read)) > 0) { read += chunk; // If we've reached the end of our buffer, check to see if there's // any more information if (read == buffer.Length) { int nextByte = stream.ReadByte(); // End of stream? If so, we're done if (nextByte==-1) return buffer; // Nope. Resize the buffer, put in the byte we've just // read, and continue byte[] newBuffer = new byte[buffer.Length*2]; Array.Copy(buffer, newBuffer, buffer.Length); newBuffer[read]=(byte)nextByte; buffer = newBuffer; read++; } } // Buffer is now too big. Shrink it. byte[] ret = new byte[read]; Array.Copy(buffer, ret, read); return ret; } /// <summary> /// Creates a new stream from an existing one, using a start and end /// position in the main stream /// </summary> /// <returns></returns> private static Stream HIDEStreamSplit( Stream inStream, long lngStartPosition, long lngEndPosition, int intBlockSize ) { Stream objOutStream = new MemoryStream(); byte[] arrBytTransferBlock = new byte[intBlockSize]; int intRealBlockSize = 0; bool blnDo = true; // ERROR ! -invalid input if (lngStartPosition >= lngEndPosition) return null; // error - endposition lies beyond end of instream if (lngEndPosition >= inStream.Length) return null; // move to position in main string from which reading will begin inStream.Seek( lngStartPosition, SeekOrigin.Begin ); while (blnDo) { // calcs actual block size intRealBlockSize = intBlockSize; // gets block size for final transfer if (lngEndPosition - inStream.Position < intBlockSize) { intRealBlockSize = Convert.ToInt32(lngEndPosition - inStream.Position); arrBytTransferBlock = new byte[intRealBlockSize]; blnDo = false; // loop will finish current run then break } // reads data into transfer byte array inStream.Read( arrBytTransferBlock, 0, intRealBlockSize ); // writes data into new stream objOutStream.Write(arrBytTransferBlock, 0, intRealBlockSize ); } // rewind output stream (becase thats what courteous ppl do) objOutStream.Seek(0, SeekOrigin.Begin); return objOutStream; } /// <summary> /// Inserts a given length of data from a point in one string, into another string, /// also at a given position /// </summary> /// <param name="srcStream">Stream which data will be copied from</param> /// <param name="targetStream"></param> /// <param name="srcPosition">Position in source stream from which data will be read</param> /// <param name="targetPosition">Position in target stream where data will be inserted</param> /// <param name="insertLength">The length of data in source stream to be copied to target stream</param> /// <param name="blockSize">Block size for buffering</param> public static Stream InsertStream( Stream srcStream, Stream targetStream, long srcPosition, long targetPosition, long insertLength, int blockSize ) { Stream finalStream = new MemoryStream(); byte[] buffer = new byte[blockSize]; bool blnDo = true; int realBlockSize = 0; // actual size of transfer block - usually = intBlockSize, but on final transfer can be less // move to position in main string where merging will begin srcStream.Seek( srcPosition, SeekOrigin.Begin ); targetStream.Seek( 0, SeekOrigin.Begin ); realBlockSize = blockSize; // copy all data in target stream BEFORE the insert point in target stream. // data is copied to the final output stream while (blnDo) { // calcs actual block size // gets block size for final transfer if (targetPosition - targetStream.Position < blockSize) { realBlockSize = Convert.ToInt32(targetPosition - targetStream.Position); if (realBlockSize == 0) break; buffer = new byte[realBlockSize]; blnDo = false; // loop will finish current run then break } // reads data into transfer byte array targetStream.Read(buffer, 0, realBlockSize); // writes data into new stream finalStream.Write(buffer, 0, realBlockSize); } buffer = new byte[blockSize]; realBlockSize = blockSize; blnDo = true; // copy src data while (blnDo) { // calcs actual block size // gets block size for final transfer if (insertLength - srcStream.Position < blockSize) { realBlockSize = Convert.ToInt32(insertLength- srcStream.Position); if (realBlockSize == 0) break; buffer = new byte[realBlockSize]; blnDo = false; // loop will finish current run then break } // reads data into transfer byte array srcStream.Read(buffer, 0, realBlockSize); // writes data into new stream finalStream.Write(buffer, 0, realBlockSize); } buffer = new byte[blockSize]; realBlockSize = blockSize; blnDo = true; // trailing target data while (blnDo) { // calcs actual block size // gets block size for final transfer if (targetStream.Length - targetStream.Position < blockSize) { realBlockSize = Convert.ToInt32(targetStream.Length - targetStream.Position); if (realBlockSize == 0) break; buffer = new byte[realBlockSize]; blnDo = false; // loop will finish current run then break } // reads data into transfer byte array targetStream.Read(buffer, 0, realBlockSize); // writes data into new stream finalStream.Write(buffer, 0, realBlockSize); } return finalStream; } /// <summary> /// Returns a stream minus a "clipped" section /// </summary> /// <param name="inStream"></param> /// <param name="position"></param> /// <param name="length"></param> /// <param name="bufferSize"></param> /// <returns></returns> public static Stream CutStream( Stream inStream, long position, long length, int bufferSize ) { Stream outStream = new MemoryStream(); byte[] buffer = new byte[bufferSize]; inStream.Seek(0,SeekOrigin.Begin); // copies pre-clip section while (inStream.Position < position) { if (position - inStream.Position < bufferSize) buffer = new byte[position - inStream.Position]; inStream.Read(buffer,0, buffer.Length); outStream.Write(buffer, 0, buffer.Length); } // skip over "clip" section inStream.Seek(position + length, SeekOrigin.Begin); // copies post-clip section while (inStream.Position < inStream.Length) { if (inStream.Length - inStream.Position < bufferSize) buffer = new byte[inStream.Length - inStream.Position]; inStream.Read(buffer,0, buffer.Length); outStream.Write(buffer, 0, buffer.Length); } // "rewind" output stream before returning outStream.Seek(0,SeekOrigin.Begin); return outStream; } /// <summary> /// Merges one stream into another at a given position /// </summary> /// <param name="objMainStream"></param> /// <param name="objStreamToMerge"></param> /// <param name="lngMergePosition"></param> public static void MergeStream( Stream objMainStream, Stream objStreamToMerge, long lngMergePosition, int intBlockSize ) { byte[] arrBytTransferBlock = new byte[intBlockSize]; bool blnDo = true; int intRealBlockSize = 0; // actual size of transfer block - usually = intBlockSize, but on final transfer can be less //error - beyond range of main stream // move to position in main string where mergingr will begin objMainStream.Seek( lngMergePosition, SeekOrigin.Begin ); // need to move merged streamt to its start objStreamToMerge.Seek( 0, SeekOrigin.Begin ); // sets default block size intRealBlockSize = intBlockSize; while (blnDo) { // calcs actual block size // gets block size for final transfer if (objStreamToMerge.Length - objStreamToMerge.Position < intBlockSize) { intRealBlockSize = Convert.ToInt32(objStreamToMerge.Length - objStreamToMerge.Position); arrBytTransferBlock = new byte[intRealBlockSize]; blnDo = false; // loop will finish current run then break } // reads data into transfer byte array objStreamToMerge.Read( arrBytTransferBlock, 0, intRealBlockSize); // writes data into new stream objMainStream.Write( arrBytTransferBlock, 0, intRealBlockSize); } } /// <summary> /// Returns the position in a stream, of a sequence of bytes. Returns -1 /// if the sequence is not found /// </summary> /// <param name="objCheckStream"></param> /// <param name="bytCheckForByteBlock"></param> /// <returns></returns> public static long ByteArrayPositionInStream( Stream s, byte[] bytes ) { byte[] buffer = new byte[bytes.Length]; long lngPosition = 0; // "rewind" stream s.Seek( 0, SeekOrigin.Begin); while (s.Position < s.Length - bytes.Length) { // reads _1_ byte into stream s.Read( buffer, 0, buffer.Length); if (ByteArrayLib.AreEqual( buffer, bytes, false )) { return lngPosition; } lngPosition ++; // advance stream forward 1 step s.Seek( lngPosition, SeekOrigin.Begin); } return -1; } /// <summary> Converts a string to byte array </summary> /// <param name="strInput"></param> /// <returns></returns> public static byte[] StringToByteArray( string input ) { // note - returns byte array instead of byte because it's just // easier to use byte arrays! I'm lazy!! byte[] bytes = new byte[input.Length]; Encoder objEncoder = Encoding.Default.GetEncoder(); objEncoder.GetBytes( input.ToCharArray(), 0, input.Length, bytes, 0, true); return bytes; } /// <summary> /// Converts byte array to string /// </summary> /// <param name="input"></param> /// <returns></returns> public static string ByteArrayToString( byte[] input) { Decoder decoder = Encoding.Default.GetDecoder(); char[] output = new char[input.Length]; decoder.GetChars( input, 0, input.Length, output, 0); return output.ToString(); } /// <summary> Copies the entire contents of one binary stream to another binary stream</summary> public static void StreamCopyAll( Stream source, Stream target, int bufferSize ) { // rewind src stream source.Seek(0, SeekOrigin.Begin); int size = 0; byte[] buffer = new byte[bufferSize]; bool doloop = true; while (doloop) { if (source.Length - source.Position < bufferSize) { buffer = new byte[source.Length - source.Position]; doloop = false; // last loop run } size += source.Read(buffer, 0, buffer.Length); target.Write(buffer, 0, buffer.Length); } } public static string EncodeBase64(string content) { MemoryStream mOut = (MemoryStream)StringToBinaryStream(content, 128); return Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length); } public static string DecodeBase64(string content) { byte[] bPlain = new byte[content.Length]; // this will throw an exception if the data is not base64 encoded! bPlain = Convert.FromBase64CharArray(content.ToCharArray(), 0, content.Length); return ByteArrayToString(bPlain); } } }
/* AspNetPager source code This file is part of AspNetPager. Copyright 2003-2015 Webdiyer(http://en.webdiyer.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.ComponentModel; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; using System.Web; using System.Security.Permissions; [assembly: WebResource("Wuqi.Webdiyer.ANPScript.js", "text/javascript")] namespace Wuqi.Webdiyer { #region AspNetPager Server Control /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Class[@name="AspNetPager"]/*'/> [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)] [DefaultProperty("PageSize")] [DefaultEvent("PageChanged")] [ParseChildren(false)] [PersistChildren(false)] [ANPDescription("desc_AspNetPager")] [Designer(typeof(PagerDesigner))] [ToolboxData("<{0}:AspNetPager runat=server></{0}:AspNetPager>")] [System.Drawing.ToolboxBitmap(typeof(AspNetPager), "AspNetPager.bmp")] public partial class AspNetPager : WebControl, INamingContainer, IPostBackEventHandler, IPostBackDataHandler { protected override HtmlTextWriterTag TagKey { get { switch (LayoutType) { case LayoutType.Table: return HtmlTextWriterTag.Table; case LayoutType.Ul: return HtmlTextWriterTag.Ul; default: return HtmlTextWriterTag.Div; } } } #region Control Rendering Logic /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="OnInit"]/*'/> protected override void OnInit(EventArgs e) { base.OnInit(e); if (null != CloneFrom && string.Empty != CloneFrom.Trim()) { AspNetPager ctrl = Parent.FindControl(CloneFrom) as AspNetPager; if (null == ctrl) { string errStr = SR.GetString("def_CloneFromTypeError"); throw new ArgumentException(errStr.Replace("%controlID%", CloneFrom), "CloneFrom"); } if (null != ctrl.cloneFrom && this == ctrl.cloneFrom) { string errStr = SR.GetString("def_RecursiveCloneFrom"); throw new ArgumentException(errStr, "CloneFrom"); } cloneFrom = ctrl; CssClass = cloneFrom.CssClass; Width = cloneFrom.Width; Height = cloneFrom.Height; HorizontalAlign = cloneFrom.HorizontalAlign; BackColor = cloneFrom.BackColor; BackImageUrl = cloneFrom.BackImageUrl; BorderColor = cloneFrom.BorderColor; BorderStyle = cloneFrom.BorderStyle; BorderWidth = cloneFrom.BorderWidth; Font.CopyFrom(cloneFrom.Font); ForeColor = cloneFrom.ForeColor; EnableViewState = cloneFrom.EnableViewState; Enabled = cloneFrom.Enabled; } } /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="OnLoad"]/*'/> protected override void OnLoad(EventArgs e) { if (UrlPaging) { currentUrl = Page.Request.Path; queryString = Page.Request.ServerVariables["Query_String"]; if (!string.IsNullOrEmpty(queryString)&&queryString.StartsWith("?")) //mono <v2.8 compatible queryString = queryString.TrimStart('?'); if (!Page.IsPostBack && cloneFrom == null) { int index; int.TryParse(Page.Request.QueryString[UrlPageIndexName], out index); if (index <= 0) index = 1; else if (ReverseUrlPageIndex) index = PageCount - index + 1; PageChangingEventArgs args = new PageChangingEventArgs(index); OnPageChanging(args); } } else { inputPageIndex = Page.Request.Form[UniqueID + "_input"]; } base.OnLoad(e); if ((UrlPaging || (!UrlPaging && PageIndexBoxType == PageIndexBoxType.TextBox)) && (ShowPageIndexBox == ShowPageIndexBox.Always || (ShowPageIndexBox == ShowPageIndexBox.Auto && PageCount >= ShowBoxThreshold))) { HttpContext.Current.Items[scriptRegItemName] = true; } } /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="OnPreRender"]/*'/> //protected override void OnPreRender(EventArgs e) //{ // Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Wuqi.Webdiyer.ANPScript.js"); // base.OnPreRender(e); //} /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="AddAttributesToRender"]/*'/> protected override void AddAttributesToRender(HtmlTextWriter writer) { if (Page != null && !UrlPaging) Page.VerifyRenderingInServerForm(this); const string isANPScriptRegistered = "isANPScriptRegistered"; if (!DesignMode && HttpContext.Current.Items[scriptRegItemName] != null && HttpContext.Current.Items[isANPScriptRegistered] == null) { writer.Write("<script type=\"text/javascript\" src=\""); writer.Write(Page.ClientScript.GetWebResourceUrl(this.GetType(), "Wuqi.Webdiyer.ANPScript.js")); writer.WriteLine("\"></script>"); HttpContext.Current.Items[isANPScriptRegistered] = true; } if (HorizontalAlign != HorizontalAlign.NotSet) writer.AddStyleAttribute(HtmlTextWriterStyle.TextAlign, HorizontalAlign.ToString().ToLower()); if (!string.IsNullOrEmpty(BackImageUrl)) writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundImage, BackImageUrl); base.AddAttributesToRender(writer); } /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="RenderBeginTag"]/*'/> public override void RenderBeginTag(HtmlTextWriter writer) { bool showPager = (PageCount > 1 || (PageCount <= 1 && AlwaysShow)); writer.WriteLine(); writer.Write("<!-- "); writer.Write(SR.GetString("def_CopyrightText")); writer.WriteLine(" -->"); if (!showPager) { writer.Write("<!--"); writer.Write(SR.GetString("def_AutoHideInfo")); writer.Write("-->"); } else base.RenderBeginTag(writer); } /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="RenderEndTag"]/*'/> public override void RenderEndTag(HtmlTextWriter writer) { if (PageCount > 1 || (PageCount <= 1 && AlwaysShow)) base.RenderEndTag(writer); writer.WriteLine(); writer.Write("<!-- "); writer.Write(SR.GetString("def_CopyrightText")); writer.WriteLine(" -->"); writer.WriteLine(); } /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Method[@name="RenderContents"]/*'/> protected override void RenderContents(HtmlTextWriter writer) { if (PageCount <= 1 && !AlwaysShow) return; writer.Indent = 0; if (ShowCustomInfoSection != ShowCustomInfoSection.Never) { if (LayoutType == LayoutType.Table) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); //<tr> } if (ShowCustomInfoSection == ShowCustomInfoSection.Left) { RenderCustomInfoSection(writer); RenderNavigationSection(writer); } else { RenderNavigationSection(writer); RenderCustomInfoSection(writer); } if (LayoutType == LayoutType.Table) { writer.RenderEndTag(); //</tr> } } else RenderPagingElements(writer); } #endregion } #endregion #region PageChangingEventHandler Delegate /// <include file='AspNetPagerDocs.xml' path='AspNetPagerDoc/Delegate[@name="PageChangingEventHandler"]/*'/> public delegate void PageChangingEventHandler(object src, PageChangingEventArgs e); #endregion }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Log.DestinationIPFIXBinding", Namespace="urn:iControl")] public partial class LogDestinationIPFIX : iControlInterface { public LogDestinationIPFIX() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void create( string [] destinations, string [] pools, string [] profiles ) { this.Invoke("create", new object [] { destinations, pools, profiles}); } public System.IAsyncResult Begincreate(string [] destinations,string [] pools,string [] profiles, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { destinations, pools, profiles}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_ipfix_destinations //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void delete_all_ipfix_destinations( ) { this.Invoke("delete_all_ipfix_destinations", new object [0]); } public System.IAsyncResult Begindelete_all_ipfix_destinations(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_ipfix_destinations", new object[0], callback, asyncState); } public void Enddelete_all_ipfix_destinations(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_ipfix_destination //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void delete_ipfix_destination( string [] destinations ) { this.Invoke("delete_ipfix_destination", new object [] { destinations}); } public System.IAsyncResult Begindelete_ipfix_destination(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_ipfix_destination", new object[] { destinations}, callback, asyncState); } public void Enddelete_ipfix_destination(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] destinations ) { object [] results = this.Invoke("get_description", new object [] { destinations}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { destinations}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_log_protocol //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LogDestinationIPFIXProtocolVersion [] get_log_protocol( string [] destinations ) { object [] results = this.Invoke("get_log_protocol", new object [] { destinations}); return ((LogDestinationIPFIXProtocolVersion [])(results[0])); } public System.IAsyncResult Beginget_log_protocol(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_log_protocol", new object[] { destinations}, callback, asyncState); } public LogDestinationIPFIXProtocolVersion [] Endget_log_protocol(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LogDestinationIPFIXProtocolVersion [])(results[0])); } //----------------------------------------------------------------------- // get_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_pool( string [] destinations ) { object [] results = this.Invoke("get_pool", new object [] { destinations}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_pool(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_pool", new object[] { destinations}, callback, asyncState); } public string [] Endget_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_serverssl_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_serverssl_profile( string [] destinations ) { object [] results = this.Invoke("get_serverssl_profile", new object [] { destinations}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_serverssl_profile(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_serverssl_profile", new object[] { destinations}, callback, asyncState); } public string [] Endget_serverssl_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_template_delete_delay //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_template_delete_delay( string [] destinations ) { object [] results = this.Invoke("get_template_delete_delay", new object [] { destinations}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_template_delete_delay(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_delete_delay", new object[] { destinations}, callback, asyncState); } public long [] Endget_template_delete_delay(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_template_retransmit_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_template_retransmit_interval( string [] destinations ) { object [] results = this.Invoke("get_template_retransmit_interval", new object [] { destinations}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_template_retransmit_interval(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_template_retransmit_interval", new object[] { destinations}, callback, asyncState); } public long [] Endget_template_retransmit_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_transport_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_transport_profile( string [] destinations ) { object [] results = this.Invoke("get_transport_profile", new object [] { destinations}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_transport_profile(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_transport_profile", new object[] { destinations}, callback, asyncState); } public string [] Endget_transport_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_description( string [] destinations, string [] descriptions ) { this.Invoke("set_description", new object [] { destinations, descriptions}); } public System.IAsyncResult Beginset_description(string [] destinations,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { destinations, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_log_protocol //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_log_protocol( string [] destinations, LogDestinationIPFIXProtocolVersion [] protocols ) { this.Invoke("set_log_protocol", new object [] { destinations, protocols}); } public System.IAsyncResult Beginset_log_protocol(string [] destinations,LogDestinationIPFIXProtocolVersion [] protocols, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_log_protocol", new object[] { destinations, protocols}, callback, asyncState); } public void Endset_log_protocol(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_pool //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_pool( string [] destinations, string [] pools ) { this.Invoke("set_pool", new object [] { destinations, pools}); } public System.IAsyncResult Beginset_pool(string [] destinations,string [] pools, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_pool", new object[] { destinations, pools}, callback, asyncState); } public void Endset_pool(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_serverssl_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_serverssl_profile( string [] destinations, string [] profiles ) { this.Invoke("set_serverssl_profile", new object [] { destinations, profiles}); } public System.IAsyncResult Beginset_serverssl_profile(string [] destinations,string [] profiles, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_serverssl_profile", new object[] { destinations, profiles}, callback, asyncState); } public void Endset_serverssl_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_delete_delay //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_template_delete_delay( string [] destinations, long [] delays ) { this.Invoke("set_template_delete_delay", new object [] { destinations, delays}); } public System.IAsyncResult Beginset_template_delete_delay(string [] destinations,long [] delays, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_delete_delay", new object[] { destinations, delays}, callback, asyncState); } public void Endset_template_delete_delay(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_template_retransmit_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_template_retransmit_interval( string [] destinations, long [] intervals ) { this.Invoke("set_template_retransmit_interval", new object [] { destinations, intervals}); } public System.IAsyncResult Beginset_template_retransmit_interval(string [] destinations,long [] intervals, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_template_retransmit_interval", new object[] { destinations, intervals}, callback, asyncState); } public void Endset_template_retransmit_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_transport_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationIPFIX", RequestNamespace="urn:iControl:Log/DestinationIPFIX", ResponseNamespace="urn:iControl:Log/DestinationIPFIX")] public void set_transport_profile( string [] destinations, string [] profiles ) { this.Invoke("set_transport_profile", new object [] { destinations, profiles}); } public System.IAsyncResult Beginset_transport_profile(string [] destinations,string [] profiles, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_transport_profile", new object[] { destinations, profiles}, callback, asyncState); } public void Endset_transport_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Log.DestinationIPFIX.ProtocolVersion", Namespace = "urn:iControl")] public enum LogDestinationIPFIXProtocolVersion { IPFIX_LOG_PROTOCOL_UNKNOWN, IPFIX_LOG_PROTOCOL_IPFIX, IPFIX_LOG_PROTOCOL_NETFLOW_9, } //======================================================================= // Structs //======================================================================= }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class OrderByDescendingTests { // Class which is passed as an argument for EqualityComparer public class CaseInsensitiveComparer : IComparer<string> { public int Compare(string x, string y) { return string.Compare(x.ToLower(), y.ToLower()); } } // EqualityComparer to ignore case sensitivity: Added to support PLINQ public class CaseInsensitiveEqualityComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { if (string.Compare(x.ToLower(), y.ToLower()) == 0) return true; return false; } public int GetHashCode(string obj) { return getCaseInsensitiveString(obj).GetHashCode(); } private string getCaseInsensitiveString(string word) { char[] wordchars = word.ToCharArray(); String newWord = ""; foreach (char c in wordchars) { newWord = newWord + (c.ToString().ToLower()); } return newWord; } } private struct Record { #pragma warning disable 0649 public string Name; public int Score; #pragma warning restore 0649 } public class OrderByDescending009 { private static int OrderByDescending001() { var q = from x1 in new int[] { 1, 6, 0, -1, 3 } from x2 in new int[] { 55, 49, 9, -100, 24, 25 } select new { a1 = x1, a2 = x2 }; var rst1 = q.OrderByDescending(e => e.a1); var rst2 = q.OrderByDescending(e => e.a1); return Verification.Allequal(rst1, rst2); } private static int OrderByDescending002() { var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 } from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x2) select new { a1 = x1, a2 = x2 }; var rst1 = q.OrderByDescending(e => e.a1).ThenBy(f => f.a2); var rst2 = q.OrderByDescending(e => e.a1).ThenBy(f => f.a2); return Verification.Allequal(rst1, rst2); } public static int Main() { int ret = RunTest(OrderByDescending001) + RunTest(OrderByDescending002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending1 { // Overload-1: source is empty public static int Test1() { int[] source = { }; int[] expected = { }; var actual = source.OrderByDescending((e) => e); return Verification.Allequal(expected, actual); } public static int Main() { return Test1(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending2 { // Overload-1: keySelector returns null public static int Test2() { int?[] source = { null, null, null }; int?[] expected = { null, null, null }; var actual = source.OrderByDescending((e) => e); return Verification.Allequal(expected, actual); } public static int Main() { return Test2(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending3 { // Overload-1: All elements have the same key public static int Test3() { int?[] source = { 9, 9, 9, 9, 9, 9 }; int?[] expected = { 9, 9, 9, 9, 9, 9 }; var actual = source.OrderByDescending((e) => e); return Verification.Allequal(expected, actual); } public static int Main() { return Test3(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending4 { // Overload-2: All elements have different keys. // Verify keySelector function is called. public static int Test4() { Record[] source = new Record[]{ new Record{Name = "Alpha", Score = 90}, new Record{Name = "Robert", Score = 45}, new Record{Name = "Prakash", Score = 99}, new Record{ Name = "Bob", Score = 0} }; Record[] expected = new Record[]{new Record{Name = "Robert", Score = 45}, new Record{Name = "Prakash", Score = 99}, new Record{Name = "Bob", Score = 0}, new Record{Name = "Alpha", Score = 90} }; var actual = source.OrderByDescending((e) => e.Name, null); return Verification.Allequal(expected, actual); } public static int Main() { return Test4(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending5 { // Overload-2: 1st and last elements have same key and duplicate elements. // Verify the given comparer function is called. Also verifies order is preserved // This test calls AllequalCompaer with a EqualityComparer which is casInsensitive. This change is to help PLINQ team run our tests public static int Test5() { string[] source = { "Prakash", "Alpha", "DAN", "dan", "Prakash" }; string[] expected = { "Prakash", "Prakash", "DAN", "dan", "Alpha" }; var actual = source.OrderByDescending((e) => e, new CaseInsensitiveComparer()); return Verification.AllequalComparer(expected, actual, new CaseInsensitiveEqualityComparer()); } public static int Main() { return Test5(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending6 { // Overload-2: 1st and last elements have same key and duplicate elements. // Verify default comparer is called. public static int Test6() { string[] source = { "Prakash", "Alpha", "DAN", "dan", "Prakash" }; string[] expected = { "Prakash", "Prakash", "DAN", "dan", "Alpha" }; var actual = source.OrderByDescending((e) => e, null); return Verification.Allequal(expected, actual); } public static int Main() { return Test6(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending7 { // Overload-2: Elements are in ascending order public static int Test7() { int[] source = { -75, -50, 0, 5, 9, 30, 100 }; int[] expected = { 100, 30, 9, 5, 0, -50, -75 }; var actual = source.OrderByDescending((e) => e, null); return Verification.Allequal(expected, actual); } public static int Main() { return Test7(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class OrderByDescending8 { // Overload-2: Verify Order is preserved public static int Test8() { Record[] source = new Record[]{ new Record{Name = "Alpha", Score = 90}, new Record{Name = "Robert", Score = 45}, new Record{Name = "Prakash", Score = 99}, new Record{ Name = "Bob", Score = 90}, new Record{Name = "Thomas", Score = 45}, new Record{Name = "Tim", Score = 45}, new Record{Name = "Mark", Score = 45}, }; Record[] expected = new Record[]{new Record{Name = "Prakash", Score = 99}, new Record{Name = "Alpha", Score = 90}, new Record{ Name = "Bob", Score = 90}, new Record{Name = "Robert", Score = 45}, new Record{Name = "Thomas", Score = 45}, new Record{Name = "Tim", Score = 45}, new Record{Name = "Mark", Score = 45}, }; var actual = source.Select((e, i) => new { V = e, I = i }).OrderByDescending((e) => e.V.Score).ThenBy((e) => e.I).Select((e) => e.V); //var actual = source.OrderByDescending((e) => e.Score, null); return Verification.Allequal(expected, actual); } public static int Main() { return Test8(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using mshtml; using OpenLiveWriter.Mshtml; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.HtmlEditor { /// <summary> /// Summary description for HtmlBlockFormatHelper. /// </summary> public class HtmlBlockFormatHelper { private MshtmlMarkupServices _markupServices; private HtmlEditorControl _editor; public HtmlBlockFormatHelper(HtmlEditorControl editor) { _editor = editor; _markupServices = (_editor as IHtmlEditorComponentContext).MarkupServices; } public static void ApplyBlockStyle(HtmlEditorControl editor, _ELEMENT_TAG_ID styleTagId, MarkupRange selection, MarkupRange maximumBounds, MarkupRange postOpSelection) { new HtmlBlockFormatHelper(editor).ApplyBlockStyle(styleTagId, selection, maximumBounds, postOpSelection); } private void ApplyBlockStyle(_ELEMENT_TAG_ID styleTagId, MarkupRange selection, MarkupRange maximumBounds, MarkupRange postOpSelection) { Debug.Assert(selection != maximumBounds, "selection and maximumBounds must be distinct objects"); SelectionPositionPreservationCookie selectionPreservationCookie = null; //update the range cling and gravity so it will stick with the re-arranged block content selection.Start.PushCling(false); selection.Start.PushGravity(_POINTER_GRAVITY.POINTER_GRAVITY_Left); selection.End.PushCling(false); selection.End.PushGravity(_POINTER_GRAVITY.POINTER_GRAVITY_Right); try { if (selection.IsEmpty()) { //nothing is selected, so expand the selection to cover the entire parent block element IHTMLElementFilter stopFilter = ElementFilters.CreateCompoundElementFilter(ElementFilters.BLOCK_ELEMENTS, new IHTMLElementFilter(IsSplitStopElement)); MovePointerLeftUntilRegionBreak(selection.Start, stopFilter, maximumBounds.Start); MovePointerRightUntilRegionBreak(selection.End, stopFilter, maximumBounds.End); } using (IUndoUnit undo = _editor.CreateSelectionUndoUnit(selection)) { selectionPreservationCookie = SelectionPositionPreservationHelper.Save(_markupServices, postOpSelection, selection); if (selection.IsEmptyOfContent()) { ApplyBlockFormatToEmptySelection(selection, styleTagId, maximumBounds); } else { ApplyBlockFormatToContentSelection(selection, styleTagId, maximumBounds); } undo.Commit(); } } finally { selection.Start.PopCling(); selection.Start.PopGravity(); selection.End.PopCling(); selection.End.PopGravity(); } if (!SelectionPositionPreservationHelper.Restore(selectionPreservationCookie, selection, selection.Clone())) selection.ToTextRange().select(); } private void ApplyBlockFormatToContentSelection(MarkupRange selection, _ELEMENT_TAG_ID styleTagId, MarkupRange maximumBounds) { MarkupRange[] stylableBlockRegions = GetSelectableBlockRegions(selection); if (stylableBlockRegions.Length > 0) { // // We want to make sure that the selection reflects only the // blocks that were changed. Unposition the start and end // pointers and then make sure they cover the stylable block // regions, no more, no less. selection.Start.Unposition(); selection.End.Unposition(); foreach (MarkupRange range in stylableBlockRegions) { ApplyBlockStyleToRange(styleTagId, range, maximumBounds); if (!selection.Start.Positioned || range.Start.IsLeftOf(selection.Start)) selection.Start.MoveToPointer(range.Start); if (!selection.End.Positioned || range.End.IsRightOf(selection.End)) selection.End.MoveToPointer(range.End); } } } private void ApplyBlockFormatToEmptySelection(MarkupRange selection, _ELEMENT_TAG_ID styleTagId, MarkupRange maximumBounds) { bool deleteParentBlock = false; //expand the selection to include the parent content block. If the expansion can cover the block element //without exceeding the maximum bounds, then delete the parent element and wrap the selection in the //new block element. If the maximum bounds are exceeded, then just wrap the selection around the bounds. IHTMLElementFilter stopFilter = ElementFilters.CreateCompoundElementFilter(ElementFilters.BLOCK_ELEMENTS, new IHTMLElementFilter(IsSplitStopElement)); MovePointerLeftUntilRegionBreak(selection.Start, stopFilter, maximumBounds.Start); MovePointerRightUntilRegionBreak(selection.End, stopFilter, maximumBounds.End); MarkupRange tmpRange = selection.Clone(); tmpRange.End.MoveToPointer(selection.Start); IHTMLElement startStopParent = tmpRange.End.GetParentElement(stopFilter); if (startStopParent != null) { tmpRange.Start.MoveAdjacentToElement(startStopParent, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin); if (tmpRange.IsEmptyOfContent()) //the range from the selection the the block start is empty { tmpRange.Start.MoveToPointer(selection.End); IHTMLElement endStopParent = tmpRange.Start.GetParentElement(stopFilter); if (endStopParent != null && startStopParent.sourceIndex == endStopParent.sourceIndex) { tmpRange.Start.MoveAdjacentToElement(endStopParent, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); if (tmpRange.IsEmptyOfContent()) //the range from the selection the the block end is empty { tmpRange.MoveToElement(endStopParent, true); if (maximumBounds.InRange(tmpRange) && !(endStopParent is IHTMLTableCell)) { deleteParentBlock = true; //the parent has no useful content outside the selection, so it's safe to delete } } } } } //delete the block parent (if appropriate) and wrap the selection in the new block element. if (deleteParentBlock) { (startStopParent as IHTMLDOMNode).removeNode(false); } IHTMLElement newBlock = WrapRangeInBlockElement(selection, styleTagId); selection.MoveToElement(newBlock, false); } private void ApplyBlockStyleToRange(_ELEMENT_TAG_ID styleTagId, MarkupRange range, MarkupRange maximumBounds) { //update the range cling and gravity so it will stick with the re-arranged block content range.Start.PushCling(false); range.Start.PushGravity(_POINTER_GRAVITY.POINTER_GRAVITY_Left); range.End.PushCling(false); range.End.PushGravity(_POINTER_GRAVITY.POINTER_GRAVITY_Right); try { MarkupPointer deeperPoint = GetDeeperPoint(range.Start, range.End); MarkupPointer insertionPoint = _markupServices.CreateMarkupPointer(deeperPoint); insertionPoint.Cling = false; //if the insertion point parent block contains content, split the block. If the parent //block is now empty, then just delete the parent block. IHTMLElement parentBlock = insertionPoint.GetParentElement( ElementFilters.CreateCompoundElementFilter(ElementFilters.BLOCK_ELEMENTS, new IHTMLElementFilter(IsSplitStopElement))); //temporarily stage the range content at the end of the document so that the split //operation doesn't damage the original range content MarkupRange stagedBlockContent = _markupServices.CreateMarkupRange(); stagedBlockContent.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left; stagedBlockContent.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right; stagedBlockContent.Start.MoveAdjacentToElement(GetBodyElement(), _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); stagedBlockContent.End.MoveToPointer(stagedBlockContent.Start); MarkupPointer stagedBlockInsertionPoint = _markupServices.CreateMarkupPointer(GetBodyElement(), _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); stagedBlockInsertionPoint.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right; // Pass over all opening elements between parent's adj_beforeend and the start of selection (range.start) // Any element (_enterscope) that is not closed before the close of selection is essentially // containing the selection completely, and needs to be copied into the staging area. // ex: <p><a href="http://msn.com">abc[selection]def</a></p> // Here, the <a> element encloses completely the selection and needs to be explicitly copied to the // staging area. for (MarkupPointer i = _markupServices.CreateMarkupPointer(parentBlock, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin); i.IsLeftOf(range.Start); i.Right(true)) { MarkupContext iContext = i.Right(false); if (iContext.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && iContext.Element is IHTMLAnchorElement) { MarkupPointer j = _markupServices.CreateMarkupPointer(iContext.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); if (j.IsRightOfOrEqualTo(range.End)) { // Copy the tag at posn. i to location stagedBlockInsertionPoint // This is openning tag. Closing tag will be // automatically added by MSHTML. MarkupPointer i1 = i.Clone(); i1.Right(true); _markupServices.Copy(i, i1, stagedBlockInsertionPoint); // Skip over the closing tag, so stagedBlockInsertionPoint points between the openning and the closing stagedBlockInsertionPoint.Left(true); } j.Unposition(); } } //move the range content into the staged position _markupServices.Move(range.Start, range.End, stagedBlockInsertionPoint); stagedBlockInsertionPoint.Unposition(); bool splitBlock = !RemoveEmptyParentBlock(range.Clone(), parentBlock, maximumBounds); // If the range endpoint NOT chosen as the insertion point lies in a different block element, and // that parent block element is now empty, then just delete the parent block. MarkupPointer shallowerPoint = (deeperPoint.IsEqualTo(range.Start)) ? range.End : range.Start; MarkupPointer nonInsertionPoint = _markupServices.CreateMarkupPointer(shallowerPoint); IHTMLElement otherParentBlock = nonInsertionPoint.GetParentElement( ElementFilters.CreateCompoundElementFilter(ElementFilters.BLOCK_ELEMENTS, new IHTMLElementFilter(IsSplitStopElement))); if (otherParentBlock.sourceIndex != parentBlock.sourceIndex) RemoveEmptyParentBlock(range.Clone(), otherParentBlock, maximumBounds); if (splitBlock) { //split the block at the insertion point SplitBlockForApplyingBlockStyles(insertionPoint, maximumBounds); } //move the staged block content back to the insertion point and setup the range pointers //to wrap the re-inserted block content. range.Start.MoveToPointer(insertionPoint); range.End.MoveToPointer(insertionPoint); _markupServices.Move(stagedBlockContent.Start, stagedBlockContent.End, insertionPoint); //Note: the range is now re-positioned around the same content, but all of the parent //elements have been closed to prepare for getting new parent block elements around the //range //convert the range's content into block regions and remove block elements that were //parenting the regions. InnerBlockRegion[] blockRegions = GetNormalizedBlockContentRegions(range); //update all of the block regions with the desired new block style element foreach (InnerBlockRegion blockRegion in blockRegions) { IHTMLElement newParentElement = WrapRangeInBlockElement(blockRegion.ContentRange, styleTagId); // The old parent element may have had an alignment set on it. IHTMLElement oldParentElement = blockRegion.OldParentElement ?? parentBlock; if (oldParentElement != null) { string oldAlignment = oldParentElement.getAttribute("align", 2) as string; if (!String.IsNullOrEmpty(oldAlignment)) newParentElement.setAttribute("align", oldAlignment, 0); } } } finally { range.Start.PopCling(); range.Start.PopGravity(); range.End.PopCling(); range.End.PopGravity(); } } /// <summary> /// Returns true if the parent element was removed and false otherwise. /// </summary> private bool RemoveEmptyParentBlock(MarkupRange range, IHTMLElement parentBlock, MarkupRange maximumBounds) { if (parentBlock != null) { range.MoveToElement(parentBlock, false); if (maximumBounds.InRange(range) && range.IsEmptyOfContent()) { if (!IsSplitStopElement(parentBlock)) { //delete the parent node (only if it doesn't fall outside the maxrange (bug 465995)) range.MoveToElement(parentBlock, true); //expand the range around deletion area to test for maxBounds exceeded if (maximumBounds.InRange(range)) { (parentBlock as IHTMLDOMNode).removeNode(true); return true; } } } } return false; } /// <summary> /// Returns the markup pointer that is most deeply placed within the DOM. /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> private MarkupPointer GetDeeperPoint(MarkupPointer p1, MarkupPointer p2) { IHTMLElement startElement = p1.CurrentScope; IHTMLElement endElement = p2.CurrentScope; int startSourceIndex = startElement != null ? startElement.sourceIndex : -1; int endSourceIndex = startElement != null ? endElement.sourceIndex : -1; if (startSourceIndex > endSourceIndex || (startSourceIndex == endSourceIndex && p1.IsRightOfOrEqualTo(p2))) return p1; else return p2; } private IHTMLElement WrapRangeInBlockElement(MarkupRange blockRegion, _ELEMENT_TAG_ID styleTagId) { MarkupRange insertionRange = _markupServices.CreateMarkupRange(); //create the new block element IHTMLElement newBlockElement = _markupServices.CreateElement(styleTagId, null); //insert the new block element in front of the block content insertionRange.Start.MoveToPointer(blockRegion.Start); insertionRange.End.MoveToPointer(blockRegion.Start); _markupServices.InsertElement(newBlockElement, insertionRange.Start, insertionRange.End); //move the block content inside the new block element insertionRange.Start.MoveAdjacentToElement(newBlockElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin); blockRegion.Start.MoveAdjacentToElement(newBlockElement, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd); _markupServices.Move(blockRegion.Start, blockRegion.End, insertionRange.Start); return newBlockElement; } private IHTMLElement GetBodyElement() { return (_markupServices.MarkupServicesRaw as IHTMLDocument2).body; } private void SplitBlockForApplyingBlockStyles(MarkupPointer splitPoint, MarkupRange maximumBounds) { //find the split stop parent IHTMLElement splitStop = splitPoint.GetParentElement(new IHTMLElementFilter(IsSplitStopElement)); if (splitStop != null) { MarkupPointer stopLocation = _markupServices.CreateMarkupPointer(splitStop, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin); if (maximumBounds.InRange(stopLocation)) { stopLocation.MoveAdjacentToElement(splitStop, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); if (maximumBounds.InRange(stopLocation)) { maximumBounds = maximumBounds.Clone(); maximumBounds.MoveToElement(splitStop, false); } } } MarkupHelpers.SplitBlockForInsertionOrBreakout(_markupServices, maximumBounds, splitPoint); } private bool IsSplitStopElement(IHTMLElement e) { return ElementFilters.IsListItemElement(e) || ElementFilters.IsBlockQuoteElement(e) || ElementFilters.IsTableCellElement(e); } /// <summary> /// Splits the specified range into self-contained stylable block regions. /// </summary> /// <param name="range"></param> /// <returns></returns> private MarkupRange[] GetSelectableBlockRegions(MarkupRange range) { ArrayList regions = new ArrayList(); ElementBreakRegion[] breakRegions = SplitIntoElementRegions(range, new IHTMLElementFilter(IsSplitStopElement)); //DumpBreakRegions(breakRegions); foreach (ElementBreakRegion breakRegion in breakRegions) { //save the closed block range and start the next range if (!breakRegion.ContentRange.IsEmptyOfContent()) regions.Add(breakRegion.ContentRange); } return (MarkupRange[])regions.ToArray(typeof(MarkupRange)); } /// <summary> /// Splits the specified range into block regions, and removes all block elements. /// </summary> /// <param name="range"></param> /// <returns></returns> private InnerBlockRegion[] GetNormalizedBlockContentRegions(MarkupRange range) { ArrayList regions = new ArrayList(); ElementBreakRegion[] breakRegions = SplitIntoElementRegions(range, ElementFilters.BLOCK_ELEMENTS); //DumpBreakRegions(breakRegions); foreach (ElementBreakRegion breakRegion in breakRegions) { //save the closed block range and start the next range if (!breakRegion.ContentRange.IsEmptyOfContent()) regions.Add(new InnerBlockRegion(breakRegion.ContentRange, breakRegion.BreakStartElement ?? breakRegion.BreakEndElement)); //remove the break elements if they should be deleted if (ShouldDeleteForBlockFormatting(breakRegion.BreakStartElement)) _markupServices.RemoveElement(breakRegion.BreakStartElement); if (ShouldDeleteForBlockFormatting(breakRegion.BreakEndElement)) _markupServices.RemoveElement(breakRegion.BreakEndElement); } return (InnerBlockRegion[])regions.ToArray(typeof(InnerBlockRegion)); } /*private void DumpBreakRegions(params ElementBreakRegion[] breakRegions) { foreach(ElementBreakRegion breakRegion in breakRegions) { String elementStartName = breakRegion.BreakStartElement != null ? breakRegion.BreakStartElement.tagName : ""; String elementEndName = breakRegion.BreakEndElement != null ? breakRegion.BreakEndElement.tagName : ""; String breakContent = breakRegion.ContentRange.Text; if(breakContent != null) breakContent = breakContent.Replace('\r', ' ').Replace('\n', ' '); else breakContent = ""; Trace.WriteLine(String.Format("<{0}>{1}<{2}>", elementStartName, breakContent, elementEndName)); } }*/ /// <summary> /// Splits the specified range into regions based on a region break filter. /// </summary> /// <param name="range"></param> /// <returns></returns> private ElementBreakRegion[] SplitIntoElementRegions(MarkupRange range, IHTMLElementFilter regionBreakFilter) { ArrayList regions = new ArrayList(); MarkupRange blockRange = _markupServices.CreateMarkupRange(); blockRange.Start.MoveToPointer(range.Start); blockRange.End.MoveToPointer(range.Start); MarkupContext moveContext = new MarkupContext(); ElementBreakRegion currentRegion = new ElementBreakRegion(blockRange, null, null); while (currentRegion.ContentRange.End.IsLeftOf(range.End)) { if (moveContext.Element != null) { if (regionBreakFilter(moveContext.Element)) { //move the end of the region back before the break element to close this region currentRegion.ContentRange.End.Left(true); //save the closed region and start the next region currentRegion.BreakEndElement = moveContext.Element; regions.Add(currentRegion); currentRegion = new ElementBreakRegion(currentRegion.ContentRange.Clone(), moveContext.Element, null); currentRegion.ContentRange.Start.MoveToPointer(currentRegion.ContentRange.End); //move the region start over the break element currentRegion.ContentRange.Start.Right(true, moveContext); currentRegion.ContentRange.End.MoveToPointer(currentRegion.ContentRange.Start); } } currentRegion.ContentRange.End.Right(true, moveContext); } //save the last break region if (moveContext.Element != null && regionBreakFilter(moveContext.Element)) { //move the end of the region back before the break element to close this region currentRegion.ContentRange.End.Left(true); } if (currentRegion.ContentRange.End.IsRightOf(range.End)) currentRegion.ContentRange.End.MoveToPointer(range.End); regions.Add(currentRegion); return (ElementBreakRegion[])regions.ToArray(typeof(ElementBreakRegion)); } private void MovePointerLeftUntilRegionBreak(MarkupPointer p, IHTMLElementFilter regionBreakFilter, MarkupPointer leftBoundary) { MarkupContext moveContext = new MarkupContext(); while (p.IsRightOf(leftBoundary)) { p.Left(true, moveContext); if (moveContext.Element != null && regionBreakFilter(moveContext.Element)) { p.Right(true); return; } } } private void MovePointerRightUntilRegionBreak(MarkupPointer p, IHTMLElementFilter regionBreakFilter, MarkupPointer rightBoundary) { MarkupContext moveContext = new MarkupContext(); while (p.IsLeftOf(rightBoundary)) { p.Right(true, moveContext); if (moveContext.Element != null && regionBreakFilter(moveContext.Element)) { p.Left(true); return; } } } private bool ShouldDeleteForBlockFormatting(IHTMLElement e) { if (e == null || e.sourceIndex == -1) return false; Debug.Assert(!ElementFilters.IsListItemElement(e) && !ElementFilters.IsBlockQuoteElement(e) && !ElementFilters.IsTableCellElement(e), ""); return ElementFilters.IsBlockElement(e) && !ElementFilters.IsListItemElement(e) && !ElementFilters.IsBlockQuoteElement(e); } private class ElementBreakRegion { public ElementBreakRegion(MarkupRange contentRange, IHTMLElement breakStartElement, IHTMLElement breakEndElement) { BreakStartElement = breakStartElement; BreakEndElement = breakEndElement; ContentRange = contentRange; } public IHTMLElement BreakStartElement; public IHTMLElement BreakEndElement; public MarkupRange ContentRange; } /// <summary> /// Represents the inner region of a block element after the parent block element has been removed. /// </summary> private class InnerBlockRegion { public InnerBlockRegion(MarkupRange contentRange, IHTMLElement oldParentElement) { OldParentElement = oldParentElement; ContentRange = contentRange; } /// <summary> /// Be careful: this element has probably been removed from the DOM. /// </summary> public IHTMLElement OldParentElement { get; private set; } public MarkupRange ContentRange { get; private set; } } } /// <summary> /// As part of some editing operations, blocks of HTML can /// be violently changed. For example, when changing the /// block style (like going from p to h1) the entire block /// is deleted and rewritten. In these cases the selection /// gets lost. This class helps restore the selection to /// approximately where it was before. /// /// Before the change is applied, call Init so the class can /// save the position of the cursor relative to the visible /// characters in the range. After the change is applied, call /// Restore to put the cursor back to approximately where it /// was originally. Each call takes a MarkupRange that represents /// the boundary of the range that's being changed--at least /// the text contained therein should be the same for both calls. /// /// Limitations: /// * Doesn't preserve position relative to non-textual markup, /// like images, br's, etc. This means if the initial selection /// is adjacent to one of these things instead of surrounded on /// both sides by text (or the edge of the bounds/block) then the /// resulting placement will be approximate only. /// * Only works if the selection is empty. /// </summary> public class SelectionPositionPreservationHelper { public static SelectionPositionPreservationCookie Save(MshtmlMarkupServices markupServices, MarkupRange selection, MarkupRange bounds) { return new SelectionPositionPreservationCookie(markupServices, selection, bounds); } public static bool Restore(SelectionPositionPreservationCookie cookie, MarkupRange selection, MarkupRange bounds) { if (cookie == null) return false; return cookie.Restore(selection, bounds); } } public class SelectionPositionPreservationCookie { private readonly string initialMarkup; private readonly int movesRight; private readonly int charsLeft; internal SelectionPositionPreservationCookie(MshtmlMarkupServices markupServices, MarkupRange selection, MarkupRange bounds) { if (!selection.IsEmpty()) return; initialMarkup = bounds.HtmlText; NormalizeBounds(ref bounds); MarkupPointer p = bounds.Start.Clone(); movesRight = 0; while (p.IsLeftOf(selection.Start)) { movesRight++; p.Right(true); if (p.IsRightOf(bounds.End)) { movesRight = int.MaxValue; p.MoveToPointer(bounds.End); break; } } charsLeft = 0; while (p.IsRightOf(selection.Start)) { charsLeft++; p.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVCHAR); } } internal bool Restore(MarkupRange selection, MarkupRange bounds) { if (initialMarkup == null) return false; NormalizeBounds(ref bounds); /* if (initialMarkup != bounds.HtmlText) { Trace.Fail("Unexpected markup"); Trace.WriteLine(initialMarkup); Trace.WriteLine(bounds.HtmlText); return false; } */ selection.Start.MoveToPointer(bounds.Start); if (movesRight == int.MaxValue) { selection.Start.MoveToPointer(bounds.End); } else { for (int i = 0; i < movesRight; i++) { selection.Start.Right(true); } } for (int i = 0; i < charsLeft; i++) { selection.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVCHAR); } selection.Collapse(true); selection.ToTextRange().select(); Debug.Assert(bounds.InRange(selection, true), "Selection was out of bounds"); return true; } private static void NormalizeBounds(ref MarkupRange bounds) { bool cloned = false; if (bounds.Start.IsRightOf(bounds.End)) { if (!cloned) { cloned = true; bounds = bounds.Clone(); } bounds.Normalize(); } MarkupContext ctx = bounds.Start.Right(false); while (ctx.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && ElementFilters.IsBlockElement(ctx.Element)) { if (!cloned) { cloned = true; bounds = bounds.Clone(); } bounds.Start.Right(true); bounds.Start.Right(false, ctx); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Wintellect.PowerCollections; class Event : IComparable { public DateTime date; public String title; public String location; public Event(DateTime date, String title, String location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + title); if (location != null && location != "") { toString.Append(" | " + location); } return toString.ToString(); } } class Program { static StringBuilder output = new StringBuilder(); static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } class EventHolder { MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); byTitle.Add(title.ToLower(), newEvent); byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in byTitle[title]) { removed++; byDate.Remove(eventToRemove); } byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = byDate.RangeFrom(new Event(date, "", ""), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } static EventHolder events = new EventHolder(); static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = ""; } else { eventTitle = commandForExecution.Substring( firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1) .Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } }
//----------------------------------------------------------------------------- // Copyright (c) 2014 Daniel Buckmaster // // 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. //----------------------------------------------------------------------------- // These values should align with enum PolyFlags in walkabout/nav.h $Nav::WalkFlag = 1 << 0; $Nav::SwimFlag = 1 << 1; $Nav::JumpFlag = 1 << 2; $Nav::LedgeFlag = 1 << 3; $Nav::DropFlag = 1 << 4; $Nav::ClimbFlag = 1 << 5; $Nav::TeleportFlag = 1 << 6; function initializeNavEditor() { echo(" % - Initializing Navigation Editor"); // Execute all relevant scripts and GUIs. exec("./navEditor.cs"); exec("./NavEditorGui.gui"); exec("./NavEditorToolbar.gui"); exec("./NavEditorConsoleDlg.gui"); exec("./CreateNewNavMeshDlg.gui"); // Add ourselves to EditorGui, where all the other tools reside NavEditorGui.setVisible(false); NavEditorToolbar.setVisible(false); NavEditorOptionsWindow.setVisible(false); NavEditorTreeWindow.setVisible(false); NavEditorConsoleDlg.setVisible(false); EditorGui.add(NavEditorGui); EditorGui.add(NavEditorToolbar); EditorGui.add(NavEditorOptionsWindow); EditorGui.add(NavEditorTreeWindow); EditorGui.add(NavEditorConsoleDlg); new ScriptObject(NavEditorPlugin) { superClass = "EditorPlugin"; editorGui = NavEditorGui; }; // Bind shortcuts for the nav editor. %map = new ActionMap(); %map.bindCmd(keyboard, "1", "ENavEditorSelectModeBtn.performClick();", ""); %map.bindCmd(keyboard, "2", "ENavEditorLinkModeBtn.performClick();", ""); %map.bindCmd(keyboard, "3", "ENavEditorCoverModeBtn.performClick();", ""); %map.bindCmd(keyboard, "4", "ENavEditorTileModeBtn.performClick();", ""); %map.bindCmd(keyboard, "5", "ENavEditorTestModeBtn.performClick();", ""); %map.bindCmd(keyboard, "c", "NavEditorConsoleBtn.performClick();", ""); NavEditorPlugin.map = %map; NavEditorPlugin.initSettings(); } function destroyNavEditor() { } function NavEditorPlugin::onWorldEditorStartup(%this) { // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu("Navigation Editor", "", NavEditorPlugin); // Add ourselves to the ToolsToolbar. %tooltip = "Navigation Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar("NavEditorPlugin", "NavEditorPalette", expandFilename("tools/navEditor/images/nav-editor"), %tooltip); GuiWindowCtrl::attach(NavEditorOptionsWindow, NavEditorTreeWindow); // Add ourselves to the Editor Settings window. exec("./NavEditorSettingsTab.gui"); ESettingsWindow.addTabPage(ENavEditorSettingsPage); ENavEditorSettingsPage.init(); // Add items to World Editor Creator EWCreatorWindow.beginGroup("Navigation"); EWCreatorWindow.registerMissionObject("CoverPoint", "Cover point"); EWCreatorWindow.registerMissionObject("NavPath", "Nav Path"); EWCreatorWindow.endGroup(); } function ENavEditorSettingsPage::init(%this) { // Initialises the settings controls in the settings dialog box. %this-->SpawnClassOptions.clear(); %this-->SpawnClassOptions.add("AIPlayer"); %this-->SpawnClassOptions.setFirstSelected(); } function NavEditorPlugin::onActivated(%this) { %this.readSettings(); // Set a global variable so everyone knows we're editing! $Nav::EditorOpen = true; // Start off in Select mode. ToolsPaletteArray->NavEditorSelectMode.performClick(); EditorGui.bringToFront(NavEditorGui); NavEditorGui.setVisible(true); NavEditorGui.makeFirstResponder(true); NavEditorToolbar.setVisible(true); NavEditorOptionsWindow.setVisible(true); NavEditorTreeWindow.setVisible(true); // Inspect the ServerNavMeshSet, which contains all the NavMesh objects // in the mission. if(!isObject(ServerNavMeshSet)) new SimSet(ServerNavMeshSet); if(ServerNavMeshSet.getCount() == 0) MessageBoxYesNo("No NavMesh", "There is no NavMesh in this level. Would you like to create one?" SPC "If not, please use the Nav Editor to create a new NavMesh.", "Canvas.pushDialog(CreateNewNavMeshDlg);"); NavTreeView.open(ServerNavMeshSet, true); // Push our keybindings to the top. (See initializeNavEditor for where this // map was created.) %this.map.push(); // Store this on a dynamic field // in order to restore whatever setting // the user had before. %this.prevGizmoAlignment = GlobalGizmoProfile.alignment; // Always use Object alignment. GlobalGizmoProfile.alignment = "Object"; // Set the status until some other editing mode adds useful information. EditorGuiStatusBar.setInfo("Navigation editor."); EditorGuiStatusBar.setSelection(""); // Allow the Gui to setup. NavEditorGui.onEditorActivated(); Parent::onActivated(%this); } function NavEditorPlugin::onDeactivated(%this) { %this.writeSettings(); $Nav::EditorOpen = false; NavEditorGui.setVisible(false); NavEditorToolbar.setVisible(false); NavEditorOptionsWindow.setVisible(false); NavEditorTreeWindow.setVisible(false); %this.map.pop(); // Restore the previous Gizmo alignment settings. GlobalGizmoProfile.alignment = %this.prevGizmoAlignment; // Allow the Gui to cleanup. NavEditorGui.onEditorDeactivated(); Parent::onDeactivated(%this); } function NavEditorPlugin::onEditMenuSelect(%this, %editMenu) { %hasSelection = false; } function NavEditorPlugin::handleDelete(%this) { // Event happens when the user hits 'delete'. NavEditorGui.deleteSelected(); } function NavEditorPlugin::handleEscape(%this) { return NavEditorGui.onEscapePressed(); } function NavEditorPlugin::isDirty(%this) { return NavEditorGui.isDirty; } function NavEditorPlugin::onSaveMission(%this, %missionFile) { if(NavEditorGui.isDirty) { getScene(0).save(%missionFile); NavEditorGui.isDirty = false; } } //----------------------------------------------------------------------------- // Settings //----------------------------------------------------------------------------- function NavEditorPlugin::initSettings(%this) { EditorSettings.beginGroup("NavEditor", true); EditorSettings.setDefaultValue("SpawnClass", "AIPlayer"); EditorSettings.setDefaultValue("SpawnDatablock", "DefaultPlayerData"); EditorSettings.endGroup(); } function NavEditorPlugin::readSettings(%this) { EditorSettings.beginGroup("NavEditor", true); // Currently these are globals because of the way they are accessed in navMesh.cpp. $Nav::Editor::renderMesh = EditorSettings.value("RenderMesh"); $Nav::Editor::renderPortals = EditorSettings.value("RenderPortals"); $Nav::Editor::renderBVTree = EditorSettings.value("RenderBVTree"); NavEditorGui.spawnClass = EditorSettings.value("SpawnClass"); NavEditorGui.spawnDatablock = EditorSettings.value("SpawnDatablock"); NavEditorGui.backgroundBuild = EditorSettings.value("BackgroundBuild"); NavEditorGui.saveIntermediates = EditorSettings.value("SaveIntermediates"); NavEditorGui.playSoundWhenDone = EditorSettings.value("PlaySoundWhenDone"); // Build in the background by default, unless a preference has been saved. if (NavEditorGui.backgroundBuild $= "") { NavEditorGui.backgroundBuild = true; } EditorSettings.endGroup(); } function NavEditorPlugin::writeSettings(%this) { EditorSettings.beginGroup("NavEditor", true); EditorSettings.setValue("RenderMesh", $Nav::Editor::renderMesh); EditorSettings.setValue("RenderPortals", $Nav::Editor::renderPortals); EditorSettings.setValue("RenderBVTree", $Nav::Editor::renderBVTree); EditorSettings.setValue("SpawnClass", NavEditorGui.spawnClass); EditorSettings.setValue("SpawnDatablock", NavEditorGui.spawnDatablock); EditorSettings.setValue("BackgroundBuild", NavEditorGui.backgroundBuild); EditorSettings.setValue("SaveIntermediates", NavEditorGui.saveIntermediates); EditorSettings.setValue("PlaySoundWhenDone", NavEditorGui.playSoundWhenDone); EditorSettings.endGroup(); } function ESettingsWindowPopup::onWake(%this) { %this.setSelected(%this.findText(EditorSettings.value(%this.editorSettingsValue))); } function ESettingsWindowPopup::onSelect(%this) { EditorSettings.setValue(%this.editorSettingsValue, %this.getText()); eval(%this.editorSettingsRead); }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Networking.IPsecIkeDaemonBinding", Namespace="urn:iControl")] public partial class NetworkingIPsecIkeDaemon : iControlInterface { public NetworkingIPsecIkeDaemon() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_description( ) { object [] results = this.Invoke("get_description", new object [0]); return ((string)(results[0])); } public System.IAsyncResult Beginget_description(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[0], callback, asyncState); } public string Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_iskamp_natt_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_iskamp_natt_port( ) { object [] results = this.Invoke("get_iskamp_natt_port", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_iskamp_natt_port(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_iskamp_natt_port", new object[0], callback, asyncState); } public long Endget_iskamp_natt_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_iskamp_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_iskamp_port( ) { object [] results = this.Invoke("get_iskamp_port", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_iskamp_port(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_iskamp_port", new object[0], callback, asyncState); } public long Endget_iskamp_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_natt_keep_alive //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_natt_keep_alive( ) { object [] results = this.Invoke("get_natt_keep_alive", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_natt_keep_alive(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_natt_keep_alive", new object[0], callback, asyncState); } public long Endget_natt_keep_alive(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] public void set_description( string description ) { this.Invoke("set_description", new object [] { description}); } public System.IAsyncResult Beginset_description(string description, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { description}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_iskamp_natt_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] public void set_iskamp_natt_port( long value ) { this.Invoke("set_iskamp_natt_port", new object [] { value}); } public System.IAsyncResult Beginset_iskamp_natt_port(long value, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_iskamp_natt_port", new object[] { value}, callback, asyncState); } public void Endset_iskamp_natt_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_iskamp_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] public void set_iskamp_port( long value ) { this.Invoke("set_iskamp_port", new object [] { value}); } public System.IAsyncResult Beginset_iskamp_port(long value, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_iskamp_port", new object[] { value}, callback, asyncState); } public void Endset_iskamp_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_natt_keep_alive //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkeDaemon", RequestNamespace="urn:iControl:Networking/IPsecIkeDaemon", ResponseNamespace="urn:iControl:Networking/IPsecIkeDaemon")] public void set_natt_keep_alive( long value ) { this.Invoke("set_natt_keep_alive", new object [] { value}); } public System.IAsyncResult Beginset_natt_keep_alive(long value, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_natt_keep_alive", new object[] { value}, callback, asyncState); } public void Endset_natt_keep_alive(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
using System; using System.Collections.Generic; using BTDB.KVDBLayer.BTreeMem; namespace BTDB.KVDBLayer; class InMemoryKeyValueDBTransaction : IKeyValueDBTransaction { readonly InMemoryKeyValueDB _keyValueDB; IBTreeRootNode? _btreeRoot; readonly List<NodeIdxPair> _stack = new List<NodeIdxPair>(); bool _writing; readonly bool _readOnly; bool _preapprovedWriting; long _keyIndex; long _cursorMovedCounter; public InMemoryKeyValueDBTransaction(InMemoryKeyValueDB keyValueDB, IBTreeRootNode btreeRoot, bool writing, bool readOnly) { _preapprovedWriting = writing; _readOnly = readOnly; _keyValueDB = keyValueDB; _btreeRoot = btreeRoot; _keyIndex = -1; _cursorMovedCounter = 0; } public bool FindFirstKey(in ReadOnlySpan<byte> prefix) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out _keyIndex, prefix, (uint)prefix.Length) == FindResult.NotFound) { return false; } return true; } public bool FindLastKey(in ReadOnlySpan<byte> prefix) { _cursorMovedCounter++; _keyIndex = _btreeRoot!.FindLastWithPrefix(prefix); if (_keyIndex == -1) { _stack.Clear(); return false; } _btreeRoot!.FillStackByIndex(_stack, _keyIndex); return true; } public bool FindPreviousKey(in ReadOnlySpan<byte> prefix) { if (_keyIndex < 0) return FindLastKey(prefix); _cursorMovedCounter++; if (_btreeRoot!.FindPreviousKey(_stack)) { if (CheckPrefixIn(prefix, GetCurrentKeyFromStack())) { _keyIndex--; return true; } } InvalidateCurrentKey(); return false; } public bool FindNextKey(in ReadOnlySpan<byte> prefix) { if (_keyIndex < 0) return FindFirstKey(prefix); _cursorMovedCounter++; if (_btreeRoot!.FindNextKey(_stack)) { if (CheckPrefixIn(prefix, GetCurrentKeyFromStack())) { _keyIndex++; return true; } } InvalidateCurrentKey(); return false; } public FindResult Find(in ReadOnlySpan<byte> key, uint prefixLen) { _cursorMovedCounter++; return _btreeRoot!.FindKey(_stack, out _keyIndex, key, prefixLen); } public bool CreateOrUpdateKeyValue(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value) { _cursorMovedCounter++; MakeWritable(); var ctx = new CreateOrUpdateCtx { Key = key, Value = value, Stack = _stack }; _btreeRoot!.CreateOrUpdate(ref ctx); _keyIndex = ctx.KeyIndex; return ctx.Created; } void MakeWritable() { if (_writing) return; if (_preapprovedWriting) { _writing = true; _preapprovedWriting = false; return; } if (_readOnly) { throw new BTDBTransactionRetryException("Cannot write from readOnly transaction"); } var oldBTreeRoot = _btreeRoot; _btreeRoot = _keyValueDB.MakeWritableTransaction(this, oldBTreeRoot!); _btreeRoot.DescriptionForLeaks = _descriptionForLeaks; _writing = true; InvalidateCurrentKey(); } public long GetKeyValueCount() { return _btreeRoot!.CalcKeyCount(); } public long GetKeyIndex() { if (_keyIndex < 0) return -1; return _keyIndex; } public bool SetKeyIndex(in ReadOnlySpan<byte> prefix, long index) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out _keyIndex, prefix, (uint)prefix.Length) == FindResult.NotFound) { return false; } index += _keyIndex; if (index < _btreeRoot!.CalcKeyCount()) { _btreeRoot!.FillStackByIndex(_stack, index); _keyIndex = index; if (CheckPrefixIn(prefix, GetCurrentKeyFromStack())) { return true; } } InvalidateCurrentKey(); return false; } public bool SetKeyIndex(long index) { _cursorMovedCounter++; _keyIndex = index; if (index < 0 || index >= _btreeRoot!.CalcKeyCount()) { InvalidateCurrentKey(); return false; } _btreeRoot!.FillStackByIndex(_stack, index); return true; } bool CheckPrefixIn(in ReadOnlySpan<byte> prefix, in ReadOnlySpan<byte> key) { return BTreeRoot.KeyStartsWithPrefix(prefix, key); } ReadOnlySpan<byte> GetCurrentKeyFromStack() { var nodeIdxPair = _stack[^1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx); } public void InvalidateCurrentKey() { _cursorMovedCounter++; _keyIndex = -1; _stack.Clear(); } public bool IsValidKey() { return _keyIndex >= 0; } public ReadOnlySpan<byte> GetKey() { if (!IsValidKey()) return new ReadOnlySpan<byte>(); return GetCurrentKeyFromStack(); } public byte[] GetKeyToArray() { var nodeIdxPair = _stack[^1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).ToArray(); } public ReadOnlySpan<byte> GetKey(ref byte buffer, int bufferLength) { if (!IsValidKey()) return new ReadOnlySpan<byte>(); return GetCurrentKeyFromStack(); } public ReadOnlySpan<byte> GetClonedValue(ref byte buffer, int bufferLength) { // it is always read only memory already return GetValue(); } public ReadOnlySpan<byte> GetValue() { if (!IsValidKey()) return new ReadOnlySpan<byte>(); var nodeIdxPair = _stack[^1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); } void EnsureValidKey() { if (_keyIndex < 0) { throw new InvalidOperationException("Current key is not valid"); } } public void SetValue(in ReadOnlySpan<byte> value) { EnsureValidKey(); var keyIndexBackup = _keyIndex; MakeWritable(); if (_keyIndex != keyIndexBackup) { _keyIndex = keyIndexBackup; _btreeRoot!.FillStackByIndex(_stack, _keyIndex); } var nodeIdxPair = _stack[^1]; ((IBTreeLeafNode)nodeIdxPair.Node).SetMemberValue(nodeIdxPair.Idx, value); } public void EraseCurrent() { _cursorMovedCounter++; EnsureValidKey(); var keyIndex = _keyIndex; MakeWritable(); InvalidateCurrentKey(); _btreeRoot!.EraseRange(keyIndex, keyIndex); } public bool EraseCurrent(in ReadOnlySpan<byte> exactKey) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out var keyIndex, exactKey, 0) != FindResult.Exact) { InvalidateCurrentKey(); return false; } MakeWritable(); InvalidateCurrentKey(); _btreeRoot!.EraseRange(keyIndex, keyIndex); return true; } public bool EraseCurrent(in ReadOnlySpan<byte> exactKey, ref byte buffer, int bufferLength, out ReadOnlySpan<byte> value) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out var keyIndex, exactKey, 0) != FindResult.Exact) { InvalidateCurrentKey(); value = ReadOnlySpan<byte>.Empty; return false; } _keyIndex = 0; // Fake value is enough value = GetClonedValue(ref buffer, bufferLength); MakeWritable(); InvalidateCurrentKey(); _btreeRoot!.EraseRange(keyIndex, keyIndex); return true; } public void EraseAll() { _cursorMovedCounter++; EraseRange(0, GetKeyValueCount() - 1); } public void EraseRange(long firstKeyIndex, long lastKeyIndex) { if (firstKeyIndex < 0) firstKeyIndex = 0; if (lastKeyIndex >= GetKeyValueCount()) lastKeyIndex = GetKeyValueCount() - 1; if (lastKeyIndex < firstKeyIndex) return; _cursorMovedCounter++; MakeWritable(); InvalidateCurrentKey(); _btreeRoot!.EraseRange(firstKeyIndex, lastKeyIndex); } public bool IsWriting() { return _writing || _preapprovedWriting; } public bool IsReadOnly() { return _readOnly; } public bool IsDisposed() { return _btreeRoot == null; } public ulong GetCommitUlong() { return _btreeRoot!.CommitUlong; } public void SetCommitUlong(ulong value) { if (_btreeRoot!.CommitUlong != value) { MakeWritable(); _btreeRoot!.CommitUlong = value; } } public void NextCommitTemporaryCloseTransactionLog() { // There is no transaction log ... } public void Commit() { if (_btreeRoot! == null) throw new BTDBException("Transaction already committed or disposed"); InvalidateCurrentKey(); var currentBtreeRoot = _btreeRoot; _btreeRoot = null; if (_preapprovedWriting) { _preapprovedWriting = false; _keyValueDB.RevertWritingTransaction(); } else if (_writing) { _keyValueDB.CommitWritingTransaction(currentBtreeRoot!); _writing = false; } } public void Dispose() { if (_writing || _preapprovedWriting) { _keyValueDB.RevertWritingTransaction(); _writing = false; _preapprovedWriting = false; } _btreeRoot = null; } public long GetTransactionNumber() { return _btreeRoot!.TransactionId; } public long CursorMovedCounter => _cursorMovedCounter; public KeyValuePair<uint, uint> GetStorageSizeOfCurrentKey() { var nodeIdxPair = _stack[^1]; return new KeyValuePair<uint, uint>( (uint)((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).Length, (uint)((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx).Length); } public ulong GetUlong(uint idx) { return _btreeRoot!.GetUlong(idx); } public void SetUlong(uint idx, ulong value) { if (_btreeRoot!.GetUlong(idx) != value) { MakeWritable(); _btreeRoot!.SetUlong(idx, value); } } public uint GetUlongCount() { return _btreeRoot!.GetUlongCount(); } string? _descriptionForLeaks; public DateTime CreatedTime { get; } = DateTime.UtcNow; public string? DescriptionForLeaks { get => _descriptionForLeaks; set { _descriptionForLeaks = value; if (_preapprovedWriting || _writing) _btreeRoot!.DescriptionForLeaks = value; } } public IKeyValueDB Owner => _keyValueDB; public bool RollbackAdvised { get; set; } }
// ---------------------------------------------------------------------------- // <copyright file="PunClasses.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH // </copyright> // <summary> // Wraps up smaller classes that don't need their own file. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- #pragma warning disable 1587 /// \defgroup publicApi Public API /// \brief Groups the most important classes that you need to understand early on. /// /// \defgroup optionalGui Optional Gui Elements /// \brief Useful GUI elements for PUN. /// /// \defgroup callbacks Callbacks /// \brief Callback Interfaces #pragma warning restore 1587 namespace Photon.Pun { using System; using System.Collections.Generic; using System.Reflection; using ExitGames.Client.Photon; using UnityEngine; using UnityEngine.SceneManagement; using Photon.Realtime; using SupportClassPun = ExitGames.Client.Photon.SupportClass; /// <summary>Replacement for RPC attribute with different name. Used to flag methods as remote-callable.</summary> public class PunRPC : Attribute { } /// <summary>Defines the OnPhotonSerializeView method to make it easy to implement correctly for observable scripts.</summary> /// \ingroup callbacks public interface IPunObservable { /// <summary> /// Called by PUN several times per second, so that your script can write and read synchronization data for the PhotonView. /// </summary> /// <remarks> /// This method will be called in scripts that are assigned as Observed component of a PhotonView.<br/> /// PhotonNetwork.SerializationRate affects how often this method is called.<br/> /// PhotonNetwork.SendRate affects how often packages are sent by this client.<br/> /// /// Implementing this method, you can customize which data a PhotonView regularly synchronizes. /// Your code defines what is being sent (content) and how your data is used by receiving clients. /// /// Unlike other callbacks, <i>OnPhotonSerializeView only gets called when it is assigned /// to a PhotonView</i> as PhotonView.observed script. /// /// To make use of this method, the PhotonStream is essential. It will be in "writing" mode" on the /// client that controls a PhotonView (PhotonStream.IsWriting == true) and in "reading mode" on the /// remote clients that just receive that the controlling client sends. /// /// If you skip writing any value into the stream, PUN will skip the update. Used carefully, this can /// conserve bandwidth and messages (which have a limit per room/second). /// /// Note that OnPhotonSerializeView is not called on remote clients when the sender does not send /// any update. This can't be used as "x-times per second Update()". /// </remarks> /// \ingroup publicApi void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info); } /// <summary> /// This interface is used as definition of all callback methods of PUN, except OnPhotonSerializeView. Preferably, implement them individually. /// </summary> /// <remarks> /// This interface is available for completeness, more than for actually implementing it in a game. /// You can implement each method individually in any MonoMehaviour, without implementing IPunCallbacks. /// /// PUN calls all callbacks by name. Don't use implement callbacks with fully qualified name. /// Example: IPunCallbacks.OnConnected won't get called by Unity's SendMessage(). /// /// PUN will call these methods on any script that implements them, analog to Unity's events and callbacks. /// The situation that triggers the call is described per method. /// /// OnPhotonSerializeView is NOT called like these callbacks! It's usage frequency is much higher and it is implemented in: IPunObservable. /// </remarks> /// \ingroup callbacks public interface IPunOwnershipCallbacks { /// <summary> /// Called when another player requests ownership of a PhotonView from you (the current owner). /// </summary> /// <remarks> /// The parameter viewAndPlayer contains: /// /// PhotonView view = viewAndPlayer[0] as PhotonView; /// /// Player requestingPlayer = viewAndPlayer[1] as Player; /// </remarks> /// <param name="targetView">PhotonView for which ownership gets requested.</param> /// <param name="requestingPlayer">Player who requests ownership.</param> void OnOwnershipRequest(PhotonView targetView, Player requestingPlayer); /// <summary> /// Called when ownership of a PhotonView is transfered to another player. /// </summary> /// <remarks> /// The parameter viewAndPlayers contains: /// /// PhotonView view = viewAndPlayers[0] as PhotonView; /// /// Player newOwner = viewAndPlayers[1] as Player; /// /// Player oldOwner = viewAndPlayers[2] as Player; /// </remarks> /// <example>void OnOwnershipTransfered(object[] viewAndPlayers) {} //</example> /// <param name="targetView">PhotonView for which ownership changed.</param> /// <param name="previousOwner">Player who was the previous owner (or null, if none).</param> void OnOwnershipTransfered(PhotonView targetView, Player previousOwner); } /// \ingroup callbacks public interface IPunInstantiateMagicCallback { void OnPhotonInstantiate(PhotonMessageInfo info); } /// <summary> /// Defines an interface for object pooling, used in PhotonNetwork.Instantiate and PhotonNetwork.Destroy. /// </summary> /// <remarks> /// To apply your custom IPunPrefabPool, set PhotonNetwork.PrefabPool. /// /// The pool has to return a valid, disabled GameObject when PUN calls Instantiate. /// Also, the position and rotation must be applied. /// /// Note that Awake and Start are only called once by Unity, so scripts on re-used GameObjects /// should make use of OnEnable and or OnDisable. When OnEnable gets called, the PhotonView /// is already updated to the new values. /// /// To be able to enable a GameObject, Instantiate must return an inactive object. /// /// Before PUN "destroys" GameObjects, it will disable them. /// /// If a component implements IPunInstantiateMagicCallback, PUN will call OnPhotonInstantiate /// when the networked object gets instantiated. If no components implement this on a prefab, /// PUN will optimize the instantiation and no longer looks up IPunInstantiateMagicCallback /// via GetComponents. /// </remarks> public interface IPunPrefabPool { /// <summary> /// Called to get an instance of a prefab. Must return valid, disabled GameObject with PhotonView. /// </summary> /// <param name="prefabId">The id of this prefab.</param> /// <param name="position">The position for the instance.</param> /// <param name="rotation">The rotation for the instance.</param> /// <returns>A disabled instance to use by PUN or null if the prefabId is unknown.</returns> GameObject Instantiate(string prefabId, Vector3 position, Quaternion rotation); /// <summary> /// Called to destroy (or just return) the instance of a prefab. It's disabled and the pool may reset and cache it for later use in Instantiate. /// </summary> /// <remarks> /// A pool needs some way to find out which type of GameObject got returned via Destroy(). /// It could be a tag, name, a component or anything similar. /// </remarks> /// <param name="gameObject">The instance to destroy.</param> void Destroy(GameObject gameObject); } /// <summary> /// This class adds the property photonView, while logging a warning when your game still uses the networkView. /// </summary> public class MonoBehaviourPun : MonoBehaviour { /// <summary>Cache field for the PhotonView on this GameObject.</summary> private PhotonView pvCache; /// <summary>A cached reference to a PhotonView on this GameObject.</summary> /// <remarks> /// If you intend to work with a PhotonView in a script, it's usually easier to write this.photonView. /// /// If you intend to remove the PhotonView component from the GameObject but keep this Photon.MonoBehaviour, /// avoid this reference or modify this code to use PhotonView.Get(obj) instead. /// </remarks> public PhotonView photonView { get { if (this.pvCache == null) { this.pvCache = PhotonView.Get(this); } return this.pvCache; } } } /// <summary> /// This class provides a .photonView and all callbacks/events that PUN can call. Override the events/methods you want to use. /// </summary> /// <remarks> /// By extending this class, you can implement individual methods as override. /// /// Visual Studio and MonoDevelop should provide the list of methods when you begin typing "override". /// <b>Your implementation does not have to call "base.method()".</b> /// /// This class implements all callback interfaces and extends <see cref="Photon.Pun.MonoBehaviourPun"/>. /// </remarks> /// \ingroup callbacks // the documentation for the interface methods becomes inherited when Doxygen builds it. public class MonoBehaviourPunCallbacks : MonoBehaviourPun, IConnectionCallbacks , IMatchmakingCallbacks , IInRoomCallbacks, ILobbyCallbacks { public virtual void OnEnable() { PhotonNetwork.AddCallbackTarget(this); } public virtual void OnDisable() { PhotonNetwork.RemoveCallbackTarget(this); } /// <summary> /// Called to signal that the raw connection got established but before the client can call operation on the server. /// </summary> /// <remarks> /// After the (low level transport) connection is established, the client will automatically send /// the Authentication operation, which needs to get a response before the client can call other operations. /// /// Your logic should wait for either: OnRegionListReceived or OnConnectedToMaster. /// /// This callback is useful to detect if the server can be reached at all (technically). /// Most often, it's enough to implement OnDisconnected(). /// /// This is not called for transitions from the masterserver to game servers. /// </remarks> public virtual void OnConnected() { } /// <summary> /// Called when the local user/client left a room, so the game's logic can clean up it's internal state. /// </summary> /// <remarks> /// When leaving a room, the LoadBalancingClient will disconnect the Game Server and connect to the Master Server. /// This wraps up multiple internal actions. /// /// Wait for the callback OnConnectedToMaster, before you use lobbies and join or create rooms. /// </remarks> public virtual void OnLeftRoom() { } /// <summary> /// Called after switching to a new MasterClient when the current one leaves. /// </summary> /// <remarks> /// This is not called when this client enters a room. /// The former MasterClient is still in the player list when this method get called. /// </remarks> public virtual void OnMasterClientSwitched(Player newMasterClient) { } /// <summary> /// Called when the server couldn't create a room (OpCreateRoom failed). /// </summary> /// <remarks> /// The most common cause to fail creating a room, is when a title relies on fixed room-names and the room already exists. /// </remarks> /// <param name="returnCode">Operation ReturnCode from the server.</param> /// <param name="message">Debug message for the error.</param> public virtual void OnCreateRoomFailed(short returnCode, string message) { } /// <summary> /// Called when a previous OpJoinRoom call failed on the server. /// </summary> /// <remarks> /// The most common causes are that a room is full or does not exist (due to someone else being faster or closing the room). /// </remarks> /// <param name="returnCode">Operation ReturnCode from the server.</param> /// <param name="message">Debug message for the error.</param> public virtual void OnJoinRoomFailed(short returnCode, string message) { } /// <summary> /// Called when this client created a room and entered it. OnJoinedRoom() will be called as well. /// </summary> /// <remarks> /// This callback is only called on the client which created a room (see OpCreateRoom). /// /// As any client might close (or drop connection) anytime, there is a chance that the /// creator of a room does not execute OnCreatedRoom. /// /// If you need specific room properties or a "start signal", implement OnMasterClientSwitched() /// and make each new MasterClient check the room's state. /// </remarks> public virtual void OnCreatedRoom() { } /// <summary> /// Called on entering a lobby on the Master Server. The actual room-list updates will call OnRoomListUpdate. /// </summary> /// <remarks> /// While in the lobby, the roomlist is automatically updated in fixed intervals (which you can't modify in the public cloud). /// The room list gets available via OnRoomListUpdate. /// </remarks> public virtual void OnJoinedLobby() { } /// <summary> /// Called after leaving a lobby. /// </summary> /// <remarks> /// When you leave a lobby, [OpCreateRoom](@ref OpCreateRoom) and [OpJoinRandomRoom](@ref OpJoinRandomRoom) /// automatically refer to the default lobby. /// </remarks> public virtual void OnLeftLobby() { } /// <summary> /// Called after disconnecting from the Photon server. It could be a failure or intentional /// </summary> /// <remarks> /// The reason for this disconnect is provided as DisconnectCause. /// </remarks> public virtual void OnDisconnected(DisconnectCause cause) { } /// <summary> /// Called when the Name Server provided a list of regions for your title. /// </summary> /// <remarks>Check the RegionHandler class description, to make use of the provided values.</remarks> /// <param name="regionHandler">The currently used RegionHandler.</param> public virtual void OnRegionListReceived(RegionHandler regionHandler) { } /// <summary> /// Called for any update of the room-listing while in a lobby (InLobby) on the Master Server. /// </summary> /// <remarks> /// Each item is a RoomInfo which might include custom properties (provided you defined those as lobby-listed when creating a room). /// Not all types of lobbies provide a listing of rooms to the client. Some are silent and specialized for server-side matchmaking. /// </remarks> public virtual void OnRoomListUpdate(List<RoomInfo> roomList) { } /// <summary> /// Called when the LoadBalancingClient entered a room, no matter if this client created it or simply joined. /// </summary> /// <remarks> /// When this is called, you can access the existing players in Room.Players, their custom properties and Room.CustomProperties. /// /// In this callback, you could create player objects. For example in Unity, instantiate a prefab for the player. /// /// If you want a match to be started "actively", enable the user to signal "ready" (using OpRaiseEvent or a Custom Property). /// </remarks> public virtual void OnJoinedRoom() { } /// <summary> /// Called when a remote player entered the room. This Player is already added to the playerlist. /// </summary> /// <remarks> /// If your game starts with a certain number of players, this callback can be useful to check the /// Room.playerCount and find out if you can start. /// </remarks> public virtual void OnPlayerEnteredRoom(Player newPlayer) { } /// <summary> /// Called when a remote player left the room or became inactive. Check otherPlayer.IsInactive. /// </summary> /// <remarks> /// If another player leaves the room or if the server detects a lost connection, this callback will /// be used to notify your game logic. /// /// Depending on the room's setup, players may become inactive, which means they may return and retake /// their spot in the room. In such cases, the Player stays in the Room.Players dictionary. /// /// If the player is not just inactive, it gets removed from the Room.Players dictionary, before /// the callback is called. /// </remarks> public virtual void OnPlayerLeftRoom(Player otherPlayer) { } /// <summary> /// Called when a previous OpJoinRandom call failed on the server. /// </summary> /// <remarks> /// The most common causes are that a room is full or does not exist (due to someone else being faster or closing the room). /// /// When using multiple lobbies (via OpJoinLobby or a TypedLobby parameter), another lobby might have more/fitting rooms.<br/> /// </remarks> /// <param name="returnCode">Operation ReturnCode from the server.</param> /// <param name="message">Debug message for the error.</param> public virtual void OnJoinRandomFailed(short returnCode, string message) { } /// <summary> /// Called when the client is connected to the Master Server and ready for matchmaking and other tasks. /// </summary> /// <remarks> /// The list of available rooms won't become available unless you join a lobby via LoadBalancingClient.OpJoinLobby. /// You can join rooms and create them even without being in a lobby. The default lobby is used in that case. /// </remarks> public virtual void OnConnectedToMaster() { } /// <summary> /// Called when a room's custom properties changed. The propertiesThatChanged contains all that was set via Room.SetCustomProperties. /// </summary> /// <remarks> /// Since v1.25 this method has one parameter: Hashtable propertiesThatChanged.<br/> /// Changing properties must be done by Room.SetCustomProperties, which causes this callback locally, too. /// </remarks> /// <param name="propertiesThatChanged"></param> public virtual void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged) { } /// <summary> /// Called when custom player-properties are changed. Player and the changed properties are passed as object[]. /// </summary> /// <remarks> /// Changing properties must be done by Player.SetCustomProperties, which causes this callback locally, too. /// </remarks> /// /// <param name="targetPlayer">Contains Player that changed.</param> /// <param name="changedProps">Contains the properties that changed.</param> public virtual void OnPlayerPropertiesUpdate(Player target, Hashtable changedProps) { } /// <summary> /// Called when the server sent the response to a FindFriends request. /// </summary> /// <remarks> /// After calling OpFindFriends, the Master Server will cache the friend list and send updates to the friend /// list. The friends includes the name, userId, online state and the room (if any) for each requested user/friend. /// /// Use the friendList to update your UI and store it, if the UI should highlight changes. /// </remarks> public virtual void OnFriendListUpdate(List<FriendInfo> friendList) { } /// <summary> /// Called when your Custom Authentication service responds with additional data. /// </summary> /// <remarks> /// Custom Authentication services can include some custom data in their response. /// When present, that data is made available in this callback as Dictionary. /// While the keys of your data have to be strings, the values can be either string or a number (in Json). /// You need to make extra sure, that the value type is the one you expect. Numbers become (currently) int64. /// /// Example: void OnCustomAuthenticationResponse(Dictionary&lt;string, object&gt; data) { ... } /// </remarks> /// <see cref="https://doc.photonengine.com/en-us/realtime/current/reference/custom-authentication"/> public virtual void OnCustomAuthenticationResponse(Dictionary<string, object> data) { } /// <summary> /// Called when the custom authentication failed. Followed by disconnect! /// </summary> /// <remarks> /// Custom Authentication can fail due to user-input, bad tokens/secrets. /// If authentication is successful, this method is not called. Implement OnJoinedLobby() or OnConnectedToMaster() (as usual). /// /// During development of a game, it might also fail due to wrong configuration on the server side. /// In those cases, logging the debugMessage is very important. /// /// Unless you setup a custom authentication service for your app (in the [Dashboard](https://dashboard.photonengine.com)), /// this won't be called! /// </remarks> /// <param name="debugMessage">Contains a debug message why authentication failed. This has to be fixed during development.</param> public virtual void OnCustomAuthenticationFailed (string debugMessage) { } //TODO: Check if this needs to be implemented // in: IOptionalInfoCallbacks public virtual void OnWebRpcResponse(OperationResponse response) { } //TODO: Check if this needs to be implemented // in: IOptionalInfoCallbacks public virtual void OnLobbyStatisticsUpdate(List<TypedLobbyInfo> lobbyStatistics) { } } /// <summary> /// Container class for info about a particular message, RPC or update. /// </summary> /// \ingroup publicApi public struct PhotonMessageInfo { private readonly int timeInt; /// <summary>The sender of a message / event. May be null.</summary> public readonly Player Sender; public readonly PhotonView photonView; public PhotonMessageInfo(Player player, int timestamp, PhotonView view) { this.Sender = player; this.timeInt = timestamp; this.photonView = view; } [Obsolete("Use SentServerTime instead.")] public double timestamp { get { uint u = (uint) this.timeInt; double t = u; return t / 1000.0d; } } public double SentServerTime { get { uint u = (uint)this.timeInt; double t = u; return t / 1000.0d; } } public int SentServerTimestamp { get { return this.timeInt; } } public override string ToString() { return string.Format("[PhotonMessageInfo: Sender='{1}' Senttime={0}]", this.SentServerTime, this.Sender); } } /// <summary>Defines Photon event-codes as used by PUN.</summary> internal class PunEvent { public const byte RPC = 200; public const byte SendSerialize = 201; public const byte Instantiation = 202; public const byte CloseConnection = 203; public const byte Destroy = 204; public const byte RemoveCachedRPCs = 205; public const byte SendSerializeReliable = 206; // TS: added this but it's not really needed anymore public const byte DestroyPlayer = 207; // TS: added to make others remove all GOs of a player public const byte OwnershipRequest = 209; public const byte OwnershipTransfer = 210; public const byte VacantViewIds = 211; } /// <summary> /// This container is used in OnPhotonSerializeView() to either provide incoming data of a PhotonView or for you to provide it. /// </summary> /// <remarks> /// The IsWriting property will be true if this client is the "owner" of the PhotonView (and thus the GameObject). /// Add data to the stream and it's sent via the server to the other players in a room. /// On the receiving side, IsWriting is false and the data should be read. /// /// Send as few data as possible to keep connection quality up. An empty PhotonStream will not be sent. /// /// Use either Serialize() for reading and writing or SendNext() and ReceiveNext(). The latter two are just explicit read and /// write methods but do about the same work as Serialize(). It's a matter of preference which methods you use. /// </remarks> /// \ingroup publicApi public class PhotonStream { private List<object> writeData; private object[] readData; private byte currentItem; //Used to track the next item to receive. /// <summary>If true, this client should add data to the stream to send it.</summary> public bool IsWriting { get; private set; } /// <summary>If true, this client should read data send by another client.</summary> public bool IsReading { get { return !this.IsWriting; } } /// <summary>Count of items in the stream.</summary> public int Count { get { return this.IsWriting ? this.writeData.Count : this.readData.Length; } } /// <summary> /// Creates a stream and initializes it. Used by PUN internally. /// </summary> public PhotonStream(bool write, object[] incomingData) { this.IsWriting = write; if (!write && incomingData != null) { this.readData = incomingData; } } public void SetReadStream(object[] incomingData, byte pos = 0) { this.readData = incomingData; this.currentItem = pos; this.IsWriting = false; } internal void SetWriteStream(List<object> newWriteData, byte pos = 0) { if (pos != newWriteData.Count) { throw new Exception("SetWriteStream failed, because count does not match position value. pos: "+ pos + " newWriteData.Count:" + newWriteData.Count); } this.writeData = newWriteData; this.currentItem = pos; this.IsWriting = true; } internal List<object> GetWriteStream() { return this.writeData; } [Obsolete("Either SET the writeData with an empty List or use Clear().")] internal void ResetWriteStream() { this.writeData.Clear(); } /// <summary>Read next piece of data from the stream when IsReading is true.</summary> public object ReceiveNext() { if (this.IsWriting) { Debug.LogError("Error: you cannot read this stream that you are writing!"); return null; } object obj = this.readData[this.currentItem]; this.currentItem++; return obj; } /// <summary>Read next piece of data from the stream without advancing the "current" item.</summary> public object PeekNext() { if (this.IsWriting) { Debug.LogError("Error: you cannot read this stream that you are writing!"); return null; } object obj = this.readData[this.currentItem]; //this.currentItem++; return obj; } /// <summary>Add another piece of data to send it when IsWriting is true.</summary> public void SendNext(object obj) { if (!this.IsWriting) { Debug.LogError("Error: you cannot write/send to this stream that you are reading!"); return; } this.writeData.Add(obj); } [Obsolete("writeData is a list now. Use and re-use it directly.")] public bool CopyToListAndClear(List<object> target) { if (!this.IsWriting) return false; target.AddRange(this.writeData); this.writeData.Clear(); return true; } /// <summary>Turns the stream into a new object[].</summary> public object[] ToArray() { return this.IsWriting ? this.writeData.ToArray() : this.readData; } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref bool myBool) { if (this.IsWriting) { this.writeData.Add(myBool); } else { if (this.readData.Length > this.currentItem) { myBool = (bool) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref int myInt) { if (this.IsWriting) { this.writeData.Add(myInt); } else { if (this.readData.Length > this.currentItem) { myInt = (int) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref string value) { if (this.IsWriting) { this.writeData.Add(value); } else { if (this.readData.Length > this.currentItem) { value = (string) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref char value) { if (this.IsWriting) { this.writeData.Add(value); } else { if (this.readData.Length > this.currentItem) { value = (char) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref short value) { if (this.IsWriting) { this.writeData.Add(value); } else { if (this.readData.Length > this.currentItem) { value = (short) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref float obj) { if (this.IsWriting) { this.writeData.Add(obj); } else { if (this.readData.Length > this.currentItem) { obj = (float) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref Player obj) { if (this.IsWriting) { this.writeData.Add(obj); } else { if (this.readData.Length > this.currentItem) { obj = (Player) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref Vector3 obj) { if (this.IsWriting) { this.writeData.Add(obj); } else { if (this.readData.Length > this.currentItem) { obj = (Vector3) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref Vector2 obj) { if (this.IsWriting) { this.writeData.Add(obj); } else { if (this.readData.Length > this.currentItem) { obj = (Vector2) this.readData[this.currentItem]; this.currentItem++; } } } /// <summary> /// Will read or write the value, depending on the stream's IsWriting value. /// </summary> public void Serialize(ref Quaternion obj) { if (this.IsWriting) { this.writeData.Add(obj); } else { if (this.readData.Length > this.currentItem) { obj = (Quaternion) this.readData[this.currentItem]; this.currentItem++; } } } } public class SceneManagerHelper { public static string ActiveSceneName { get { Scene s = SceneManager.GetActiveScene(); return s.name; } } public static int ActiveSceneBuildIndex { get { return SceneManager.GetActiveScene().buildIndex; } } #if UNITY_EDITOR /// <summary>In Editor, we can access the active scene's name.</summary> public static string EditorActiveSceneName { get { return SceneManager.GetActiveScene().name; } } #endif } /// <summary> /// The default implementation of a PrefabPool for PUN, which actually Instantiates and Destroys GameObjects but pools a resource. /// </summary> /// <remarks> /// This pool is not actually storing GameObjects for later reuse. Instead, it's destroying used GameObjects. /// However, prefabs will be loaded from a Resources folder and cached, which speeds up Instantiation a bit. /// /// The ResourceCache is public, so it can be filled without relying on the Resources folders. /// </remarks> public class DefaultPool : IPunPrefabPool { /// <summary>Contains a GameObject per prefabId, to speed up instantiation.</summary> public readonly Dictionary<string, GameObject> ResourceCache = new Dictionary<string, GameObject>(); /// <summary>Returns an inactive instance of a networked GameObject, to be used by PUN.</summary> /// <param name="prefabId">String identifier for the networked object.</param> /// <param name="position">Location of the new object.</param> /// <param name="rotation">Rotation of the new object.</param> /// <returns></returns> public GameObject Instantiate(string prefabId, Vector3 position, Quaternion rotation) { GameObject res = null; bool cached = this.ResourceCache.TryGetValue(prefabId, out res); if (!cached) { res = (GameObject)Resources.Load(prefabId, typeof(GameObject)); if (res == null) { Debug.LogError("DefaultPool failed to load \"" + prefabId + "\" . Make sure it's in a \"Resources\" folder."); } else { this.ResourceCache.Add(prefabId, res); } } bool wasActive = res.activeSelf; if (wasActive) res.SetActive(false); GameObject instance =GameObject.Instantiate(res, position, rotation) as GameObject; if (wasActive) res.SetActive(true); return instance; } /// <summary>Simply destroys a GameObject.</summary> /// <param name="gameObject">The GameObject to get rid of.</param> public void Destroy(GameObject gameObject) { GameObject.Destroy(gameObject); } } /// <summary>Small number of extension methods that make it easier for PUN to work cross-Unity-versions.</summary> public static class PunExtensions { public static Dictionary<MethodInfo, ParameterInfo[]> ParametersOfMethods = new Dictionary<MethodInfo, ParameterInfo[]>(); public static ParameterInfo[] GetCachedParemeters(this MethodInfo mo) { ParameterInfo[] result; bool cached = ParametersOfMethods.TryGetValue(mo, out result); if (!cached) { result = mo.GetParameters(); ParametersOfMethods[mo] = result; } return result; } public static PhotonView[] GetPhotonViewsInChildren(this UnityEngine.GameObject go) { return go.GetComponentsInChildren<PhotonView>(true) as PhotonView[]; } public static PhotonView GetPhotonView(this UnityEngine.GameObject go) { return go.GetComponent<PhotonView>() as PhotonView; } /// <summary>compares the squared magnitude of target - second to given float value</summary> public static bool AlmostEquals(this Vector3 target, Vector3 second, float sqrMagnitudePrecision) { return (target - second).sqrMagnitude < sqrMagnitudePrecision; // TODO: inline vector methods to optimize? } /// <summary>compares the squared magnitude of target - second to given float value</summary> public static bool AlmostEquals(this Vector2 target, Vector2 second, float sqrMagnitudePrecision) { return (target - second).sqrMagnitude < sqrMagnitudePrecision; // TODO: inline vector methods to optimize? } /// <summary>compares the angle between target and second to given float value</summary> public static bool AlmostEquals(this Quaternion target, Quaternion second, float maxAngle) { return Quaternion.Angle(target, second) < maxAngle; } /// <summary>compares two floats and returns true of their difference is less than floatDiff</summary> public static bool AlmostEquals(this float target, float second, float floatDiff) { return Mathf.Abs(target - second) < floatDiff; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Classes: DirectoryObjectSecurity class ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Collections; using System.Security.Principal; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Security.AccessControl { public abstract class DirectoryObjectSecurity: ObjectSecurity { #region Constructors protected DirectoryObjectSecurity() : base(true, true) { return; } protected DirectoryObjectSecurity(CommonSecurityDescriptor securityDescriptor) : base(securityDescriptor) { return; } #endregion #region Private Methods private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, bool includeInherited, System.Type targetType) { ReadLock(); try { AuthorizationRuleCollection result = new AuthorizationRuleCollection(); if (!SecurityIdentifier.IsValidTargetTypeStatic(targetType)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeIdentityReferenceType"), "targetType"); } CommonAcl acl = null; if (access) { if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0) { acl = _securityDescriptor.DiscretionaryAcl; } } else // !access == audit { if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != 0) { acl = _securityDescriptor.SystemAcl; } } if (acl == null) { // // The required ACL was not present; return an empty collection. // return result; } IdentityReferenceCollection irTarget = null; if (targetType != typeof(SecurityIdentifier )) { IdentityReferenceCollection irSource = new IdentityReferenceCollection(acl.Count); for (int i = 0; i < acl.Count; i++) { // // Calling the indexer on a common ACL results in cloning, // (which would not be the case if we were to use the internal RawAcl property) // but also ensures that the resulting order of ACEs is proper // However, this is a big price to pay - cloning all the ACEs just so that // the canonical order could be ascertained just once. // A better way would be to have an internal method that would canonicalize the ACL // and call it once, then use the RawAcl. // QualifiedAce ace = acl[i] as QualifiedAce; if (ace == null) { // // Only consider qualified ACEs // continue; } if (ace.IsCallback == true) { // // Ignore callback ACEs // continue; } if (access) { if (ace.AceQualifier != AceQualifier.AccessAllowed && ace.AceQualifier != AceQualifier.AccessDenied) { continue; } } else { if (ace.AceQualifier != AceQualifier.SystemAudit) { continue; } } irSource.Add( ace.SecurityIdentifier ); } irTarget = irSource.Translate(targetType); } for (int i = 0; i < acl.Count; i++) { // // Calling the indexer on a common ACL results in cloning, // (which would not be the case if we were to use the internal RawAcl property) // but also ensures that the resulting order of ACEs is proper // However, this is a big price to pay - cloning all the ACEs just so that // the canonical order could be ascertained just once. // A better way would be to have an internal method that would canonicalize the ACL // and call it once, then use the RawAcl. // QualifiedAce ace = acl[i] as CommonAce; if (ace == null) { ace = acl[i] as ObjectAce; if (ace == null) { // // Only consider common or object ACEs // continue; } } if (ace.IsCallback == true) { // // Ignore callback ACEs // continue; } if (access) { if (ace.AceQualifier != AceQualifier.AccessAllowed && ace.AceQualifier != AceQualifier.AccessDenied) { continue; } } else { if (ace.AceQualifier != AceQualifier.SystemAudit) { continue; } } if ((includeExplicit && ((ace.AceFlags & AceFlags.Inherited) == 0)) || (includeInherited && ((ace.AceFlags & AceFlags.Inherited) != 0))) { IdentityReference iref = (targetType == typeof(SecurityIdentifier )) ? ace.SecurityIdentifier : irTarget[i]; if (access) { AccessControlType type; if (ace.AceQualifier == AceQualifier.AccessAllowed) { type = AccessControlType.Allow; } else { type = AccessControlType.Deny; } if (ace is ObjectAce) { ObjectAce objectAce = ace as ObjectAce; result.AddRule(AccessRuleFactory(iref, objectAce.AccessMask, objectAce.IsInherited, objectAce.InheritanceFlags, objectAce.PropagationFlags, type, objectAce.ObjectAceType, objectAce.InheritedObjectAceType)); } else { CommonAce commonAce = ace as CommonAce; if (commonAce == null) { continue; } result.AddRule(AccessRuleFactory(iref, commonAce.AccessMask, commonAce.IsInherited, commonAce.InheritanceFlags, commonAce.PropagationFlags, type)); } } else { if (ace is ObjectAce) { ObjectAce objectAce = ace as ObjectAce; result.AddRule(AuditRuleFactory(iref, objectAce.AccessMask, objectAce.IsInherited, objectAce.InheritanceFlags, objectAce.PropagationFlags, objectAce.AuditFlags, objectAce.ObjectAceType, objectAce.InheritedObjectAceType)); } else { CommonAce commonAce = ace as CommonAce; if (commonAce == null) { continue; } result.AddRule(AuditRuleFactory(iref, commonAce.AccessMask, commonAce.IsInherited, commonAce.InheritanceFlags, commonAce.PropagationFlags, commonAce.AuditFlags)); } } } } return result; } finally { ReadUnlock(); } } // // Modifies the DACL // private bool ModifyAccess(AccessControlModification modification, ObjectAccessRule rule, out bool modified) { bool result = true; if (_securityDescriptor.DiscretionaryAcl == null) { if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || modification == AccessControlModification.RemoveSpecific) { modified = false; return result; } _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(IsContainer, IsDS, GenericAcl.AclRevisionDS, 1); _securityDescriptor.AddControlFlags(ControlFlags.DiscretionaryAclPresent); } else if ((modification == AccessControlModification.Add || modification == AccessControlModification.Set || modification == AccessControlModification.Reset ) && ( rule.ObjectFlags != ObjectAceFlags.None )) { // // This will result in an object ace being added to the dacl, so the dacl revision must be AclRevisionDS // if ( _securityDescriptor.DiscretionaryAcl.Revision < GenericAcl.AclRevisionDS ) { // // we need to create a new dacl with the same aces as the existing one but the revision should be AclRevisionDS // byte[] binaryForm = new byte[_securityDescriptor.DiscretionaryAcl.BinaryLength]; _securityDescriptor.DiscretionaryAcl.GetBinaryForm(binaryForm, 0); binaryForm[0] = GenericAcl.AclRevisionDS; // revision is the first byte of the binary form _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(IsContainer, IsDS, new RawAcl(binaryForm, 0)); } } SecurityIdentifier sid = rule.IdentityReference.Translate(typeof(SecurityIdentifier )) as SecurityIdentifier; if (rule.AccessControlType == AccessControlType.Allow) { switch (modification) { case AccessControlModification.Add : _securityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Set : _securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Reset : _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty); _securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Remove : result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.RemoveAll : result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty); if (result == false) { Contract.Assert(false, "Invalid operation"); throw new SystemException(); } break; case AccessControlModification.RemoveSpecific : _securityDescriptor.DiscretionaryAcl.RemoveAccessSpecific(AccessControlType.Allow, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; default : throw new ArgumentOutOfRangeException( "modification", Environment.GetResourceString( "ArgumentOutOfRange_Enum" )); } } else if (rule.AccessControlType == AccessControlType.Deny) { switch (modification) { case AccessControlModification.Add : _securityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Set : _securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Reset : _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty); _securityDescriptor.DiscretionaryAcl.SetAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Remove : result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.RemoveAll : result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty); if (result == false) { Contract.Assert(false, "Invalid operation"); throw new SystemException(); } break; case AccessControlModification.RemoveSpecific : _securityDescriptor.DiscretionaryAcl.RemoveAccessSpecific(AccessControlType.Deny, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; default : throw new ArgumentOutOfRangeException( "modification", Environment.GetResourceString( "ArgumentOutOfRange_Enum" )); } } else { Contract.Assert(false, "rule.AccessControlType unrecognized"); throw new SystemException(); } modified = result; AccessRulesModified |= modified; return result; } // // Modifies the SACL // private bool ModifyAudit(AccessControlModification modification, ObjectAuditRule rule, out bool modified) { bool result = true; if (_securityDescriptor.SystemAcl == null) { if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || modification == AccessControlModification.RemoveSpecific) { modified = false; return result; } _securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, GenericAcl.AclRevisionDS, 1); _securityDescriptor.AddControlFlags(ControlFlags.SystemAclPresent); } else if ((modification == AccessControlModification.Add || modification == AccessControlModification.Set || modification == AccessControlModification.Reset ) && ( rule.ObjectFlags != ObjectAceFlags.None )) { // // This will result in an object ace being added to the sacl, so the sacl revision must be AclRevisionDS // if ( _securityDescriptor.SystemAcl.Revision < GenericAcl.AclRevisionDS ) { // // we need to create a new sacl with the same aces as the existing one but the revision should be AclRevisionDS // byte[] binaryForm = new byte[_securityDescriptor.SystemAcl.BinaryLength]; _securityDescriptor.SystemAcl.GetBinaryForm(binaryForm, 0); binaryForm[0] = GenericAcl.AclRevisionDS; // revision is the first byte of the binary form _securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, new RawAcl(binaryForm, 0)); } } SecurityIdentifier sid = rule.IdentityReference.Translate(typeof(SecurityIdentifier )) as SecurityIdentifier; switch (modification) { case AccessControlModification.Add : _securityDescriptor.SystemAcl.AddAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Set : _securityDescriptor.SystemAcl.SetAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Reset : _securityDescriptor.SystemAcl.RemoveAudit(AuditFlags.Failure | AuditFlags.Success, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty); _securityDescriptor.SystemAcl.SetAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.Remove : result = _securityDescriptor.SystemAcl.RemoveAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; case AccessControlModification.RemoveAll : result = _securityDescriptor.SystemAcl.RemoveAudit(AuditFlags.Failure | AuditFlags.Success, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty); if (result == false) { Contract.Assert(false, "Invalid operation"); throw new SystemException(); } break; case AccessControlModification.RemoveSpecific : _securityDescriptor.SystemAcl.RemoveAuditSpecific(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType); break; default : throw new ArgumentOutOfRangeException( "modification", Environment.GetResourceString( "ArgumentOutOfRange_Enum" )); } modified = result; AuditRulesModified |= modified; return result; } #endregion #region public Methods public virtual AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type, Guid objectType, Guid inheritedObjectType) { throw new NotImplementedException(); } public virtual AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags, Guid objectType, Guid inheritedObjectType) { throw new NotImplementedException(); } protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified) { if ( !this.AccessRuleType.IsAssignableFrom(rule.GetType()) ) { throw new ArgumentException( Environment.GetResourceString("AccessControl_InvalidAccessRuleType"), "rule"); } Contract.EndContractBlock(); return ModifyAccess(modification, rule as ObjectAccessRule, out modified); } protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified) { if ( !this.AuditRuleType.IsAssignableFrom(rule.GetType()) ) { throw new ArgumentException( Environment.GetResourceString("AccessControl_InvalidAuditRuleType"), "rule"); } Contract.EndContractBlock(); return ModifyAudit(modification, rule as ObjectAuditRule, out modified); } #endregion #region Public Methods protected void AddAccessRule(ObjectAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAccess(AccessControlModification.Add, rule, out modified); } finally { WriteUnlock(); } return; } protected void SetAccessRule(ObjectAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAccess(AccessControlModification.Set, rule, out modified); } finally { WriteUnlock(); } } protected void ResetAccessRule(ObjectAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAccess(AccessControlModification.Reset, rule, out modified); } finally { WriteUnlock(); } } protected bool RemoveAccessRule(ObjectAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { if (_securityDescriptor == null) { return true; } bool modified; return ModifyAccess(AccessControlModification.Remove, rule, out modified); } finally { WriteUnlock(); } } protected void RemoveAccessRuleAll(ObjectAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { if (_securityDescriptor == null) { return; } bool modified; ModifyAccess(AccessControlModification.RemoveAll, rule, out modified); } finally { WriteUnlock(); } } protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); if (_securityDescriptor == null) { return; } WriteLock(); try { bool modified; ModifyAccess(AccessControlModification.RemoveSpecific, rule, out modified); } finally { WriteUnlock(); } } protected void AddAuditRule(ObjectAuditRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAudit(AccessControlModification.Add, rule, out modified); } finally { WriteUnlock(); } } protected void SetAuditRule(ObjectAuditRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAudit(AccessControlModification.Set, rule, out modified); } finally { WriteUnlock(); } } protected bool RemoveAuditRule(ObjectAuditRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; return ModifyAudit(AccessControlModification.Remove, rule, out modified); } finally { WriteUnlock(); } } protected void RemoveAuditRuleAll(ObjectAuditRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAudit(AccessControlModification.RemoveAll, rule, out modified); } finally { WriteUnlock(); } } protected void RemoveAuditRuleSpecific(ObjectAuditRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } Contract.EndContractBlock(); WriteLock(); try { bool modified; ModifyAudit(AccessControlModification.RemoveSpecific, rule, out modified); } finally { WriteUnlock(); } } public AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, System.Type targetType) { return GetRules(true, includeExplicit, includeInherited, targetType); } public AuthorizationRuleCollection GetAuditRules(bool includeExplicit, bool includeInherited, System.Type targetType) { return GetRules(false, includeExplicit, includeInherited, targetType); } #endregion } }
using Prism.Properties; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Input; namespace Prism.Commands { /// <summary> /// The CompositeCommand composes one or more ICommands. /// </summary> public class CompositeCommand : ICommand { private readonly List<ICommand> _registeredCommands = new List<ICommand>(); private readonly bool _monitorCommandActivity; private readonly EventHandler _onRegisteredCommandCanExecuteChangedHandler; /// <summary> /// Initializes a new instance of <see cref="CompositeCommand"/>. /// </summary> public CompositeCommand() { this._onRegisteredCommandCanExecuteChangedHandler = new EventHandler(this.OnRegisteredCommandCanExecuteChanged); } /// <summary> /// Initializes a new instance of <see cref="CompositeCommand"/>. /// </summary> /// <param name="monitorCommandActivity">Indicates when the command activity is going to be monitored.</param> public CompositeCommand(bool monitorCommandActivity) : this() { this._monitorCommandActivity = monitorCommandActivity; } /// <summary> /// Adds a command to the collection and signs up for the <see cref="ICommand.CanExecuteChanged"/> event of it. /// </summary> /// <remarks> /// If this command is set to monitor command activity, and <paramref name="command"/> /// implements the <see cref="IActiveAwareCommand"/> interface, this method will subscribe to its /// <see cref="IActiveAwareCommand.IsActiveChanged"/> event. /// </remarks> /// <param name="command">The command to register.</param> public virtual void RegisterCommand(ICommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); if (command == this) { throw new ArgumentException(Resources.CannotRegisterCompositeCommandInItself); } lock (this._registeredCommands) { if (this._registeredCommands.Contains(command)) { throw new InvalidOperationException(Resources.CannotRegisterSameCommandTwice); } this._registeredCommands.Add(command); } command.CanExecuteChanged += this._onRegisteredCommandCanExecuteChangedHandler; this.OnCanExecuteChanged(); if (this._monitorCommandActivity) { var activeAwareCommand = command as IActiveAware; if (activeAwareCommand != null) { activeAwareCommand.IsActiveChanged += this.Command_IsActiveChanged; } } } /// <summary> /// Removes a command from the collection and removes itself from the <see cref="ICommand.CanExecuteChanged"/> event of it. /// </summary> /// <param name="command">The command to unregister.</param> public virtual void UnregisterCommand(ICommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); bool removed; lock (this._registeredCommands) { removed = this._registeredCommands.Remove(command); } if (removed) { command.CanExecuteChanged -= this._onRegisteredCommandCanExecuteChangedHandler; this.OnCanExecuteChanged(); if (this._monitorCommandActivity) { var activeAwareCommand = command as IActiveAware; if (activeAwareCommand != null) { activeAwareCommand.IsActiveChanged -= this.Command_IsActiveChanged; } } } } private void OnRegisteredCommandCanExecuteChanged(object sender, EventArgs e) { this.OnCanExecuteChanged(); } /// <summary> /// Forwards <see cref="ICommand.CanExecute"/> to the registered commands and returns /// <see langword="true" /> if all of the commands return <see langword="true" />. /// </summary> /// <param name="parameter">Data used by the command. /// If the command does not require data to be passed, this object can be set to <see langword="null" />. /// </param> /// <returns><see langword="true" /> if all of the commands return <see langword="true" />; otherwise, <see langword="false" />.</returns> public virtual bool CanExecute(object parameter) { bool hasEnabledCommandsThatShouldBeExecuted = false; ICommand[] commandList; lock (this._registeredCommands) { commandList = this._registeredCommands.ToArray(); } foreach (ICommand command in commandList) { if (this.ShouldExecute(command)) { if (!command.CanExecute(parameter)) { return false; } hasEnabledCommandsThatShouldBeExecuted = true; } } return hasEnabledCommandsThatShouldBeExecuted; } /// <summary> /// Occurs when any of the registered commands raise <see cref="ICommand.CanExecuteChanged"/>. /// </summary> public virtual event EventHandler CanExecuteChanged; /// <summary> /// Forwards <see cref="ICommand.Execute"/> to the registered commands. /// </summary> /// <param name="parameter">Data used by the command. /// If the command does not require data to be passed, this object can be set to <see langword="null" />. /// </param> public virtual void Execute(object parameter) { Queue<ICommand> commands; lock (this._registeredCommands) { commands = new Queue<ICommand>(this._registeredCommands.Where(this.ShouldExecute).ToList()); } while (commands.Count > 0) { ICommand command = commands.Dequeue(); command.Execute(parameter); } } /// <summary> /// Evaluates if a command should execute. /// </summary> /// <param name="command">The command to evaluate.</param> /// <returns>A <see cref="bool"/> value indicating whether the command should be used /// when evaluating <see cref="CompositeCommand.CanExecute"/> and <see cref="CompositeCommand.Execute"/>.</returns> /// <remarks> /// If this command is set to monitor command activity, and <paramref name="command"/> /// implements the <see cref="IActiveAwareCommand"/> interface, /// this method will return <see langword="false" /> if the command's <see cref="IActiveAwareCommand.IsActive"/> /// property is <see langword="false" />; otherwise it always returns <see langword="true" />.</remarks> protected virtual bool ShouldExecute(ICommand command) { var activeAwareCommand = command as IActiveAware; if (this._monitorCommandActivity && activeAwareCommand != null) { return activeAwareCommand.IsActive; } return true; } /// <summary> /// Gets the list of all the registered commands. /// </summary> /// <value>A list of registered commands.</value> /// <remarks>This returns a copy of the commands subscribed to the CompositeCommand.</remarks> public IList<ICommand> RegisteredCommands { get { IList<ICommand> commandList; lock (this._registeredCommands) { commandList = this._registeredCommands.ToList(); } return commandList; } } /// <summary> /// Raises <see cref="ICommand.CanExecuteChanged"/> on the UI thread so every /// command invoker can requery <see cref="ICommand.CanExecute"/> to check if the /// <see cref="CompositeCommand"/> can execute. /// </summary> protected virtual void OnCanExecuteChanged() { var handler = CanExecuteChanged; if (handler != null) { handler(this, EventArgs.Empty); } } /// <summary> /// Handler for IsActiveChanged events of registered commands. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">EventArgs to pass to the event.</param> private void Command_IsActiveChanged(object sender, EventArgs e) { this.OnCanExecuteChanged(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Collections.ObjectModel; namespace Moq { /// <summary> /// The intention of <see cref="ExpressionStringBuilder"/> is to create a more readable /// string representation for the failure message. /// </summary> internal class ExpressionStringBuilder { private readonly Expression expression; private StringBuilder builder; private Func<Type, string> getTypeName; internal static string GetString(Expression expression) { return GetString(expression, type => type.Name); } internal static string GetString(Expression expression, Func<Type, string> getTypeName) { var builder = new ExpressionStringBuilder(getTypeName, expression); return builder.ToString(); } public ExpressionStringBuilder(Func<Type, string> getTypeName, Expression expression) { this.getTypeName = getTypeName; this.expression = expression; } public override string ToString() { builder = new StringBuilder(); ToString(expression); return builder.ToString(); } public void ToString(Expression exp) { if (exp == null) { builder.Append("null"); return; } switch (exp.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: ToStringUnary((UnaryExpression)exp); return; case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: ToStringBinary((BinaryExpression)exp); return; case ExpressionType.TypeIs: ToStringTypeIs((TypeBinaryExpression)exp); return; case ExpressionType.Conditional: ToStringConditional((ConditionalExpression)exp); return; case ExpressionType.Constant: ToStringConstant((ConstantExpression)exp); return; case ExpressionType.Parameter: ToStringParameter((ParameterExpression)exp); return; case ExpressionType.MemberAccess: ToStringMemberAccess((MemberExpression)exp); return; case ExpressionType.Call: ToStringMethodCall((MethodCallExpression)exp); return; case ExpressionType.Lambda: ToStringLambda((LambdaExpression)exp); return; case ExpressionType.New: ToStringNew((NewExpression)exp); return; case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: ToStringNewArray((NewArrayExpression)exp); return; case ExpressionType.Invoke: ToStringInvocation((InvocationExpression)exp); return; case ExpressionType.MemberInit: ToStringMemberInit((MemberInitExpression)exp); return; case ExpressionType.ListInit: ToStringListInit((ListInitExpression)exp); return; default: throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); } } private void ToStringBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: ToStringMemberAssignment((MemberAssignment)binding); return; case MemberBindingType.MemberBinding: ToStringMemberMemberBinding((MemberMemberBinding)binding); return; case MemberBindingType.ListBinding: ToStringMemberListBinding((MemberListBinding)binding); return; default: throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } private void ToStringElementInitializer(ElementInit initializer) { builder.Append("{ "); ToStringExpressionList(initializer.Arguments); builder.Append(" }"); return; } private void ToStringUnary(UnaryExpression u) { switch (u.NodeType) { case ExpressionType.Convert: case ExpressionType.ConvertChecked: builder.Append("(").Append(this.getTypeName(u.Type)).Append(")"); ToString(u.Operand); //builder.Append(")"); return; case ExpressionType.ArrayLength: ToString(u.Operand); builder.Append(".Length"); return; case ExpressionType.Negate: case ExpressionType.NegateChecked: builder.Append("-"); ToString(u.Operand); return; case ExpressionType.Not: builder.Append("!("); ToString(u.Operand); builder.Append(")"); return; case ExpressionType.Quote: ToString(u.Operand); return; case ExpressionType.TypeAs: builder.Append("("); ToString(u.Operand); builder.Append(" as "); builder.Append(u.Type.DisplayName(this.getTypeName)); builder.Append(")"); return; } return; } private void ToStringBinary(BinaryExpression b) { if (b.NodeType == ExpressionType.ArrayIndex) { ToString(b.Left); builder.Append("["); ToString(b.Right); builder.Append("]"); } else { string @operator = ToStringOperator(b.NodeType); if (NeedEncloseInParen(b.Left)) { builder.Append("("); ToString(b.Left); builder.Append(")"); } else { ToString(b.Left); } builder.Append(" "); builder.Append(@operator); builder.Append(" "); if (NeedEncloseInParen(b.Right)) { builder.Append("("); ToString(b.Right); builder.Append(")"); } else { ToString(b.Right); } } } private static bool NeedEncloseInParen(Expression operand) { return operand.NodeType == ExpressionType.AndAlso || operand.NodeType == ExpressionType.OrElse; } private void ToStringTypeIs(TypeBinaryExpression b) { ToString(b.Expression); return; } private void ToStringConstant(ConstantExpression c) { var value = c.Value; if (value != null) { if (value is string) { builder.Append("\"").Append(value).Append("\""); } else if (value.ToString() == value.GetType().ToString()) { // Perhaps is better without nothing (at least for local variables) //builder.Append("<value>"); } else if (c.Type.IsEnum()) { builder.Append(c.Type.DisplayName(this.getTypeName)).Append(".").Append(value); } else { builder.Append(value); } } else { builder.Append("null"); } } private void ToStringConditional(ConditionalExpression c) { ToString(c.Test); ToString(c.IfTrue); ToString(c.IfFalse); return; } private void ToStringParameter(ParameterExpression p) { if (p.Name != null) { builder.Append(p.Name); } else { builder.Append("<param>"); } } private void ToStringMemberAccess(MemberExpression m) { if (m.Expression != null) { ToString(m.Expression); } else { builder.Append(m.Member.DeclaringType.DisplayName(this.getTypeName)); } builder.Append("."); builder.Append(m.Member.Name); return; } private void ToStringMethodCall(MethodCallExpression node) { if (node != null) { var paramFrom = 0; var expression = node.Object; // @mbrit - 2012-05-30 - changed... // if (Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null) if (node.Method.GetCustomAttribute(typeof(ExtensionAttribute)) != null) { paramFrom = 1; expression = node.Arguments[0]; } if (expression != null) { ToString(expression); } else // Method is static { this.builder.Append(this.getTypeName(node.Method.DeclaringType)); } if (node.Method.IsPropertyIndexerGetter()) { this.builder.Append("["); AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString); this.builder.Append("]"); } else if (node.Method.IsPropertyIndexerSetter()) { this.builder.Append("["); AsCommaSeparatedValues(node.Arguments .Skip(paramFrom) .Take(node.Arguments.Count - paramFrom), ToString); this.builder.Append("] = "); ToString(node.Arguments.Last()); } else if (node.Method.IsPropertyGetter()) { this.builder.Append(".").Append(node.Method.Name.Substring(4)); } else if (node.Method.IsPropertySetter()) { this.builder.Append(".").Append(node.Method.Name.Substring(4)).Append(" = "); ToString(node.Arguments.Last()); } else if (node.Method.IsGenericMethod) { this.builder .Append(".") .Append(node.Method.Name) .Append("<") .Append(string.Join(",", node.Method.GetGenericArguments().Select(s => this.getTypeName(s)).ToArray())) .Append(">("); AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString); this.builder.Append(")"); } else { this.builder .Append(".") .Append(node.Method.Name) .Append("("); AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString); this.builder.Append(")"); } } } private void ToStringExpressionList(ReadOnlyCollection<Expression> original) { AsCommaSeparatedValues(original, ToString); return; } private void ToStringMemberAssignment(MemberAssignment assignment) { builder.Append(assignment.Member.Name); builder.Append("= "); ToString(assignment.Expression); return; } private void ToStringMemberMemberBinding(MemberMemberBinding binding) { ToStringBindingList(binding.Bindings); return; } private void ToStringMemberListBinding(MemberListBinding binding) { ToStringElementInitializerList(binding.Initializers); return; } private void ToStringBindingList(IEnumerable<MemberBinding> original) { bool appendComma = false; foreach (var exp in original) { if (appendComma) { builder.Append(", "); } ToStringBinding(exp); appendComma = true; } return; } private void ToStringElementInitializerList(ReadOnlyCollection<ElementInit> original) { for (int i = 0, n = original.Count; i < n; i++) { ToStringElementInitializer(original[i]); } return; } private void ToStringLambda(LambdaExpression lambda) { if (lambda.Parameters.Count == 1) { ToStringParameter(lambda.Parameters[0]); } else { builder.Append("("); AsCommaSeparatedValues(lambda.Parameters, ToStringParameter); builder.Append(")"); } builder.Append(" => "); ToString(lambda.Body); return; } private void ToStringNew(NewExpression nex) { Type type = (nex.Constructor == null) ? nex.Type : nex.Constructor.DeclaringType; builder.Append("new "); builder.Append(type.DisplayName(this.getTypeName)); builder.Append("("); AsCommaSeparatedValues(nex.Arguments, ToString); builder.Append(")"); return; } private void ToStringMemberInit(MemberInitExpression init) { ToStringNew(init.NewExpression); builder.Append(" { "); ToStringBindingList(init.Bindings); builder.Append(" }"); return; } private void ToStringListInit(ListInitExpression init) { ToStringNew(init.NewExpression); builder.Append(" { "); bool appendComma = false; foreach (var initializer in init.Initializers) { if (appendComma) { builder.Append(", "); } ToStringElementInitializer(initializer); appendComma = true; } builder.Append(" }"); return; } private void ToStringNewArray(NewArrayExpression na) { switch (na.NodeType) { case ExpressionType.NewArrayInit: builder.Append("new[] { "); AsCommaSeparatedValues(na.Expressions, ToString); builder.Append(" }"); return; case ExpressionType.NewArrayBounds: builder.Append("new "); builder.Append(na.Type.GetElementType().DisplayName(this.getTypeName)); builder.Append("["); AsCommaSeparatedValues(na.Expressions, ToString); builder.Append("]"); return; } } private void AsCommaSeparatedValues<T>(IEnumerable<T> source, Action<T> toStringAction) where T : Expression { bool appendComma = false; foreach (var exp in source) { if (appendComma) { builder.Append(", "); } toStringAction(exp); appendComma = true; } } private void ToStringInvocation(InvocationExpression iv) { ToStringExpressionList(iv.Arguments); return; } internal static string ToStringOperator(ExpressionType nodeType) { switch (nodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: return "+"; case ExpressionType.And: return "&"; case ExpressionType.AndAlso: return "&&"; case ExpressionType.Coalesce: return "??"; case ExpressionType.Divide: return "/"; case ExpressionType.Equal: return "=="; case ExpressionType.ExclusiveOr: return "^"; case ExpressionType.GreaterThan: return ">"; case ExpressionType.GreaterThanOrEqual: return ">="; case ExpressionType.LeftShift: return "<<"; case ExpressionType.LessThan: return "<"; case ExpressionType.LessThanOrEqual: return "<="; case ExpressionType.Modulo: return "%"; case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: return "*"; case ExpressionType.NotEqual: return "!="; case ExpressionType.Or: return "|"; case ExpressionType.OrElse: return "||"; case ExpressionType.Power: return "^"; case ExpressionType.RightShift: return ">>"; case ExpressionType.Subtract: case ExpressionType.SubtractChecked: return "-"; } return nodeType.ToString(); } } internal static class StringExtensions { public static string[] Lines(this string source) { return source.Split(new[] { Environment.NewLine }, StringSplitOptions.None); } public static string AsCommaSeparatedValues(this IEnumerable<string> source) { if (source == null) { return string.Empty; } var result = new StringBuilder(100); bool appendComma = false; foreach (var value in source) { if (appendComma) { result.Append(", "); } result.Append(value); appendComma = true; } return result.ToString(); } } internal static class TypeExtensions { public static string DisplayName(this Type source, Func<Type, string> getName) { if (source == null) { throw new ArgumentNullException("source"); } var builder = new StringBuilder(100); builder.Append(getName(source).Split('`').First()); if (source.IsGenericType()) { builder.Append("<"); builder.Append(source.GetGenericArguments().Select(t => getName(t)).AsCommaSeparatedValues()); builder.Append(">"); } return builder.ToString(); } } // internal class ExpressionStringBuilder : ExpressionVisitor // { // private StringBuilder output = new StringBuilder(); // private Func<MethodInfo, string> getMethodName; // private ExpressionStringBuilder(Func<MethodInfo, string> getMethodName) // { // this.getMethodName = getMethodName; // } // internal static string GetString(Expression expression) // { // return GetString(expression, method => method.GetName()); // } // internal static string GetString(Expression expression, Func<MethodInfo, string> getMethodName) // { // var builder = new ExpressionStringBuilder(getMethodName); // builder.Visit(expression); // return builder.output.ToString(); // } // protected override Expression VisitBinary(BinaryExpression node) // { // if (node != null) // { // if (node.NodeType == ExpressionType.ArrayIndex) // { // this.Visit(node.Left); // this.output.Append("["); // this.Visit(node.Right); // this.output.Append("]"); // } // else // { // var @operator = GetStringOperator(node.NodeType); // if (IsParentEnclosed(node.Left)) // { // this.output.Append("("); // this.Visit(node.Left); // this.output.Append(")"); // } // else // { // this.Visit(node.Left); // } // output.Append(" ").Append(@operator).Append(" "); // if (IsParentEnclosed(node.Right)) // { // this.output.Append("("); // this.Visit(node.Right); // this.output.Append(")"); // } // else // { // this.Visit(node.Right); // } // } // } // return node; // } // protected override Expression VisitConditional(ConditionalExpression node) // { // if (node != null) // { // this.Visit(node.Test); // this.Visit(node.IfTrue); // this.Visit(node.IfFalse); // } // return node; // } // protected override Expression VisitConstant(ConstantExpression node) // { // if (node != null) // { // var value = node.Value; // if (value != null) // { // if (value is string) // { // this.output.Append('"').Append(value).Append('"'); // } // else if (node.Type.IsEnum()) // { // this.output.Append(node.Type.Name).Append(".").Append(value); // } // else if (value.ToString() != value.GetType().ToString()) // { // this.output.Append(value); // } // } // else // { // this.output.Append("null"); // } // } // return node; // } // protected override ElementInit VisitElementInit(ElementInit node) // { // if (node != null) // { // this.Visit(node.Arguments); // } // return node; // } // protected override Expression VisitInvocation(InvocationExpression node) // { // if (node != null) // { // this.Visit(node.Arguments); // } // return node; // } //#if NET3x // protected override Expression VisitLambda(LambdaExpression node) //#else // protected override Expression VisitLambda<T>(Expression<T> node) //#endif // { // if (node != null) // { // if (node.Parameters.Count == 1) // { // this.VisitParameter(node.Parameters[0]); // } // else // { // this.output.Append("("); // this.Visit(node.Parameters, n => this.VisitParameter(n), 0, node.Parameters.Count); // this.output.Append(")"); // } // output.Append(" => "); // this.Visit(node.Body); // } // return node; // } // protected override Expression VisitListInit(ListInitExpression node) // { // if (node != null) // { // this.VisitNew(node.NewExpression); // Visit(node.Initializers, n => this.VisitElementInit(n)); // } // return node; // } // protected override Expression VisitMember(MemberExpression node) // { // if (node != null) // { // if (node.Expression != null) // { // this.Visit(node.Expression); // } // else // { // this.output.Append(node.Member.DeclaringType.Name); // } // this.output.Append(".").Append(node.Member.Name); // } // return node; // } // protected override Expression VisitMemberInit(MemberInitExpression node) // { // if (node != null) // { // this.VisitNew(node.NewExpression); // Visit(node.Bindings, n => this.VisitMemberBinding(n)); // } // return node; // } // protected override MemberListBinding VisitMemberListBinding(MemberListBinding node) // { // if (node != null) // { // Visit(node.Initializers, n => this.VisitElementInit(n)); // } // return node; // } // protected override MemberAssignment VisitMemberAssignment(MemberAssignment node) // { // if (node != null) // { // this.Visit(node.Expression); // } // return node; // } // protected override MemberBinding VisitMemberBinding(MemberBinding node) // { // if (node != null) // { // switch (node.BindingType) // { // case MemberBindingType.Assignment: // this.VisitMemberAssignment((MemberAssignment)node); // break; // case MemberBindingType.MemberBinding: // this.VisitMemberMemberBinding((MemberMemberBinding)node); // break; // case MemberBindingType.ListBinding: // this.VisitMemberListBinding((MemberListBinding)node); // break; // default: // throw new InvalidOperationException(string.Format( // CultureInfo.CurrentCulture, // "Unhandled binding type '{0}'", // node.BindingType)); // } // } // return node; // } // protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) // { // if (node != null) // { // Visit(node.Bindings, n => this.VisitMemberBinding(n)); // } // return node; // } // protected override Expression VisitMethodCall(MethodCallExpression node) // { // if (node != null) // { // var paramFrom = 0; // var expression = node.Object; // if (Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null) // { // paramFrom = 1; // expression = node.Arguments[0]; // } // if (expression != null) // { // this.Visit(expression); // } // else // Method is static // { // this.output.Append(node.Method.DeclaringType.Name); // } // if (node.Method.IsPropertyIndexerGetter()) // { // this.output.Append("["); // this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count); // this.output.Append("]"); // } // else if (node.Method.IsPropertyIndexerSetter()) // { // this.output.Append("["); // this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count - 1); // this.output.Append("] = "); // this.Visit(node.Arguments.Last()); // } // else if (node.Method.IsPropertyGetter()) // { // this.output.Append(".").Append(node.Method.Name.Substring(4)); // } // else if (node.Method.IsPropertySetter()) // { // this.output.Append(".").Append(node.Method.Name.Substring(4)).Append(" = "); // this.Visit(node.Arguments.Last()); // } // else if (node.Method.IsGenericMethod) // { // this.output // .Append(".") // .Append(this.getMethodName(node.Method)) // .Append("<") // .Append(string.Join(",", node.Method.GetGenericArguments().Select(s => s.Name))) // .Append(">("); // this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count); // output.Append(")"); // } // else // { // this.output.Append(".").Append(this.getMethodName(node.Method)).Append("("); // this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count); // output.Append(")"); // } // } // return node; // } // protected override Expression VisitNew(NewExpression node) // { // if (node != null) // { // this.Visit(node.Arguments); // } // return node; // } // protected override Expression VisitNewArray(NewArrayExpression node) // { // if (node != null) // { // this.output.Append("new[] { "); // this.Visit(node.Expressions); // this.output.Append(" }"); // } // return node; // } // protected override Expression VisitParameter(ParameterExpression node) // { // if (node != null) // { // this.output.Append(node.Name != null ? node.Name : "<param>"); // } // return node; // } // protected override Expression VisitTypeBinary(TypeBinaryExpression node) // { // return node != null ? this.Visit(node.Expression) : node; // } // protected override Expression VisitUnary(UnaryExpression node) // { // if (node != null) // { // switch (node.NodeType) // { // case ExpressionType.Negate: // case ExpressionType.NegateChecked: // this.output.Append("-"); // this.Visit(node.Operand); // break; // case ExpressionType.Not: // this.output.Append("!("); // this.Visit(node.Operand); // this.output.Append(")"); // break; // case ExpressionType.Quote: // this.Visit(node.Operand); // break; // case ExpressionType.TypeAs: // this.output.Append("("); // this.Visit(node.Operand); // this.output.Append(" as ").Append(node.Type.Name).Append(")"); // break; // } // } // return node; // } // private static string GetStringOperator(ExpressionType nodeType) // { // switch (nodeType) // { // case ExpressionType.Add: // case ExpressionType.AddChecked: // return "+"; // case ExpressionType.And: // return "&"; // case ExpressionType.AndAlso: // return "&&"; // case ExpressionType.Coalesce: // return "??"; // case ExpressionType.Divide: // return "/"; // case ExpressionType.Equal: // return "=="; // case ExpressionType.ExclusiveOr: // return "^"; // case ExpressionType.GreaterThan: // return ">"; // case ExpressionType.GreaterThanOrEqual: // return ">="; // case ExpressionType.LeftShift: // return "<<"; // case ExpressionType.LessThan: // return "<"; // case ExpressionType.LessThanOrEqual: // return "<="; // case ExpressionType.Modulo: // return "%"; // case ExpressionType.Multiply: // case ExpressionType.MultiplyChecked: // return "*"; // case ExpressionType.NotEqual: // return "!="; // case ExpressionType.Or: // return "|"; // case ExpressionType.OrElse: // return "||"; // case ExpressionType.Power: // return "^"; // case ExpressionType.RightShift: // return ">>"; // case ExpressionType.Subtract: // case ExpressionType.SubtractChecked: // return "-"; // } // return nodeType.ToString(); // } // private static bool IsParentEnclosed(Expression node) // { // return node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse; // } // private void Visit<T>(IList<T> arguments, Func<T, Expression> elementVisitor, int paramFrom, int paramTo) // { // var appendComma = false; // for (var index = paramFrom; index < paramTo; index++) // { // if (appendComma) // { // this.output.Append(", "); // } // elementVisitor(arguments[index]); // appendComma = true; // } // } // } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Core; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; namespace Microsoft.AspNetCore.Mvc.ModelBinding { internal static class ModelBindingHelper { /// <summary> /// Updates the specified <paramref name="model"/> instance using the specified /// <paramref name="modelBinderFactory"/> and the specified <paramref name="valueProvider"/> and executes /// validation using the specified <paramref name="objectModelValidator"/>. /// </summary> /// <typeparam name="TModel">The type of the model object.</typeparam> /// <param name="model">The model instance to update and validate.</param> /// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>. /// </param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing request.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/> used for binding.</param> /// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param> /// <param name="objectModelValidator">The <see cref="IObjectModelValidator"/> used for validating the /// bound values.</param> /// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful</returns> public static Task<bool> TryUpdateModelAsync<TModel>( TModel model, string prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator) where TModel : class { return TryUpdateModelAsync( model, prefix, actionContext, metadataProvider, modelBinderFactory, valueProvider, objectModelValidator, // Includes everything by default. propertyFilter: (m) => true); } /// <summary> /// Updates the specified <paramref name="model"/> instance using the specified <paramref name="modelBinderFactory"/> /// and the specified <paramref name="valueProvider"/> and executes validation using the specified /// <paramref name="objectModelValidator"/>. /// </summary> /// <typeparam name="TModel">The type of the model object.</typeparam> /// <param name="model">The model instance to update and validate.</param> /// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>. /// </param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing request.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/> used for binding.</param> /// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param> /// <param name="objectModelValidator">The <see cref="IObjectModelValidator"/> used for validating the /// bound values.</param> /// <param name="includeExpressions">Expression(s) which represent top level properties /// which need to be included for the current model.</param> /// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful</returns> public static Task<bool> TryUpdateModelAsync<TModel>( TModel model, string prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator, params Expression<Func<TModel, object>>[] includeExpressions) where TModel : class { if (includeExpressions == null) { throw new ArgumentNullException(nameof(includeExpressions)); } var expression = GetPropertyFilterExpression(includeExpressions); var propertyFilter = expression.Compile(); return TryUpdateModelAsync( model, prefix, actionContext, metadataProvider, modelBinderFactory, valueProvider, objectModelValidator, propertyFilter); } /// <summary> /// Updates the specified <paramref name="model"/> instance using the specified <paramref name="modelBinderFactory"/> /// and the specified <paramref name="valueProvider"/> and executes validation using the specified /// <paramref name="objectModelValidator"/>. /// </summary> /// <typeparam name="TModel">The type of the model object.</typeparam> /// <param name="model">The model instance to update and validate.</param> /// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>. /// </param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing request.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/> used for binding.</param> /// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param> /// <param name="objectModelValidator">The <see cref="IObjectModelValidator"/> used for validating the /// bound values.</param> /// <param name="propertyFilter"> /// A predicate which can be used to filter properties(for inclusion/exclusion) at runtime. /// </param> /// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful</returns> public static Task<bool> TryUpdateModelAsync<TModel>( TModel model, string prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator, Func<ModelMetadata, bool> propertyFilter) where TModel : class { return TryUpdateModelAsync( model, typeof(TModel), prefix, actionContext, metadataProvider, modelBinderFactory, valueProvider, objectModelValidator, propertyFilter); } /// <summary> /// Updates the specified <paramref name="model"/> instance using the specified <paramref name="modelBinderFactory"/> /// and the specified <paramref name="valueProvider"/> and executes validation using the specified /// <paramref name="objectModelValidator"/>. /// </summary> /// <param name="model">The model instance to update and validate.</param> /// <param name="modelType">The type of model instance to update and validate.</param> /// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>. /// </param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing request.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/> used for binding.</param> /// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param> /// <param name="objectModelValidator">The <see cref="IObjectModelValidator"/> used for validating the /// bound values.</param> /// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful</returns> public static Task<bool> TryUpdateModelAsync( object model, Type modelType, string prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator) { return TryUpdateModelAsync( model, modelType, prefix, actionContext, metadataProvider, modelBinderFactory, valueProvider, objectModelValidator, // Includes everything by default. propertyFilter: (m) => true); } /// <summary> /// Updates the specified <paramref name="model"/> instance using the specified <paramref name="modelBinderFactory"/> /// and the specified <paramref name="valueProvider"/> and executes validation using the specified /// <paramref name="objectModelValidator"/>. /// </summary> /// <param name="model">The model instance to update and validate.</param> /// <param name="modelType">The type of model instance to update and validate.</param> /// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>. /// </param> /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing request.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/> used for binding.</param> /// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param> /// <param name="objectModelValidator">The <see cref="IObjectModelValidator"/> used for validating the /// bound values.</param> /// <param name="propertyFilter">A predicate which can be used to /// filter properties(for inclusion/exclusion) at runtime.</param> /// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful</returns> public static async Task<bool> TryUpdateModelAsync( object model, Type modelType, string prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator, Func<ModelMetadata, bool> propertyFilter) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (modelType == null) { throw new ArgumentNullException(nameof(modelType)); } if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } if (modelBinderFactory == null) { throw new ArgumentNullException(nameof(modelBinderFactory)); } if (valueProvider == null) { throw new ArgumentNullException(nameof(valueProvider)); } if (objectModelValidator == null) { throw new ArgumentNullException(nameof(objectModelValidator)); } if (propertyFilter == null) { throw new ArgumentNullException(nameof(propertyFilter)); } if (!modelType.IsAssignableFrom(model.GetType())) { var message = Resources.FormatModelType_WrongType( model.GetType().FullName, modelType.FullName); throw new ArgumentException(message, nameof(modelType)); } var modelMetadata = metadataProvider.GetMetadataForType(modelType); if (modelMetadata.BoundConstructor != null) { throw new NotSupportedException(Resources.FormatTryUpdateModel_RecordTypeNotSupported(nameof(TryUpdateModelAsync), modelType)); } var modelState = actionContext.ModelState; var modelBindingContext = DefaultModelBindingContext.CreateBindingContext( actionContext, valueProvider, modelMetadata, bindingInfo: null, modelName: prefix); modelBindingContext.Model = model; modelBindingContext.PropertyFilter = propertyFilter; var factoryContext = new ModelBinderFactoryContext() { Metadata = modelMetadata, BindingInfo = new BindingInfo() { BinderModelName = modelMetadata.BinderModelName, BinderType = modelMetadata.BinderType, BindingSource = modelMetadata.BindingSource, PropertyFilterProvider = modelMetadata.PropertyFilterProvider, }, // We're using the model metadata as the cache token here so that TryUpdateModelAsync calls // for the same model type can share a binder. This won't overlap with normal model binding // operations because they use the ParameterDescriptor for the token. CacheToken = modelMetadata, }; var binder = modelBinderFactory.CreateBinder(factoryContext); await binder.BindModelAsync(modelBindingContext); var modelBindingResult = modelBindingContext.Result; if (modelBindingResult.IsModelSet) { objectModelValidator.Validate( actionContext, modelBindingContext.ValidationState, modelBindingContext.ModelName, modelBindingResult.Model); return modelState.IsValid; } return false; } // Internal for tests internal static string GetPropertyName(Expression expression) { if (expression.NodeType == ExpressionType.Convert || expression.NodeType == ExpressionType.ConvertChecked) { // For Boxed Value Types expression = ((UnaryExpression)expression).Operand; } if (expression.NodeType != ExpressionType.MemberAccess) { throw new InvalidOperationException( Resources.FormatInvalid_IncludePropertyExpression(expression.NodeType)); } var memberExpression = (MemberExpression)expression; if (memberExpression.Member is PropertyInfo memberInfo) { if (memberExpression.Expression!.NodeType != ExpressionType.Parameter) { // Chained expressions and non parameter based expressions are not supported. throw new InvalidOperationException( Resources.FormatInvalid_IncludePropertyExpression(expression.NodeType)); } return memberInfo.Name; } else { // Fields are also not supported. throw new InvalidOperationException( Resources.FormatInvalid_IncludePropertyExpression(expression.NodeType)); } } /// <summary> /// Creates an expression for a predicate to limit the set of properties used in model binding. /// </summary> /// <typeparam name="TModel">The model type.</typeparam> /// <param name="expressions">Expressions identifying the properties to allow for binding.</param> /// <returns>An expression which can be used with <see cref="IPropertyFilterProvider"/>.</returns> public static Expression<Func<ModelMetadata, bool>> GetPropertyFilterExpression<TModel>( Expression<Func<TModel, object>>[] expressions) { if (expressions.Length == 0) { // If nothing is included explicitly, treat everything as included. return (m) => true; } var firstExpression = GetPredicateExpression(expressions[0]); var orWrapperExpression = firstExpression.Body; foreach (var expression in expressions.Skip(1)) { var predicate = GetPredicateExpression(expression); orWrapperExpression = Expression.OrElse( orWrapperExpression, Expression.Invoke(predicate, firstExpression.Parameters)); } return Expression.Lambda<Func<ModelMetadata, bool>>(orWrapperExpression, firstExpression.Parameters); } private static Expression<Func<ModelMetadata, bool>> GetPredicateExpression<TModel>( Expression<Func<TModel, object>> expression) { var propertyName = GetPropertyName(expression.Body); return (metadata) => string.Equals(metadata.PropertyName, propertyName, StringComparison.Ordinal); } /// <summary> /// Clears <see cref="ModelStateDictionary"/> entries for <see cref="ModelMetadata"/>. /// </summary> /// <param name="modelType">The <see cref="Type"/> of the model.</param> /// <param name="modelState">The <see cref="ModelStateDictionary"/> associated with the model.</param> /// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param> /// <param name="modelKey">The entry to clear. </param> public static void ClearValidationStateForModel( Type modelType, ModelStateDictionary modelState, IModelMetadataProvider metadataProvider, string modelKey) { if (modelType == null) { throw new ArgumentNullException(nameof(modelType)); } if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } ClearValidationStateForModel(metadataProvider.GetMetadataForType(modelType), modelState, modelKey); } /// <summary> /// Clears <see cref="ModelStateDictionary"/> entries for <see cref="ModelMetadata"/>. /// </summary> /// <param name="modelMetadata">The <see cref="ModelMetadata"/>.</param> /// <param name="modelState">The <see cref="ModelStateDictionary"/> associated with the model.</param> /// <param name="modelKey">The entry to clear. </param> public static void ClearValidationStateForModel( ModelMetadata modelMetadata, ModelStateDictionary modelState, string? modelKey) { if (modelMetadata == null) { throw new ArgumentNullException(nameof(modelMetadata)); } if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } if (string.IsNullOrEmpty(modelKey)) { // If model key is empty, we have to do a best guess to try and clear the appropriate // keys. Clearing the empty prefix would clear the state of ALL entries, which might wipe out // data from other models. if (modelMetadata.IsEnumerableType) { // We expect that any key beginning with '[' is an index. We can't just infer the indexes // used, so we clear all keys that look like <empty prefix -> index>. // // In the unlikely case that multiple top-level collections where bound to the empty prefix, // you're just out of luck. foreach (var kvp in modelState) { if (kvp.Key.Length > 0 && kvp.Key[0] == '[') { // Starts with an indexer kvp.Value.Errors.Clear(); kvp.Value.ValidationState = ModelValidationState.Unvalidated; } } } else if (modelMetadata.IsComplexType) { for (var i = 0; i < modelMetadata.Properties.Count; i++) { var property = modelMetadata.Properties[i]; modelState.ClearValidationState((property.BinderModelName ?? property.PropertyName)!); } } else { // Simple types bind to a single entry. So clear the entry with the empty-key, in the // unlikely event that it has errors. var entry = modelState[string.Empty]; if (entry != null) { entry.Errors.Clear(); entry.ValidationState = ModelValidationState.Unvalidated; } } } else { // If model key is non-empty, we just want to clear all keys with that prefix. We expect // model binding to have only used this key (and suffixes) for all entries related to // this model. modelState.ClearValidationState(modelKey); } } internal static TModel? CastOrDefault<TModel>(object? model) { return (model is TModel tModel) ? tModel : default; } /// <summary> /// Gets an indication whether <see cref="M:GetCompatibleCollection{T}"/> is likely to return a usable /// non-<c>null</c> value. /// </summary> /// <typeparam name="T">The element type of the <see cref="ICollection{T}"/> required.</typeparam> /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param> /// <returns> /// <c>true</c> if <see cref="M:GetCompatibleCollection{T}"/> is likely to return a usable non-<c>null</c> /// value; <c>false</c> otherwise. /// </returns> /// <remarks>"Usable" in this context means the property can be set or its value reused.</remarks> public static bool CanGetCompatibleCollection<T>(ModelBindingContext bindingContext) { var model = bindingContext.Model; var modelType = bindingContext.ModelType; if (typeof(T).IsAssignableFrom(modelType)) { // Scalar case. Existing model is not relevant and property must always be set. Will use a List<T> // intermediate and set property to first element, if any. return true; } if (modelType == typeof(T[])) { // Can't change the length of an existing array or replace it. Will use a List<T> intermediate and set // property to an array created from that. return true; } if (!typeof(IEnumerable<T>).IsAssignableFrom(modelType)) { // Not a supported collection. return false; } if (model is ICollection<T> collection && !collection.IsReadOnly) { // Can use the existing collection. return true; } // Most likely the model is null. // Also covers the corner case where the model implements IEnumerable<T> but not ICollection<T> e.g. // public IEnumerable<T> Property { get; set; } = new T[0]; if (modelType.IsAssignableFrom(typeof(List<T>))) { return true; } // Will we be able to activate an instance and use that? return modelType.IsClass && !modelType.IsAbstract && typeof(ICollection<T>).IsAssignableFrom(modelType); } /// <summary> /// Creates an <see cref="ICollection{T}"/> instance compatible with <paramref name="bindingContext"/>'s /// <see cref="ModelBindingContext.ModelType"/>. /// </summary> /// <typeparam name="T">The element type of the <see cref="ICollection{T}"/> required.</typeparam> /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param> /// <returns> /// An <see cref="ICollection{T}"/> instance compatible with <paramref name="bindingContext"/>'s /// <see cref="ModelBindingContext.ModelType"/>. /// </returns> /// <remarks> /// Should not be called if <see cref="CanGetCompatibleCollection{T}"/> returned <c>false</c>. /// </remarks> public static ICollection<T> GetCompatibleCollection<T>(ModelBindingContext bindingContext) { return GetCompatibleCollection<T>(bindingContext, capacity: null); } /// <summary> /// Creates an <see cref="ICollection{T}"/> instance compatible with <paramref name="bindingContext"/>'s /// <see cref="ModelBindingContext.ModelType"/>. /// </summary> /// <typeparam name="T">The element type of the <see cref="ICollection{T}"/> required.</typeparam> /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param> /// <param name="capacity"> /// Capacity for use when creating a <see cref="List{T}"/> instance. Not used when creating another type. /// </param> /// <returns> /// An <see cref="ICollection{T}"/> instance compatible with <paramref name="bindingContext"/>'s /// <see cref="ModelBindingContext.ModelType"/>. /// </returns> /// <remarks> /// Should not be called if <see cref="CanGetCompatibleCollection{T}"/> returned <c>false</c>. /// </remarks> public static ICollection<T> GetCompatibleCollection<T>(ModelBindingContext bindingContext, int capacity) { return GetCompatibleCollection<T>(bindingContext, (int?)capacity); } private static ICollection<T> GetCompatibleCollection<T>(ModelBindingContext bindingContext, int? capacity) { var model = bindingContext.Model; var modelType = bindingContext.ModelType; // There's a limited set of collection types we can create here. // // For the simple cases: Choose List<T> if the destination type supports it (at least as an intermediary). // // For more complex cases: If the destination type is a class that implements ICollection<T>, then activate // an instance and return that. // // Otherwise just give up. if (typeof(T).IsAssignableFrom(modelType)) { return CreateList<T>(capacity); } if (modelType == typeof(T[])) { return CreateList<T>(capacity); } // Does collection exist and can it be reused? if (model is ICollection<T> collection && !collection.IsReadOnly) { collection.Clear(); return collection; } if (modelType.IsAssignableFrom(typeof(List<T>))) { return CreateList<T>(capacity); } return (ICollection<T>)Activator.CreateInstance(modelType)!; } private static List<T> CreateList<T>(int? capacity) { return capacity.HasValue ? new List<T>(capacity.Value) : new List<T>(); } /// <summary> /// Converts the provided <paramref name="value"/> to a value of <see cref="Type"/> <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The <see cref="Type"/> for conversion.</typeparam> /// <param name="value">The value to convert."/></param> /// <param name="culture">The <see cref="CultureInfo"/> for conversion.</param> /// <returns> /// The converted value or the default value of <typeparamref name="T"/> if the value could not be converted. /// </returns> [return: NotNullIfNotNull("value")] public static T? ConvertTo<T>(object? value, CultureInfo? culture) { var converted = ConvertTo(value, typeof(T), culture); return converted == null ? default : (T)converted; } /// <summary> /// Converts the provided <paramref name="value"/> to a value of <see cref="Type"/> <paramref name="type"/>. /// </summary> /// <param name="value">The value to convert."/></param> /// <param name="type">The <see cref="Type"/> for conversion.</param> /// <param name="culture">The <see cref="CultureInfo"/> for conversion.</param> /// <returns> /// The converted value or <c>null</c> if the value could not be converted. /// </returns> public static object? ConvertTo(object? value, Type type, CultureInfo? culture) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (value == null) { // For value types, treat null values as though they were the default value for the type. return type.IsValueType ? Activator.CreateInstance(type) : null; } if (type.IsAssignableFrom(value.GetType())) { return value; } var cultureToUse = culture ?? CultureInfo.InvariantCulture; return UnwrapPossibleArrayType(value, type, cultureToUse); } private static object? UnwrapPossibleArrayType(object value, Type destinationType, CultureInfo culture) { // array conversion results in four cases, as below var valueAsArray = value as Array; if (destinationType.IsArray) { var destinationElementType = destinationType.GetElementType()!; if (valueAsArray != null) { // case 1: both destination + source type are arrays, so convert each element var converted = (IList)Array.CreateInstance(destinationElementType, valueAsArray.Length); for (var i = 0; i < valueAsArray.Length; i++) { converted[i] = ConvertSimpleType(valueAsArray.GetValue(i), destinationElementType, culture); } return converted; } else { // case 2: destination type is array but source is single element, so wrap element in // array + convert var element = ConvertSimpleType(value, destinationElementType, culture); var converted = (IList)Array.CreateInstance(destinationElementType, 1); converted[0] = element; return converted; } } else if (valueAsArray != null) { // case 3: destination type is single element but source is array, so extract first element + convert if (valueAsArray.Length > 0) { var elementValue = valueAsArray.GetValue(0); return ConvertSimpleType(elementValue, destinationType, culture); } else { // case 3(a): source is empty array, so can't perform conversion return null; } } // case 4: both destination + source type are single elements, so convert return ConvertSimpleType(value, destinationType, culture); } private static object? ConvertSimpleType(object? value, Type destinationType, CultureInfo culture) { if (value == null || destinationType.IsAssignableFrom(value.GetType())) { return value; } // In case of a Nullable object, we try again with its underlying type. destinationType = UnwrapNullableType(destinationType); // if this is a user-input value but the user didn't type anything, return no value if (value is string valueAsString && string.IsNullOrWhiteSpace(valueAsString)) { return null; } var converter = TypeDescriptor.GetConverter(destinationType); var canConvertFrom = converter.CanConvertFrom(value.GetType()); if (!canConvertFrom) { converter = TypeDescriptor.GetConverter(value.GetType()); } if (!(canConvertFrom || converter.CanConvertTo(destinationType))) { // EnumConverter cannot convert integer, so we verify manually if (destinationType.IsEnum && (value is int || value is uint || value is long || value is ulong || value is short || value is ushort || value is byte || value is sbyte)) { return Enum.ToObject(destinationType, value); } throw new InvalidOperationException( Resources.FormatValueProviderResult_NoConverterExists(value.GetType(), destinationType)); } try { return canConvertFrom ? converter.ConvertFrom(null, culture, value) : converter.ConvertTo(null, culture, value, destinationType); } catch (FormatException) { throw; } catch (Exception ex) { if (ex.InnerException == null) { throw; } else { // TypeConverter throws System.Exception wrapping the FormatException, // so we throw the inner exception. ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); // This code is never reached because the previous line will always throw. throw; } } } private static Type UnwrapNullableType(Type destinationType) { return Nullable.GetUnderlyingType(destinationType) ?? destinationType; } } }
// // MRIControlable.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; namespace PortableRealm { // Interface for anything that has the potential to take activities (player characters, natives, monsters) public interface MRIControllable : MRIGamePiece { #region Properties // Where the controllable is. MRILocation Location {get; set;} // How the controllable is moving. MRGame.eMoveType MoveType {get; set;} // Returns a list of hidden roads/paths the controllable has discovered. IList<MRRoad> DiscoveredRoads {get;} // The hidden state of the controllable bool Hidden {get; set;} // base weight of the controllable MRGame.eStrength BaseWeight { get; } // base vulnerability of the controllable MRGame.eStrength BaseVulnerability { get; } // current vulnerability of the controllable MRGame.eStrength CurrentVulnerability { get; set; } // Actual gold the controllable has int BaseGold { get; set; } // Effective gold the controllable has int EffectiveGold { get; } /// <summary> /// Returns the current attack strength of the controllable. /// </summary> /// <value>The current strength.</value> MRGame.eStrength CurrentStrength { get; } /// <summary> /// Returns the current attack speed of the controllable. /// </summary> /// <value>The current attack speed.</value> int CurrentAttackSpeed { get; } /// <summary> /// Returns the current move speed of the controllable. /// </summary> /// <value>The current move speed.</value> int CurrentMoveSpeed { get; } /// <summary> /// Returns the current sharpness of the controllable's weapon. /// </summary> /// <value>The current sharpness.</value> int CurrentSharpness { get; } /// <summary> /// Returns the type of weapon used by the denizen. /// </summary> /// <value>The type of the weapon.</value> MRWeapon.eWeaponType WeaponType { get; } /// <summary> /// Gets the length of the controllable's weapon. /// </summary> /// <value>The length of the weapon.</value> int WeaponLength { get; } /// <summary> /// Gets or sets a value indicating whether this <see cref="MRIControlable"/> is blocked. /// </summary> /// <value><c>true</c> if blocked; otherwise, <c>false</c>.</value> bool Blocked { get; set; } /// <summary> /// Gets or sets the combat target. /// </summary> /// <value>The combat target.</value> MRIControllable CombatTarget { get; set; } /// <summary> /// Returns the list of things attacking this target. /// </summary> /// <value>The attackers.</value> IList<MRIControllable> Attackers { get; } /// <summary> /// Returns the list of attackers who killed this controllable. /// </summary> /// <value>The killers.</value> IList<MRIControllable> Killers { get; } /// <summary> /// Returns the attack direction being used this round. /// </summary> /// <value>The attack type.</value> MRCombatManager.eAttackType AttackType { get; } /// <summary> /// Returns the maneuver direction being used this round. /// </summary> /// <value>The defense type.</value> MRCombatManager.eDefenseType DefenseType { get; } // The combat sheet the controllable is on. MRCombatSheetData CombatSheet { get; set; } // The controllable this controllable is luring in combat. MRIControllable Luring { get; set; } // The controllable luring this controllable in combat. MRIControllable Lurer { get; set; } /// <summary> /// Gets a value indicating whether the comtrollable is dead. /// </summary> /// <value><c>true</c> if the controllable is dead; otherwise, <c>false</c>.</value> bool IsDead { get; } /// <summary> /// Returns how many combatants killed this controllable (due to simultanious attacks) /// </summary> /// <value>The killer count.</value> int KillerCount { get; } /// <summary> /// Returns if this is a red-side up tremendous monster. /// </summary> /// <value><c>true</c> if this instance is red side monster; otherwise, <c>false</c>.</value> bool IsRedSideMonster { get; } #endregion #region Methods // Does initialization associated with birdsong. void StartBirdsong(); // Does initialization associated with sunrise. void StartSunrise(); // Does initialization associated with daylight. void StartDaylight(); // Does initialization associated with sunset. void StartSunset(); // Does initialization associated with evening. void StartEvening(); // Does initialization associated with midnight. void StartMidnight(); // Returns the activity list for a given day. If the activity list doesn't exist, it will be created. MRActivityList ActivitiesForDay(int day); // Removes all blank activities from the end of the activities lists. void CleanupActivities(); // Tests if the controllable is allowed to do the activity. bool CanExecuteActivity(MRActivity activity); // Tells the controllable an activity was performed void ExecutedActivity(MRActivity activity); // Tests if this controllable activates a map chit to summon monsters bool ActivatesChit(MRMapChit chit); // Returns the die pool for a given roll type MRDiePool DiePool(MRGame.eRollTypes roll); // Flags a site as being discovered void DiscoverSite(MRMapChit.eSiteChitType site); // Returns if a site has been discovered bool DiscoveredSite(MRMapChit.eSiteChitType site); // Flags a treasure as being discovered void DiscoverTreasure(uint treasureId); // Returns if a treasure has been discovered bool DiscoveredTreasure(uint treasureId); // Returns if a site can be looted by the controllable bool CanLootSite(MRSiteChit site); // Returns if a twit site can be looted by the controllable bool CanLootTwit(MRTreasure twit); // Called when a site is looted by the controllable void OnSiteLooted(MRSiteChit site, bool success); // Called when a twit site is looted by the controllable void OnTwitLooted(MRTreasure twit, bool success); // Adds an item to the controllable's items. void AddItem(MRItem item); // Returns the weight of the heaviest item owned by the controllable MRGame.eStrength GetHeaviestWeight(bool includeHorse, bool includeSelf); // Adds a controllable to the list of things attacking this target void AddAttacker(MRIControllable attacker); // Removes a controllable from the list of things attacking this target void RemoveAttacker(MRIControllable attacker); // Called when the controllable hits its target void HitTarget(MRIControllable target, bool targetDead); // Called when the controllable misses its target void MissTarget(MRIControllable target); /// <summary> /// Awards the spoils of combat for killing a combatant. /// </summary> /// <param name="killed">Combatant that was killed.</param> /// <param name="awardFraction">Fraction of the spoils to award (due to shared kills).</param> void AwardSpoils(MRIControllable killed, float awardFraction); #endregion } }
using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using Orleans.ServiceBus.Providers; using Orleans.Streams; using Orleans.TestingHost.Utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; using Microsoft.Azure.EventHubs; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Orleans.Configuration; using TestExtensions; using Xunit; using Orleans.ServiceBus.Providers.Testing; using Orleans.Hosting; namespace ServiceBus.Tests.EvictionStrategyTests { [TestCategory("EventHub"), TestCategory("Streaming")] public class EHPurgeLogicTests { private CachePressureInjectionMonitor cachePressureInjectionMonitor; private PurgeDecisionInjectionPredicate purgePredicate; private SerializationManager serializationManager; private EventHubAdapterReceiver receiver1; private EventHubAdapterReceiver receiver2; private ObjectPool<FixedSizeBuffer> bufferPool; private TimeSpan timeOut = TimeSpan.FromSeconds(30); private EventHubPartitionSettings ehSettings; private ConcurrentBag<EventHubQueueCacheForTesting> cacheList; private List<EHEvictionStrategyForTesting> evictionStrategyList; private ITelemetryProducer telemetryProducer; public EHPurgeLogicTests() { //an mock eh settings this.ehSettings = new EventHubPartitionSettings { Hub = new EventHubOptions(), Partition = "MockPartition", ReceiverOptions = new EventHubReceiverOptions() }; //set up cache pressure monitor and purge predicate this.cachePressureInjectionMonitor = new CachePressureInjectionMonitor(); this.purgePredicate = new PurgeDecisionInjectionPredicate(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30)); //set up serialization env var environment = SerializationTestEnvironment.InitializeWithDefaults(); this.serializationManager = environment.SerializationManager; //set up buffer pool, small buffer size make it easy for cache to allocate multiple buffers var oneKB = 1024; this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneKB)); this.telemetryProducer = NullTelemetryProducer.Instance; } [Fact, TestCategory("BVT")] public async Task EventhubQueueCache_WontPurge_WhenUnderPressure() { InitForTesting(); var tasks = new List<Task>(); //add items into cache, make sure will allocate multiple buffers from the pool int itemAddToCache = 100; foreach(var cache in this.cacheList) tasks.Add(AddDataIntoCache(cache, itemAddToCache)); await Task.WhenAll(tasks); //set cachePressureMonitor to be underPressure this.cachePressureInjectionMonitor.isUnderPressure = true; //set purgePredicate to be ShouldPurge this.purgePredicate.ShouldPurge = true; //perform purge IList<IBatchContainer> ignore; this.receiver1.TryPurgeFromCache(out ignore); this.receiver2.TryPurgeFromCache(out ignore); //Assert int expectedItemCountInCacheList = itemAddToCache + itemAddToCache; Assert.Equal(expectedItemCountInCacheList, GetItemCountInAllCache(this.cacheList)); } [Fact, TestCategory("BVT")] public async Task EventhubQueueCache_WontPurge_WhenTimePurgePredicateSaysDontPurge() { InitForTesting(); var tasks = new List<Task>(); //add items into cache int itemAddToCache = 100; foreach (var cache in this.cacheList) tasks.Add(AddDataIntoCache(cache, itemAddToCache)); await Task.WhenAll(tasks); //set cachePressureMonitor to be underPressure this.cachePressureInjectionMonitor.isUnderPressure = false; //set purgePredicate to be ShouldPurge this.purgePredicate.ShouldPurge = false; //perform purge IList<IBatchContainer> ignore; this.receiver1.TryPurgeFromCache(out ignore); this.receiver2.TryPurgeFromCache(out ignore); //Assert int expectedItemCountInCacheList = itemAddToCache + itemAddToCache; Assert.Equal(expectedItemCountInCacheList, GetItemCountInAllCache(this.cacheList)); } [Fact, TestCategory("BVT")] public async Task EventhubQueueCache_WillPurge_WhenTimePurgePredicateSaysPurge_And_NotUnderPressure() { InitForTesting(); var tasks = new List<Task>(); //add items into cache int itemAddToCache = 100; foreach (var cache in this.cacheList) tasks.Add(AddDataIntoCache(cache, itemAddToCache)); await Task.WhenAll(tasks); //set cachePressureMonitor to be underPressure this.cachePressureInjectionMonitor.isUnderPressure = false; //set purgePredicate to be ShouldPurge this.purgePredicate.ShouldPurge = true; //perform purge IList<IBatchContainer> ignore; this.receiver1.TryPurgeFromCache(out ignore); this.receiver2.TryPurgeFromCache(out ignore); //Assert int expectedItemCountInCaches = 0; //items got purged Assert.Equal(expectedItemCountInCaches, GetItemCountInAllCache(this.cacheList)); } [Fact, TestCategory("BVT")] public async Task EventhubQueueCache_EvictionStrategy_Behavior() { InitForTesting(); var tasks = new List<Task>(); //add items into cache int itemAddToCache = 100; foreach (var cache in this.cacheList) tasks.Add(AddDataIntoCache(cache, itemAddToCache)); await Task.WhenAll(tasks); //set up condition so that purge will be performed this.cachePressureInjectionMonitor.isUnderPressure = false; this.purgePredicate.ShouldPurge = true; //Each cache should each have buffers allocated this.evictionStrategyList.ForEach(strategy => Assert.True(strategy.InUseBuffers.Count > 0)); //perform purge //after purge, inUseBuffers should be purged and return to the pool, except for the current buffer var expectedPurgedBuffers = new List<FixedSizeBuffer>(); this.evictionStrategyList.ForEach(strategy => { var purgedBufferList = strategy.InUseBuffers.ToArray<FixedSizeBuffer>(); //last one in purgedBufferList should be current buffer, which shouldn't be purged for (int i = 0; i < purgedBufferList.Count() - 1; i++) expectedPurgedBuffers.Add(purgedBufferList[i]); }); IList<IBatchContainer> ignore; this.receiver1.TryPurgeFromCache(out ignore); this.receiver2.TryPurgeFromCache(out ignore); //Each cache should have all buffers purged, except for current buffer this.evictionStrategyList.ForEach(strategy => Assert.Single(strategy.InUseBuffers)); var oldBuffersInCaches = new List<FixedSizeBuffer>(); this.evictionStrategyList.ForEach(strategy => { foreach (var inUseBuffer in strategy.InUseBuffers) oldBuffersInCaches.Add(inUseBuffer); }); //add items into cache again itemAddToCache = 100; foreach (var cache in this.cacheList) tasks.Add(AddDataIntoCache(cache, itemAddToCache)); await Task.WhenAll(tasks); //block pool should have purged buffers returned by now, and used those to allocate buffer for new item var newBufferAllocated = new List<FixedSizeBuffer>(); this.evictionStrategyList.ForEach(strategy => { foreach (var inUseBuffer in strategy.InUseBuffers) newBufferAllocated.Add(inUseBuffer); }); //remove old buffer in cache, to get newly allocated buffers after purge newBufferAllocated.RemoveAll(buffer => oldBuffersInCaches.Contains(buffer)); //purged buffer should return to the pool after purge, and used to allocate new buffer expectedPurgedBuffers.ForEach(buffer => Assert.Contains(buffer, newBufferAllocated)); } private void InitForTesting() { this.cacheList = new ConcurrentBag<EventHubQueueCacheForTesting>(); this.evictionStrategyList = new List<EHEvictionStrategyForTesting>(); var monitorDimensions = new EventHubReceiverMonitorDimensions { EventHubPartition = this.ehSettings.Partition, EventHubPath = this.ehSettings.Hub.Path, }; this.receiver1 = new EventHubAdapterReceiver(this.ehSettings, this.CacheFactory, this.CheckPointerFactory, NullLoggerFactory.Instance, new DefaultEventHubReceiverMonitor(monitorDimensions, this.telemetryProducer), new LoadSheddingOptions(), this.telemetryProducer); this.receiver2 = new EventHubAdapterReceiver(this.ehSettings, this.CacheFactory, this.CheckPointerFactory, NullLoggerFactory.Instance, new DefaultEventHubReceiverMonitor(monitorDimensions, this.telemetryProducer), new LoadSheddingOptions(), this.telemetryProducer); this.receiver1.Initialize(this.timeOut); this.receiver2.Initialize(this.timeOut); } private int GetItemCountInAllCache(ConcurrentBag<EventHubQueueCacheForTesting> caches) { int itemCount = 0; foreach (var cache in caches) { itemCount += cache.ItemCount; } return itemCount; } private async Task AddDataIntoCache(EventHubQueueCacheForTesting cache, int count) { await Task.Delay(10); List<EventData> messages = Enumerable.Range(0, count) .Select(i => MakeEventData(i)) .ToList(); cache.Add(messages, DateTime.UtcNow); } private EventData MakeEventData(long sequenceNumber) { byte[] ignore = { 12, 23 }; var eventData = new EventData(ignore); DateTime now = DateTime.UtcNow; var offSet = Guid.NewGuid().ToString() + now.ToString(); eventData.SetOffset(offSet); //set sequence number eventData.SetSequenceNumber(sequenceNumber); //set enqueue time eventData.SetEnqueuedTimeUtc(now); return eventData; } private NodeConfiguration GetNodeConfiguration() { return new NodeConfiguration(); } private Task<IStreamQueueCheckpointer<string>> CheckPointerFactory(string partition) { return Task.FromResult<IStreamQueueCheckpointer<string>>(NoOpCheckpointer.Instance); } private IEventHubQueueCache CacheFactory(string partition, IStreamQueueCheckpointer<string> checkpointer, ILoggerFactory loggerFactory, ITelemetryProducer telemetryProducer) { var cacheLogger = loggerFactory.CreateLogger($"{typeof(EventHubQueueCacheForTesting)}.{partition}"); var evictionStrategy = new EHEvictionStrategyForTesting(cacheLogger, null, null, this.purgePredicate); this.evictionStrategyList.Add(evictionStrategy); var cache = new EventHubQueueCacheForTesting(checkpointer, new MockEventHubCacheAdaptor(this.serializationManager, this.bufferPool), EventHubDataComparer.Instance, cacheLogger, evictionStrategy); cache.AddCachePressureMonitor(this.cachePressureInjectionMonitor); this.cacheList.Add(cache); return cache; } } }
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.StreamAnalytics { /// <summary> /// Operations for Azure Stream Analytics subscription information. /// </summary> internal partial class SubscriptionOperations : IServiceOperations<StreamAnalyticsManagementClient>, ISubscriptionOperations { /// <summary> /// Initializes a new instance of the SubscriptionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubscriptionOperations(StreamAnalyticsManagementClient client) { this._client = client; } private StreamAnalyticsManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.StreamAnalytics.StreamAnalyticsManagementClient. /// </summary> public StreamAnalyticsManagementClient Client { get { return this._client; } } /// <summary> /// Get the stream analytics quotas of a subscription. /// </summary> /// <param name='location'> /// Required. The region that you want to check the quotas. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the get stream analytics quotas operation. /// </returns> public async Task<SubscriptionQuotasGetResponse> GetQuotasAsync(string location, CancellationToken cancellationToken) { // Validate if (location == null) { throw new ArgumentNullException("location"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); TracingAdapter.Enter(invocationId, this, "GetQuotasAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.StreamAnalytics/locations/"; url = url + Uri.EscapeDataString(location); url = url + "/quotas"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); 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 httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 SubscriptionQuotasGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionQuotasGetResponse(); 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)) { SubscriptionQuotas subscriptionQuotasInstance = new SubscriptionQuotas(); result.Value.Add(subscriptionQuotasInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); subscriptionQuotasInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { SubscriptionQuotasProperties propertiesInstance = new SubscriptionQuotasProperties(); subscriptionQuotasInstance.Properties = propertiesInstance; JToken maxCountValue = propertiesValue["maxCount"]; if (maxCountValue != null && maxCountValue.Type != JTokenType.Null) { int maxCountInstance = ((int)maxCountValue); propertiesInstance.MaxCount = maxCountInstance; } JToken currentCountValue = propertiesValue["currentCount"]; if (currentCountValue != null && currentCountValue.Type != JTokenType.Null) { int currentCountInstance = ((int)currentCountValue); propertiesInstance.CurrentCount = currentCountInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } 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(); } } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.Diagnostics.SymbolStore; using Mono.Cecil.Cil; using Mono.Collections.Generic; #if !READ_ONLY namespace Mono.Cecil.Pdb { public class PdbWriter : Cil.ISymbolWriter { readonly ModuleDefinition module; readonly SymWriter writer; readonly Dictionary<string, SymDocumentWriter> documents; internal PdbWriter (ModuleDefinition module, SymWriter writer) { this.module = module; this.writer = writer; this.documents = new Dictionary<string, SymDocumentWriter> (); } public bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header) { header = writer.GetDebugInfo (out directory); return true; } public void Write (MethodBody body) { var method_token = body.Method.MetadataToken; var sym_token = new SymbolToken (method_token.ToInt32 ()); var instructions = CollectInstructions (body); if (instructions.Count == 0) return; var start_offset = 0; var end_offset = body.CodeSize; writer.OpenMethod (sym_token); writer.OpenScope (start_offset); DefineSequencePoints (instructions); DefineVariables (body, start_offset, end_offset); writer.CloseScope (end_offset); writer.CloseMethod (); } Collection<Instruction> CollectInstructions (MethodBody body) { var collection = new Collection<Instruction> (); var instructions = body.Instructions; for (int i = 0; i < instructions.Count; i++) { var instruction = instructions [i]; var sequence_point = instruction.SequencePoint; if (sequence_point == null) continue; GetDocument (sequence_point.Document); collection.Add (instruction); } return collection; } void DefineVariables (MethodBody body, int start_offset, int end_offset) { if (!body.HasVariables) return; var sym_token = new SymbolToken (body.LocalVarToken.ToInt32 ()); var variables = body.Variables; for (int i = 0; i < variables.Count; i++) { var variable = variables [i]; CreateLocalVariable (variable, sym_token, start_offset, end_offset); } } void DefineSequencePoints (Collection<Instruction> instructions) { for (int i = 0; i < instructions.Count; i++) { var instruction = instructions [i]; var sequence_point = instruction.SequencePoint; writer.DefineSequencePoints ( GetDocument (sequence_point.Document), new [] { instruction.Offset }, new [] { sequence_point.StartLine }, new [] { sequence_point.StartColumn }, new [] { sequence_point.EndLine }, new [] { sequence_point.EndColumn }); } } void CreateLocalVariable (VariableDefinition variable, SymbolToken local_var_token, int start_offset, int end_offset) { writer.DefineLocalVariable2 ( variable.Name, 0, local_var_token, SymAddressKind.ILOffset, variable.Index, 0, 0, start_offset, end_offset); } SymDocumentWriter GetDocument (Document document) { if (document == null) return null; SymDocumentWriter doc_writer; if (documents.TryGetValue (document.Url, out doc_writer)) return doc_writer; doc_writer = writer.DefineDocument ( document.Url, document.Language.ToGuid (), document.LanguageVendor.ToGuid (), document.Type.ToGuid ()); documents [document.Url] = doc_writer; return doc_writer; } public void Write (MethodSymbols symbols) { var sym_token = new SymbolToken (symbols.MethodToken.ToInt32 ()); var start_offset = 0; var end_offset = symbols.CodeSize; writer.OpenMethod (sym_token); writer.OpenScope (start_offset); DefineSequencePoints (symbols); DefineVariables (symbols, start_offset, end_offset); writer.CloseScope (end_offset); writer.CloseMethod (); } void DefineSequencePoints (MethodSymbols symbols) { var instructions = symbols.instructions; for (int i = 0; i < instructions.Count; i++) { var instruction = instructions [i]; var sequence_point = instruction.SequencePoint; writer.DefineSequencePoints ( GetDocument (sequence_point.Document), new [] { instruction.Offset }, new [] { sequence_point.StartLine }, new [] { sequence_point.StartColumn }, new [] { sequence_point.EndLine }, new [] { sequence_point.EndColumn }); } } void DefineVariables (MethodSymbols symbols, int start_offset, int end_offset) { if (!symbols.HasVariables) return; var sym_token = new SymbolToken (symbols.LocalVarToken.ToInt32 ()); var variables = symbols.Variables; for (int i = 0; i < variables.Count; i++) { var variable = variables [i]; CreateLocalVariable (variable, sym_token, start_offset, end_offset); } } public void Dispose () { var entry_point = module.EntryPoint; if (entry_point != null) writer.SetUserEntryPoint (new SymbolToken (entry_point.MetadataToken.ToInt32 ())); writer.Close (); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Net.Http.Headers { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is not a collection")] public sealed class HttpRequestHeaders : HttpHeaders { private static readonly Dictionary<string, HttpHeaderParser> s_parserStore = CreateParserStore(); private static readonly HashSet<string> s_invalidHeaders = CreateInvalidHeaders(); private HttpGeneralHeaders _generalHeaders; private HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> _accept; private HttpHeaderValueCollection<NameValueWithParametersHeaderValue> _expect; private bool _expectContinueSet; private HttpHeaderValueCollection<EntityTagHeaderValue> _ifMatch; private HttpHeaderValueCollection<EntityTagHeaderValue> _ifNoneMatch; private HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> _te; private HttpHeaderValueCollection<ProductInfoHeaderValue> _userAgent; private HttpHeaderValueCollection<StringWithQualityHeaderValue> _acceptCharset; private HttpHeaderValueCollection<StringWithQualityHeaderValue> _acceptEncoding; private HttpHeaderValueCollection<StringWithQualityHeaderValue> _acceptLanguage; #region Request Headers public HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> Accept { get { if (_accept == null) { _accept = new HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue>( HttpKnownHeaderNames.Accept, this); } return _accept; } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Charset", Justification = "The HTTP header name is 'Accept-Charset'.")] public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptCharset { get { if (_acceptCharset == null) { _acceptCharset = new HttpHeaderValueCollection<StringWithQualityHeaderValue>( HttpKnownHeaderNames.AcceptCharset, this); } return _acceptCharset; } } public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptEncoding { get { if (_acceptEncoding == null) { _acceptEncoding = new HttpHeaderValueCollection<StringWithQualityHeaderValue>( HttpKnownHeaderNames.AcceptEncoding, this); } return _acceptEncoding; } } public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptLanguage { get { if (_acceptLanguage == null) { _acceptLanguage = new HttpHeaderValueCollection<StringWithQualityHeaderValue>( HttpKnownHeaderNames.AcceptLanguage, this); } return _acceptLanguage; } } public AuthenticationHeaderValue Authorization { get { return (AuthenticationHeaderValue)GetParsedValues(HttpKnownHeaderNames.Authorization); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Authorization, value); } } public HttpHeaderValueCollection<NameValueWithParametersHeaderValue> Expect { get { return ExpectCore; } } public bool? ExpectContinue { get { if (ExpectCore.IsSpecialValueSet) { return true; } if (_expectContinueSet) { return false; } return null; } set { if (value == true) { _expectContinueSet = true; ExpectCore.SetSpecialValue(); } else { _expectContinueSet = value != null; ExpectCore.RemoveSpecialValue(); } } } public string From { get { return (string)GetParsedValues(HttpKnownHeaderNames.From); } set { // Null and empty string are equivalent. In this case it means, remove the From header value (if any). if (value == string.Empty) { value = null; } if ((value != null) && !HeaderUtilities.IsValidEmailAddress(value)) { throw new FormatException(SR.net_http_headers_invalid_from_header); } SetOrRemoveParsedValue(HttpKnownHeaderNames.From, value); } } public string Host { get { return (string)GetParsedValues(HttpKnownHeaderNames.Host); } set { // Null and empty string are equivalent. In this case it means, remove the Host header value (if any). if (value == string.Empty) { value = null; } string host = null; if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false, out host) != value.Length)) { throw new FormatException(SR.net_http_headers_invalid_host_header); } SetOrRemoveParsedValue(HttpKnownHeaderNames.Host, value); } } public HttpHeaderValueCollection<EntityTagHeaderValue> IfMatch { get { if (_ifMatch == null) { _ifMatch = new HttpHeaderValueCollection<EntityTagHeaderValue>( HttpKnownHeaderNames.IfMatch, this); } return _ifMatch; } } public DateTimeOffset? IfModifiedSince { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.IfModifiedSince, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfModifiedSince, value); } } public HttpHeaderValueCollection<EntityTagHeaderValue> IfNoneMatch { get { if (_ifNoneMatch == null) { _ifNoneMatch = new HttpHeaderValueCollection<EntityTagHeaderValue>( HttpKnownHeaderNames.IfNoneMatch, this); } return _ifNoneMatch; } } public RangeConditionHeaderValue IfRange { get { return (RangeConditionHeaderValue)GetParsedValues(HttpKnownHeaderNames.IfRange); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfRange, value); } } public DateTimeOffset? IfUnmodifiedSince { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.IfUnmodifiedSince, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfUnmodifiedSince, value); } } public int? MaxForwards { get { object storedValue = GetParsedValues(HttpKnownHeaderNames.MaxForwards); if (storedValue != null) { return (int)storedValue; } return null; } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.MaxForwards, value); } } public AuthenticationHeaderValue ProxyAuthorization { get { return (AuthenticationHeaderValue)GetParsedValues(HttpKnownHeaderNames.ProxyAuthorization); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.ProxyAuthorization, value); } } public RangeHeaderValue Range { get { return (RangeHeaderValue)GetParsedValues(HttpKnownHeaderNames.Range); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Range, value); } } public Uri Referrer { get { return (Uri)GetParsedValues(HttpKnownHeaderNames.Referer); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Referer, value); } } public HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> TE { get { if (_te == null) { _te = new HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue>( HttpKnownHeaderNames.TE, this); } return _te; } } public HttpHeaderValueCollection<ProductInfoHeaderValue> UserAgent { get { if (_userAgent == null) { _userAgent = new HttpHeaderValueCollection<ProductInfoHeaderValue>(HttpKnownHeaderNames.UserAgent, this); } return _userAgent; } } private HttpHeaderValueCollection<NameValueWithParametersHeaderValue> ExpectCore { get { if (_expect == null) { _expect = new HttpHeaderValueCollection<NameValueWithParametersHeaderValue>( HttpKnownHeaderNames.Expect, this, HeaderUtilities.ExpectContinue); } return _expect; } } #endregion #region General Headers public CacheControlHeaderValue CacheControl { get { return _generalHeaders.CacheControl; } set { _generalHeaders.CacheControl = value; } } public HttpHeaderValueCollection<string> Connection { get { return _generalHeaders.Connection; } } public bool? ConnectionClose { get { return _generalHeaders.ConnectionClose; } set { _generalHeaders.ConnectionClose = value; } } public DateTimeOffset? Date { get { return _generalHeaders.Date; } set { _generalHeaders.Date = value; } } public HttpHeaderValueCollection<NameValueHeaderValue> Pragma { get { return _generalHeaders.Pragma; } } public HttpHeaderValueCollection<string> Trailer { get { return _generalHeaders.Trailer; } } public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding { get { return _generalHeaders.TransferEncoding; } } public bool? TransferEncodingChunked { get { return _generalHeaders.TransferEncodingChunked; } set { _generalHeaders.TransferEncodingChunked = value; } } public HttpHeaderValueCollection<ProductHeaderValue> Upgrade { get { return _generalHeaders.Upgrade; } } public HttpHeaderValueCollection<ViaHeaderValue> Via { get { return _generalHeaders.Via; } } public HttpHeaderValueCollection<WarningHeaderValue> Warning { get { return _generalHeaders.Warning; } } #endregion internal HttpRequestHeaders() { _generalHeaders = new HttpGeneralHeaders(this); base.SetConfiguration(s_parserStore, s_invalidHeaders); } private static Dictionary<string, HttpHeaderParser> CreateParserStore() { var parserStore = new Dictionary<string, HttpHeaderParser>(StringComparer.OrdinalIgnoreCase); parserStore.Add(HttpKnownHeaderNames.Accept, MediaTypeHeaderParser.MultipleValuesParser); parserStore.Add(HttpKnownHeaderNames.AcceptCharset, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.AcceptEncoding, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.AcceptLanguage, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.Authorization, GenericHeaderParser.SingleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.Expect, GenericHeaderParser.MultipleValueNameValueWithParametersParser); parserStore.Add(HttpKnownHeaderNames.From, GenericHeaderParser.MailAddressParser); parserStore.Add(HttpKnownHeaderNames.Host, GenericHeaderParser.HostParser); parserStore.Add(HttpKnownHeaderNames.IfMatch, GenericHeaderParser.MultipleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.IfModifiedSince, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.IfNoneMatch, GenericHeaderParser.MultipleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.IfRange, GenericHeaderParser.RangeConditionParser); parserStore.Add(HttpKnownHeaderNames.IfUnmodifiedSince, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.MaxForwards, Int32NumberHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.ProxyAuthorization, GenericHeaderParser.SingleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.Range, GenericHeaderParser.RangeParser); parserStore.Add(HttpKnownHeaderNames.Referer, UriHeaderParser.RelativeOrAbsoluteUriParser); parserStore.Add(HttpKnownHeaderNames.TE, TransferCodingHeaderParser.MultipleValueWithQualityParser); parserStore.Add(HttpKnownHeaderNames.UserAgent, ProductInfoHeaderParser.MultipleValueParser); HttpGeneralHeaders.AddParsers(parserStore); return parserStore; } private static HashSet<string> CreateInvalidHeaders() { var invalidHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HttpContentHeaders.AddKnownHeaders(invalidHeaders); return invalidHeaders; // Note: Reserved response header names are allowed as custom request header names. Reserved response // headers have no defined meaning or format when used on a request. This enables a server to accept // any headers sent from the client as either content headers or request headers. } internal static void AddKnownHeaders(HashSet<string> headerSet) { Debug.Assert(headerSet != null); headerSet.Add(HttpKnownHeaderNames.Accept); headerSet.Add(HttpKnownHeaderNames.AcceptCharset); headerSet.Add(HttpKnownHeaderNames.AcceptEncoding); headerSet.Add(HttpKnownHeaderNames.AcceptLanguage); headerSet.Add(HttpKnownHeaderNames.Authorization); headerSet.Add(HttpKnownHeaderNames.Expect); headerSet.Add(HttpKnownHeaderNames.From); headerSet.Add(HttpKnownHeaderNames.Host); headerSet.Add(HttpKnownHeaderNames.IfMatch); headerSet.Add(HttpKnownHeaderNames.IfModifiedSince); headerSet.Add(HttpKnownHeaderNames.IfNoneMatch); headerSet.Add(HttpKnownHeaderNames.IfRange); headerSet.Add(HttpKnownHeaderNames.IfUnmodifiedSince); headerSet.Add(HttpKnownHeaderNames.MaxForwards); headerSet.Add(HttpKnownHeaderNames.ProxyAuthorization); headerSet.Add(HttpKnownHeaderNames.Range); headerSet.Add(HttpKnownHeaderNames.Referer); headerSet.Add(HttpKnownHeaderNames.TE); headerSet.Add(HttpKnownHeaderNames.UserAgent); } internal override void AddHeaders(HttpHeaders sourceHeaders) { base.AddHeaders(sourceHeaders); HttpRequestHeaders sourceRequestHeaders = sourceHeaders as HttpRequestHeaders; Debug.Assert(sourceRequestHeaders != null); // Copy special values but do not overwrite. _generalHeaders.AddSpecialsFrom(sourceRequestHeaders._generalHeaders); bool? expectContinue = ExpectContinue; if (!expectContinue.HasValue) { ExpectContinue = sourceRequestHeaders.ExpectContinue; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Identity Provider details. /// </summary> [Rest.Serialization.JsonTransformation] public partial class IdentityProviderContract : Resource { /// <summary> /// Initializes a new instance of the IdentityProviderContract class. /// </summary> public IdentityProviderContract() { CustomInit(); } /// <summary> /// Initializes a new instance of the IdentityProviderContract class. /// </summary> /// <param name="clientId">Client Id of the Application in the external /// Identity Provider. It is App ID for Facebook login, Client ID for /// Google login, App ID for Microsoft.</param> /// <param name="clientSecret">Client secret of the Application in /// external Identity Provider, used to authenticate login request. For /// example, it is App Secret for Facebook login, API Key for Google /// login, Public Key for Microsoft.</param> /// <param name="id">Resource ID.</param> /// <param name="name">Resource name.</param> /// <param name="type">Resource type for API Management /// resource.</param> /// <param name="identityProviderContractType">Identity Provider Type /// identifier. Possible values include: 'facebook', 'google', /// 'microsoft', 'twitter', 'aad', 'aadB2C'</param> /// <param name="allowedTenants">List of Allowed Tenants when /// configuring Azure Active Directory login.</param> /// <param name="signupPolicyName">Signup Policy Name. Only applies to /// AAD B2C Identity Provider.</param> /// <param name="signinPolicyName">Signin Policy Name. Only applies to /// AAD B2C Identity Provider.</param> /// <param name="profileEditingPolicyName">Profile Editing Policy Name. /// Only applies to AAD B2C Identity Provider.</param> /// <param name="passwordResetPolicyName">Password Reset Policy Name. /// Only applies to AAD B2C Identity Provider.</param> public IdentityProviderContract(string clientId, string clientSecret, string id = default(string), string name = default(string), string type = default(string), IdentityProviderType? identityProviderContractType = default(IdentityProviderType?), IList<string> allowedTenants = default(IList<string>), string signupPolicyName = default(string), string signinPolicyName = default(string), string profileEditingPolicyName = default(string), string passwordResetPolicyName = default(string)) : base(id, name, type) { IdentityProviderContractType = identityProviderContractType; AllowedTenants = allowedTenants; SignupPolicyName = signupPolicyName; SigninPolicyName = signinPolicyName; ProfileEditingPolicyName = profileEditingPolicyName; PasswordResetPolicyName = passwordResetPolicyName; ClientId = clientId; ClientSecret = clientSecret; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets identity Provider Type identifier. Possible values /// include: 'facebook', 'google', 'microsoft', 'twitter', 'aad', /// 'aadB2C' /// </summary> [JsonProperty(PropertyName = "properties.type")] public IdentityProviderType? IdentityProviderContractType { get; set; } /// <summary> /// Gets or sets list of Allowed Tenants when configuring Azure Active /// Directory login. /// </summary> [JsonProperty(PropertyName = "properties.allowedTenants")] public IList<string> AllowedTenants { get; set; } /// <summary> /// Gets or sets signup Policy Name. Only applies to AAD B2C Identity /// Provider. /// </summary> [JsonProperty(PropertyName = "properties.signupPolicyName")] public string SignupPolicyName { get; set; } /// <summary> /// Gets or sets signin Policy Name. Only applies to AAD B2C Identity /// Provider. /// </summary> [JsonProperty(PropertyName = "properties.signinPolicyName")] public string SigninPolicyName { get; set; } /// <summary> /// Gets or sets profile Editing Policy Name. Only applies to AAD B2C /// Identity Provider. /// </summary> [JsonProperty(PropertyName = "properties.profileEditingPolicyName")] public string ProfileEditingPolicyName { get; set; } /// <summary> /// Gets or sets password Reset Policy Name. Only applies to AAD B2C /// Identity Provider. /// </summary> [JsonProperty(PropertyName = "properties.passwordResetPolicyName")] public string PasswordResetPolicyName { get; set; } /// <summary> /// Gets or sets client Id of the Application in the external Identity /// Provider. It is App ID for Facebook login, Client ID for Google /// login, App ID for Microsoft. /// </summary> [JsonProperty(PropertyName = "properties.clientId")] public string ClientId { get; set; } /// <summary> /// Gets or sets client secret of the Application in external Identity /// Provider, used to authenticate login request. For example, it is /// App Secret for Facebook login, API Key for Google login, Public Key /// for Microsoft. /// </summary> [JsonProperty(PropertyName = "properties.clientSecret")] public string ClientSecret { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (ClientId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ClientId"); } if (ClientSecret == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ClientSecret"); } if (AllowedTenants != null) { if (AllowedTenants.Count > 32) { throw new ValidationException(ValidationRules.MaxItems, "AllowedTenants", 32); } } if (SignupPolicyName != null) { if (SignupPolicyName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "SignupPolicyName", 1); } } if (SigninPolicyName != null) { if (SigninPolicyName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "SigninPolicyName", 1); } } if (ProfileEditingPolicyName != null) { if (ProfileEditingPolicyName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "ProfileEditingPolicyName", 1); } } if (PasswordResetPolicyName != null) { if (PasswordResetPolicyName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "PasswordResetPolicyName", 1); } } if (ClientId != null) { if (ClientId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "ClientId", 1); } } if (ClientSecret != null) { if (ClientSecret.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "ClientSecret", 1); } } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; using VR = UnityEngine.VR; /// <summary> /// Add OVROverlay script to an object with an optional mesh primitive /// rendered as a TimeWarp overlay instead by drawing it into the eye buffer. /// This will take full advantage of the display resolution and avoid double /// resampling of the texture. /// /// If the texture is dynamically generated, as for an interactive GUI or /// animation, it must be explicitly triple buffered to avoid flickering /// when it is referenced asynchronously by TimeWarp, check OVRRTOverlayConnector.cs for triple buffers design /// /// We support 3 types of Overlay shapes right now /// 1. Quad : This is most common overlay type , you render a quad in Timewarp space. /// 2. Cylinder: [Mobile Only][Experimental], Display overlay as partial surface of a cylinder /// * The cylinder's center will be your game object's center /// * We encoded the cylinder's parameters in transform.scale, /// **[scale.z] is the radius of the cylinder /// **[scale.y] is the height of the cylinder /// **[scale.x] is the length of the arc of cylinder /// * Limitations /// **Only the half of the cylinder can be displayed, which means the arc angle has to be smaller than 180 degree, [scale.x] / [scale.z] <= PI /// **Your camera has to be inside of the inscribed sphere of the cylinder, the overlay will be faded out automatically when the camera is close to the inscribed sphere's surface. /// **Translation only works correctly with vrDriver 1.04 or above /// 3. Cubemap: Display overlay as a cube map /// 4. OffcenterCubemap: [Mobile Only] Display overlay as a cube map with a texture coordinate offset /// * The actually sampling will looks like [color = texture(cubeLayerSampler, normalize(direction) + offset)] instead of [color = texture( cubeLayerSampler, direction )] /// * The extra center offset can be feed from transform.position /// * Note: if transform.position's magnitude is greater than 1, which will cause some cube map pixel always invisible /// Which is usually not what people wanted, we don't kill the ability for developer to do so here, but will warn out. /// </summary> public class OVROverlay : MonoBehaviour { public enum OverlayShape { Quad = OVRPlugin.OverlayShape.Quad, // Display overlay as a quad Cylinder = OVRPlugin.OverlayShape.Cylinder, // [Mobile Only][Experimental] Display overlay as a cylinder, Translation only works correctly with vrDriver 1.04 or above Cubemap = OVRPlugin.OverlayShape.Cubemap, // Display overlay as a cube map OffcenterCubemap = OVRPlugin.OverlayShape.OffcenterCubemap, // Display overlay as a cube map with a center offset } public enum OverlayType { None, // Disabled the overlay Underlay, // Eye buffers blend on top Overlay, // Blends on top of the eye buffer OverlayShowLod // (Deprecated) Blends on top and colorizes texture level of detail }; #if UNITY_ANDROID && !UNITY_EDITOR const int maxInstances = 3; #else const int maxInstances = 15; #endif internal static OVROverlay[] instances = new OVROverlay[maxInstances]; /// <summary> /// Specify overlay's type /// </summary> public OverlayType currentOverlayType = OverlayType.Overlay; /// <summary> /// If true, the texture's content is copied to the compositor each frame. /// </summary> public bool isDynamic = true; /// <summary> /// Specify overlay's shape /// </summary> public OverlayShape currentOverlayShape = OverlayShape.Quad; private OverlayShape _prevOverlayShape = OverlayShape.Quad; private static Material premultiplyMaterial; /// <summary> /// Try to avoid setting texture frequently when app is running, texNativePtr updating is slow since rendering thread synchronization /// Please cache your nativeTexturePtr and use OverrideOverlayTextureInfo /// </summary> public Texture[] textures = new Texture[] { null, null }; private Texture[][] externalTextures; private Texture[] cachedTextures = new Texture[] { null, null }; private IntPtr[] texNativePtrs = new IntPtr[] { IntPtr.Zero, IntPtr.Zero }; private OVRPlugin.LayerLayout layout = OVRPlugin.LayerLayout.Mono; private int texturesPerStage = 1; private int layerIndex = -1; // Controls the composition order based on wake-up time. private int layerId = 0; // The layer's internal handle in the compositor. private GCHandle layerIdHandle; private IntPtr layerIdPtr = IntPtr.Zero; OVRPlugin.LayerDesc layerDesc; private int frameIndex = 0; Renderer rend; [HideInInspector] public bool isMultiviewEnabled = false; /// <summary> /// Use this function to set texture and texNativePtr when app is running /// GetNativeTexturePtr is a slow behavior, the value should be pre-cached /// </summary> public void OverrideOverlayTextureInfo(Texture srcTexture, IntPtr nativePtr, VR.VRNode node) { int index = (node == VR.VRNode.RightEye) ? 1 : 0; if (textures.Length <= index) return; textures[index] = srcTexture; cachedTextures[index] = srcTexture; texNativePtrs[index] = nativePtr; } void Awake() { Debug.Log("Overlay Awake"); if (premultiplyMaterial == null) premultiplyMaterial = new Material(Shader.Find("Oculus/Alpha Premultiply")); rend = GetComponent<Renderer>(); if (textures.Length == 0) textures = new Texture[] { null }; // Backward compatibility if (rend != null && textures[0] == null) textures[0] = rend.material.mainTexture; if (textures[0] != null) { cachedTextures[0] = textures[0]; texNativePtrs[0] = textures[0].GetNativeTexturePtr(); } #if UNITY_ANDROID && !UNITY_EDITOR if (textures.Length == 2 && textures[1] != null) layout = (isMultiviewEnabled) ? OVRPlugin.LayerLayout.Array : OVRPlugin.LayerLayout.Stereo; texturesPerStage = (layout == OVRPlugin.LayerLayout.Stereo) ? 2 : 1; #endif } void OnEnable() { if (!OVRManager.isHmdPresent) { enabled = false; return; } OnDisable(); for (int i = 0; i < maxInstances; ++i) { if (instances[i] == null || instances[i] == this) { layerIndex = i; instances[i] = this; break; } } layerIdHandle = GCHandle.Alloc(layerId, GCHandleType.Pinned); layerIdPtr = layerIdHandle.AddrOfPinnedObject(); } void OnDisable() { if (layerIndex != -1) { // Turn off the overlay if it was on. OVRPlugin.EnqueueSubmitLayer(true, false, IntPtr.Zero, IntPtr.Zero, -1, 0, OVRPose.identity.ToPosef(), Vector3.one.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)_prevOverlayShape); instances[layerIndex] = null; } if (layerIdPtr != IntPtr.Zero) { OVRPlugin.EnqueueDestroyLayer(layerIdPtr); layerIdPtr = IntPtr.Zero; layerIdHandle.Free(); } layerIndex = -1; } int prevFrameIndex = -1; void OnRenderObject() { // The overlay must be specified every eye frame, because it is positioned relative to the // current head location. If frames are dropped, it will be time warped appropriately, // just like the eye buffers. if (!Camera.current.CompareTag("MainCamera") || Camera.current.cameraType != CameraType.Game || layerIndex == -1 || currentOverlayType == OverlayType.None || textures.Length < texturesPerStage) return; // Don't submit the same frame twice. if (Time.frameCount <= prevFrameIndex) return; prevFrameIndex = Time.frameCount; #if !UNITY_ANDROID || UNITY_EDITOR if (currentOverlayShape == OverlayShape.OffcenterCubemap) { Debug.LogWarning("Overlay shape " + currentOverlayShape + " is not supported on current platform"); } #endif for (int i = 0; i < texturesPerStage; ++i) { if (textures[i] != cachedTextures[i]) { cachedTextures[i] = textures[i]; if (cachedTextures[i] != null) texNativePtrs[i] = cachedTextures[i].GetNativeTexturePtr(); } if (currentOverlayShape == OverlayShape.Cubemap) { if (textures[i] != null && textures[i].GetType() != typeof(Cubemap)) { Debug.LogError("Need Cubemap texture for cube map overlay"); return; } } } if (cachedTextures[0] == null || texNativePtrs[0] == IntPtr.Zero) return; bool overlay = (currentOverlayType == OverlayType.Overlay); bool headLocked = false; for (var t = transform; t != null && !headLocked; t = t.parent) headLocked |= (t == Camera.current.transform); OVRPose pose = (headLocked) ? transform.ToHeadSpacePose() : transform.ToTrackingSpacePose(); Vector3 scale = transform.lossyScale; for (int i = 0; i < 3; ++i) scale[i] /= Camera.current.transform.lossyScale[i]; #if !UNITY_ANDROID if (currentOverlayShape == OverlayShape.Cubemap) { pose.position = Camera.current.transform.position; } #endif // Pack the offsetCenter directly into pose.position for offcenterCubemap if (currentOverlayShape == OverlayShape.OffcenterCubemap) { pose.position = transform.position; if ( pose.position.magnitude > 1.0f ) { Debug.LogWarning("your cube map center offset's magnitude is greater than 1, which will cause some cube map pixel always invisible ."); } } // Cylinder overlay sanity checking if (currentOverlayShape == OverlayShape.Cylinder) { float arcAngle = scale.x / scale.z / (float)Math.PI * 180.0f; if (arcAngle > 180.0f) { Debug.LogError("Cylinder overlay's arc angle has to be below 180 degree, current arc angle is " + arcAngle + " degree." ); return ; } } OVRPlugin.Sizei size = new OVRPlugin.Sizei() { w = textures[0].width, h = textures[0].height }; int flags = (int)OVRPlugin.LayerFlags.TextureOriginAtBottomLeft; int mipLevels = 1; int sampleCount = 1; TextureFormat txFormat = TextureFormat.BGRA32; OVRPlugin.EyeTextureFormat etFormat = OVRPlugin.EyeTextureFormat.B8G8R8A8_sRGB; RenderTextureFormat rtFormat = RenderTextureFormat.BGRA32; var tex2D = textures[0] as Texture2D; if (tex2D != null) { if (tex2D.format == TextureFormat.RGBAHalf || tex2D.format == TextureFormat.RGBAFloat) { txFormat = TextureFormat.RGBAHalf; etFormat = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP; rtFormat = RenderTextureFormat.ARGBHalf; } } var rt = textures[0] as RenderTexture; if (rt != null) { sampleCount = rt.antiAliasing; if (rt.format == RenderTextureFormat.ARGBHalf) { txFormat = TextureFormat.RGBAHalf; etFormat = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP; rtFormat = RenderTextureFormat.ARGBHalf; } } bool needsSetup = ( !layerDesc.TextureSize.Equals(size) || layerDesc.SampleCount != sampleCount || layerDesc.LayerFlags != flags || layerDesc.Shape != (OVRPlugin.OverlayShape)currentOverlayShape || layerDesc.Layout != layout || layerDesc.Format != etFormat); OVRPlugin.LayerDesc desc = new OVRPlugin.LayerDesc(); if (layerIdPtr != IntPtr.Zero && needsSetup) { if ((int)layerIdHandle.Target != 0) OVRPlugin.EnqueueDestroyLayer(layerIdPtr); desc = OVRPlugin.CalculateLayerDesc((OVRPlugin.OverlayShape)currentOverlayShape, layout, size, mipLevels, sampleCount, etFormat, flags); OVRPlugin.EnqueueSetupLayer(desc, layerIdPtr); layerId = (int)layerIdHandle.Target; if (layerId > 0) layerDesc = desc; } if (layerId > 0) { // For newer SDKs, blit directly to the surface that will be used in compositing. int stageCount = OVRPlugin.GetLayerTextureStageCount(layerId); if (externalTextures == null) { frameIndex = 0; externalTextures = new Texture[texturesPerStage][]; } for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId) { if (externalTextures[eyeId] == null) externalTextures[eyeId] = new Texture[stageCount]; int stage = frameIndex % stageCount; IntPtr externalTex = OVRPlugin.GetLayerTexture(layerId, stage, (OVRPlugin.Eye)eyeId); if (externalTex == IntPtr.Zero) continue; bool needsCopy = isDynamic; Texture et = externalTextures[eyeId][stage]; if (et == null) { bool isSrgb = (etFormat == OVRPlugin.EyeTextureFormat.B8G8R8A8_sRGB || etFormat == OVRPlugin.EyeTextureFormat.R8G8B8A8_sRGB); if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap) et = Texture2D.CreateExternalTexture(size.w, size.h, txFormat, mipLevels > 1, isSrgb, externalTex); #if UNITY_2017_1_OR_NEWER else //et = Cubemap.CreateExternalTexture(size.w, size.h, txFormat, mipLevels > 1, isSrgb, externalTex); et = Cubemap.CreateExternalTexture(size.w, /* size.h, */ txFormat, mipLevels > 1, /*isSrgb, */ externalTex); #endif externalTextures[eyeId][stage] = et; needsCopy = true; } if (needsCopy) { // The compositor uses premultiplied alpha, so multiply it here. if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap) { var tempRT = RenderTexture.GetTemporary(size.w, size.h, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount); #if UNITY_ANDROID && !UNITY_EDITOR Graphics.Blit(textures[eyeId], tempRT); //Resolve, decompress, swizzle, etc not handled by simple CopyTexture. #else Graphics.Blit(textures[eyeId], tempRT, premultiplyMaterial); #endif Graphics.CopyTexture(tempRT, 0, 0, et, 0, 0); RenderTexture.ReleaseTemporary(tempRT); } #if UNITY_2017_1_OR_NEWER else { var tempRTSrc = RenderTexture.GetTemporary(size.w, size.h, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount); var tempRTDst = RenderTexture.GetTemporary(size.w, size.h, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount); for (int face = 0; face < 6; ++face) { //HACK: It would be much more efficient to blit directly from textures[eyeId] to et, but Unity's API doesn't support that. //Suggest using a native plugin to render directly to a cubemap layer for 360 video, etc. Graphics.CopyTexture(textures[eyeId], face, 0, tempRTSrc, 0, 0); Graphics.Blit(tempRTSrc, tempRTDst, premultiplyMaterial); Graphics.CopyTexture(tempRTDst, 0, 0, et, face, 0); } RenderTexture.ReleaseTemporary(tempRTSrc); RenderTexture.ReleaseTemporary(tempRTDst); } #endif } } bool isOverlayVisible = OVRPlugin.EnqueueSubmitLayer(overlay, headLocked, texNativePtrs[0], texNativePtrs[1], layerId, frameIndex, pose.flipZ().ToPosef(), scale.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)currentOverlayShape); if (isDynamic) ++frameIndex; _prevOverlayShape = currentOverlayShape; if (rend) rend.enabled = !isOverlayVisible; } } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // 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 SafetySharp.Compiler.Analyzers { using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Modeling; using Roslyn.Symbols; /// <summary> /// Ensures that port declarations are valid. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp), UsedImplicitly] public sealed class PortKindAnalyzer : Analyzer { /// <summary> /// The error diagnostic emitted by the analyzer when an event is a port. /// </summary> private static readonly DiagnosticInfo _eventPort = DiagnosticInfo.Error( DiagnosticIdentifier.EventPort, "Events cannot be ports.", "Event '{0}' cannot be used to declare a port."); /// <summary> /// The error diagnostic emitted by the analyzer when an indexer is a required port. /// </summary> private static readonly DiagnosticInfo _indexerPort = DiagnosticInfo.Error( DiagnosticIdentifier.IndexerPort, "Indexers cannot be required ports.", "Indexer '{0}' cannot be used to declare a required port."); /// <summary> /// The error diagnostic emitted by the analyzer when a port is generic. /// </summary> private static readonly DiagnosticInfo _genericPort = DiagnosticInfo.Error( DiagnosticIdentifier.GenericPort, "Ports are not allowed to declare any type parameters.", "'{0}' is not allowed to declare any type parameters."); /// <summary> /// The error diagnostic emitted by the analyzer when the update method is extern. /// </summary> private static readonly DiagnosticInfo _externUpdateMethod = DiagnosticInfo.Error( DiagnosticIdentifier.ExternUpdateMethod, "A component's Update method cannot be extern.", $"'{{0}}' cannot be extern as it overrides '{typeof(Component).FullName}.Update()'."); /// <summary> /// The error diagnostic emitted by the analyzer when a provided port is extern. /// </summary> private static readonly DiagnosticInfo _externProvidedPort = DiagnosticInfo.Error( DiagnosticIdentifier.ExternProvidedPort, $"A method or property marked with '{typeof(ProvidedAttribute).FullName}' cannot be extern.", "Provided port '{0}' cannot be extern."); /// <summary> /// The error diagnostic emitted by the analyzer when a required port is not extern. /// </summary> private static readonly DiagnosticInfo _nonExternRequiredPort = DiagnosticInfo.Error( DiagnosticIdentifier.NonExternRequiredPort, $"A method or property marked with '{typeof(RequiredAttribute).FullName}' must be extern.", "Required port '{0}' must be extern."); /// <summary> /// The error diagnostic emitted by the analyzer when a port is static. /// </summary> private static readonly DiagnosticInfo _staticPort = DiagnosticInfo.Error( DiagnosticIdentifier.StaticPort, "A port cannot be static.", "Port '{0}' cannot be static."); /// <summary> /// The error diagnostic emitted by the analyzer when the update method is marked as a port. /// </summary> private static readonly DiagnosticInfo _updateMethodMarkedAsPort = DiagnosticInfo.Error( DiagnosticIdentifier.UpdateMethodMarkedAsPort, $"A component's Update method cannot be marked with '{typeof(RequiredAttribute).FullName}'.", $"'{{0}}' overrides '{typeof(Component).FullName}.Update()' and therefore cannot be marked with '{typeof(RequiredAttribute).FullName}'."); /// <summary> /// The error diagnostic emitted by the analyzer if a method or property is marked as both required and provided. /// </summary> private static readonly DiagnosticInfo _ambiguousPortKind = DiagnosticInfo.Error( DiagnosticIdentifier.AmbiguousPortKind, $"A method or property cannot be marked with both '{typeof(RequiredAttribute).FullName}' and '{typeof(ProvidedAttribute).FullName}'.", $"'{{0}}' cannot be marked with both '{typeof(RequiredAttribute).FullName}' and '{typeof(ProvidedAttribute).FullName}'."); /// <summary> /// The error diagnostic emitted by the analyzer when a property accessor is marked as either required or provided. /// </summary> private static readonly DiagnosticInfo _portPropertyAccessor = DiagnosticInfo.Error( DiagnosticIdentifier.PortPropertyAccessor, $"Property getters and setters cannot be marked with either '{typeof(RequiredAttribute).FullName}' or '{typeof(ProvidedAttribute).FullName}'.", $"'{{0}}' cannot be marked with either '{typeof(RequiredAttribute).FullName}' or '{typeof(ProvidedAttribute).FullName}'."); /// <summary> /// The error diagnostic emitted by the analyzer when an interface method or property is unmarked. /// </summary> private static readonly DiagnosticInfo _unmarkedInterfacePort = DiagnosticInfo.Error( DiagnosticIdentifier.UnmarkedInterfacePort, $"A method or property within a component interface must be marked with either '{typeof(RequiredAttribute).FullName}' or '{typeof(ProvidedAttribute).FullName}'.", $"'{{0}}' must be marked with either '{typeof(RequiredAttribute).FullName}' or '{typeof(ProvidedAttribute).FullName}'."); /// <summary> /// Initializes a new instance. /// </summary> public PortKindAnalyzer() : base(_externProvidedPort, _nonExternRequiredPort, _ambiguousPortKind, _updateMethodMarkedAsPort, _staticPort, _externUpdateMethod, _portPropertyAccessor, _unmarkedInterfacePort, _genericPort, _indexerPort, _eventPort) { } /// <summary> /// Called once at session start to register actions in the analysis context. /// </summary> protected override void Initialize(CompilationStartAnalysisContext context) { context.RegisterSymbolAction(Analyze, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event); } /// <summary> /// Performs the analysis. /// </summary> /// <param name="context">The context in which the analysis should be performed.</param> private static void Analyze(SymbolAnalysisContext context) { var compilation = context.Compilation; var symbol = context.Symbol; if (!symbol.ContainingType.AllInterfaces.Contains(compilation.GetTypeSymbol<IComponent>())) return; var methodSymbol = symbol as IMethodSymbol; var hasRequiredAttribute = symbol.HasAttribute<RequiredAttribute>(compilation); var hasProvidedAttribute = symbol.HasAttribute<ProvidedAttribute>(compilation); if (symbol.IsStatic) { if (hasRequiredAttribute || hasProvidedAttribute) _staticPort.Emit(context, symbol, symbol.ToDisplayString()); } var propertySymbol = methodSymbol?.AssociatedSymbol as IPropertySymbol; if (propertySymbol != null) { if (hasProvidedAttribute || hasRequiredAttribute) _portPropertyAccessor.Emit(context, symbol, symbol.ToDisplayString()); if (propertySymbol.IsIndexer && (propertySymbol.IsExtern || propertySymbol.HasAttribute<RequiredAttribute>(compilation))) _indexerPort.Emit(context, propertySymbol, propertySymbol); return; } if (methodSymbol != null && methodSymbol.Arity != 0) _genericPort.Emit(context, methodSymbol, methodSymbol); if (methodSymbol != null && methodSymbol.IsUpdateMethod(compilation)) { if (hasRequiredAttribute || hasProvidedAttribute) _updateMethodMarkedAsPort.Emit(context, symbol, symbol.ToDisplayString()); else if (methodSymbol.IsExtern) _externUpdateMethod.Emit(context, symbol, symbol.ToDisplayString()); return; } if (hasRequiredAttribute && hasProvidedAttribute) { _ambiguousPortKind.Emit(context, symbol, symbol.ToDisplayString()); return; } if (symbol.ContainingType.TypeKind == TypeKind.Interface) { if (!hasRequiredAttribute && !hasProvidedAttribute && (symbol is IMethodSymbol || symbol is IPropertySymbol)) _unmarkedInterfacePort.Emit(context, symbol, symbol.ToDisplayString()); } else { if (hasProvidedAttribute && symbol.IsExtern) _externProvidedPort.Emit(context, symbol, symbol.ToDisplayString()); else if (hasRequiredAttribute && !symbol.IsExtern) _nonExternRequiredPort.Emit(context, symbol, symbol.ToDisplayString()); } if (symbol is IEventSymbol && (hasRequiredAttribute || hasProvidedAttribute || symbol.IsExtern)) _eventPort.Emit(context, symbol, symbol); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * 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 Infoplus.Model { /// <summary> /// OrderSource /// </summary> [DataContract] public partial class OrderSource : IEquatable<OrderSource> { /// <summary> /// Initializes a new instance of the <see cref="OrderSource" /> class. /// </summary> [JsonConstructorAttribute] protected OrderSource() { } /// <summary> /// Initializes a new instance of the <see cref="OrderSource" /> class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="Name">Name (required).</param> /// <param name="PackingNotes">PackingNotes.</param> /// <param name="RequireCartonizedASN">RequireCartonizedASN (default to false).</param> /// <param name="RequireGS1128Label">RequireGS1128Label (default to false).</param> /// <param name="ShippingNotes">ShippingNotes.</param> /// <param name="PackingSlipId">PackingSlipId.</param> /// <param name="OrderConfirmationEmailId">OrderConfirmationEmailId.</param> /// <param name="ShipmentConfirmationEmailId">ShipmentConfirmationEmailId.</param> public OrderSource(int? LobId = null, string Name = null, string PackingNotes = null, bool? RequireCartonizedASN = null, bool? RequireGS1128Label = null, string ShippingNotes = null, int? PackingSlipId = null, int? OrderConfirmationEmailId = null, int? ShipmentConfirmationEmailId = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for OrderSource and cannot be null"); } else { this.LobId = LobId; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for OrderSource and cannot be null"); } else { this.Name = Name; } this.PackingNotes = PackingNotes; // use default value if no "RequireCartonizedASN" provided if (RequireCartonizedASN == null) { this.RequireCartonizedASN = false; } else { this.RequireCartonizedASN = RequireCartonizedASN; } // use default value if no "RequireGS1128Label" provided if (RequireGS1128Label == null) { this.RequireGS1128Label = false; } else { this.RequireGS1128Label = RequireGS1128Label; } this.ShippingNotes = ShippingNotes; this.PackingSlipId = PackingSlipId; this.OrderConfirmationEmailId = OrderConfirmationEmailId; this.ShipmentConfirmationEmailId = ShipmentConfirmationEmailId; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets PackingNotes /// </summary> [DataMember(Name="packingNotes", EmitDefaultValue=false)] public string PackingNotes { get; set; } /// <summary> /// Gets or Sets RequireCartonizedASN /// </summary> [DataMember(Name="requireCartonizedASN", EmitDefaultValue=false)] public bool? RequireCartonizedASN { get; set; } /// <summary> /// Gets or Sets RequireGS1128Label /// </summary> [DataMember(Name="requireGS1128Label", EmitDefaultValue=false)] public bool? RequireGS1128Label { get; set; } /// <summary> /// Gets or Sets ShippingNotes /// </summary> [DataMember(Name="shippingNotes", EmitDefaultValue=false)] public string ShippingNotes { get; set; } /// <summary> /// Gets or Sets PackingSlipId /// </summary> [DataMember(Name="packingSlipId", EmitDefaultValue=false)] public int? PackingSlipId { get; set; } /// <summary> /// Gets or Sets OrderConfirmationEmailId /// </summary> [DataMember(Name="orderConfirmationEmailId", EmitDefaultValue=false)] public int? OrderConfirmationEmailId { get; set; } /// <summary> /// Gets or Sets ShipmentConfirmationEmailId /// </summary> [DataMember(Name="shipmentConfirmationEmailId", EmitDefaultValue=false)] public int? ShipmentConfirmationEmailId { 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 OrderSource {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" PackingNotes: ").Append(PackingNotes).Append("\n"); sb.Append(" RequireCartonizedASN: ").Append(RequireCartonizedASN).Append("\n"); sb.Append(" RequireGS1128Label: ").Append(RequireGS1128Label).Append("\n"); sb.Append(" ShippingNotes: ").Append(ShippingNotes).Append("\n"); sb.Append(" PackingSlipId: ").Append(PackingSlipId).Append("\n"); sb.Append(" OrderConfirmationEmailId: ").Append(OrderConfirmationEmailId).Append("\n"); sb.Append(" ShipmentConfirmationEmailId: ").Append(ShipmentConfirmationEmailId).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 OrderSource); } /// <summary> /// Returns true if OrderSource instances are equal /// </summary> /// <param name="other">Instance of OrderSource to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderSource other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.PackingNotes == other.PackingNotes || this.PackingNotes != null && this.PackingNotes.Equals(other.PackingNotes) ) && ( this.RequireCartonizedASN == other.RequireCartonizedASN || this.RequireCartonizedASN != null && this.RequireCartonizedASN.Equals(other.RequireCartonizedASN) ) && ( this.RequireGS1128Label == other.RequireGS1128Label || this.RequireGS1128Label != null && this.RequireGS1128Label.Equals(other.RequireGS1128Label) ) && ( this.ShippingNotes == other.ShippingNotes || this.ShippingNotes != null && this.ShippingNotes.Equals(other.ShippingNotes) ) && ( this.PackingSlipId == other.PackingSlipId || this.PackingSlipId != null && this.PackingSlipId.Equals(other.PackingSlipId) ) && ( this.OrderConfirmationEmailId == other.OrderConfirmationEmailId || this.OrderConfirmationEmailId != null && this.OrderConfirmationEmailId.Equals(other.OrderConfirmationEmailId) ) && ( this.ShipmentConfirmationEmailId == other.ShipmentConfirmationEmailId || this.ShipmentConfirmationEmailId != null && this.ShipmentConfirmationEmailId.Equals(other.ShipmentConfirmationEmailId) ); } /// <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.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.PackingNotes != null) hash = hash * 59 + this.PackingNotes.GetHashCode(); if (this.RequireCartonizedASN != null) hash = hash * 59 + this.RequireCartonizedASN.GetHashCode(); if (this.RequireGS1128Label != null) hash = hash * 59 + this.RequireGS1128Label.GetHashCode(); if (this.ShippingNotes != null) hash = hash * 59 + this.ShippingNotes.GetHashCode(); if (this.PackingSlipId != null) hash = hash * 59 + this.PackingSlipId.GetHashCode(); if (this.OrderConfirmationEmailId != null) hash = hash * 59 + this.OrderConfirmationEmailId.GetHashCode(); if (this.ShipmentConfirmationEmailId != null) hash = hash * 59 + this.ShipmentConfirmationEmailId.GetHashCode(); return hash; } } } }
using System.Linq; using System.Threading.Tasks; using AlgoRun.Server.Entities; using AlgoRun.Server.Services.Abstract; using AlgoRun.Server.ViewModels.ManageViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace AlgoRun.Server.Controllers.api { [Authorize] public class ManageController : BaseController { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { // Generate the token and send it var user = await GetCurrentUserAsync(); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsTwillioAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return Challenge(properties, provider); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
// // - PropertiesReader.cs - // // Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Carbonfrost.Commons.Shared.Runtime { class PropertiesReader : DisposableObject { public const string AnnotationKey = "#annotation"; // $NON-NLS-1 public const string CategoryKey = "#category"; // $NON-NLS-1 static readonly char[] GetCommentChars = { ';', '#', '!' }; private string key; private string value; private string category = string.Empty; private PropertyNodeKind nodeKind; private readonly StreamContext streamContext; public bool AllowUriDereferences { get; set; } private TextReader BaseReader { get; set; } public string Category { get { return category; } } public string Key { get { return key; } } public PropertyNodeKind NodeKind { get { return nodeKind; } } public string QualifiedKey { get { if (this.category.Length == 0) { return key; } else { return this.category + "." + key; // $NON-NLS-1 } } } public string Value { get { return value; } } public PropertiesReader(TextReader source) { this.streamContext = StreamContext.Null; this.BaseReader = source; } public PropertiesReader(StreamContext source, Encoding encoding = null) { this.streamContext = source; this.BaseReader = source.OpenText(encoding); } public bool Read() { string line = this.BaseReader.ReadLine(); if (line == null) { return false; } // This removes preceeding whitespace on continued lines line = line.Trim(); // Skip blank lines while (line.Length == 0) { line = this.BaseReader.ReadLine(); if (line == null) { return false; } line = line.Trim(); } // This is a category line if (line.StartsWith("[", StringComparison.Ordinal)) { // $NON-NLS-1 if (line.EndsWith("]", StringComparison.Ordinal)) { // $NON-NLS-1 EnterCategory(line); } else throw RuntimeFailure.PropertiesCategoryMissingBrackets(); } else { // Either pick this as a comment or a property if (line[0] == ';' || line[0] == '!' || line[0] == '#') { EnterComment(line); } else { StringBuilder buffer = new StringBuilder(); // Deal with line continuations \ // New to 1.3: assume that if a equals sign is missing, it is part // of the previous line while (line != null && line.EndsWith("\\", StringComparison.Ordinal)) { buffer.Append(line, 0, line.Length - 1); line = this.BaseReader.ReadLine(); if (line != null) { line = line.Trim(); } } if (line != null) { buffer.AppendLine(line); } EnterText(buffer.ToString()); } } return true; } public bool MoveToProperty() { bool readResult = false; // Skip past comments and categories do { readResult = Read(); } while (NodeKind != PropertyNodeKind.Property && readResult == true); return readResult; } public IEnumerable<KeyValuePair<string, string>> ReadToEnd() { while (MoveToProperty()) { yield return new KeyValuePair<string, string>(this.QualifiedKey, this.Value); } } private void EnterCategory(string categoryDeclaration) { this.key = PropertiesReader.CategoryKey; this.value = this.category = categoryDeclaration.Substring(1, categoryDeclaration.Length - 2); this.nodeKind = PropertyNodeKind.Category; } private void EnterComment(string commentLine) { this.nodeKind = PropertyNodeKind.Annotation; this.key = PropertiesReader.AnnotationKey; if (commentLine.Length == 1) { this.value = string.Empty; } else { this.value = commentLine.Substring(1); } } private void EnterText(string line) { int equalsIndex = line.IndexOf('='); if (equalsIndex < 0) { throw RuntimeFailure.PropertyDeclarationMissingKey(); } string newKey = null; string newValue = null; if (equalsIndex == line.Length - 1) { newKey = line.Substring(0, line.Length - 1); newValue = string.Empty; } else { newKey = line.Substring(0, equalsIndex); newValue = line.Substring(equalsIndex + 1).Trim(); } this.key = newKey; string url; if (this.AllowUriDereferences && TryUrlSyntax(newValue, out url)) { this.value = this.streamContext.ChangePath(url).ReadAllText(); } else { this.value = Utility.Unescape(newValue); } this.nodeKind = PropertyNodeKind.Property; } static readonly string URL_FUNC = "url("; private static bool TryUrlSyntax(string urlText, out string result) { int length = urlText.Length; if (length > (URL_FUNC.Length + 1)) { if (urlText.StartsWith(URL_FUNC, StringComparison.OrdinalIgnoreCase) && urlText[length - 1] == ')') { // $NON-NLS-1 string url; if ((urlText[4] == '"' && urlText[length - 2] == '"') || (urlText[4] == '\'' && urlText[length - 2] == '\'')) { url = urlText.Substring(URL_FUNC.Length + 1, urlText.Length - URL_FUNC.Length - 2); } else { // url() url = urlText.Substring(URL_FUNC.Length, urlText.Length - URL_FUNC.Length - 1); } result = null; // TODO Try URL syntax return true; } } result = null; return false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace MixedRealityToolkit.Utilities.Solvers { /// <summary> /// SurfaceMagnetism casts rays to Surfaces in the world align the object to the surface. /// </summary> public class SolverSurfaceMagnetism : Solver { #region public enums public enum RaycastDirectionEnum { CameraFacing, ToObject, ToLinkedPosition } public enum RaycastModeEnum { Simple, Box, Sphere } public enum OrientModeEnum { None, Vertical, Full, Blended } #endregion #region public members [Tooltip("LayerMask to apply Surface Magnetism to")] public LayerMask MagneticSurface = 0; [Tooltip("Max distance to check for surfaces")] public float MaxDistance = 3.0f; [Tooltip("Closest distance to bring object")] public float CloseDistance = 0.5f; [Tooltip("Offset from surface along surface normal")] public float SurfaceNormalOffset = 0.5f; [Tooltip("Offset from surface along ray cast direction")] public float SurfaceRayOffset = 0; [Tooltip("Surface raycast mode. Simple = single raycast, Complex = bbox corners")] public RaycastModeEnum raycastMode = RaycastModeEnum.Simple; [Tooltip("Number of rays per edge, should be odd. Total casts is n^2")] public int BoxRaysPerEdge = 3; [Tooltip("If true, use orthographic casting for box lines instead of perspective")] public bool OrthoBoxCast = false; [Tooltip("Align to ray cast direction if box cast hits many normals facing in varying directions")] public float MaximumNormalVariance = 0.5f; [Tooltip("Radius to use for sphere cast")] public float SphereSize = 1.0f; [Tooltip("When doing volume casts, use size override if non-zero instead of object's current scale")] public float VolumeCastSizeOverride = 0; [Tooltip("When doing volume casts, use linked AltScale instead of object's current scale")] public bool UseLinkedAltScaleOverride = false; // This is broken [Tooltip("Instead of using mesh normal, extract normal from tex coord (SR is reported to put smoothed normals in there)")] bool UseTexCoordNormals = false; [Tooltip("Raycast direction. Can cast from head in facing dir, or cast from head to object position")] public RaycastDirectionEnum raycastDirection = RaycastDirectionEnum.ToLinkedPosition; [Tooltip("Orientation mode. None = no orienting, Vertical = Face head, but always oriented up/down, Full = Aligned to surface normal completely")] public OrientModeEnum orientationMode = OrientModeEnum.Vertical; [Tooltip("Orientation Blend Value 0.0 = All head 1.0 = All surface")] public float OrientBlend = 0.65f; [HideInInspector] public bool OnSurface; #endregion #region private members private BoxCollider m_BoxCollider; private const float maxDot = 0.97f; #endregion protected override void Start() { base.Start(); if (raycastMode == RaycastModeEnum.Box) { m_BoxCollider = GetComponent<BoxCollider>(); if (m_BoxCollider == null) { Debug.LogError("Box raycast mode requires a BoxCollider, but none was found! Defaulting to Simple raycast mode"); raycastMode = RaycastModeEnum.Simple; } if (Application.isEditor) { RaycastHelper.DebugEnabled = true; } } if (Application.isEditor && UseTexCoordNormals) { Debug.LogWarning("Disabling tex coord normals while in editor mode"); UseTexCoordNormals = false; } } /// <summary> /// Wraps the raycast call in one spot. /// </summary> /// <param name="origin"></param> /// <param name="direction"></param> /// <param name="distance"></param> /// <param name="result"></param> /// <returns>bool, true if a surface was hit</returns> private static bool DefaultRaycast(Vector3 origin, Vector3 direction, float distance, LayerMask surface, out RaycastResultHelper result) { return RaycastHelper.First(origin, direction, distance, surface, out result); } private static bool DefaultSpherecast(Vector3 origin, Vector3 direction, float radius, float distance, LayerMask surface, out RaycastResultHelper result) { return RaycastHelper.SphereFirst(origin, direction, radius, distance, surface, out result); } /// <summary> /// Where should rays originate from? /// </summary> /// <returns>Vector3</returns> Vector3 GetRaycastOrigin() { if (solverHandler.TransformTarget == null) { return Vector3.zero; } return solverHandler.TransformTarget.position; } /// <summary> /// Which point should the ray cast toward? Not really the 'end' of the ray. The ray may be cast along /// the head facing direction, from the eye to the object, or to the solver's linked position (working from /// the previous solvers) /// </summary> /// <returns>Vector3, a point on the ray besides the origin</returns> Vector3 GetRaycastEndPoint() { Vector3 ret = Vector3.forward; switch (raycastDirection) { case RaycastDirectionEnum.CameraFacing: ret = solverHandler.TransformTarget.position + solverHandler.TransformTarget.forward; break; case RaycastDirectionEnum.ToObject: ret = transform.position; break; case RaycastDirectionEnum.ToLinkedPosition: ret = solverHandler.GoalPosition; break; } return ret; } /// <summary> /// Calculate the raycast direction based on the two ray points /// </summary> /// <returns>Vector3, the direction of the raycast</returns> Vector3 GetRaycastDirection() { Vector3 ret = Vector3.forward; if (raycastDirection == RaycastDirectionEnum.CameraFacing) { if (solverHandler.TransformTarget) { ret = solverHandler.TransformTarget.forward; } } else { ret = (GetRaycastEndPoint() - GetRaycastOrigin()).normalized; } return ret; } /// <summary> /// Calculates how the object should orient to the surface. May be none to pass shared orientation through, /// oriented to the surface but fully vertical, fully oriented to the surface normal, or a slerped blend /// of the vertial orientation and the pass-through rotation. /// </summary> /// <param name="rayDir"></param> /// <param name="surfaceNormal"></param> /// <returns>Quaternion, the orientation to use for the object</returns> Quaternion CalculateMagnetismOrientation(Vector3 rayDir, Vector3 surfaceNormal) { // Calculate the surface rotation Vector3 newDir = -surfaceNormal; if (IsNormalVertical(newDir)) { newDir = rayDir; } newDir.y = 0; Quaternion surfaceRot = Quaternion.LookRotation(newDir, Vector3.up); switch (orientationMode) { case OrientModeEnum.None: return solverHandler.GoalRotation; case OrientModeEnum.Vertical: return surfaceRot; case OrientModeEnum.Full: return Quaternion.LookRotation(-surfaceNormal, Vector3.up); case OrientModeEnum.Blended: return Quaternion.Slerp(solverHandler.GoalRotation, surfaceRot, OrientBlend); default: return Quaternion.identity; } } /// <summary> /// Checks if a normal is nearly vertical /// </summary> /// <param name="normal"></param> /// <returns>bool</returns> bool IsNormalVertical(Vector3 normal) { return 1f - Mathf.Abs(normal.y) < 0.01f; } /// <summary> /// A constant scale override may be specified for volumetric raycasts, oherwise uses the current value of the solver link's alt scale /// </summary> /// <returns>float</returns> float GetScaleOverride() { if (UseLinkedAltScaleOverride) { return solverHandler.AltScale.Current.magnitude; } return VolumeCastSizeOverride; } public override void SolverUpdate() { // Pass-through by default this.GoalPosition = WorkingPos; this.GoalRotation = WorkingRot; // Determine raycast params Ray ray = new Ray(GetRaycastOrigin(), GetRaycastDirection()); // Skip if there's no valid direction if (ray.direction == Vector3.zero) { return; } float ScaleOverride = GetScaleOverride(); float len; bool bHit; RaycastResultHelper result; Vector3 hitDelta; switch (raycastMode) { case RaycastModeEnum.Simple: default: // Do the cast! bHit = DefaultRaycast(ray.origin, ray.direction, MaxDistance, MagneticSurface, out result); OnSurface = bHit; if (UseTexCoordNormals) { result.OverrideNormalFromTextureCoord(); } // Enforce CloseDistance hitDelta = result.Point - ray.origin; len = hitDelta.magnitude; if (len < CloseDistance) { result.OverridePoint(ray.origin + ray.direction * CloseDistance); } // Apply results if (bHit) { GoalPosition = result.Point + SurfaceNormalOffset * result.Normal + SurfaceRayOffset * ray.direction; GoalRotation = CalculateMagnetismOrientation(ray.direction, result.Normal); } break; case RaycastModeEnum.Box: Vector3 scale = transform.lossyScale; if (ScaleOverride > 0) { scale = scale.normalized * ScaleOverride; } Quaternion orientation = orientationMode == OrientModeEnum.None ? Quaternion.LookRotation(ray.direction, Vector3.up) : CalculateMagnetismOrientation(ray.direction, Vector3.up); Matrix4x4 targetMatrix = Matrix4x4.TRS(Vector3.zero, orientation, scale); if (m_BoxCollider == null) { m_BoxCollider = this.GetComponent<BoxCollider>(); } Vector3 extents = m_BoxCollider.size; Vector3[] positions; Vector3[] normals; bool[] hits; if (RaycastHelper.CastBoxExtents(extents, transform.position, targetMatrix, ray, MaxDistance, MagneticSurface, DefaultRaycast, BoxRaysPerEdge, OrthoBoxCast, out positions, out normals, out hits)) { Plane plane; float distance; // place an unconstrained plane down the ray. Never use vertical constrain. FindPlacementPlane(ray.origin, ray.direction, positions, normals, hits, m_BoxCollider.size.x, MaximumNormalVariance, false, orientationMode == OrientModeEnum.None, out plane, out distance); // If placing on a horzizontal surface, need to adjust the calculated distance by half the app height float verticalCorrectionOffset = 0; if (IsNormalVertical(plane.normal) && !Mathf.Approximately(ray.direction.y, 0)) { float boxSurfaceOffsetVert = targetMatrix.MultiplyVector(new Vector3(0, extents.y / 2f, 0)).magnitude; Vector3 correctionVec = boxSurfaceOffsetVert * (ray.direction / ray.direction.y); verticalCorrectionOffset = -correctionVec.magnitude; } float boxSurfaceOffset = targetMatrix.MultiplyVector(new Vector3(0, 0, extents.z / 2f)).magnitude; // Apply boxSurfaceOffset to rayDir and not surfaceNormalDir to reduce sliding GoalPosition = ray.origin + ray.direction * Mathf.Max(CloseDistance, distance + SurfaceRayOffset + boxSurfaceOffset + verticalCorrectionOffset) + plane.normal * (0 * boxSurfaceOffset + SurfaceNormalOffset); GoalRotation = CalculateMagnetismOrientation(ray.direction, plane.normal); OnSurface = true; } else { OnSurface = false; } break; case RaycastModeEnum.Sphere: // Do the cast! float size = ScaleOverride > 0 ? ScaleOverride : transform.lossyScale.x * SphereSize; bHit = DefaultSpherecast(ray.origin, ray.direction, size, MaxDistance, MagneticSurface, out result); OnSurface = bHit; // Enforce CloseDistance hitDelta = result.Point - ray.origin; len = hitDelta.magnitude; if (len < CloseDistance) { result.OverridePoint(ray.origin + ray.direction * CloseDistance); } // Apply results if (bHit) { GoalPosition = result.Point + SurfaceNormalOffset * result.Normal + SurfaceRayOffset * ray.direction; GoalRotation = CalculateMagnetismOrientation(ray.direction, result.Normal); } break; } // Do frame to frame updates of transform, smoothly toward the goal, if desired UpdateWorkingPosToGoal(); UpdateWorkingRotToGoal(); } /// <summary> /// Calculates a plane from all raycast hit locations upon which the object may align /// </summary> /// <param name="origin"></param> /// <param name="direction"></param> /// <param name="positions"></param> /// <param name="normals"></param> /// <param name="hits"></param> /// <param name="assetWidth"></param> /// <param name="maxNormalVariance"></param> /// <param name="constrainVertical"></param> /// <param name="bUseClosestDistance"></param> /// <param name="plane"></param> /// <param name="closestDistance"></param> private static void FindPlacementPlane(Vector3 origin, Vector3 direction, Vector3[] positions, Vector3[] normals, bool[] hits, float assetWidth, float maxNormalVariance, bool constrainVertical, bool bUseClosestDistance, out Plane plane, out float closestDistance) { bool debugEnabled = RaycastHelper.DebugEnabled; int numRays = positions.Length; Vector3 originalDirection = direction; if (constrainVertical) { direction.y = 0.0f; direction = direction.normalized; } // go through all the points and find the closest distance int closestPoint = -1; closestDistance = float.PositiveInfinity; float farthestDistance = 0f; int numHits = 0; Vector3 averageNormal = Vector3.zero; for (int i = 0; i < numRays; i++) { if (hits[i] != false) { float dist = Vector3.Dot(direction, positions[i] - origin); if (dist < closestDistance) { closestPoint = i; closestDistance = dist; } if (dist > farthestDistance) { farthestDistance = dist; } averageNormal += normals[i]; ++numHits; } } averageNormal /= numHits; // Calculate variance of all normals float variance = 0; for (int i = 0; i < numRays; ++i) { if (hits[i] != false) { variance += (normals[i] - averageNormal).magnitude; } } variance /= numHits; // If variance is too high, I really don't want to deal with this surface // And if we don't even have enough rays, I'm not confident about this at all if (variance > maxNormalVariance || numHits < numRays / 4) { plane = new Plane(-direction, positions[closestPoint]); return; } // go through all the points and find the most orthagonal plane float lowAngle = float.PositiveInfinity; int lowIndex = -1; float highAngle = float.NegativeInfinity; int highIndex = -1; for (int i = 0; i < numRays; i++) { if (hits[i] == false || i == closestPoint) { continue; } Vector3 diff = (positions[i] - positions[closestPoint]); if (constrainVertical) { diff.y = 0.0f; diff.Normalize(); if (diff == Vector3.zero) { continue; } } else { diff.Normalize(); } float angle = Vector3.Dot(direction, diff); if (angle < lowAngle) { lowAngle = angle; lowIndex = i; } } if (!constrainVertical && lowIndex != -1) { for (int i = 0; i < numRays; i++) { if (hits[i] == false || i == closestPoint || i == lowIndex) { continue; } float dot = Mathf.Abs(Vector3.Dot((positions[i] - positions[closestPoint]).normalized, (positions[lowIndex] - positions[closestPoint]).normalized)); if (dot > maxDot) { continue; } Vector3 normal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], positions[i] - positions[closestPoint]).normalized; float nextAngle = Mathf.Abs(Vector3.Dot(direction, normal)); if (nextAngle > highAngle) { highAngle = nextAngle; highIndex = i; } } } Vector3 placementNormal; if (lowIndex != -1) { if (debugEnabled) { Debug.DrawLine(positions[closestPoint], positions[lowIndex], Color.red); } if (highIndex != -1) { if (debugEnabled) { Debug.DrawLine(positions[closestPoint], positions[highIndex], Color.green); } placementNormal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], positions[highIndex] - positions[closestPoint]).normalized; } else { Vector3 planeUp = Vector3.Cross(positions[lowIndex] - positions[closestPoint], direction); placementNormal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], constrainVertical ? Vector3.up : planeUp).normalized; } if (debugEnabled) { Debug.DrawLine(positions[closestPoint], positions[closestPoint] + placementNormal, Color.blue); } } else { placementNormal = direction * -1.0f; } if (Vector3.Dot(placementNormal, direction) > 0.0f) { placementNormal *= -1.0f; } plane = new Plane(placementNormal, positions[closestPoint]); if (debugEnabled) { Debug.DrawRay(positions[closestPoint], placementNormal, Color.cyan); } // Figure out how far the plane should be. if (!bUseClosestDistance && closestPoint >= 0) { float centerPlaneDistance; Ray centerPlaneRay = new Ray(origin, originalDirection); if (plane.Raycast(centerPlaneRay, out centerPlaneDistance) || centerPlaneDistance != 0) { // When the plane is nearly parallel to the user, we need to clamp the distance to where the raycasts hit. closestDistance = Mathf.Clamp(centerPlaneDistance, closestDistance, farthestDistance + assetWidth * 0.5f); } else { Debug.LogError("FindPlacementPlane: Not expected to have the center point not intersect the plane."); } } } } }
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate001.dlgate001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate001.dlgate001; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression; // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E += new Dele(C.Foo); if (c.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate002.dlgate002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate002.dlgate002; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression; (no event accessor declaration) // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E += new Dele(C.Foo); if (c.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic001.dynamic001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic001.dynamic001; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic002.dynamic002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic002.dynamic002; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic003.dynamic003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic003.dynamic003; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic004.dynamic004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic004.dynamic004; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty001.fieldproperty001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty001.fieldproperty001; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public event Dele E; public C() { field = C.Foo; } public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); //c.E += C.Foo; C c = new C(); d.E += c.field; if (d.DoEvent(9) != 9) return 1; d.E -= c.field; d.E += c.Field; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty002.fieldproperty002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty002.fieldproperty002; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public Dele E; public C() { field = C.Foo; } public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); //c.E += C.Foo; C c = new C(); d.E += c.field; if (d.DoEvent(9) != 9) return 1; d.E -= c.field; d.E += c.Field; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null001.null001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null001.null001; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // Negative: rhs is null literal : lhs is not null // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E += (Dele)C.Foo; c.E += null; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null002.null002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null002.null002; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // Negative: rhs is null literal : lhs is null // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); int result = 0; try { c.E += null; result += 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.AmbigBinaryOps, e.Message, "+=", "<null>", "<null>")) return 1; } return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return001.return001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return001.return001; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public static Dele Bar() { return C.Foo; } public event Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += C.Bar(); if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return002.return002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return002.return002; // <Area> Dynamic -- compound operator</Area> // <Title> compound operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public static Dele Bar() { return C.Foo; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += C.Bar(); if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> }