context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Support; using IndexReader = Lucene.Net.Index.IndexReader; using MultipleTermPositions = Lucene.Net.Index.MultipleTermPositions; using Term = Lucene.Net.Index.Term; using TermPositions = Lucene.Net.Index.TermPositions; using ToStringUtils = Lucene.Net.Util.ToStringUtils; namespace Lucene.Net.Search { /// <summary> MultiPhraseQuery is a generalized version of PhraseQuery, with an added /// method <see cref="Add(Term[])" />. /// To use this class, to search for the phrase "Microsoft app*" first use /// add(Term) on the term "Microsoft", then find all terms that have "app" as /// prefix using IndexReader.terms(Term), and use MultiPhraseQuery.add(Term[] /// terms) to add them to the query. /// /// </summary> /// <version> 1.0 /// </version> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class MultiPhraseQuery:Query { private System.String field; private System.Collections.Generic.List<Term[]> termArrays = new System.Collections.Generic.List<Term[]>(); private System.Collections.Generic.List<int> positions = new System.Collections.Generic.List<int>(); private int slop = 0; /// <summary>Gets or sets the phrase slop for this query.</summary> /// <seealso cref="PhraseQuery.Slop"> /// </seealso> public virtual int Slop { get { return slop; } set { slop = value; } } /// <summary>Add a single term at the next position in the phrase.</summary> /// <seealso cref="PhraseQuery.Add(Term)"> /// </seealso> public virtual void Add(Term term) { Add(new Term[]{term}); } /// <summary>Add multiple terms at the next position in the phrase. Any of the terms /// may match. /// /// </summary> /// <seealso cref="PhraseQuery.Add(Term)"> /// </seealso> public virtual void Add(Term[] terms) { int position = 0; if (positions.Count > 0) position = positions[positions.Count - 1] + 1; Add(terms, position); } /// <summary> Allows to specify the relative position of terms within the phrase. /// /// </summary> /// <seealso cref="PhraseQuery.Add(Term, int)"> /// </seealso> /// <param name="terms"> /// </param> /// <param name="position"> /// </param> public virtual void Add(Term[] terms, int position) { if (termArrays.Count == 0) field = terms[0].Field; for (int i = 0; i < terms.Length; i++) { if ((System.Object) terms[i].Field != (System.Object) field) { throw new System.ArgumentException("All phrase terms must be in the same field (" + field + "): " + terms[i]); } } termArrays.Add(terms); positions.Add(position); } /// <summary> Returns a List&lt;Term[]&gt; of the terms in the multiphrase. /// Do not modify the List or its contents. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual System.Collections.Generic.IList<Term[]> GetTermArrays() { return termArrays.AsReadOnly(); } /// <summary> Returns the relative positions of terms in this phrase.</summary> public virtual int[] GetPositions() { int[] result = new int[positions.Count]; for (int i = 0; i < positions.Count; i++) result[i] = positions[i]; return result; } // inherit javadoc public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms) { foreach(Term[] arr in termArrays) { terms.UnionWith(arr); } } //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 private class MultiPhraseWeight:Weight { private void InitBlock(MultiPhraseQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private MultiPhraseQuery enclosingInstance; public MultiPhraseQuery Enclosing_Instance { get { return enclosingInstance; } } private Similarity similarity; private float value_Renamed; private float idf; private float queryNorm; private float queryWeight; public MultiPhraseWeight(MultiPhraseQuery enclosingInstance, Searcher searcher) { InitBlock(enclosingInstance); this.similarity = Enclosing_Instance.GetSimilarity(searcher); // compute idf int maxDoc = searcher.MaxDoc; foreach (Term[] terms in enclosingInstance.termArrays) { foreach (Term term in terms) { idf += similarity.Idf(searcher.DocFreq(term), maxDoc); } } } public override Query Query { get { return Enclosing_Instance; } } public override float Value { get { return value_Renamed; } } public override float GetSumOfSquaredWeights() { queryWeight = idf*Enclosing_Instance.Boost; // compute query weight return queryWeight*queryWeight; // square it } public override void Normalize(float queryNorm) { this.queryNorm = queryNorm; queryWeight *= queryNorm; // normalize query weight value_Renamed = queryWeight * idf; // idf for document } public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer) { if (Enclosing_Instance.termArrays.Count == 0) // optimize zero-term case return null; TermPositions[] tps = new TermPositions[Enclosing_Instance.termArrays.Count]; for (int i = 0; i < tps.Length; i++) { Term[] terms = Enclosing_Instance.termArrays[i]; TermPositions p; if (terms.Length > 1) p = new MultipleTermPositions(reader, terms); else p = reader.TermPositions(terms[0]); if (p == null) return null; tps[i] = p; } if (Enclosing_Instance.slop == 0) return new ExactPhraseScorer(this, tps, Enclosing_Instance.GetPositions(), similarity, reader.Norms(Enclosing_Instance.field)); else return new SloppyPhraseScorer(this, tps, Enclosing_Instance.GetPositions(), similarity, Enclosing_Instance.slop, reader.Norms(Enclosing_Instance.field)); } public override Explanation Explain(IndexReader reader, int doc) { ComplexExplanation result = new ComplexExplanation(); result.Description = "weight(" + Query + " in " + doc + "), product of:"; Explanation idfExpl = new Explanation(idf, "idf(" + Query + ")"); // explain query weight Explanation queryExpl = new Explanation(); queryExpl.Description = "queryWeight(" + Query + "), product of:"; Explanation boostExpl = new Explanation(Enclosing_Instance.Boost, "boost"); if (Enclosing_Instance.Boost != 1.0f) queryExpl.AddDetail(boostExpl); queryExpl.AddDetail(idfExpl); Explanation queryNormExpl = new Explanation(queryNorm, "queryNorm"); queryExpl.AddDetail(queryNormExpl); queryExpl.Value = boostExpl.Value * idfExpl.Value * queryNormExpl.Value; result.AddDetail(queryExpl); // explain field weight ComplexExplanation fieldExpl = new ComplexExplanation(); fieldExpl.Description = "fieldWeight(" + Query + " in " + doc + "), product of:"; PhraseScorer scorer = (PhraseScorer)Scorer(reader, true, false); if (scorer == null) { return new Explanation(0.0f, "no matching docs"); } Explanation tfExplanation = new Explanation(); int d = scorer.Advance(doc); float phraseFreq = (d == doc) ? scorer.CurrentFreq() : 0.0f; tfExplanation.Value = similarity.Tf(phraseFreq); tfExplanation.Description = "tf(phraseFreq=" + phraseFreq + ")"; fieldExpl.AddDetail(tfExplanation); fieldExpl.AddDetail(idfExpl); Explanation fieldNormExpl = new Explanation(); byte[] fieldNorms = reader.Norms(Enclosing_Instance.field); float fieldNorm = fieldNorms != null?Similarity.DecodeNorm(fieldNorms[doc]):1.0f; fieldNormExpl.Value = fieldNorm; fieldNormExpl.Description = "fieldNorm(field=" + Enclosing_Instance.field + ", doc=" + doc + ")"; fieldExpl.AddDetail(fieldNormExpl); fieldExpl.Match = tfExplanation.IsMatch; fieldExpl.Value = tfExplanation.Value * idfExpl.Value * fieldNormExpl.Value; result.AddDetail(fieldExpl); System.Boolean? tempAux = fieldExpl.Match; result.Match = tempAux; // combine them result.Value = queryExpl.Value * fieldExpl.Value; if (queryExpl.Value == 1.0f) return fieldExpl; return result; } } public override Query Rewrite(IndexReader reader) { if (termArrays.Count == 1) { // optimize one-term case Term[] terms = termArrays[0]; BooleanQuery boq = new BooleanQuery(true); for (int i = 0; i < terms.Length; i++) { boq.Add(new TermQuery(terms[i]), Occur.SHOULD); } boq.Boost = Boost; return boq; } else { return this; } } public override Weight CreateWeight(Searcher searcher) { return new MultiPhraseWeight(this, searcher); } /// <summary>Prints a user-readable version of this query. </summary> public override System.String ToString(System.String f) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); if (!field.Equals(f)) { buffer.Append(field); buffer.Append(":"); } buffer.Append("\""); System.Collections.Generic.IEnumerator<Term[]> i = termArrays.GetEnumerator(); bool first = true; while (i.MoveNext()) { if (first) { first = false; } else { buffer.Append(" "); } Term[] terms = i.Current; if (terms.Length > 1) { buffer.Append("("); for (int j = 0; j < terms.Length; j++) { buffer.Append(terms[j].Text); if (j < terms.Length - 1) buffer.Append(" "); } buffer.Append(")"); } else { buffer.Append(terms[0].Text); } } buffer.Append("\""); if (slop != 0) { buffer.Append("~"); buffer.Append(slop); } buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary>Returns true if <c>o</c> is equal to this. </summary> public override bool Equals(System.Object o) { if (!(o is MultiPhraseQuery)) return false; MultiPhraseQuery other = (MultiPhraseQuery) o; bool eq = this.Boost == other.Boost && this.slop == other.slop; if(!eq) { return false; } eq = this.termArrays.Count.Equals(other.termArrays.Count); if (!eq) { return false; } for (int i = 0; i < this.termArrays.Count; i++) { if (!Compare.CompareTermArrays((Term[])this.termArrays[i], (Term[])other.termArrays[i])) { return false; } } if(!eq) { return false; } eq = this.positions.Count.Equals(other.positions.Count); if (!eq) { return false; } for (int i = 0; i < this.positions.Count; i++) { if (!((int)this.positions[i] == (int)other.positions[i])) { return false; } } return true; } /// <summary>Returns a hash code value for this object.</summary> public override int GetHashCode() { int posHash = 0; foreach(int pos in positions) { posHash += pos.GetHashCode(); } return BitConverter.ToInt32(BitConverter.GetBytes(Boost), 0) ^ slop ^ TermArraysHashCode() ^ posHash ^ 0x4AC65113; } // Breakout calculation of the termArrays hashcode private int TermArraysHashCode() { int hashCode = 1; foreach(Term[] termArray in termArrays) { // Java uses Arrays.hashCode(termArray) hashCode = 31*hashCode + (termArray == null ? 0 : ArraysHashCode(termArray)); } return hashCode; } private int ArraysHashCode(Term[] termArray) { if (termArray == null) return 0; int result = 1; for (int i = 0; i < termArray.Length; i++) { Term term = termArray[i]; result = 31 * result + (term == null?0:term.GetHashCode()); } return result; } // Breakout calculation of the termArrays equals private bool TermArraysEquals(System.Collections.Generic.List<Term[]> termArrays1, System.Collections.Generic.List<Term[]> termArrays2) { if (termArrays1.Count != termArrays2.Count) { return false; } var iterator1 = termArrays1.GetEnumerator(); var iterator2 = termArrays2.GetEnumerator(); while (iterator1.MoveNext()) { Term[] termArray1 = iterator1.Current; Term[] termArray2 = iterator2.Current; if (!(termArray1 == null ? termArray2 == null : TermEquals(termArray1, termArray2))) { return false; } } return true; } public static bool TermEquals(System.Array array1, System.Array array2) { bool result = false; if ((array1 == null) && (array2 == null)) result = true; else if ((array1 != null) && (array2 != null)) { if (array1.Length == array2.Length) { int length = array1.Length; result = true; for (int index = 0; index < length; index++) { if (!(array1.GetValue(index).Equals(array2.GetValue(index)))) { result = false; break; } } } } 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.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest() { _log = TestLogging.GetInstance(); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. // We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up. Assert.InRange(nic.Speed, -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_AccessInstanceProperties_NoExceptions_Osx() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv4", "true")] [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); return; // Only check IPv4 loopback } } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv4", "true")] [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv6", "true")] [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv6", "true")] [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX [ActiveIssue("https://github.com/dotnet/corefx/issues/20014", TargetFrameworkMonikers.Uap)] public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_GetIPInterfaceStatistics_Success_OSX() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [PlatformSpecific(~TestPlatforms.OSX)] [InlineData(false)] [InlineData(true)] [ActiveIssue(19314, TargetFrameworkMonikers.UapAot)] [ActiveIssue(20014, TargetFrameworkMonikers.Uap)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: folio/rpc/reservation_folio_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Folio.RPC { public static partial class ReservationFolioSvc { static readonly string __ServiceName = "holms.types.folio.rpc.ReservationFolioSvc"; static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> __Marshaller_ReservationIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.ReservationIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse> __Marshaller_ReservationFolioSvcGetFolioStateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> __Marshaller_FolioSvcGetOnFileCardsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest> __Marshaller_ReservationFolioSvcGetSummariesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse> __Marshaller_ReservationFolioSvcGetSummariesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest> __Marshaller_ReservationFolioSvcCardAuthorizationFromStoredCardRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Marshaller_CardAuthorizationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest> __Marshaller_CardAuthorizationFromPresentCardRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest> __Marshaller_CardAuthorizationFromNotPresentCardRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest> __Marshaller_FolioSvcAuthorizationModificationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> __Marshaller_FolioSvcAuthorizationModificationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest> __Marshaller_ReservationFolioSvcPostCardPaymentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> __Marshaller_FolioSvcPostCardPaymentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest> __Marshaller_ReservationFolioSvcPostCheckPaymentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> __Marshaller_FolioSvcPostCheckPaymentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest> __Marshaller_ReservationFolioSvcPostCashPaymentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> __Marshaller_FolioSvcPostCashResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator> __Marshaller_FolioCheckCashPaymentIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator> __Marshaller_PaymentCardSaleIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Marshaller_FolioSvcCancelPaymentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest> __Marshaller_ReservationFolioSvcPaymentCardRefundRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> __Marshaller_FolioSvcRefundResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest> __Marshaller_ReservationFolioSvcPostCashRefundRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest> __Marshaller_ReservationFolioSvcPostLodgingChargeCorrectionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest> __Marshaller_ReservationFolioSvcPostIncidentalChargeCorrectionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest> __Marshaller_ReservationFolioSvcPostMiscChargeCorrectionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator> __Marshaller_PaymentCardRefundIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator> __Marshaller_CustomerPaymentCardIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest> __Marshaller_ReservationFolioSvcTransferOpenAuthorizationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse> __Marshaller_ReservationFolioSvcTransferOpenAuthorizationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse.Parser.ParseFrom); static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse> __Method_GetReservationFolioState = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse>( grpc::MethodType.Unary, __ServiceName, "GetReservationFolioState", __Marshaller_ReservationIndicator, __Marshaller_ReservationFolioSvcGetFolioStateResponse); static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> __Method_GetOnFileCards = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse>( grpc::MethodType.Unary, __ServiceName, "GetOnFileCards", __Marshaller_ReservationIndicator, __Marshaller_FolioSvcGetOnFileCardsResponse); static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> __Method_GetOnFileCardsForGSA = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse>( grpc::MethodType.Unary, __ServiceName, "GetOnFileCardsForGSA", __Marshaller_ReservationIndicator, __Marshaller_FolioSvcGetOnFileCardsResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest, global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse> __Method_GetFolioSummaries = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest, global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse>( grpc::MethodType.Unary, __ServiceName, "GetFolioSummaries", __Marshaller_ReservationFolioSvcGetSummariesRequest, __Marshaller_ReservationFolioSvcGetSummariesResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Method_AddCardAuthorizationFromStoredCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse>( grpc::MethodType.Unary, __ServiceName, "AddCardAuthorizationFromStoredCard", __Marshaller_ReservationFolioSvcCardAuthorizationFromStoredCardRequest, __Marshaller_CardAuthorizationResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Method_AddCardAuthorizationFromPresentedCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse>( grpc::MethodType.Unary, __ServiceName, "AddCardAuthorizationFromPresentedCard", __Marshaller_CardAuthorizationFromPresentCardRequest, __Marshaller_CardAuthorizationResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> __Method_AddCardAuthorizationFromNotPresentCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest, global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse>( grpc::MethodType.Unary, __ServiceName, "AddCardAuthorizationFromNotPresentCard", __Marshaller_CardAuthorizationFromNotPresentCardRequest, __Marshaller_CardAuthorizationResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest, global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> __Method_ChangeAuthorizationAmount = new grpc::Method<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest, global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse>( grpc::MethodType.Unary, __ServiceName, "ChangeAuthorizationAmount", __Marshaller_FolioSvcAuthorizationModificationRequest, __Marshaller_FolioSvcAuthorizationModificationResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> __Method_PostCardPayment = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse>( grpc::MethodType.Unary, __ServiceName, "PostCardPayment", __Marshaller_ReservationFolioSvcPostCardPaymentRequest, __Marshaller_FolioSvcPostCardPaymentResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> __Method_PostCheckPayment = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse>( grpc::MethodType.Unary, __ServiceName, "PostCheckPayment", __Marshaller_ReservationFolioSvcPostCheckPaymentRequest, __Marshaller_FolioSvcPostCheckPaymentResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> __Method_PostCashPayment = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse>( grpc::MethodType.Unary, __ServiceName, "PostCashPayment", __Marshaller_ReservationFolioSvcPostCashPaymentRequest, __Marshaller_FolioSvcPostCashResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CancelCashCheckPayment = new grpc::Method<global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "CancelCashCheckPayment", __Marshaller_FolioCheckCashPaymentIndicator, __Marshaller_Empty); static readonly grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Method_CancelCardPayment = new grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse>( grpc::MethodType.Unary, __ServiceName, "CancelCardPayment", __Marshaller_PaymentCardSaleIndicator, __Marshaller_FolioSvcCancelPaymentResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> __Method_RefundTokenizedCard = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse>( grpc::MethodType.Unary, __ServiceName, "RefundTokenizedCard", __Marshaller_ReservationFolioSvcPaymentCardRefundRequest, __Marshaller_FolioSvcRefundResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> __Method_PostCashRefund = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest, global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse>( grpc::MethodType.Unary, __ServiceName, "PostCashRefund", __Marshaller_ReservationFolioSvcPostCashRefundRequest, __Marshaller_FolioSvcPostCashResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PostLodgingChargeCorrection = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "PostLodgingChargeCorrection", __Marshaller_ReservationFolioSvcPostLodgingChargeCorrectionRequest, __Marshaller_Empty); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PostIncidentalChargeCorrection = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "PostIncidentalChargeCorrection", __Marshaller_ReservationFolioSvcPostIncidentalChargeCorrectionRequest, __Marshaller_Empty); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PostMiscChargeCorrection = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "PostMiscChargeCorrection", __Marshaller_ReservationFolioSvcPostMiscChargeCorrectionRequest, __Marshaller_Empty); static readonly grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Method_CancelCardRefund = new grpc::Method<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse>( grpc::MethodType.Unary, __ServiceName, "CancelCardRefund", __Marshaller_PaymentCardRefundIndicator, __Marshaller_FolioSvcCancelPaymentResponse); static readonly grpc::Method<global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> __Method_SoftDeleteCard = new grpc::Method<global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator, global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse>( grpc::MethodType.Unary, __ServiceName, "SoftDeleteCard", __Marshaller_CustomerPaymentCardIndicator, __Marshaller_FolioSvcCancelPaymentResponse); static readonly grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest, global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse> __Method_TransferOpenAuthorizations = new grpc::Method<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest, global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse>( grpc::MethodType.Unary, __ServiceName, "TransferOpenAuthorizations", __Marshaller_ReservationFolioSvcTransferOpenAuthorizationRequest, __Marshaller_ReservationFolioSvcTransferOpenAuthorizationResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Folio.RPC.ReservationFolioSvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of ReservationFolioSvc</summary> public abstract partial class ReservationFolioSvcBase { /// <summary> /// Get info /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse> GetReservationFolioState(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCards(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsForGSA(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse> GetFolioSummaries(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Card authorization /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromStoredCard(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromPresentedCard(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromNotPresentCard(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> ChangeAuthorizationAmount(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Payment application/cancellation/refund /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> PostCardPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> PostCheckPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CancelCashCheckPayment(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardPayment(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> RefundTokenizedCard(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashRefund(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Charge correction /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PostLodgingChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PostIncidentalChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PostMiscChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> ///Card Refund Cancelation /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> SoftDeleteCard(global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse> TransferOpenAuthorizations(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for ReservationFolioSvc</summary> public partial class ReservationFolioSvcClient : grpc::ClientBase<ReservationFolioSvcClient> { /// <summary>Creates a new client for ReservationFolioSvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ReservationFolioSvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for ReservationFolioSvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ReservationFolioSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ReservationFolioSvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ReservationFolioSvcClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Get info /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse GetReservationFolioState(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetReservationFolioState(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get info /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse GetReservationFolioState(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetReservationFolioState, null, options, request); } /// <summary> /// Get info /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse> GetReservationFolioStateAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetReservationFolioStateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get info /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetFolioStateResponse> GetReservationFolioStateAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetReservationFolioState, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse GetOnFileCards(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOnFileCards(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse GetOnFileCards(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetOnFileCards, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOnFileCardsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetOnFileCards, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse GetOnFileCardsForGSA(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOnFileCardsForGSA(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse GetOnFileCardsForGSA(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetOnFileCardsForGSA, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsForGSAAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOnFileCardsForGSAAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcGetOnFileCardsResponse> GetOnFileCardsForGSAAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetOnFileCardsForGSA, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse GetFolioSummaries(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetFolioSummaries(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse GetFolioSummaries(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetFolioSummaries, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse> GetFolioSummariesAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetFolioSummariesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesResponse> GetFolioSummariesAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcGetSummariesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetFolioSummaries, null, options, request); } /// <summary> /// Card authorization /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromStoredCard(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AddCardAuthorizationFromStoredCard(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Card authorization /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromStoredCard(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AddCardAuthorizationFromStoredCard, null, options, request); } /// <summary> /// Card authorization /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromStoredCardAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AddCardAuthorizationFromStoredCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Card authorization /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromStoredCardAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcCardAuthorizationFromStoredCardRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AddCardAuthorizationFromStoredCard, null, options, request); } public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromPresentedCard(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AddCardAuthorizationFromPresentedCard(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromPresentedCard(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AddCardAuthorizationFromPresentedCard, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromPresentedCardAsync(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AddCardAuthorizationFromPresentedCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromPresentedCardAsync(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromPresentCardRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AddCardAuthorizationFromPresentedCard, null, options, request); } public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromNotPresentCard(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AddCardAuthorizationFromNotPresentCard(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse AddCardAuthorizationFromNotPresentCard(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AddCardAuthorizationFromNotPresentCard, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromNotPresentCardAsync(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AddCardAuthorizationFromNotPresentCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse> AddCardAuthorizationFromNotPresentCardAsync(global::HOLMS.Types.Folio.RPC.CardAuthorizationFromNotPresentCardRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AddCardAuthorizationFromNotPresentCard, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse ChangeAuthorizationAmount(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ChangeAuthorizationAmount(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse ChangeAuthorizationAmount(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ChangeAuthorizationAmount, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> ChangeAuthorizationAmountAsync(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ChangeAuthorizationAmountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationResponse> ChangeAuthorizationAmountAsync(global::HOLMS.Types.Folio.RPC.FolioSvcAuthorizationModificationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ChangeAuthorizationAmount, null, options, request); } /// <summary> /// Payment application/cancellation/refund /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse PostCardPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCardPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Payment application/cancellation/refund /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse PostCardPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostCardPayment, null, options, request); } /// <summary> /// Payment application/cancellation/refund /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> PostCardPaymentAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCardPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Payment application/cancellation/refund /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCardPaymentResponse> PostCardPaymentAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCardPaymentRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostCardPayment, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse PostCheckPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCheckPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse PostCheckPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostCheckPayment, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> PostCheckPaymentAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCheckPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCheckPaymentResponse> PostCheckPaymentAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCheckPaymentRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostCheckPayment, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCashPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashPayment(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostCashPayment, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashPaymentAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCashPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashPaymentAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashPaymentRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostCashPayment, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelCashCheckPayment(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelCashCheckPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelCashCheckPayment(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CancelCashCheckPayment, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelCashCheckPaymentAsync(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelCashCheckPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelCashCheckPaymentAsync(global::HOLMS.Types.Folio.FolioCheckCashPaymentIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CancelCashCheckPayment, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardPayment(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelCardPayment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardPayment(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CancelCardPayment, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardPaymentAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelCardPaymentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardPaymentAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CancelCardPayment, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse RefundTokenizedCard(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RefundTokenizedCard(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse RefundTokenizedCard(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_RefundTokenizedCard, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> RefundTokenizedCardAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RefundTokenizedCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcRefundResponse> RefundTokenizedCardAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPaymentCardRefundRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_RefundTokenizedCard, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashRefund(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCashRefund(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse PostCashRefund(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostCashRefund, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashRefundAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostCashRefundAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcPostCashResponse> PostCashRefundAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostCashRefundRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostCashRefund, null, options, request); } /// <summary> /// Charge correction /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty PostLodgingChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostLodgingChargeCorrection(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Charge correction /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty PostLodgingChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostLodgingChargeCorrection, null, options, request); } /// <summary> /// Charge correction /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostLodgingChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostLodgingChargeCorrectionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Charge correction /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostLodgingChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostLodgingChargeCorrectionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostLodgingChargeCorrection, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty PostIncidentalChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostIncidentalChargeCorrection(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty PostIncidentalChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostIncidentalChargeCorrection, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostIncidentalChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostIncidentalChargeCorrectionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostIncidentalChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostIncidentalChargeCorrectionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostIncidentalChargeCorrection, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty PostMiscChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostMiscChargeCorrection(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty PostMiscChargeCorrection(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PostMiscChargeCorrection, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostMiscChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PostMiscChargeCorrectionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PostMiscChargeCorrectionAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcPostMiscChargeCorrectionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PostMiscChargeCorrection, null, options, request); } /// <summary> ///Card Refund Cancelation /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelCardRefund(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> ///Card Refund Cancelation /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse CancelCardRefund(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CancelCardRefund, null, options, request); } /// <summary> ///Card Refund Cancelation /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardRefundAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelCardRefundAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> ///Card Refund Cancelation /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> CancelCardRefundAsync(global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CancelCardRefund, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse SoftDeleteCard(global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SoftDeleteCard(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse SoftDeleteCard(global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SoftDeleteCard, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> SoftDeleteCardAsync(global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SoftDeleteCardAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.FolioSvcCancelPaymentResponse> SoftDeleteCardAsync(global::HOLMS.Types.Money.Cards.CustomerPaymentCardIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SoftDeleteCard, null, options, request); } public virtual global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse TransferOpenAuthorizations(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return TransferOpenAuthorizations(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse TransferOpenAuthorizations(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_TransferOpenAuthorizations, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse> TransferOpenAuthorizationsAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return TransferOpenAuthorizationsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationResponse> TransferOpenAuthorizationsAsync(global::HOLMS.Types.Folio.RPC.ReservationFolioSvcTransferOpenAuthorizationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_TransferOpenAuthorizations, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override ReservationFolioSvcClient NewInstance(ClientBaseConfiguration configuration) { return new ReservationFolioSvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(ReservationFolioSvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_GetReservationFolioState, serviceImpl.GetReservationFolioState) .AddMethod(__Method_GetOnFileCards, serviceImpl.GetOnFileCards) .AddMethod(__Method_GetOnFileCardsForGSA, serviceImpl.GetOnFileCardsForGSA) .AddMethod(__Method_GetFolioSummaries, serviceImpl.GetFolioSummaries) .AddMethod(__Method_AddCardAuthorizationFromStoredCard, serviceImpl.AddCardAuthorizationFromStoredCard) .AddMethod(__Method_AddCardAuthorizationFromPresentedCard, serviceImpl.AddCardAuthorizationFromPresentedCard) .AddMethod(__Method_AddCardAuthorizationFromNotPresentCard, serviceImpl.AddCardAuthorizationFromNotPresentCard) .AddMethod(__Method_ChangeAuthorizationAmount, serviceImpl.ChangeAuthorizationAmount) .AddMethod(__Method_PostCardPayment, serviceImpl.PostCardPayment) .AddMethod(__Method_PostCheckPayment, serviceImpl.PostCheckPayment) .AddMethod(__Method_PostCashPayment, serviceImpl.PostCashPayment) .AddMethod(__Method_CancelCashCheckPayment, serviceImpl.CancelCashCheckPayment) .AddMethod(__Method_CancelCardPayment, serviceImpl.CancelCardPayment) .AddMethod(__Method_RefundTokenizedCard, serviceImpl.RefundTokenizedCard) .AddMethod(__Method_PostCashRefund, serviceImpl.PostCashRefund) .AddMethod(__Method_PostLodgingChargeCorrection, serviceImpl.PostLodgingChargeCorrection) .AddMethod(__Method_PostIncidentalChargeCorrection, serviceImpl.PostIncidentalChargeCorrection) .AddMethod(__Method_PostMiscChargeCorrection, serviceImpl.PostMiscChargeCorrection) .AddMethod(__Method_CancelCardRefund, serviceImpl.CancelCardRefund) .AddMethod(__Method_SoftDeleteCard, serviceImpl.SoftDeleteCard) .AddMethod(__Method_TransferOpenAuthorizations, serviceImpl.TransferOpenAuthorizations).Build(); } } } #endregion
using System; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; namespace Signum.Entities { [Serializable] public class OperationSymbol : Symbol { private OperationSymbol() { } private OperationSymbol(Type declaringType, string fieldName) : base(declaringType, fieldName) { } public static class Construct<T> where T : class, IEntity { public static ConstructSymbol<T>.Simple Simple(Type declaringType, string fieldName) { return new SimpleImp(new OperationSymbol(declaringType, fieldName)); } public static ConstructSymbol<T>.From<F> From<F>(Type declaringType, string fieldName) where F : class, IEntity { return new FromImp<F>(new OperationSymbol(declaringType, fieldName)); } public static ConstructSymbol<T>.FromMany<F> FromMany<F>(Type declaringType, string fieldName) where F : class, IEntity { return new FromManyImp<F>(new OperationSymbol(declaringType, fieldName)); } [Serializable] class SimpleImp : ConstructSymbol<T>.Simple { public SimpleImp(OperationSymbol symbol) { this.Symbol = symbol; } public OperationSymbol Symbol { get; internal set; } public override string ToString() { return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol); } } [Serializable] class FromImp<F> : ConstructSymbol<T>.From<F> where F : class, IEntity { public FromImp(OperationSymbol symbol) { Symbol = symbol; } public OperationSymbol Symbol { get; private set; } public Type BaseType { get { return typeof(F); } } public override string ToString() { return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol); } } [Serializable] class FromManyImp<F> : ConstructSymbol<T>.FromMany<F> where F : class, IEntity { public FromManyImp(OperationSymbol symbol) { Symbol = symbol; } public OperationSymbol Symbol { get; set; } public Type BaseType { get { return typeof(F); } } public override string ToString() { return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol); } } } public static ExecuteSymbol<T> Execute<T>(Type declaringType, string fieldName) where T : class, IEntity { return new ExecuteSymbolImp<T>(new OperationSymbol(declaringType, fieldName)); } public static DeleteSymbol<T> Delete<T>(Type declaringType, string fieldName) where T : class, IEntity { return new DeleteSymbolImp<T>(new OperationSymbol(declaringType, fieldName)); } [Serializable] class ExecuteSymbolImp<T> : ExecuteSymbol<T> where T : class, IEntity { public ExecuteSymbolImp(OperationSymbol symbol) { Symbol = symbol; } public OperationSymbol Symbol { get; private set; } public Type BaseType { get { return typeof(T); } } public override string ToString() { return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol); } } [Serializable] class DeleteSymbolImp<T> : DeleteSymbol<T> where T : class, IEntity { public DeleteSymbolImp(OperationSymbol symbol) { Symbol = symbol; } public OperationSymbol Symbol { get; private set; } public Type BaseType { get { return typeof(T); } } public override string ToString() { return "{0}({1})".FormatWith(this.GetType().TypeName(), Symbol); } } } public interface IOperationSymbolContainer { OperationSymbol Symbol { get; } } public interface IEntityOperationSymbolContainer : IOperationSymbolContainer { } public interface IEntityOperationSymbolContainer<in T> : IEntityOperationSymbolContainer where T : class, IEntity { Type BaseType { get; } } public static class ConstructSymbol<T> where T : class, IEntity { public interface Simple : IOperationSymbolContainer { } public interface From<in F> : IEntityOperationSymbolContainer<F> where F : class, IEntity { } public interface FromMany<in F> : IOperationSymbolContainer where F : class, IEntity { Type BaseType { get; } } } public interface ExecuteSymbol<in T> : IEntityOperationSymbolContainer<T> where T : class, IEntity { } public interface DeleteSymbol<in T> : IEntityOperationSymbolContainer<T> where T : class, IEntity { } [Serializable] public class OperationInfo { public OperationInfo(OperationSymbol symbol, OperationType type) { this.OperationSymbol = symbol; this.OperationType = type; } public OperationSymbol OperationSymbol { get; internal set; } public OperationType OperationType { get; internal set; } public bool? CanBeModified { get; internal set; } public bool? CanBeNew { get; internal set; } public bool? HasStates { get; internal set; } public bool? HasCanExecute { get; internal set; } public bool Returns { get; internal set; } public Type? ReturnType { get; internal set; } public Type? BaseType { get; internal set; } public override string ToString() { return "{0} ({1})".FormatWith(OperationSymbol, OperationType); } public bool IsEntityOperation { get { return OperationType == OperationType.Execute || OperationType == OperationType.ConstructorFrom || OperationType == OperationType.Delete; } } } [InTypeScript(true)] public enum OperationType { Execute, Delete, Constructor, ConstructorFrom, ConstructorFromMany } [InTypeScript(true), DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description)] public enum PropertyOperation { Set, AddElement, ChangeElements, RemoveElements, ModifyEntity, CreateNewEntiy, } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Text; using Generator.Documentation.Python; using Generator.Enums; using Generator.IO; namespace Generator.Encoder.Python { [Generator(TargetLanguage.Python)] sealed class PythonInstrCreateGen : InstrCreateGen { readonly GeneratorContext generatorContext; readonly IdentifierConverter idConverter; readonly IdentifierConverter rustIdConverter; readonly PythonDocCommentWriter docWriter; readonly Rust.GenCreateNameArgs genNames; readonly StringBuilder sb; public PythonInstrCreateGen(GeneratorContext generatorContext) : base(generatorContext.Types) { this.generatorContext = generatorContext; idConverter = PythonIdentifierConverter.Create(); rustIdConverter = RustIdentifierConverter.Create(); docWriter = new PythonDocCommentWriter(idConverter, TargetLanguage.Rust, isInRootModule: true); genNames = new Rust.GenCreateNameArgs { CreatePrefix = "create", Register = "_reg", Memory = "_mem", Int32 = "_i32", UInt32 = "_u32", Int64 = "_i64", UInt64 = "_u64", }; sb = new StringBuilder(); } protected override (TargetLanguage language, string id, string filename) GetFileInfo() => (TargetLanguage.Rust, "Create", generatorContext.Types.Dirs.GetPythonRustFilename("instruction.rs")); sealed class MethodArgInfo { public readonly string RustName; public readonly string PythonName; public MethodArgInfo(string rustName, string pythonName) { RustName = rustName; PythonName = pythonName; } } sealed class GeneratedMethodInfo { public readonly CreateMethod Method; public readonly bool CanFail; /// <summary>iced_x86 method name</summary> public readonly string RustMethodName; /// <summary>iced_x86_py method name which is also the name used by all Python code</summary> public readonly string PythonMethodName; /// <summary>Extra argument info, eg. Rust/Python arg names</summary> public readonly MethodArgInfo[] ArgInfos; public GeneratedMethodInfo(CreateMethod method, bool canFail, string rustMethodName, string pythonMethodName, IdentifierConverter rustIdConverter, IdentifierConverter pythonIdConverter) { Method = method; CanFail = canFail; RustMethodName = rustMethodName; PythonMethodName = pythonMethodName; ArgInfos = new MethodArgInfo[method.Args.Count]; for (int i = 0; i < method.Args.Count; i++) { var origName = method.Args[i].Name; var rustName = rustIdConverter.Argument(origName); var pythonName = pythonIdConverter.Argument(origName); ArgInfos[i] = new MethodArgInfo(rustName: rustName, pythonName: pythonName); } } } readonly struct GenerateMethodContext { public readonly FileWriter Writer; public readonly GeneratedMethodInfo Info; public CreateMethod Method => Info.Method; public GenerateMethodContext(FileWriter writer, GeneratedMethodInfo info) { Writer = writer; Info = info; } } void GenerateMethod(FileWriter writer, CreateMethod method, bool canFail, Action<GenerateMethodContext> genMethod, string? rustMethodName = null, string? pythonMethodName = null) { rustMethodName ??= Rust.InstrCreateGenImpl.GetCreateName(sb, method, Rust.GenCreateNameArgs.RustNames); if (canFail) rustMethodName = "try_" + rustMethodName; pythonMethodName ??= Rust.InstrCreateGenImpl.GetCreateName(sb, method, genNames); var info = new GeneratedMethodInfo(method, canFail, rustMethodName, pythonMethodName, rustIdConverter, idConverter); var ctx = new GenerateMethodContext(writer, info); genMethod(ctx); } static void WriteMethodDeclArgs(in GenerateMethodContext ctx) { bool comma = false; for (int i = 0; i < ctx.Method.Args.Count; i++) { var arg = ctx.Method.Args[i]; if (comma) ctx.Writer.Write(", "); comma = true; ctx.Writer.Write(ctx.Info.ArgInfos[i].PythonName); ctx.Writer.Write(": "); switch (arg.Type) { case MethodArgType.Code: case MethodArgType.Register: case MethodArgType.RepPrefixKind: // All enums are u32 args ctx.Writer.Write("u32"); break; case MethodArgType.Memory: ctx.Writer.Write("MemoryOperand"); break; case MethodArgType.UInt8: ctx.Writer.Write("u8"); break; case MethodArgType.UInt16: ctx.Writer.Write("u16"); break; case MethodArgType.Int32: ctx.Writer.Write("i32"); break; case MethodArgType.PreferedInt32: case MethodArgType.UInt32: ctx.Writer.Write("u32"); break; case MethodArgType.Int64: ctx.Writer.Write("i64"); break; case MethodArgType.UInt64: ctx.Writer.Write("u64"); break; case MethodArgType.ByteSlice: ctx.Writer.Write("&PyAny"); break; case MethodArgType.ByteArray: case MethodArgType.WordArray: case MethodArgType.DwordArray: case MethodArgType.QwordArray: case MethodArgType.BytePtr: case MethodArgType.WordPtr: case MethodArgType.DwordPtr: case MethodArgType.QwordPtr: case MethodArgType.WordSlice: case MethodArgType.DwordSlice: case MethodArgType.QwordSlice: case MethodArgType.ArrayIndex: case MethodArgType.ArrayLength: default: throw new InvalidOperationException(); } } } void WriteTextSignature(in GenerateMethodContext ctx) { sb.Clear(); sb.Append("#[text_signature = \"("); foreach (var argInfo in ctx.Info.ArgInfos) { sb.Append(argInfo.PythonName); sb.Append(", "); } sb.Append("/)\"]"); ctx.Writer.WriteLine(sb.ToString()); } void WriteDefaultArgs(in GenerateMethodContext ctx) { sb.Clear(); sb.Append("#[args("); int defaultArgsCount = 0; for (int i = 0; i < ctx.Method.Args.Count; i++) { var defaultValue = ctx.Method.Args[i].DefaultValue; if (defaultValue is null) continue; if (defaultArgsCount > 0) sb.Append(", "); defaultArgsCount++; var argName = ctx.Info.ArgInfos[i].PythonName; sb.Append(argName); sb.Append(" = "); switch (defaultValue) { case EnumValue enumValue: sb.Append(enumValue.Value); break; default: throw new InvalidOperationException(); } } sb.Append(")]"); if (defaultArgsCount > 0) ctx.Writer.WriteLine(sb.ToString()); } static (string sphinxType, string pythonType, string? descType) GetArgType(MethodArgType type) => type switch { MethodArgType.Code => (":class:`Code`", "Code", null), MethodArgType.Register => (":class:`Register`", "Register", null), MethodArgType.RepPrefixKind => (":class:`RepPrefixKind`", "RepPrefixKind", null), MethodArgType.Memory => (":class:`MemoryOperand`", "MemoryOperand", null), MethodArgType.UInt8 => ("int", "int", "``u8``"), MethodArgType.UInt16 => ("int", "int", "``u16``"), MethodArgType.Int32 => ("int", "int", "``i32``"), MethodArgType.PreferedInt32 or MethodArgType.UInt32 => ("int", "int", "``u32``"), MethodArgType.Int64 => ("int", "int", "``i64``"), MethodArgType.UInt64 => ("int", "int", "``u64``"), MethodArgType.ByteSlice => ("bytes, bytearray", "Union[bytes, bytearray]", null), _ => throw new InvalidOperationException(), }; void WriteDocs(in GenerateMethodContext ctx, Func<IEnumerable<(string type, string text)>>? getThrowsDocs) { const string typeName = "Instruction"; docWriter.BeginWrite(ctx.Writer); foreach (var doc in ctx.Info.Method.Docs) docWriter.WriteDocLine(ctx.Writer, doc, typeName); docWriter.WriteLine(ctx.Writer, string.Empty); docWriter.WriteLine(ctx.Writer, "Args:"); for (int i = 0; i < ctx.Info.Method.Args.Count; i++) { var arg = ctx.Info.Method.Args[i]; var typeInfo = GetArgType(arg.Type); docWriter.Write($" `{idConverter.Argument(arg.Name)}` ({typeInfo.sphinxType}): "); if (typeInfo.descType is not null) docWriter.Write($"({typeInfo.descType}) "); docWriter.WriteDocLine(ctx.Writer, arg.Doc, typeName); } docWriter.WriteLine(ctx.Writer, string.Empty); docWriter.WriteLine(ctx.Writer, "Returns:"); docWriter.WriteLine(ctx.Writer, $" :class:`{typeName}`: Created instruction"); if (getThrowsDocs is not null) { docWriter.WriteLine(ctx.Writer, string.Empty); docWriter.WriteLine(ctx.Writer, "Raises:"); foreach (var doc in getThrowsDocs()) { if (!doc.text.StartsWith("If ", StringComparison.Ordinal)) throw new InvalidOperationException(); docWriter.WriteLine(ctx.Writer, $" {doc.type}: {doc.text}"); } } docWriter.EndWrite(ctx.Writer); } void WriteMethod(in GenerateMethodContext ctx, Func<IEnumerable<(string type, string text)>>? getThrowsDocs) { WriteDocs(ctx, getThrowsDocs); ctx.Writer.WriteLine("#[rustfmt::skip]"); ctx.Writer.WriteLine("#[staticmethod]"); WriteTextSignature(ctx); WriteDefaultArgs(ctx); ctx.Writer.Write($"fn {ctx.Info.PythonMethodName}("); WriteMethodDeclArgs(ctx); ctx.Writer.WriteLine(") -> PyResult<Self> {"); using (ctx.Writer.Indent()) { for (int i = 0; i < ctx.Method.Args.Count; i++) { var arg = ctx.Method.Args[i]; // Verify all enum args (they're u32 args) string? checkFunc; bool isUnsafe = false; switch (arg.Type) { case MethodArgType.Code: checkFunc = "to_code"; break; case MethodArgType.Register: checkFunc = "to_register"; break; case MethodArgType.RepPrefixKind: checkFunc = "to_rep_prefix_kind"; break; case MethodArgType.ByteSlice: checkFunc = "get_temporary_byte_array_ref"; isUnsafe = true; break; default: checkFunc = null; break; } if (checkFunc is not null) { var argName = ctx.Info.ArgInfos[i].PythonName; if (isUnsafe) ctx.Writer.WriteLine($"let {argName} = unsafe {{ {checkFunc}({argName})? }};"); else ctx.Writer.WriteLine($"let {argName} = {checkFunc}({argName})?;"); } } } } void WriteCall(in GenerateMethodContext ctx) { using (ctx.Writer.Indent()) { sb.Clear(); sb.Append("Ok("); sb.Append("Instruction { instr: iced_x86::Instruction::"); sb.Append(ctx.Info.RustMethodName); sb.Append('('); for (int i = 0; i < ctx.Method.Args.Count; i++) { if (i > 0) sb.Append(", "); switch (ctx.Method.Args[i].Type) { case MethodArgType.Memory: sb.Append(ctx.Info.ArgInfos[i].PythonName); sb.Append(".mem"); break; default: sb.Append(ctx.Info.ArgInfos[i].PythonName); break; } } sb.Append(")"); if (ctx.Info.CanFail) sb.Append(".map_err(to_value_error)?"); sb.Append(" })"); ctx.Writer.WriteLine(sb.ToString()); } } protected override void GenCreate(FileWriter writer, CreateMethod method, InstructionGroup group) { bool canFail = Rust.InstrCreateGenImpl.HasTryMethod(method); GenerateMethod(writer, method, canFail, GenCreate); } void GenCreate(GenerateMethodContext ctx) { Func<IEnumerable<(string type, string text)>>? getThrowsDocs = null; if (ctx.Info.CanFail) getThrowsDocs = () => new[] { ("ValueError", "If the immediate is invalid") }; WriteMethod(ctx, getThrowsDocs); WriteCall(ctx); ctx.Writer.WriteLine("}"); } protected override void GenCreateBranch(FileWriter writer, CreateMethod method) => GenerateMethod(writer, method, canFail: true, GenCreateBranch, Rust.RustInstrCreateGenNames.with_branch, "create_branch"); void GenCreateBranch(GenerateMethodContext ctx) { WriteMethod(ctx, () => new[] { ("ValueError", "If the created instruction doesn't have a near branch operand") }); WriteCall(ctx); ctx.Writer.WriteLine("}"); } protected override void GenCreateFarBranch(FileWriter writer, CreateMethod method) => GenerateMethod(writer, method, canFail: true, GenCreateFarBranch, Rust.RustInstrCreateGenNames.with_far_branch, "create_far_branch"); void GenCreateFarBranch(GenerateMethodContext ctx) { WriteMethod(ctx, () => new[] { ("ValueError", "If the created instruction doesn't have a far branch operand") }); WriteCall(ctx); ctx.Writer.WriteLine("}"); } protected override void GenCreateXbegin(FileWriter writer, CreateMethod method) => GenerateMethod(writer, method, canFail: true, GenCreateXbegin, Rust.RustInstrCreateGenNames.with_xbegin, "create_xbegin"); void GenCreateXbegin(GenerateMethodContext ctx) { WriteMethod(ctx, () => GetAddressSizeThrowsDocs(ctx)); WriteCall(ctx); ctx.Writer.WriteLine("}"); } (string type, string text)[] GetAddressSizeThrowsDocs(in GenerateMethodContext ctx) { var arg = ctx.Method.Args[0]; if (arg.Name != "addressSize" && arg.Name != "bitness") throw new InvalidOperationException(); return new[] { ("ValueError", $"If `{idConverter.Argument(arg.Name)}` is not one of 16, 32, 64.") }; } protected override void GenCreateString_Reg_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) => GenStringInstr(writer, method, methodBaseName); void GenStringInstr(FileWriter writer, CreateMethod method, string methodBaseName) { var rustName = rustIdConverter.Method("With" + methodBaseName); var pythonName = idConverter.Method("Create" + methodBaseName); GenerateMethod(writer, method, canFail: true, GenStringInstr, rustName, pythonName); } void GenStringInstr(GenerateMethodContext ctx) { WriteMethod(ctx, () => GetAddressSizeThrowsDocs(ctx)); WriteCall(ctx); ctx.Writer.WriteLine("}"); } protected override void GenCreateString_Reg_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) => GenStringInstr(writer, method, methodBaseName); protected override void GenCreateString_ESRDI_Reg(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) => GenStringInstr(writer, method, methodBaseName); protected override void GenCreateString_SegRSI_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code) => GenStringInstr(writer, method, methodBaseName); protected override void GenCreateString_ESRDI_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code) => GenStringInstr(writer, method, methodBaseName); protected override void GenCreateMaskmov(FileWriter writer, CreateMethod method, string methodBaseName, EnumValue code) => GenStringInstr(writer, method, methodBaseName); protected override void GenCreateDeclareData(FileWriter writer, CreateMethod method, DeclareDataKind kind) { var (rustName, pythonName) = kind switch { DeclareDataKind.Byte => (Rust.RustInstrCreateGenNames.with_declare_byte, "create_declare_byte"), DeclareDataKind.Word => (Rust.RustInstrCreateGenNames.with_declare_word, "create_declare_word"), DeclareDataKind.Dword => (Rust.RustInstrCreateGenNames.with_declare_dword, "create_declare_dword"), DeclareDataKind.Qword => (Rust.RustInstrCreateGenNames.with_declare_qword, "create_declare_qword"), _ => throw new InvalidOperationException(), }; pythonName = pythonName + "_" + method.Args.Count.ToString(); rustName = Rust.RustInstrCreateGenNames.AppendArgCount(rustName, method.Args.Count); // It can't fail since the 'db' feature is always enabled, but we must still call the try_xxx methods GenerateMethod(writer, method, canFail: true, GenCreateDeclareData, rustName, pythonName); } void GenCreateDeclareData(GenerateMethodContext ctx) { ctx.Writer.WriteLine(); WriteMethod(ctx, null); WriteCall(ctx); ctx.Writer.WriteLine("}"); } void GenCreateDeclareDataSlice(FileWriter writer, CreateMethod method, int elemSize, string rustName, string pythonName) => GenerateMethod(writer, method, canFail: true, ctx => GenCreateDeclareDataSlice(ctx, elemSize), rustName, pythonName); void GenCreateDeclareDataSlice(GenerateMethodContext ctx, int elemSize) { ctx.Writer.WriteLine(); var errors = new[] { ("ValueError", $"If `len({idConverter.Argument(ctx.Method.Args[0].Name)})` is not 1-{16 / elemSize}"), ("TypeError", $"If `{idConverter.Argument(ctx.Method.Args[0].Name)}` is not a supported type"), }; WriteMethod(ctx, () => errors); WriteCall(ctx); ctx.Writer.WriteLine("}"); } protected override void GenCreateDeclareDataArray(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType) { switch (kind) { case DeclareDataKind.Byte: switch (arrayType) { case ArrayType.BytePtr: case ArrayType.ByteArray: break; case ArrayType.ByteSlice: GenCreateDeclareDataSlice(writer, method, 1, Rust.RustInstrCreateGenNames.with_declare_byte, "create_declare_byte"); break; default: throw new InvalidOperationException(); } break; default: break; } } protected override void GenCreateDeclareDataArrayLength(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Newtonsoft.Json; using Rest; using Rest.Azure; using Rest.Serialization; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Creates an Azure Data Lake Store account management client. /// </summary> public partial class DataLakeStoreAccountManagementClient : ServiceClient<DataLakeStoreAccountManagementClient>, IDataLakeStoreAccountManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IFirewallRulesOperations. /// </summary> public virtual IFirewallRulesOperations FirewallRules { get; private set; } /// <summary> /// Gets the ITrustedIdProvidersOperations. /// </summary> public virtual ITrustedIdProvidersOperations TrustedIdProviders { get; private set; } /// <summary> /// Gets the IAccountOperations. /// </summary> public virtual IAccountOperations Account { get; private set; } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeStoreAccountManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeStoreAccountManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DataLakeStoreAccountManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DataLakeStoreAccountManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { FirewallRules = new FirewallRulesOperations(this); TrustedIdProviders = new TrustedIdProvidersOperations(this); Account = new AccountOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2016-11-01"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright Bastian Eicher // Licensed under the MIT License using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Mono.Unix; using Mono.Unix.Native; #if !NET20 && !NET40 && !NET using System.Runtime.InteropServices; #endif namespace NanoByte.Common.Native { /// <summary> /// Provides helper methods for Unix-specific features of the Mono library. /// </summary> /// <remarks> /// This class has a dependency on <c>Mono.Posix</c>. /// Make sure to check <see cref="IsUnix"/> before calling any methods in this class to avoid exceptions. /// </remarks> [SupportedOSPlatform("linux"), SupportedOSPlatform("freebsd"), SupportedOSPlatform("macos")] public static class UnixUtils { #region OS /// <summary> /// <c>true</c> if the current operating system is a Unixoid system (e.g. Linux or MacOS X). /// </summary> [SupportedOSPlatformGuard("linux"), SupportedOSPlatformGuard("freebsd"), SupportedOSPlatformGuard("macos")] public static bool IsUnix #if NET => OperatingSystem.IsLinux() || OperatingSystem.IsFreeBSD() || OperatingSystem.IsMacOS(); #elif NET20 || NET40 => Environment.OSVersion.Platform is PlatformID.Unix or PlatformID.MacOSX or (PlatformID)128; #else => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); #endif /// <summary> /// <c>true</c> if the current operating system is MacOS X. /// </summary> [SupportedOSPlatformGuard("macos")] public static bool IsMacOSX #if NET => OperatingSystem.IsMacOS(); #elif NET20 || NET40 => IsUnix && OSName == "Darwin"; #else => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); #endif /// <summary> /// <c>true</c> if there is an X Server running or the current operating system is MacOS X. /// </summary> [SupportedOSPlatformGuard("linux"), SupportedOSPlatformGuard("freebsd"), SupportedOSPlatformGuard("macos")] public static bool HasGui => IsUnix && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISPLAY")) || IsMacOSX; /// <summary> /// The operating system name as reported by the "uname" system call. /// </summary> public static string OSName { [MethodImpl(MethodImplOptions.NoInlining)] get { Syscall.uname(out var buffer); return buffer.sysname; } } /// <summary> /// The CPU type as reported by the "uname" system call (after applying some normalization). /// </summary> public static string CpuType { [MethodImpl(MethodImplOptions.NoInlining)] get { Syscall.uname(out var buffer); string cpuType = buffer.machine; // Normalize names return cpuType switch { "x86" => "i386", "amd64" => "x86_64", "Power Macintosh" => "ppc", "i86pc" => "i686", _ => cpuType }; } } #endregion #region Links /// <summary> /// Creates a new Unix symbolic link to a file or directory. /// </summary> /// <param name="sourcePath">The path of the link to create.</param> /// <param name="targetPath">The path of the existing file or directory to point to (relative to <paramref name="sourcePath"/>).</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void CreateSymlink([Localizable(false)] string sourcePath, [Localizable(false)] string targetPath) => new UnixSymbolicLinkInfo(sourcePath ?? throw new ArgumentNullException(nameof(sourcePath))) .CreateSymbolicLinkTo(targetPath ?? throw new ArgumentNullException(nameof(targetPath))); /// <summary> /// Creates a new Unix hard link between two files. /// </summary> /// <param name="sourcePath">The path of the link to create.</param> /// <param name="targetPath">The absolute path of the existing file to point to.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void CreateHardlink([Localizable(false)] string sourcePath, [Localizable(false)] string targetPath) => new UnixFileInfo(targetPath ?? throw new ArgumentNullException(nameof(targetPath))) .CreateLink(sourcePath ?? throw new ArgumentNullException(nameof(sourcePath))); /// <summary> /// Returns the Inode ID of a file. /// </summary> /// <param name="path">The path of the file.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static long GetInode([Localizable(false)] string path) => UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))).Inode; /// <summary> /// Renames a file. Atomically replaces the destination if present. /// </summary> /// <param name="source">The path of the file to rename.</param> /// <param name="destination">The new path of the file. Must reside on the same file system as <paramref name="source"/>.</param> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void Rename([Localizable(false)] string source, [Localizable(false)] string destination) { if (Stdlib.rename( source ?? throw new ArgumentNullException(nameof(source)), destination ?? throw new ArgumentNullException(nameof(destination))) != 0) throw new UnixIOException(Stdlib.GetLastError()); } #endregion #region File type /// <summary> /// Checks whether a file is a regular file (i.e. not a device file, symbolic link, etc.). /// </summary> /// <returns><c>true</c> if <paramref name="path"/> points to a regular file; <c>false</c> otherwise.</returns> /// <remarks>Will return <c>false</c> for non-existing files.</remarks> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static bool IsRegularFile([Localizable(false)] string path) => UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))).IsRegularFile; /// <summary> /// Checks whether a file is a Unix symbolic link. /// </summary> /// <param name="path">The path of the file to check.</param> /// <returns><c>true</c> if <paramref name="path"/> points to a symbolic link; <c>false</c> otherwise.</returns> /// <remarks>Will return <c>false</c> for non-existing files.</remarks> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static bool IsSymlink([Localizable(false)] string path) => UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))).IsSymbolicLink; /// <summary> /// Checks whether a file is a Unix symbolic link. /// </summary> /// <param name="path">The path of the file to check.</param> /// <param name="target">Returns the target the symbolic link points to if it exists.</param> /// <returns><c>true</c> if <paramref name="path"/> points to a symbolic link; <c>false</c> otherwise.</returns> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static bool IsSymlink( [Localizable(false)] string path, [MaybeNullWhen(false)] out string target) { if (IsSymlink(path ?? throw new ArgumentNullException(nameof(path)))) { var symlinkInfo = new UnixSymbolicLinkInfo(path); target = symlinkInfo.ContentsPath; return true; } else { target = null; return false; } } #endregion #region Permissions /// <summary>A combination of bit flags to grant everyone writing permissions.</summary> private const FileAccessPermissions AllWritePermission = FileAccessPermissions.UserWrite | FileAccessPermissions.GroupWrite | FileAccessPermissions.OtherWrite; /// <summary> /// Removes write permissions for everyone on a filesystem object (file or directory). /// </summary> /// <param name="path">The filesystem object (file or directory) to make read-only.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static void MakeReadOnly([Localizable(false)] string path) { var fileSysInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); fileSysInfo.FileAccessPermissions &= ~AllWritePermission; } /// <summary> /// Sets write permissions for the owner on a filesystem object (file or directory). /// </summary> /// <param name="path">The filesystem object (file or directory) to make writable by the owner.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static void MakeWritable([Localizable(false)] string path) { var fileSysInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); fileSysInfo.FileAccessPermissions |= FileAccessPermissions.UserWrite; } /// <summary>A combination of bit flags to grant everyone executing permissions.</summary> private const FileAccessPermissions AllExecutePermission = FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; /// <summary> /// Checks whether a file is marked as Unix-executable. /// </summary> /// <param name="path">The file to check for executable rights.</param> /// <returns><c>true</c> if <paramref name="path"/> points to an executable; <c>false</c> otherwise.</returns> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <remarks>Will return <c>false</c> for non-existing files.</remarks> public static bool IsExecutable([Localizable(false)] string path) { // Check if any execution rights are set var fileInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); return (fileInfo.FileAccessPermissions & AllExecutePermission) > 0; } /// <summary> /// Marks a file as Unix-executable or not Unix-executable. /// </summary> /// <param name="path">The file to mark as executable or not executable.</param> /// <param name="executable"><c>true</c> to mark the file as executable, <c>true</c> to mark it as not executable.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static void SetExecutable([Localizable(false)] string path, bool executable) { var fileInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); if (executable) fileInfo.FileAccessPermissions |= AllExecutePermission; // Set all execution rights else fileInfo.FileAccessPermissions &= ~AllExecutePermission; // Unset all execution rights } #endregion #region Extended file attributes /// <summary> /// Gets an extended file attribute. /// </summary> /// <param name="path">The path of the file to read the attribute from.</param> /// <param name="name">The name of the attribute to read.</param> /// <returns>The contents of the attribute as a byte array; <c>null</c> if there was a problem reading the file.</returns> [MethodImpl(MethodImplOptions.NoInlining)] public static byte[]? GetXattr([Localizable(false)] string path, [Localizable(false)] string name) => Syscall.getxattr( path ?? throw new ArgumentNullException(nameof(path)), name ?? throw new ArgumentNullException(nameof(name)), out var data) == -1 ? null : data; /// <summary> /// Sets an extended file attribute. /// </summary> /// <param name="path">The path of the file to set the attribute for.</param> /// <param name="name">The name of the attribute to set.</param> /// <param name="data">The data to write to the attribute.</param> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void SetXattr([Localizable(false)] string path, [Localizable(false)] string name, byte[] data) { if (Syscall.setxattr( path ?? throw new ArgumentNullException(nameof(path)), name ?? throw new ArgumentNullException(nameof(name)), data) == -1) throw new UnixIOException(Stdlib.GetLastError()); } #endregion #region Mount point private static readonly ProcessLauncher _stat = new("stat"); /// <summary> /// Determines the file system type a file or directory is stored on. /// </summary> /// <param name="path">The path of the file.</param> /// <returns>The name of the file system in fstab format (e.g. ext3 or ntfs-3g).</returns> /// <remarks>Only works on Linux, not on other Unixes (e.g. MacOS X).</remarks> /// <exception cref="IOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static string GetFileSystem([Localizable(false)] string path) { string fileSystem = _stat.RunAndCapture("--file-system", "--printf", "%T", path).TrimEnd('\n'); if (fileSystem == "fuseblk") { // FUSE mounts need to be looked up in /etc/fstab to determine actual file system var fstabData = Syscall.getfsfile(_stat.RunAndCapture("--printf", "%m", path).TrimEnd('\n')); if (fstabData != null) return fstabData.fs_vfstype; } return fileSystem; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsUInt32() { var test = new VectorAs__AsUInt32(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsUInt32 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector64<UInt32> value; value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector64<UInt32> value; value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<byte> byteResult = value.As<UInt32, byte>(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<double> doubleResult = value.As<UInt32, double>(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<short> shortResult = value.As<UInt32, short>(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<int> intResult = value.As<UInt32, int>(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<long> longResult = value.As<UInt32, long>(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<sbyte> sbyteResult = value.As<UInt32, sbyte>(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<float> floatResult = value.As<UInt32, float>(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<ushort> ushortResult = value.As<UInt32, ushort>(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<uint> uintResult = value.As<UInt32, uint>(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); Vector64<ulong> ulongResult = value.As<UInt32, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector64<UInt32> value; value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object byteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsByte)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<byte>)(byteResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object doubleResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsDouble)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<double>)(doubleResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object shortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt16)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<short>)(shortResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object intResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt32)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<int>)(intResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object longResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt64)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<long>)(longResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object sbyteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSByte)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<sbyte>)(sbyteResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object floatResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSingle)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<float>)(floatResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object ushortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt16)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ushort>)(ushortResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object uintResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt32)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<uint>)(uintResult), value); value = Vector64.Create(TestLibrary.Generator.GetUInt32()); object ulongResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt64)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector64<T> result, Vector64<UInt32> value, [CallerMemberName] string method = "") where T : struct { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); UInt32[] valueElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(UInt32[] resultElements, UInt32[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt32>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
namespace test.sacs { /// <date>Sep 5, 2009</date> public class Builtin1 : Test.Framework.TestCase { public Builtin1() : base("sacs_builtin_tc1", "sacs_builtin", "sacs_builtin", "test builtin topics" , "test builtin topics", null) { this.AddPreItem(new test.sacs.BuiltinInit()); this.AddPostItem(new test.sacs.BuiltinDeinit()); } public override Test.Framework.TestResult Run() { DDS.IDomainParticipant participant; DDS.ITopic topic; DDS.ITopic topic2; Test.Framework.TestResult result; string expResult = "Builtin topic test succeeded."; result = new Test.Framework.TestResult( expResult, string.Empty, Test.Framework.TestVerdict.Pass, Test.Framework.TestVerdict.Fail); participant = (DDS.IDomainParticipant)this.ResolveObject("participant"); topic = (DDS.ITopic)participant.FindTopic("DCPSParticipant", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic DCPSParticipant could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("DCPSParticipant"); if (topic2 == null) { result.Result = "Builtin Topic DCPSParticipant could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for DCPSParticipant."; return result; } topic = (DDS.ITopic)participant.FindTopic("DCPSPublication", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic DCPSPublication could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("DCPSPublication"); if (topic2 == null) { result.Result = "Builtin Topic DCPSPublication could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for DCPSPublication."; return result; } topic = (DDS.ITopic)participant.FindTopic("DCPSSubscription", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic DCPSSubscription could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("DCPSSubscription"); if (topic2 == null) { result.Result = "Builtin Topic DCPSSubscription could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for DCPSSubscription."; return result; } topic = (DDS.ITopic)participant.FindTopic("DCPSTopic", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic DCPSTopic could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("DCPSTopic"); if (topic2 == null) { result.Result = "Builtin Topic DCPSTopic could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for DCPSTopic."; return result; } topic = (DDS.ITopic)participant.FindTopic("CMParticipant", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic CMParticipant could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("CMParticipant"); if (topic2 == null) { result.Result = "Builtin Topic CMParticipant could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for CMParticipant."; return result; } topic = (DDS.ITopic)participant.FindTopic("CMPublisher", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic CMPublisher could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("CMPublisher"); if (topic2 == null) { result.Result = "Builtin Topic CMPublisher could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for CMPublisher."; return result; } topic = (DDS.ITopic)participant.FindTopic("CMSubscriber", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic CMSubscriber could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("CMSubscriber"); if (topic2 == null) { result.Result = "Builtin Topic CMSubscriber could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for CMSubscriber."; return result; } topic = (DDS.ITopic)participant.FindTopic("CMDataWriter", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic CMDataWriter could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("CMDataWriter"); if (topic2 == null) { result.Result = "Builtin Topic CMDataWriter could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for CMDataWriter."; return result; } topic = (DDS.ITopic)participant.FindTopic("CMDataReader", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic CMDataReader could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("CMDataReader"); if (topic2 == null) { result.Result = "Builtin Topic CMDataReader could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for CMDataReader."; return result; } topic = (DDS.ITopic)participant.FindTopic("DCPSType", DDS.Duration.Infinite); if (topic == null) { result.Result = "Builtin Topic DCPSType could not be found."; return result; } topic2 = (DDS.ITopic)participant.LookupTopicDescription("DCPSType"); if (topic2 == null) { result.Result = "Builtin Topic DCPSType could not be found(2)."; return result; } if (topic != topic2) { result.Result = "Resolved topics do not match for DCPSType."; return result; } result.Result = expResult; result.Verdict = Test.Framework.TestVerdict.Pass; return result; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Runtime.Serialization; using System.Text; namespace System.Management.Automation { /// <summary> /// This exception is thrown when a command cannot be found. /// </summary> [Serializable] public class CommandNotFoundException : RuntimeException { /// <summary> /// Constructs a CommandNotFoundException. This is the recommended constructor. /// </summary> /// <param name="commandName"> /// The name of the command that could not be found. /// </param> /// <param name="innerException"> /// The inner exception. /// </param> /// <param name="resourceStr"> /// This string is message template string /// </param> /// <param name="errorIdAndResourceId"> /// This string is the ErrorId passed to the ErrorRecord, and is also /// the resourceId used to look up the message template string in /// DiscoveryExceptions.txt. /// </param> /// <param name="messageArgs"> /// Additional arguments to format into the message. /// </param> internal CommandNotFoundException( string commandName, Exception innerException, string errorIdAndResourceId, string resourceStr, params object[] messageArgs) : base(BuildMessage(commandName, resourceStr, messageArgs), innerException) { _commandName = commandName; _errorId = errorIdAndResourceId; } /// <summary> /// Constructs a CommandNotFoundException. /// </summary> public CommandNotFoundException() : base() { } /// <summary> /// Constructs a CommandNotFoundException. /// </summary> /// <param name="message"> /// The message used in the exception. /// </param> public CommandNotFoundException(string message) : base(message) { } /// <summary> /// Constructs a CommandNotFoundException. /// </summary> /// <param name="message"> /// The message used in the exception. /// </param> /// <param name="innerException"> /// An exception that led to this exception. /// </param> public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) { } #region Serialization /// <summary> /// Serialization constructor for class CommandNotFoundException. /// </summary> /// <param name="info"> /// serialization information /// </param> /// <param name="context"> /// streaming context /// </param> protected CommandNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } _commandName = info.GetString("CommandName"); } /// <summary> /// Serializes the CommandNotFoundException. /// </summary> /// <param name="info"> /// serialization information /// </param> /// <param name="context"> /// streaming context /// </param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); info.AddValue("CommandName", _commandName); } #endregion Serialization #region Properties /// <summary> /// Gets the ErrorRecord information for this exception. /// </summary> public override ErrorRecord ErrorRecord { get { if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), _errorId, _errorCategory, _commandName); } return _errorRecord; } } private ErrorRecord _errorRecord; /// <summary> /// Gets the name of the command that could not be found. /// </summary> public string CommandName { get { return _commandName; } set { _commandName = value; } } private string _commandName = string.Empty; #endregion Properties #region Private private readonly string _errorId = "CommandNotFoundException"; private readonly ErrorCategory _errorCategory = ErrorCategory.ObjectNotFound; private static string BuildMessage( string commandName, string resourceStr, params object[] messageArgs ) { object[] a; if (messageArgs != null && messageArgs.Length > 0) { a = new object[messageArgs.Length + 1]; a[0] = commandName; messageArgs.CopyTo(a, 1); } else { a = new object[1]; a[0] = commandName; } return StringUtil.Format(resourceStr, a); } #endregion Private } /// <summary> /// Defines the exception thrown when a script's requirements to run specified by the #requires /// statements are not met. /// </summary> [Serializable] public class ScriptRequiresException : RuntimeException { /// <summary> /// Constructs an ScriptRequiresException. Recommended constructor for the class for /// #requires -shellId MyShellId. /// </summary> /// <param name="commandName"> /// The name of the script containing the #requires statement. /// </param> /// <param name="requiresShellId"> /// The ID of the shell that is incompatible with the current shell. /// </param> /// <param name="requiresShellPath"> /// The path to the shell specified in the #requires -shellId statement. /// </param> /// <param name="errorId"> /// The error id for this exception. /// </param> internal ScriptRequiresException( string commandName, string requiresShellId, string requiresShellPath, string errorId) : base(BuildMessage(commandName, requiresShellId, requiresShellPath, true)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); _commandName = commandName; _requiresShellId = requiresShellId; _requiresShellPath = requiresShellPath; this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.ResourceUnavailable); } /// <summary> /// Constructs an ScriptRequiresException. Recommended constructor for the class for /// #requires -version N. /// </summary> /// <param name="commandName"> /// The name of the script containing the #requires statement. /// </param> /// <param name="requiresPSVersion"> /// The Msh version that the script requires. /// </param> /// <param name="currentPSVersion"> /// The current Msh version /// </param> /// <param name="errorId"> /// The error id for this exception. /// </param> internal ScriptRequiresException( string commandName, Version requiresPSVersion, string currentPSVersion, string errorId) : base(BuildMessage(commandName, requiresPSVersion.ToString(), currentPSVersion, false)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(requiresPSVersion != null, "requiresPSVersion is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); _commandName = commandName; _requiresPSVersion = requiresPSVersion; this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.ResourceUnavailable); } /// <summary> /// Constructs an ScriptRequiresException. Recommended constructor for the class for the /// #requires -PSSnapin MyPSSnapIn statement. /// </summary> /// <param name="commandName"> /// The name of the script containing the #requires statement. /// </param> /// <param name="missingItems"> /// The missing snap-ins/modules that the script requires. /// </param> /// /// <param name="forSnapins"> /// Indicates whether the error message needs to be constructed for missing snap-ins/ missing modules. /// </param> /// <param name="errorId"> /// The error id for this exception. /// </param> internal ScriptRequiresException( string commandName, Collection<string> missingItems, string errorId, bool forSnapins) : this(commandName, missingItems, errorId, forSnapins, null) { } /// <summary> /// Constructs an ScriptRequiresException. Recommended constructor for the class for the /// #requires -PSSnapin MyPSSnapIn statement. /// </summary> /// <param name="commandName"> /// The name of the script containing the #requires statement. /// </param> /// <param name="missingItems"> /// The missing snap-ins/modules that the script requires. /// </param> /// /// <param name="forSnapins"> /// Indicates whether the error message needs to be constructed for missing snap-ins/ missing modules. /// </param> /// <param name="errorId"> /// The error id for this exception. /// </param> /// <param name="errorRecord"> /// The error Record for this exception. /// </param> internal ScriptRequiresException( string commandName, Collection<string> missingItems, string errorId, bool forSnapins, ErrorRecord errorRecord) : base(BuildMessage(commandName, missingItems, forSnapins), null, errorRecord) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(missingItems != null && missingItems.Count > 0, "missingItems is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); _commandName = commandName; _missingPSSnapIns = new ReadOnlyCollection<string>(missingItems); this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.ResourceUnavailable); } /// <summary> /// Constructs an ScriptRequiresException. Recommended constructor for the class for /// #requires -RunAsAdministrator statement. /// </summary> /// <param name="commandName"> /// The name of the script containing the #requires statement. /// </param> /// <param name="errorId"> /// The error id for this exception. /// </param> internal ScriptRequiresException( string commandName, string errorId) : base(BuildMessage(commandName)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); _commandName = commandName; this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.PermissionDenied); } /// <summary> /// Constructs an PSVersionNotCompatibleException. /// </summary> public ScriptRequiresException() : base() { } /// <summary> /// Constructs an PSVersionNotCompatibleException. /// </summary> /// <param name="message"> /// The message used in the exception. /// </param> public ScriptRequiresException(string message) : base(message) { } /// <summary> /// Constructs an PSVersionNotCompatibleException. /// </summary> /// <param name="message"> /// The message used in the exception. /// </param> /// <param name="innerException"> /// The exception that led to this exception. /// </param> public ScriptRequiresException(string message, Exception innerException) : base(message, innerException) { } #region Serialization /// <summary> /// Constructs an PSVersionNotCompatibleException using serialized data. /// </summary> /// <param name="info"> /// serialization information /// </param> /// <param name="context"> /// streaming context /// </param> protected ScriptRequiresException(SerializationInfo info, StreamingContext context) : base(info, context) { _commandName = info.GetString("CommandName"); _requiresPSVersion = (Version)info.GetValue("RequiresPSVersion", typeof(Version)); _missingPSSnapIns = (ReadOnlyCollection<string>)info.GetValue("MissingPSSnapIns", typeof(ReadOnlyCollection<string>)); _requiresShellId = info.GetString("RequiresShellId"); _requiresShellPath = info.GetString("RequiresShellPath"); } /// <summary> /// Gets the serialized data for the exception. /// </summary> /// <param name="info"> /// serialization information /// </param> /// <param name="context"> /// streaming context /// </param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); info.AddValue("CommandName", _commandName); info.AddValue("RequiresPSVersion", _requiresPSVersion, typeof(Version)); info.AddValue("MissingPSSnapIns", _missingPSSnapIns, typeof(ReadOnlyCollection<string>)); info.AddValue("RequiresShellId", _requiresShellId); info.AddValue("RequiresShellPath", _requiresShellPath); } #endregion Serialization #region Properties /// <summary> /// Gets the name of the script that contained the #requires statement. /// </summary> public string CommandName { get { return _commandName; } } private readonly string _commandName = string.Empty; /// <summary> /// Gets the PSVersion that the script requires. /// </summary> public Version RequiresPSVersion { get { return _requiresPSVersion; } } private readonly Version _requiresPSVersion; /// <summary> /// Gets the missing snap-ins that the script requires. /// </summary> public ReadOnlyCollection<string> MissingPSSnapIns { get { return _missingPSSnapIns; } } private readonly ReadOnlyCollection<string> _missingPSSnapIns = new ReadOnlyCollection<string>(Array.Empty<string>()); /// <summary> /// Gets or sets the ID of the shell. /// </summary> public string RequiresShellId { get { return _requiresShellId; } } private readonly string _requiresShellId; /// <summary> /// Gets or sets the path to the incompatible shell. /// </summary> public string RequiresShellPath { get { return _requiresShellPath; } } private readonly string _requiresShellPath; #endregion Properties #region Private private static string BuildMessage( string commandName, Collection<string> missingItems, bool forSnapins) { StringBuilder sb = new StringBuilder(); if (missingItems == null) { throw PSTraceSource.NewArgumentNullException(nameof(missingItems)); } foreach (string missingItem in missingItems) { sb.Append(missingItem).Append(", "); } if (sb.Length > 1) { sb.Remove(sb.Length - 2, 2); } if (forSnapins) { return StringUtil.Format( DiscoveryExceptions.RequiresMissingPSSnapIns, commandName, sb.ToString()); } else { return StringUtil.Format( DiscoveryExceptions.RequiresMissingModules, commandName, sb.ToString()); } } private static string BuildMessage( string commandName, string first, string second, bool forShellId) { string resourceStr = null; if (forShellId) { if (string.IsNullOrEmpty(first)) { resourceStr = DiscoveryExceptions.RequiresShellIDInvalidForSingleShell; } else { resourceStr = string.IsNullOrEmpty(second) ? DiscoveryExceptions.RequiresInterpreterNotCompatibleNoPath : DiscoveryExceptions.RequiresInterpreterNotCompatible; } } else { resourceStr = DiscoveryExceptions.RequiresPSVersionNotCompatible; } return StringUtil.Format(resourceStr, commandName, first, second); } private static string BuildMessage(string commandName) { return StringUtil.Format(DiscoveryExceptions.RequiresElevation, commandName); } #endregion Private } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Framework.Profiler; using Microsoft.Build.Internal; using Microsoft.Build.Shared; namespace Microsoft.Build.Logging { /// <summary> /// Serializes BuildEventArgs-derived objects into a provided BinaryWriter /// </summary> internal class BuildEventArgsWriter { private readonly Stream originalStream; /// <summary> /// When writing the current record, first write it to a memory stream, /// then flush to the originalStream. This is needed so that if we discover /// that we need to write a string record in the middle of writing the /// current record, we will write the string record to the original stream /// and the current record will end up after the string record. /// </summary> private readonly MemoryStream currentRecordStream; /// <summary> /// The binary writer around the originalStream. /// </summary> private readonly BinaryWriter originalBinaryWriter; /// <summary> /// The binary writer around the currentRecordStream. /// </summary> private readonly BinaryWriter currentRecordWriter; /// <summary> /// The binary writer we're currently using. Is pointing at the currentRecordWriter usually, /// but sometimes we repoint it to the originalBinaryWriter temporarily, when writing string /// and name-value records. /// </summary> private BinaryWriter binaryWriter; /// <summary> /// Hashtable used for deduplicating strings. When we need to write a string, /// we check in this hashtable first, and if we've seen the string before, /// just write out its index. Otherwise write out a string record, and then /// write the string index. A string record is guaranteed to precede its first /// usage. /// The reader will read the string records first and then be able to retrieve /// a string by its index. This allows us to keep the format streaming instead /// of writing one giant string table at the end. If a binlog is interrupted /// we'll be able to use all the information we've discovered thus far. /// </summary> private readonly Dictionary<HashKey, int> stringHashes = new Dictionary<HashKey, int>(); /// <summary> /// Hashtable used for deduplicating name-value lists. Same as strings. /// </summary> private readonly Dictionary<HashKey, int> nameValueListHashes = new Dictionary<HashKey, int>(); /// <summary> /// Index 0 is null, Index 1 is the empty string. /// Reserve indices 2-9 for future use. Start indexing actual strings at 10. /// </summary> internal const int StringStartIndex = 10; /// <summary> /// Let's reserve a few indices for future use. /// </summary> internal const int NameValueRecordStartIndex = 10; /// <summary> /// 0 is null, 1 is empty string /// 2-9 are reserved for future use. /// Start indexing at 10. /// </summary> private int stringRecordId = StringStartIndex; /// <summary> /// The index of the next record to be written. /// </summary> private int nameValueRecordId = NameValueRecordStartIndex; /// <summary> /// A temporary buffer we use when writing a NameValueList record. Avoids allocating a list each time. /// </summary> private readonly List<KeyValuePair<string, string>> nameValueListBuffer = new List<KeyValuePair<string, string>>(1024); /// <summary> /// A temporary buffer we use when hashing a NameValueList record. Stores the indices of hashed strings /// instead of the actual names and values. /// </summary> private readonly List<KeyValuePair<int, int>> nameValueIndexListBuffer = new List<KeyValuePair<int, int>>(1024); /// <summary> /// Raised when an item is encountered with a hint to embed a file into the binlog. /// </summary> public event Action<string> EmbedFile; /// <summary> /// Initializes a new instance of BuildEventArgsWriter with a BinaryWriter /// </summary> /// <param name="binaryWriter">A BinaryWriter to write the BuildEventArgs instances to</param> public BuildEventArgsWriter(BinaryWriter binaryWriter) { this.originalStream = binaryWriter.BaseStream; // this doesn't exceed 30K for smaller binlogs so seems like a reasonable // starting point to avoid reallocations in the common case this.currentRecordStream = new MemoryStream(65536); this.originalBinaryWriter = binaryWriter; this.currentRecordWriter = new BinaryWriter(currentRecordStream); this.binaryWriter = currentRecordWriter; } /// <summary> /// Write a provided instance of BuildEventArgs to the BinaryWriter /// </summary> public void Write(BuildEventArgs e) { WriteCore(e); // flush the current record and clear the MemoryStream to prepare for next use currentRecordStream.WriteTo(originalStream); currentRecordStream.SetLength(0); } /* Base types and inheritance ("EventArgs" suffix omitted): Build Telemetry LazyFormattedBuild BuildMessage CriticalBuildMessage EnvironmentVariableRead MetaprojectGenerated ProjectImported PropertyInitialValueSet PropertyReassignment TargetSkipped TaskCommandLine TaskParameter UninitializedPropertyRead BuildStatus TaskStarted TaskFinished TargetStarted TargetFinished ProjectStarted ProjectFinished BuildStarted BuildFinished ProjectEvaluationStarted ProjectEvaluationFinished BuildError BuildWarning CustomBuild ExternalProjectStarted ExternalProjectFinished */ private void WriteCore(BuildEventArgs e) { switch (e) { case BuildMessageEventArgs buildMessage: Write(buildMessage); break; case TaskStartedEventArgs taskStarted: Write(taskStarted); break; case TaskFinishedEventArgs taskFinished: Write(taskFinished); break; case TargetStartedEventArgs targetStarted: Write(targetStarted); break; case TargetFinishedEventArgs targetFinished: Write(targetFinished); break; case BuildErrorEventArgs buildError: Write(buildError); break; case BuildWarningEventArgs buildWarning: Write(buildWarning); break; case ProjectStartedEventArgs projectStarted: Write(projectStarted); break; case ProjectFinishedEventArgs projectFinished: Write(projectFinished); break; case BuildStartedEventArgs buildStarted: Write(buildStarted); break; case BuildFinishedEventArgs buildFinished: Write(buildFinished); break; case ProjectEvaluationStartedEventArgs projectEvaluationStarted: Write(projectEvaluationStarted); break; case ProjectEvaluationFinishedEventArgs projectEvaluationFinished: Write(projectEvaluationFinished); break; default: // convert all unrecognized objects to message // and just preserve the message var buildMessageEventArgs = new BuildMessageEventArgs( e.Message, e.HelpKeyword, e.SenderName, MessageImportance.Normal, e.Timestamp); buildMessageEventArgs.BuildEventContext = e.BuildEventContext ?? BuildEventContext.Invalid; Write(buildMessageEventArgs); break; } } public void WriteBlob(BinaryLogRecordKind kind, byte[] bytes) { // write the blob directly to the underlying writer, // bypassing the memory stream using var redirection = RedirectWritesToOriginalWriter(); Write(kind); Write(bytes.Length); Write(bytes); } /// <summary> /// Switches the binaryWriter used by the Write* methods to the direct underlying stream writer /// until the disposable is disposed. Useful to bypass the currentRecordWriter to write a string, /// blob or NameValueRecord that should precede the record being currently written. /// </summary> private IDisposable RedirectWritesToOriginalWriter() { binaryWriter = originalBinaryWriter; return new RedirectionScope(this); } private struct RedirectionScope : IDisposable { private readonly BuildEventArgsWriter _writer; public RedirectionScope(BuildEventArgsWriter buildEventArgsWriter) { _writer = buildEventArgsWriter; } public void Dispose() { _writer.binaryWriter = _writer.currentRecordWriter; } } private void Write(BuildStartedEventArgs e) { Write(BinaryLogRecordKind.BuildStarted); WriteBuildEventArgsFields(e); Write(e.BuildEnvironment); } private void Write(BuildFinishedEventArgs e) { Write(BinaryLogRecordKind.BuildFinished); WriteBuildEventArgsFields(e); Write(e.Succeeded); } private void Write(ProjectEvaluationStartedEventArgs e) { Write(BinaryLogRecordKind.ProjectEvaluationStarted); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.ProjectFile); } private void Write(ProjectEvaluationFinishedEventArgs e) { Write(BinaryLogRecordKind.ProjectEvaluationFinished); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.ProjectFile); if (e.GlobalProperties == null) { Write(false); } else { Write(true); WriteProperties(e.GlobalProperties); } WriteProperties(e.Properties); WriteProjectItems(e.Items); var result = e.ProfilerResult; Write(result.HasValue); if (result.HasValue) { Write(result.Value.ProfiledLocations.Count); foreach (var item in result.Value.ProfiledLocations) { Write(item.Key); Write(item.Value); } } } private void Write(ProjectStartedEventArgs e) { Write(BinaryLogRecordKind.ProjectStarted); WriteBuildEventArgsFields(e, writeMessage: false); if (e.ParentProjectBuildEventContext == null) { Write(false); } else { Write(true); Write(e.ParentProjectBuildEventContext); } WriteDeduplicatedString(e.ProjectFile); Write(e.ProjectId); WriteDeduplicatedString(e.TargetNames); WriteDeduplicatedString(e.ToolsVersion); if (e.GlobalProperties == null) { Write(false); } else { Write(true); Write(e.GlobalProperties); } WriteProperties(e.Properties); WriteProjectItems(e.Items); } private void Write(ProjectFinishedEventArgs e) { Write(BinaryLogRecordKind.ProjectFinished); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.ProjectFile); Write(e.Succeeded); } private void Write(TargetStartedEventArgs e) { Write(BinaryLogRecordKind.TargetStarted); WriteBuildEventArgsFields(e, writeMessage: false); WriteDeduplicatedString(e.TargetName); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TargetFile); WriteDeduplicatedString(e.ParentTarget); Write((int)e.BuildReason); } private void Write(TargetFinishedEventArgs e) { Write(BinaryLogRecordKind.TargetFinished); WriteBuildEventArgsFields(e, writeMessage: false); Write(e.Succeeded); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TargetFile); WriteDeduplicatedString(e.TargetName); WriteTaskItemList(e.TargetOutputs); } private void Write(TaskStartedEventArgs e) { Write(BinaryLogRecordKind.TaskStarted); WriteBuildEventArgsFields(e, writeMessage: false, writeLineAndColumn: true); Write(e.LineNumber); Write(e.ColumnNumber); WriteDeduplicatedString(e.TaskName); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TaskFile); } private void Write(TaskFinishedEventArgs e) { Write(BinaryLogRecordKind.TaskFinished); WriteBuildEventArgsFields(e, writeMessage: false); Write(e.Succeeded); WriteDeduplicatedString(e.TaskName); WriteDeduplicatedString(e.ProjectFile); WriteDeduplicatedString(e.TaskFile); } private void Write(BuildErrorEventArgs e) { Write(BinaryLogRecordKind.Error); WriteBuildEventArgsFields(e); WriteDeduplicatedString(e.Subcategory); WriteDeduplicatedString(e.Code); WriteDeduplicatedString(e.File); WriteDeduplicatedString(e.ProjectFile); Write(e.LineNumber); Write(e.ColumnNumber); Write(e.EndLineNumber); Write(e.EndColumnNumber); } private void Write(BuildWarningEventArgs e) { Write(BinaryLogRecordKind.Warning); WriteBuildEventArgsFields(e); WriteDeduplicatedString(e.Subcategory); WriteDeduplicatedString(e.Code); WriteDeduplicatedString(e.File); WriteDeduplicatedString(e.ProjectFile); Write(e.LineNumber); Write(e.ColumnNumber); Write(e.EndLineNumber); Write(e.EndColumnNumber); } private void Write(BuildMessageEventArgs e) { switch (e) { case TaskParameterEventArgs taskParameter: Write(taskParameter); break; case ProjectImportedEventArgs projectImported: Write(projectImported); break; case TargetSkippedEventArgs targetSkipped: Write(targetSkipped); break; case PropertyReassignmentEventArgs propertyReassignment: Write(propertyReassignment); break; case TaskCommandLineEventArgs taskCommandLine: Write(taskCommandLine); break; case UninitializedPropertyReadEventArgs uninitializedPropertyRead: Write(uninitializedPropertyRead); break; case EnvironmentVariableReadEventArgs environmentVariableRead: Write(environmentVariableRead); break; case PropertyInitialValueSetEventArgs propertyInitialValueSet: Write(propertyInitialValueSet); break; case CriticalBuildMessageEventArgs criticalBuildMessage: Write(criticalBuildMessage); break; default: // actual BuildMessageEventArgs Write(BinaryLogRecordKind.Message); WriteMessageFields(e, writeImportance: true); break; } } private void Write(ProjectImportedEventArgs e) { Write(BinaryLogRecordKind.ProjectImported); WriteMessageFields(e); Write(e.ImportIgnored); WriteDeduplicatedString(e.ImportedProjectFile); WriteDeduplicatedString(e.UnexpandedProject); } private void Write(TargetSkippedEventArgs e) { Write(BinaryLogRecordKind.TargetSkipped); WriteMessageFields(e, writeMessage: false); WriteDeduplicatedString(e.TargetFile); WriteDeduplicatedString(e.TargetName); WriteDeduplicatedString(e.ParentTarget); WriteDeduplicatedString(e.Condition); WriteDeduplicatedString(e.EvaluatedCondition); Write(e.OriginallySucceeded); Write((int)e.BuildReason); Write((int)e.SkipReason); binaryWriter.WriteOptionalBuildEventContext(e.OriginalBuildEventContext); } private void Write(CriticalBuildMessageEventArgs e) { Write(BinaryLogRecordKind.CriticalBuildMessage); WriteMessageFields(e); } private void Write(PropertyReassignmentEventArgs e) { Write(BinaryLogRecordKind.PropertyReassignment); WriteMessageFields(e, writeMessage: false, writeImportance: true); WriteDeduplicatedString(e.PropertyName); WriteDeduplicatedString(e.PreviousValue); WriteDeduplicatedString(e.NewValue); WriteDeduplicatedString(e.Location); } private void Write(UninitializedPropertyReadEventArgs e) { Write(BinaryLogRecordKind.UninitializedPropertyRead); WriteMessageFields(e, writeImportance: true); WriteDeduplicatedString(e.PropertyName); } private void Write(PropertyInitialValueSetEventArgs e) { Write(BinaryLogRecordKind.PropertyInitialValueSet); WriteMessageFields(e, writeImportance: true); WriteDeduplicatedString(e.PropertyName); WriteDeduplicatedString(e.PropertyValue); WriteDeduplicatedString(e.PropertySource); } private void Write(EnvironmentVariableReadEventArgs e) { Write(BinaryLogRecordKind.EnvironmentVariableRead); WriteMessageFields(e, writeImportance: true); WriteDeduplicatedString(e.EnvironmentVariableName); } private void Write(TaskCommandLineEventArgs e) { Write(BinaryLogRecordKind.TaskCommandLine); WriteMessageFields(e, writeMessage: false, writeImportance: true); WriteDeduplicatedString(e.CommandLine); WriteDeduplicatedString(e.TaskName); } private void Write(TaskParameterEventArgs e) { Write(BinaryLogRecordKind.TaskParameter); WriteMessageFields(e, writeMessage: false); Write((int)e.Kind); WriteDeduplicatedString(e.ItemType); WriteTaskItemList(e.Items, e.LogItemMetadata); } private void WriteBuildEventArgsFields(BuildEventArgs e, bool writeMessage = true, bool writeLineAndColumn = false) { var flags = GetBuildEventArgsFieldFlags(e, writeMessage); if (writeLineAndColumn) { flags |= BuildEventArgsFieldFlags.LineNumber | BuildEventArgsFieldFlags.ColumnNumber; } Write((int)flags); WriteBaseFields(e, flags); } private void WriteBaseFields(BuildEventArgs e, BuildEventArgsFieldFlags flags) { if ((flags & BuildEventArgsFieldFlags.Message) != 0) { WriteDeduplicatedString(e.RawMessage); } if ((flags & BuildEventArgsFieldFlags.BuildEventContext) != 0) { Write(e.BuildEventContext); } if ((flags & BuildEventArgsFieldFlags.ThreadId) != 0) { Write(e.ThreadId); } if ((flags & BuildEventArgsFieldFlags.HelpKeyword) != 0) { WriteDeduplicatedString(e.HelpKeyword); } if ((flags & BuildEventArgsFieldFlags.SenderName) != 0) { WriteDeduplicatedString(e.SenderName); } if ((flags & BuildEventArgsFieldFlags.Timestamp) != 0) { Write(e.Timestamp); } } private void WriteMessageFields(BuildMessageEventArgs e, bool writeMessage = true, bool writeImportance = false) { var flags = GetBuildEventArgsFieldFlags(e, writeMessage); flags = GetMessageFlags(e, flags, writeMessage, writeImportance); Write((int)flags); WriteBaseFields(e, flags); if ((flags & BuildEventArgsFieldFlags.Subcategory) != 0) { WriteDeduplicatedString(e.Subcategory); } if ((flags & BuildEventArgsFieldFlags.Code) != 0) { WriteDeduplicatedString(e.Code); } if ((flags & BuildEventArgsFieldFlags.File) != 0) { WriteDeduplicatedString(e.File); } if ((flags & BuildEventArgsFieldFlags.ProjectFile) != 0) { WriteDeduplicatedString(e.ProjectFile); } if ((flags & BuildEventArgsFieldFlags.LineNumber) != 0) { Write(e.LineNumber); } if ((flags & BuildEventArgsFieldFlags.ColumnNumber) != 0) { Write(e.ColumnNumber); } if ((flags & BuildEventArgsFieldFlags.EndLineNumber) != 0) { Write(e.EndLineNumber); } if ((flags & BuildEventArgsFieldFlags.EndColumnNumber) != 0) { Write(e.EndColumnNumber); } if ((flags & BuildEventArgsFieldFlags.Arguments) != 0) { Write(e.RawArguments.Length); for (int i = 0; i < e.RawArguments.Length; i++) { string argument = Convert.ToString(e.RawArguments[i], CultureInfo.CurrentCulture); WriteDeduplicatedString(argument); } } if ((flags & BuildEventArgsFieldFlags.Importance) != 0) { Write((int)e.Importance); } } private static BuildEventArgsFieldFlags GetMessageFlags(BuildMessageEventArgs e, BuildEventArgsFieldFlags flags, bool writeMessage = true, bool writeImportance = false) { if (e.Subcategory != null) { flags |= BuildEventArgsFieldFlags.Subcategory; } if (e.Code != null) { flags |= BuildEventArgsFieldFlags.Code; } if (e.File != null) { flags |= BuildEventArgsFieldFlags.File; } if (e.ProjectFile != null) { flags |= BuildEventArgsFieldFlags.ProjectFile; } if (e.LineNumber != 0) { flags |= BuildEventArgsFieldFlags.LineNumber; } if (e.ColumnNumber != 0) { flags |= BuildEventArgsFieldFlags.ColumnNumber; } if (e.EndLineNumber != 0) { flags |= BuildEventArgsFieldFlags.EndLineNumber; } if (e.EndColumnNumber != 0) { flags |= BuildEventArgsFieldFlags.EndColumnNumber; } if (writeMessage && e.RawArguments != null && e.RawArguments.Length > 0) { flags |= BuildEventArgsFieldFlags.Arguments; } if (writeImportance && e.Importance != MessageImportance.Low) { flags |= BuildEventArgsFieldFlags.Importance; } return flags; } private static BuildEventArgsFieldFlags GetBuildEventArgsFieldFlags(BuildEventArgs e, bool writeMessage = true) { var flags = BuildEventArgsFieldFlags.None; if (e.BuildEventContext != null) { flags |= BuildEventArgsFieldFlags.BuildEventContext; } if (e.HelpKeyword != null) { flags |= BuildEventArgsFieldFlags.HelpKeyword; } if (writeMessage) { flags |= BuildEventArgsFieldFlags.Message; } // no need to waste space for the default sender name if (e.SenderName != null && e.SenderName != "MSBuild") { flags |= BuildEventArgsFieldFlags.SenderName; } // ThreadId never seems to be used or useful for anything. //if (e.ThreadId > 0) //{ // flags |= BuildEventArgsFieldFlags.ThreadId; //} if (e.Timestamp != default(DateTime)) { flags |= BuildEventArgsFieldFlags.Timestamp; } return flags; } // Both of these are used simultaneously so can't just have a single list private readonly List<object> reusableItemsList = new List<object>(); private readonly List<object> reusableProjectItemList = new List<object>(); private void WriteTaskItemList(IEnumerable items, bool writeMetadata = true) { if (items == null) { Write(false); return; } // For target outputs bypass copying of all items to save on performance. // The proxy creates a deep clone of each item to protect against writes, // but since we're not writing we don't need the deep cloning. // Additionally, it is safe to access the underlying List<ITaskItem> as it's allocated // in a single location and noboby else mutates it after that: // https://github.com/dotnet/msbuild/blob/f0eebf2872d76ab0cd43fdc4153ba636232b222f/src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs#L564 if (items is TargetLoggingContext.TargetOutputItemsInstanceEnumeratorProxy proxy) { items = proxy.BackingItems; } int count; if (items is ICollection arrayList) { count = arrayList.Count; } else if (items is ICollection<ITaskItem> genericList) { count = genericList.Count; } else { // enumerate only once foreach (var item in items) { if (item != null) { reusableItemsList.Add(item); } } items = reusableItemsList; count = reusableItemsList.Count; } Write(count); foreach (var item in items) { if (item is ITaskItem taskItem) { Write(taskItem, writeMetadata); } else { WriteDeduplicatedString(item?.ToString() ?? ""); // itemspec Write(0); // no metadata } } reusableItemsList.Clear(); } private void WriteProjectItems(IEnumerable items) { if (items == null) { Write(0); return; } if (items is ItemDictionary<ProjectItemInstance> itemInstanceDictionary) { // If we have access to the live data from evaluation, it exposes a special method // to iterate the data structure under a lock and return results grouped by item type. // There's no need to allocate or call GroupBy this way. itemInstanceDictionary.EnumerateItemsPerType((itemType, itemList) => { WriteDeduplicatedString(itemType); WriteTaskItemList(itemList); CheckForFilesToEmbed(itemType, itemList); }); // signal the end Write(0); } // not sure when this can get hit, but best to be safe and support this else if (items is ItemDictionary<ProjectItem> itemDictionary) { itemDictionary.EnumerateItemsPerType((itemType, itemList) => { WriteDeduplicatedString(itemType); WriteTaskItemList(itemList); CheckForFilesToEmbed(itemType, itemList); }); // signal the end Write(0); } else { string currentItemType = null; // Write out a sequence of items for each item type while avoiding GroupBy // and associated allocations. We rely on the fact that items of each type // are contiguous. For each item type, write the item type name and the list // of items. Write 0 at the end (which would correspond to item type null). // This is how the reader will know how to stop. We can't write out the // count of item types at the beginning because we don't know how many there // will be (we'd have to enumerate twice to calculate that). This scheme // allows us to stream in a single pass with no allocations for intermediate // results. Internal.Utilities.EnumerateItems(items, dictionaryEntry => { string key = (string)dictionaryEntry.Key; // boundary between item types if (currentItemType != null && currentItemType != key) { WriteDeduplicatedString(currentItemType); WriteTaskItemList(reusableProjectItemList); CheckForFilesToEmbed(currentItemType, reusableProjectItemList); reusableProjectItemList.Clear(); } reusableProjectItemList.Add(dictionaryEntry.Value); currentItemType = key; }); // write out the last item type if (reusableProjectItemList.Count > 0) { WriteDeduplicatedString(currentItemType); WriteTaskItemList(reusableProjectItemList); CheckForFilesToEmbed(currentItemType, reusableProjectItemList); reusableProjectItemList.Clear(); } // signal the end Write(0); } } private void CheckForFilesToEmbed(string itemType, object itemList) { if (EmbedFile == null || !string.Equals(itemType, ItemTypeNames.EmbedInBinlog, StringComparison.OrdinalIgnoreCase) || itemList is not IEnumerable list) { return; } foreach (var item in list) { if (item is ITaskItem taskItem && !string.IsNullOrEmpty(taskItem.ItemSpec)) { EmbedFile.Invoke(taskItem.ItemSpec); } else if (item is string itemSpec && !string.IsNullOrEmpty(itemSpec)) { EmbedFile.Invoke(itemSpec); } } } private void Write(ITaskItem item, bool writeMetadata = true) { WriteDeduplicatedString(item.ItemSpec); if (!writeMetadata) { Write((byte)0); return; } // WARNING: Can't use AddRange here because CopyOnWriteDictionary in Microsoft.Build.Utilities.v4.0.dll // is broken. Microsoft.Build.Utilities.v4.0.dll loads from the GAC by XAML markup tooling and it's // implementation doesn't work with AddRange because AddRange special-cases ICollection<T> and // CopyOnWriteDictionary doesn't implement it properly. foreach (var kvp in item.EnumerateMetadata()) { nameValueListBuffer.Add(kvp); } // Don't sort metadata because we want the binary log to be fully roundtrippable // and we need to preserve the original order. //if (nameValueListBuffer.Count > 1) //{ // nameValueListBuffer.Sort((l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.Key, r.Key)); //} WriteNameValueList(); nameValueListBuffer.Clear(); } private void WriteProperties(IEnumerable properties) { if (properties == null) { Write(0); return; } Internal.Utilities.EnumerateProperties(properties, kvp => nameValueListBuffer.Add(kvp)); WriteNameValueList(); nameValueListBuffer.Clear(); } private void Write(BuildEventContext buildEventContext) { Write(buildEventContext.NodeId); Write(buildEventContext.ProjectContextId); Write(buildEventContext.TargetId); Write(buildEventContext.TaskId); Write(buildEventContext.SubmissionId); Write(buildEventContext.ProjectInstanceId); Write(buildEventContext.EvaluationId); } private void Write(IEnumerable<KeyValuePair<string, string>> keyValuePairs) { if (keyValuePairs != null) { foreach (var kvp in keyValuePairs) { nameValueListBuffer.Add(kvp); } } WriteNameValueList(); nameValueListBuffer.Clear(); } private void WriteNameValueList() { if (nameValueListBuffer.Count == 0) { Write((byte)0); return; } HashKey hash = HashAllStrings(nameValueListBuffer); if (!nameValueListHashes.TryGetValue(hash, out var recordId)) { recordId = nameValueRecordId; nameValueListHashes[hash] = nameValueRecordId; WriteNameValueListRecord(); nameValueRecordId += 1; } Write(recordId); } /// <summary> /// In the middle of writing the current record we may discover that we want to write another record /// preceding the current one, specifically the list of names and values we want to reuse in the /// future. As we are writing the current record to a MemoryStream first, it's OK to temporarily /// switch to the direct underlying stream and write the NameValueList record first. /// When the current record is done writing, the MemoryStream will flush to the underlying stream /// and the current record will end up after the NameValueList record, as desired. /// </summary> private void WriteNameValueListRecord() { // Switch the binaryWriter used by the Write* methods to the direct underlying stream writer. // We want this record to precede the record we're currently writing to currentRecordWriter // which is backed by a MemoryStream buffer using var redirectionScope = RedirectWritesToOriginalWriter(); Write(BinaryLogRecordKind.NameValueList); Write(nameValueIndexListBuffer.Count); for (int i = 0; i < nameValueListBuffer.Count; i++) { var kvp = nameValueIndexListBuffer[i]; Write(kvp.Key); Write(kvp.Value); } } /// <summary> /// Compute the total hash of all items in the nameValueList /// while simultaneously filling the nameValueIndexListBuffer with the individual /// hashes of the strings, mirroring the strings in the original nameValueList. /// This helps us avoid hashing strings twice (once to hash the string individually /// and the second time when hashing it as part of the nameValueList) /// </summary> private HashKey HashAllStrings(List<KeyValuePair<string, string>> nameValueList) { HashKey hash = new HashKey(); nameValueIndexListBuffer.Clear(); for (int i = 0; i < nameValueList.Count; i++) { var kvp = nameValueList[i]; var (keyIndex, keyHash) = HashString(kvp.Key); var (valueIndex, valueHash) = HashString(kvp.Value); hash = hash.Add(keyHash); hash = hash.Add(valueHash); nameValueIndexListBuffer.Add(new KeyValuePair<int, int>(keyIndex, valueIndex)); } return hash; } private void Write(BinaryLogRecordKind kind) { Write((int)kind); } private void Write(int value) { BinaryWriterExtensions.Write7BitEncodedInt(binaryWriter, value); } private void Write(long value) { binaryWriter.Write(value); } private void Write(byte[] bytes) { binaryWriter.Write(bytes); } private void Write(byte b) { binaryWriter.Write(b); } private void Write(bool boolean) { binaryWriter.Write(boolean); } private void WriteDeduplicatedString(string text) { var (recordId, _) = HashString(text); Write(recordId); } /// <summary> /// Hash the string and write a String record if not already hashed. /// </summary> /// <returns>Returns the string record index as well as the hash.</returns> private (int index, HashKey hash) HashString(string text) { if (text == null) { return (0, default); } else if (text.Length == 0) { return (1, default); } var hash = new HashKey(text); if (!stringHashes.TryGetValue(hash, out var recordId)) { recordId = stringRecordId; stringHashes[hash] = stringRecordId; WriteStringRecord(text); stringRecordId += 1; } return (recordId, hash); } private void WriteStringRecord(string text) { using var redirectionScope = RedirectWritesToOriginalWriter(); Write(BinaryLogRecordKind.String); binaryWriter.Write(text); } private void Write(DateTime timestamp) { binaryWriter.Write(timestamp.Ticks); Write((int)timestamp.Kind); } private void Write(TimeSpan timeSpan) { binaryWriter.Write(timeSpan.Ticks); } private void Write(EvaluationLocation item) { WriteDeduplicatedString(item.ElementName); WriteDeduplicatedString(item.ElementDescription); WriteDeduplicatedString(item.EvaluationPassDescription); WriteDeduplicatedString(item.File); Write((int)item.Kind); Write((int)item.EvaluationPass); Write(item.Line.HasValue); if (item.Line.HasValue) { Write(item.Line.Value); } Write(item.Id); Write(item.ParentId.HasValue); if (item.ParentId.HasValue) { Write(item.ParentId.Value); } } private void Write(ProfiledLocation e) { Write(e.NumberOfHits); Write(e.ExclusiveTime); Write(e.InclusiveTime); } internal readonly struct HashKey : IEquatable<HashKey> { private readonly ulong value; private HashKey(ulong i) { value = i; } public HashKey(string text) { if (text == null) { value = 0; } else { value = FnvHash64.GetHashCode(text); } } public static HashKey Combine(HashKey left, HashKey right) { return new HashKey(FnvHash64.Combine(left.value, right.value)); } public HashKey Add(HashKey other) => Combine(this, other); public bool Equals(HashKey other) { return value == other.value; } public override bool Equals(object obj) { if (obj is HashKey other) { return Equals(other); } return false; } public override int GetHashCode() { return unchecked((int)value); } public override string ToString() { return value.ToString(); } } internal static class FnvHash64 { public const ulong Offset = 14695981039346656037; public const ulong Prime = 1099511628211; public static ulong GetHashCode(string text) { ulong hash = Offset; unchecked { for (int i = 0; i < text.Length; i++) { char ch = text[i]; hash = (hash ^ ch) * Prime; } } return hash; } public static ulong Combine(ulong left, ulong right) { unchecked { return (left ^ right) * Prime; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using Xunit; namespace System.Numerics.Tests { public class cast_toTest { public delegate void ExceptionGenerator(); private const int NumberOfRandomIterations = 10; private static Random s_random = new Random(100); [Fact] public static void RunByteImplicitCastToBigIntegerTests() { // Byte Implicit Cast to BigInteger: Byte.MinValue VerifyByteImplicitCastToBigInteger(Byte.MinValue); // Byte Implicit Cast to BigInteger: 0 VerifyByteImplicitCastToBigInteger(0); // Byte Implicit Cast to BigInteger: 1 VerifyByteImplicitCastToBigInteger(1); // Byte Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyByteImplicitCastToBigInteger((Byte)s_random.Next(1, Byte.MaxValue)); } // Byte Implicit Cast to BigInteger: Byte.MaxValue VerifyByteImplicitCastToBigInteger(Byte.MaxValue); } [Fact] public static void RunSByteImplicitCastToBigIntegerTests() { // SByte Implicit Cast to BigInteger: SByte.MinValue VerifySByteImplicitCastToBigInteger(SByte.MinValue); // SByte Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySByteImplicitCastToBigInteger((SByte)s_random.Next(SByte.MinValue, 0)); } // SByte Implicit Cast to BigInteger: -1 VerifySByteImplicitCastToBigInteger(-1); // SByte Implicit Cast to BigInteger: 0 VerifySByteImplicitCastToBigInteger(0); // SByte Implicit Cast to BigInteger: 1 VerifySByteImplicitCastToBigInteger(1); // SByte Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySByteImplicitCastToBigInteger((SByte)s_random.Next(1, SByte.MaxValue)); } // SByte Implicit Cast to BigInteger: SByte.MaxValue VerifySByteImplicitCastToBigInteger(SByte.MaxValue); } [Fact] public static void RunUInt16ImplicitCastToBigIntegerTests() { // UInt16 Implicit Cast to BigInteger: UInt16.MinValue VerifyUInt16ImplicitCastToBigInteger(UInt16.MinValue); // UInt16 Implicit Cast to BigInteger: 0 VerifyUInt16ImplicitCastToBigInteger(0); // UInt16 Implicit Cast to BigInteger: 1 VerifyUInt16ImplicitCastToBigInteger(1); // UInt16 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt16ImplicitCastToBigInteger((UInt16)s_random.Next(1, UInt16.MaxValue)); } // UInt16 Implicit Cast to BigInteger: UInt16.MaxValue VerifyUInt16ImplicitCastToBigInteger(UInt16.MaxValue); } [Fact] public static void RunInt16ImplicitCastToBigIntegerTests() { // Int16 Implicit Cast to BigInteger: Int16.MinValue VerifyInt16ImplicitCastToBigInteger(Int16.MinValue); // Int16 Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt16ImplicitCastToBigInteger((Int16)s_random.Next(Int16.MinValue, 0)); } // Int16 Implicit Cast to BigInteger: -1 VerifyInt16ImplicitCastToBigInteger(-1); // Int16 Implicit Cast to BigInteger: 0 VerifyInt16ImplicitCastToBigInteger(0); // Int16 Implicit Cast to BigInteger: 1 VerifyInt16ImplicitCastToBigInteger(1); // Int16 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt16ImplicitCastToBigInteger((Int16)s_random.Next(1, Int16.MaxValue)); } // Int16 Implicit Cast to BigInteger: Int16.MaxValue VerifyInt16ImplicitCastToBigInteger(Int16.MaxValue); } [Fact] public static void RunUInt32ImplicitCastToBigIntegerTests() { // UInt32 Implicit Cast to BigInteger: UInt32.MinValue VerifyUInt32ImplicitCastToBigInteger(UInt32.MinValue); // UInt32 Implicit Cast to BigInteger: 0 VerifyUInt32ImplicitCastToBigInteger(0); // UInt32 Implicit Cast to BigInteger: 1 VerifyUInt32ImplicitCastToBigInteger(1); // UInt32 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt32ImplicitCastToBigInteger((UInt32)(UInt32.MaxValue * s_random.NextDouble())); } // UInt32 Implicit Cast to BigInteger: UInt32.MaxValue VerifyUInt32ImplicitCastToBigInteger(UInt32.MaxValue); } [Fact] public static void RunInt32ImplicitCastToBigIntegerTests() { // Int32 Implicit Cast to BigInteger: Int32.MinValue VerifyInt32ImplicitCastToBigInteger(Int32.MinValue); // Int32 Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt32ImplicitCastToBigInteger((Int32)s_random.Next(Int32.MinValue, 0)); } // Int32 Implicit Cast to BigInteger: -1 VerifyInt32ImplicitCastToBigInteger(-1); // Int32 Implicit Cast to BigInteger: 0 VerifyInt32ImplicitCastToBigInteger(0); // Int32 Implicit Cast to BigInteger: 1 VerifyInt32ImplicitCastToBigInteger(1); // Int32 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt32ImplicitCastToBigInteger((Int32)s_random.Next(1, Int32.MaxValue)); } // Int32 Implicit Cast to BigInteger: Int32.MaxValue VerifyInt32ImplicitCastToBigInteger(Int32.MaxValue); } [Fact] public static void RunUInt64ImplicitCastToBigIntegerTests() { // UInt64 Implicit Cast to BigInteger: UInt64.MinValue VerifyUInt64ImplicitCastToBigInteger(UInt64.MinValue); // UInt64 Implicit Cast to BigInteger: 0 VerifyUInt64ImplicitCastToBigInteger(0); // UInt64 Implicit Cast to BigInteger: 1 VerifyUInt64ImplicitCastToBigInteger(1); // UInt64 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt64ImplicitCastToBigInteger((UInt64)(UInt64.MaxValue * s_random.NextDouble())); } // UInt64 Implicit Cast to BigInteger: UInt64.MaxValue VerifyUInt64ImplicitCastToBigInteger(UInt64.MaxValue); } [Fact] public static void RunInt64ImplicitCastToBigIntegerTests() { // Int64 Implicit Cast to BigInteger: Int64.MinValue VerifyInt64ImplicitCastToBigInteger(Int64.MinValue); // Int64 Implicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt64ImplicitCastToBigInteger(((Int64)(Int64.MaxValue * s_random.NextDouble())) - Int64.MaxValue); } // Int64 Implicit Cast to BigInteger: -1 VerifyInt64ImplicitCastToBigInteger(-1); // Int64 Implicit Cast to BigInteger: 0 VerifyInt64ImplicitCastToBigInteger(0); // Int64 Implicit Cast to BigInteger: 1 VerifyInt64ImplicitCastToBigInteger(1); // Int64 Implicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt64ImplicitCastToBigInteger((Int64)(Int64.MaxValue * s_random.NextDouble())); } // Int64 Implicit Cast to BigInteger: Int64.MaxValue VerifyInt64ImplicitCastToBigInteger(Int64.MaxValue); } [Fact] public static void RunSingleExplicitCastToBigIntegerTests() { Single value; // Single Explicit Cast to BigInteger: Single.NegativeInfinity VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)Single.NegativeInfinity; }); // Single Explicit Cast to BigInteger: Single.MinValue VerifySingleExplicitCastToBigInteger(Single.MinValue); // Single Explicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue); } // Single Explicit Cast to BigInteger: Random Non-Integral Negative > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger((Single)(-100 * s_random.NextDouble())); } // Single Explicit Cast to BigInteger: -1 VerifySingleExplicitCastToBigInteger(-1); // Single Explicit Cast to BigInteger: 0 VerifySingleExplicitCastToBigInteger(0); // Single Explicit Cast to BigInteger: 1 VerifySingleExplicitCastToBigInteger(1); // Single Explicit Cast to BigInteger: Random Non-Integral Positive < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger((Single)(100 * s_random.NextDouble())); } // Single Explicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastToBigInteger((Single)(Single.MaxValue * s_random.NextDouble())); } // Single Explicit Cast to BigInteger: Single.MaxValue VerifySingleExplicitCastToBigInteger(Single.MaxValue); // Single Explicit Cast to BigInteger: Single.PositiveInfinity VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)Single.PositiveInfinity; }); // Single Explicit Cast to BigInteger: Single.Epsilon VerifySingleExplicitCastToBigInteger(Single.Epsilon); // Single Explicit Cast to BigInteger: Single.NaN VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)Single.NaN; }); //There are multiple ways to represent a NaN just try another one // Single Explicit Cast to BigInteger: Single.NaN 2 VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)ConvertInt32ToSingle(0x7FC00000); }); // Single Explicit Cast to BigInteger: Smallest Exponent VerifySingleExplicitCastToBigInteger((Single)Math.Pow(2, -126)); // Single Explicit Cast to BigInteger: Largest Exponent VerifySingleExplicitCastToBigInteger((Single)Math.Pow(2, 127)); // Single Explicit Cast to BigInteger: Largest number less then 1 value = 0; for (int i = 1; i <= 24; ++i) { value += (Single)(Math.Pow(2, -i)); } VerifySingleExplicitCastToBigInteger(value); // Single Explicit Cast to BigInteger: Smallest number greater then 1 value = (Single)(1 + Math.Pow(2, -23)); VerifySingleExplicitCastToBigInteger(value); // Single Explicit Cast to BigInteger: Largest number less then 2 value = 0; for (int i = 1; i <= 23; ++i) { value += (Single)(Math.Pow(2, -i)); } value += 1; VerifySingleExplicitCastToBigInteger(value); } [Fact] public static void RunDoubleExplicitCastToBigIntegerTests() { Double value; // Double Explicit Cast to BigInteger: Double.NegativeInfinity VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)Double.NegativeInfinity; }); // Double Explicit Cast to BigInteger: Double.MinValue VerifyDoubleExplicitCastToBigInteger(Double.MinValue); // Double Explicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger(((Double)(Double.MaxValue * s_random.NextDouble())) - Double.MaxValue); } // Double Explicit Cast to BigInteger: Random Non-Integral Negative > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger((Double)(-100 * s_random.NextDouble())); } // Double Explicit Cast to BigInteger: -1 VerifyDoubleExplicitCastToBigInteger(-1); // Double Explicit Cast to BigInteger: 0 VerifyDoubleExplicitCastToBigInteger(0); // Double Explicit Cast to BigInteger: 1 VerifyDoubleExplicitCastToBigInteger(1); // Double Explicit Cast to BigInteger: Random Non-Integral Positive < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger((Double)(100 * s_random.NextDouble())); } // Double Explicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastToBigInteger((Double)(Double.MaxValue * s_random.NextDouble())); } // Double Explicit Cast to BigInteger: Double.MaxValue VerifyDoubleExplicitCastToBigInteger(Double.MaxValue); // Double Explicit Cast to BigInteger: Double.PositiveInfinity VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)Double.PositiveInfinity; }); // Double Explicit Cast to BigInteger: Double.Epsilon VerifyDoubleExplicitCastToBigInteger(Double.Epsilon); // Double Explicit Cast to BigInteger: Double.NaN VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)Double.NaN; }); //There are multiple ways to represent a NaN just try another one // Double Explicit Cast to BigInteger: Double.NaN 2 VerifyException<OverflowException>(delegate () { BigInteger temp = (BigInteger)ConvertInt64ToDouble(0x7FF8000000000000); }); // Double Explicit Cast to BigInteger: Smallest Exponent VerifyDoubleExplicitCastToBigInteger((Double)Math.Pow(2, -1022)); // Double Explicit Cast to BigInteger: Largest Exponent VerifyDoubleExplicitCastToBigInteger((Double)Math.Pow(2, 1023)); // Double Explicit Cast to BigInteger: Largest number less then 1 value = 0; for (int i = 1; i <= 53; ++i) { value += (Double)(Math.Pow(2, -i)); } VerifyDoubleExplicitCastToBigInteger(value); // Double Explicit Cast to BigInteger: Smallest number greater then 1 value = (Double)(1 + Math.Pow(2, -52)); VerifyDoubleExplicitCastToBigInteger(value); // Double Explicit Cast to BigInteger: Largest number less then 2 value = 0; for (int i = 1; i <= 52; ++i) { value += (Double)(Math.Pow(2, -i)); } value += 1; VerifyDoubleExplicitCastToBigInteger(value); } [Fact] public static void RunDecimalExplicitCastToBigIntegerTests() { Decimal value; // Decimal Explicit Cast to BigInteger: Decimal.MinValue VerifyDecimalExplicitCastToBigInteger(Decimal.MinValue); // Decimal Explicit Cast to BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), true, (byte)s_random.Next(0, 29)); VerifyDecimalExplicitCastToBigInteger(value); } // Decimal Explicit Cast to BigInteger: -1 VerifyDecimalExplicitCastToBigInteger(-1); // Decimal Explicit Cast to BigInteger: 0 VerifyDecimalExplicitCastToBigInteger(0); // Decimal Explicit Cast to BigInteger: 1 VerifyDecimalExplicitCastToBigInteger(1); // Decimal Explicit Cast to BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), false, (byte)s_random.Next(0, 29)); VerifyDecimalExplicitCastToBigInteger(value); } // Decimal Explicit Cast to BigInteger: Decimal.MaxValue VerifyDecimalExplicitCastToBigInteger(Decimal.MaxValue); // Decimal Explicit Cast to BigInteger: Smallest Exponent unchecked { value = new Decimal(1, 0, 0, false, 0); } VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest Exponent and zero integer unchecked { value = new Decimal(0, 0, 0, false, 28); } VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest Exponent and non zero integer unchecked { value = new Decimal(1, 0, 0, false, 28); } VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest number less then 1 value = 1 - new Decimal(1, 0, 0, false, 28); VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Smallest number greater then 1 value = 1 + new Decimal(1, 0, 0, false, 28); VerifyDecimalExplicitCastToBigInteger(value); // Decimal Explicit Cast to BigInteger: Largest number less then 2 value = 2 - new Decimal(1, 0, 0, false, 28); VerifyDecimalExplicitCastToBigInteger(value); } private static Single ConvertInt32ToSingle(Int32 value) { return BitConverter.ToSingle(BitConverter.GetBytes(value), 0); } private static Double ConvertInt64ToDouble(Int64 value) { return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); } private static void VerifyByteImplicitCastToBigInteger(Byte value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Byte)bigInteger); if (value != Byte.MaxValue) { Assert.Equal((Byte)(value + 1), (Byte)(bigInteger + 1)); } if (value != Byte.MinValue) { Assert.Equal((Byte)(value - 1), (Byte)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifySByteImplicitCastToBigInteger(SByte value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (SByte)bigInteger); if (value != SByte.MaxValue) { Assert.Equal((SByte)(value + 1), (SByte)(bigInteger + 1)); } if (value != SByte.MinValue) { Assert.Equal((SByte)(value - 1), (SByte)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyUInt16ImplicitCastToBigInteger(UInt16 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (UInt16)bigInteger); if (value != UInt16.MaxValue) { Assert.Equal((UInt16)(value + 1), (UInt16)(bigInteger + 1)); } if (value != UInt16.MinValue) { Assert.Equal((UInt16)(value - 1), (UInt16)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyInt16ImplicitCastToBigInteger(Int16 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Int16)bigInteger); if (value != Int16.MaxValue) { Assert.Equal((Int16)(value + 1), (Int16)(bigInteger + 1)); } if (value != Int16.MinValue) { Assert.Equal((Int16)(value - 1), (Int16)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyUInt32ImplicitCastToBigInteger(UInt32 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (UInt32)bigInteger); if (value != UInt32.MaxValue) { Assert.Equal((UInt32)(value + 1), (UInt32)(bigInteger + 1)); } if (value != UInt32.MinValue) { Assert.Equal((UInt32)(value - 1), (UInt32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyInt32ImplicitCastToBigInteger(Int32 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Int32)bigInteger); if (value != Int32.MaxValue) { Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1)); } if (value != Int32.MinValue) { Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyUInt64ImplicitCastToBigInteger(UInt64 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (UInt64)bigInteger); if (value != UInt64.MaxValue) { Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1)); } if (value != UInt64.MinValue) { Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifyInt64ImplicitCastToBigInteger(Int64 value) { BigInteger bigInteger = value; Assert.Equal(value, bigInteger); Assert.Equal(value.ToString(), bigInteger.ToString()); Assert.Equal(value, (Int64)bigInteger); if (value != Int64.MaxValue) { Assert.Equal((Int64)(value + 1), (Int64)(bigInteger + 1)); } if (value != Int64.MinValue) { Assert.Equal((Int64)(value - 1), (Int64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } private static void VerifySingleExplicitCastToBigInteger(Single value) { Single expectedValue; BigInteger bigInteger; if (value < 0) { expectedValue = (Single)Math.Ceiling(value); } else { expectedValue = (Single)Math.Floor(value); } bigInteger = (BigInteger)value; Assert.Equal(expectedValue, (Single)bigInteger); // Single can only accurately represent integers between -16777216 and 16777216 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 16777216 && -16777216 < expectedValue) { Assert.Equal(expectedValue.ToString("G9"), bigInteger.ToString()); } if (expectedValue != Math.Floor(Single.MaxValue)) { Assert.Equal((Single)(expectedValue + 1), (Single)(bigInteger + 1)); } if (expectedValue != Math.Ceiling(Single.MinValue)) { Assert.Equal((Single)(expectedValue - 1), (Single)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } private static void VerifyDoubleExplicitCastToBigInteger(Double value) { Double expectedValue; BigInteger bigInteger; if (value < 0) { expectedValue = Math.Ceiling(value); } else { expectedValue = Math.Floor(value); } bigInteger = (BigInteger)value; Assert.Equal(expectedValue, (Double)bigInteger); // Double can only accurately represent integers between -9007199254740992 and 9007199254740992 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue) { Assert.Equal(expectedValue.ToString(), bigInteger.ToString()); } if (!Single.IsInfinity((Single)expectedValue)) { Assert.Equal((Double)(expectedValue + 1), (Double)(bigInteger + 1)); Assert.Equal((Double)(expectedValue - 1), (Double)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } private static void VerifyDecimalExplicitCastToBigInteger(Decimal value) { Decimal expectedValue; BigInteger bigInteger; if (value < 0) { expectedValue = Math.Ceiling(value); } else { expectedValue = Math.Floor(value); } bigInteger = (BigInteger)value; Assert.Equal(expectedValue.ToString(), bigInteger.ToString()); Assert.Equal(expectedValue, (Decimal)bigInteger); VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); if (expectedValue != Math.Floor(Decimal.MaxValue)) { Assert.Equal((Decimal)(expectedValue + 1), (Decimal)(bigInteger + 1)); } if (expectedValue != Math.Ceiling(Decimal.MinValue)) { Assert.Equal((Decimal)(expectedValue - 1), (Decimal)(bigInteger - 1)); } } private static void VerifyBigIntegerUsingIdentities(BigInteger bigInteger, bool isZero) { BigInteger tempBigInteger = new BigInteger(bigInteger.ToByteArray()); Assert.Equal(bigInteger, tempBigInteger); if (isZero) { Assert.Equal(BigInteger.Zero, bigInteger); } else { Assert.NotEqual(BigInteger.Zero, bigInteger); // x/x = 1 Assert.Equal(BigInteger.One, bigInteger / bigInteger); } // (x + 1) - 1 = x Assert.Equal(bigInteger, (bigInteger + BigInteger.One) - BigInteger.One); // (x + 1) - x = 1 Assert.Equal(BigInteger.One, (bigInteger + BigInteger.One) - bigInteger); // x - x = 0 Assert.Equal(BigInteger.Zero, bigInteger - bigInteger); // x + x = 2x Assert.Equal(2 * bigInteger, bigInteger + bigInteger); // x/1 = x Assert.Equal(bigInteger, bigInteger / BigInteger.One); // 1 * x = x Assert.Equal(bigInteger, BigInteger.One * bigInteger); } public static void VerifyException<T>(ExceptionGenerator exceptionGenerator) where T : Exception { VerifyException(typeof(T), exceptionGenerator); } public static void VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator) { try { exceptionGenerator(); Assert.True(false, String.Format("Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown", expectedExceptionType)); } catch (Exception exception) { Assert.Equal(expectedExceptionType, exception.GetType()); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using NHibernate; using NHibernate.Collection; using NHibernate.DebugHelpers; using NHibernate.Engine; using NHibernate.Loader; using NHibernate.Persister.Collection; using NHibernate.Type; using NHibernate.Util; namespace Sharetronix.Cfg.ForNHibernate { public class Net4CollectionTypeFactory : DefaultCollectionTypeFactory { public override CollectionType Set<T>(string role, string propertyRef, bool embedded) { return new GenericSetType<T>(role, propertyRef); } public override CollectionType SortedSet<T>(string role, string propertyRef, bool embedded, IComparer<T> comparer) { return new GenericSortedSetType<T>(role, propertyRef, comparer); } } [Serializable] public class GenericSortedSetType<T> : GenericSetType<T> { private readonly IComparer<T> comparer; public GenericSortedSetType(string role, string propertyRef, IComparer<T> comparer) : base(role, propertyRef) { this.comparer = comparer; } public override object Instantiate(int anticipatedSize) { return new SortedSet<T>(this.comparer); } public IComparer<T> Comparer { get { return this.comparer; } } } /// <summary> /// An <see cref="IType"/> that maps an <see cref="ISet{T}"/> collection /// to the database. /// </summary> [Serializable] public class GenericSetType<T> : SetType { /// <summary> /// Initializes a new instance of a <see cref="GenericSetType{T}"/> class for /// a specific role. /// </summary> /// <param name="role">The role the persistent collection is in.</param> /// <param name="propertyRef">The name of the property in the /// owner object containing the collection ID, or <see langword="null" /> if it is /// the primary key.</param> public GenericSetType(string role, string propertyRef) : base(role, propertyRef, false) { } public override Type ReturnedClass { get { return typeof(ISet<T>); } } /// <summary> /// Instantiates a new <see cref="IPersistentCollection"/> for the set. /// </summary> /// <param name="session">The current <see cref="ISessionImplementor"/> for the set.</param> /// <param name="persister">The current <see cref="ICollectionPersister" /> for the set.</param> /// <param name="key"></param> public override IPersistentCollection Instantiate(ISessionImplementor session, ICollectionPersister persister, object key) { return new PersistentGenericSet<T>(session); } /// <summary> /// Wraps an <see cref="IList{T}"/> in a <see cref="PersistentGenericSet&lt;T&gt;"/>. /// </summary> /// <param name="session">The <see cref="ISessionImplementor"/> for the collection to be a part of.</param> /// <param name="collection">The unwrapped <see cref="IList{T}"/>.</param> /// <returns> /// An <see cref="PersistentGenericSet&lt;T&gt;"/> that wraps the non NHibernate <see cref="IList{T}"/>. /// </returns> public override IPersistentCollection Wrap(ISessionImplementor session, object collection) { var set = collection as ISet<T>; if (set == null) { var stronglyTypedCollection = collection as ICollection<T>; if (stronglyTypedCollection == null) throw new HibernateException(Role + " must be an implementation of ISet<T> or ICollection<T>"); set = new HashSet<T>(stronglyTypedCollection); } return new PersistentGenericSet<T>(session, set); } public override object Instantiate(int anticipatedSize) { return new HashSet<T>(); } protected override void Clear(object collection) { ((ISet<T>)collection).Clear(); } protected override void Add(object collection, object element) { ((ISet<T>)collection).Add((T)element); } } /// <summary> /// A persistent wrapper for an <see cref="ISet{T}"/> /// </summary> [Serializable] [DebuggerTypeProxy(typeof(CollectionProxy<>))] public class PersistentGenericSet<T> : AbstractPersistentCollection, ISet<T> { /// <summary> /// The <see cref="ISet{T}"/> that NHibernate is wrapping. /// </summary> protected ISet<T> set; /// <summary> /// A temporary list that holds the objects while the PersistentSet is being /// populated from the database. /// </summary> /// <remarks> /// This is necessary to ensure that the object being added to the PersistentSet doesn't /// have its' <c>GetHashCode()</c> and <c>Equals()</c> methods called during the load /// process. /// </remarks> [NonSerialized] private IList<T> tempList; public PersistentGenericSet() { } // needed for serialization /// <summary> /// Constructor matching super. /// Instantiates a lazy set (the underlying set is un-initialized). /// </summary> /// <param name="session">The session to which this set will belong. </param> public PersistentGenericSet(ISessionImplementor session) : base(session) { } /// <summary> /// Instantiates a non-lazy set (the underlying set is constructed /// from the incoming set reference). /// </summary> /// <param name="session">The session to which this set will belong. </param> /// <param name="original">The underlying set data. </param> public PersistentGenericSet(ISessionImplementor session, ISet<T> original) : base(session) { // Sets can be just a view of a part of another collection. // do we need to copy it to be sure it won't be changing // underneath us? // ie. this.set.addAll(set); set = original; SetInitialized(); IsDirectlyAccessible = true; } public override bool RowUpdatePossible { get { return false; } } public override bool Empty { get { return set.Count == 0; } } public bool IsEmpty { get { return ReadSize() ? CachedSize == 0 : (set.Count == 0); } } public object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } #region ISet<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { Read(); return set.GetEnumerator(); } public bool Contains(T o) { bool? exists = ReadElementExistence(o); return exists == null ? set.Contains(o) : exists.Value; } public void CopyTo(T[] array, int arrayIndex) { Read(); Array.Copy(set.ToArray(), 0, array, arrayIndex, Count); } //public bool ContainsAll(ICollection c) //{ // Read(); // return set.ContainsAll(c); //} public bool Add(T o) { bool? exists = IsOperationQueueEnabled ? ReadElementExistence(o) : null; if (!exists.HasValue) { Initialize(true); if (set.Add(o)) { Dirty(); return true; } return false; } if (exists.Value) { return false; } QueueOperation(new SimpleAddDelayedOperation(this, o)); return true; } public void UnionWith(IEnumerable<T> other) { Read(); set.UnionWith(other); } public void IntersectWith(IEnumerable<T> other) { Read(); set.IntersectWith(other); } public void ExceptWith(IEnumerable<T> other) { Read(); set.ExceptWith(other); } public void SymmetricExceptWith(IEnumerable<T> other) { Read(); set.SymmetricExceptWith(other); } public bool IsSubsetOf(IEnumerable<T> other) { Read(); return set.IsProperSupersetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { Read(); return set.IsSupersetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { Read(); return set.IsProperSupersetOf(other); } public bool IsProperSubsetOf(IEnumerable<T> other) { Read(); return set.IsProperSubsetOf(other); } public bool Overlaps(IEnumerable<T> other) { Read(); return set.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { Read(); return set.SetEquals(other); } public bool Remove(T o) { bool? exists = PutQueueEnabled ? ReadElementExistence(o) : null; if (!exists.HasValue) { Initialize(true); if (set.Remove(o)) { Dirty(); return true; } return false; } if (exists.Value) { QueueOperation(new SimpleRemoveDelayedOperation(this, o)); return true; } return false; } void ICollection<T>.Add(T item) { Add(item); } public void Clear() { if (ClearQueueEnabled) { QueueOperation(new ClearDelayedOperation(this)); } else { Initialize(true); if (set.Count != 0) { set.Clear(); Dirty(); } } } public int Count { get { return ReadSize() ? CachedSize : set.Count; } } public bool IsReadOnly { get { return false; } } public IEnumerator GetEnumerator() { Read(); return set.GetEnumerator(); } #endregion #region DelayedOperations #region Nested type: ClearDelayedOperation protected sealed class ClearDelayedOperation : IDelayedOperation { private readonly PersistentGenericSet<T> enclosingInstance; public ClearDelayedOperation(PersistentGenericSet<T> enclosingInstance) { this.enclosingInstance = enclosingInstance; } #region IDelayedOperation Members public object AddedInstance { get { return null; } } public object Orphan { get { throw new NotSupportedException("queued clear cannot be used with orphan delete"); } } public void Operate() { enclosingInstance.set.Clear(); } #endregion } #endregion #region Nested type: SimpleAddDelayedOperation protected sealed class SimpleAddDelayedOperation : IDelayedOperation { private readonly PersistentGenericSet<T> enclosingInstance; private readonly T value; public SimpleAddDelayedOperation(PersistentGenericSet<T> enclosingInstance, T value) { this.enclosingInstance = enclosingInstance; this.value = value; } #region IDelayedOperation Members public object AddedInstance { get { return value; } } public object Orphan { get { return null; } } public void Operate() { enclosingInstance.set.Add(value); } #endregion } #endregion #region Nested type: SimpleRemoveDelayedOperation protected sealed class SimpleRemoveDelayedOperation : IDelayedOperation { private readonly PersistentGenericSet<T> enclosingInstance; private readonly T value; public SimpleRemoveDelayedOperation(PersistentGenericSet<T> enclosingInstance, T value) { this.enclosingInstance = enclosingInstance; this.value = value; } #region IDelayedOperation Members public object AddedInstance { get { return null; } } public object Orphan { get { return value; } } public void Operate() { enclosingInstance.set.Remove(value); } #endregion } #endregion #endregion public override ICollection GetSnapshot(ICollectionPersister persister) { var entityMode = Session.EntityMode; var clonedSet = new SetSnapShot<T>(set.Count); var enumerable = from object current in set select persister.ElementType.DeepCopy(current, entityMode, persister.Factory); foreach (var copied in enumerable) { clonedSet.Add((T)copied); } return clonedSet; } public override ICollection GetOrphans(object snapshot, string entityName) { var sn = new SetSnapShot<object>((IEnumerable<object>)snapshot); if (set.Count == 0) return sn; if (((ICollection)sn).Count == 0) return sn; return GetOrphans(sn, set.ToArray(), entityName, Session); } public override bool EqualsSnapshot(ICollectionPersister persister) { var elementType = persister.ElementType; var snapshot = (ISetSnapshot<T>)GetSnapshot(); if (((ICollection)snapshot).Count != set.Count) { return false; } return !(from object obj in set let oldValue = snapshot[(T)obj] where oldValue == null || elementType.IsDirty(oldValue, obj, Session) select obj).Any(); } public override bool IsSnapshotEmpty(object snapshot) { return ((ICollection)snapshot).Count == 0; } public override void BeforeInitialize(ICollectionPersister persister, int anticipatedSize) { set = (ISet<T>)persister.CollectionType.Instantiate(anticipatedSize); } /// <summary> /// Initializes this PersistentSet from the cached values. /// </summary> /// <param name="persister">The CollectionPersister to use to reassemble the PersistentSet.</param> /// <param name="disassembled">The disassembled PersistentSet.</param> /// <param name="owner">The owner object.</param> public override void InitializeFromCache(ICollectionPersister persister, object disassembled, object owner) { var array = (object[])disassembled; int size = array.Length; BeforeInitialize(persister, size); for (int i = 0; i < size; i++) { var element = (T)persister.ElementType.Assemble(array[i], Session, owner); if (element != null) { set.Add(element); } } SetInitialized(); } public override string ToString() { Read(); return StringHelper.CollectionToString(set.ToArray()); } public override object ReadFrom(IDataReader rs, ICollectionPersister role, ICollectionAliases descriptor, object owner) { var element = (T)role.ReadElement(rs, owner, descriptor.SuffixedElementAliases, Session); if (element != null) { tempList.Add(element); } return element; } /// <summary> /// Set up the temporary List that will be used in the EndRead() /// to fully create the set. /// </summary> public override void BeginRead() { base.BeginRead(); tempList = new List<T>(); } /// <summary> /// Takes the contents stored in the temporary list created during <c>BeginRead()</c> /// that was populated during <c>ReadFrom()</c> and write it to the underlying /// PersistentSet. /// </summary> public override bool EndRead(ICollectionPersister persister) { foreach (T item in tempList) { set.Add(item); } tempList = null; SetInitialized(); return true; } public override IEnumerable Entries(ICollectionPersister persister) { return set; } public override object Disassemble(ICollectionPersister persister) { var result = new object[set.Count]; int i = 0; foreach (object obj in set) { result[i++] = persister.ElementType.Disassemble(obj, Session, null); } return result; } public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula) { IType elementType = persister.ElementType; var sn = (ISetSnapshot<T>)GetSnapshot(); var deletes = new List<T>(((ICollection<T>)sn).Count); deletes.AddRange(sn.Where(obj => !set.Contains(obj))); deletes.AddRange(from obj in set let oldValue = sn[obj] where oldValue != null && elementType.IsDirty(obj, oldValue, Session) select oldValue); return deletes; } public override bool NeedsInserting(object entry, int i, IType elemType) { var sn = (ISetSnapshot<T>)GetSnapshot(); object oldKey = sn[(T)entry]; // note that it might be better to iterate the snapshot but this is safe, // assuming the user implements equals() properly, as required by the PersistentSet // contract! return oldKey == null || elemType.IsDirty(oldKey, entry, Session); } public override bool NeedsUpdating(object entry, int i, IType elemType) { return false; } public override object GetIndex(object entry, int i, ICollectionPersister persister) { throw new NotSupportedException("Sets don't have indexes"); } public override object GetElement(object entry) { return entry; } public override object GetSnapshotElement(object entry, int i) { throw new NotSupportedException("Sets don't support updating by element"); } public new void Read() { base.Read(); } public override bool Equals(object other) { var that = other as ISet<T>; if (that == null) { return false; } Read(); return set.SequenceEqual(that); } public override int GetHashCode() { Read(); return set.GetHashCode(); } public override bool EntryExists(object entry, int i) { return true; } public override bool IsWrapper(object collection) { return set == collection; } public void CopyTo(Array array, int index) { // NH : we really need to initialize the set ? Read(); Array.Copy(set.ToArray(), 0, array, index, Count); } #region Nested type: ISetSnapshot private interface ISetSnapshot<Y> : ICollection<Y>, ICollection { Y this[Y element] { get; } } #endregion #region Nested type: SetSnapShot [Serializable] private class SetSnapShot<V> : ISetSnapshot<V> { private readonly List<V> elements; private SetSnapShot() { elements = new List<V>(); } public SetSnapShot(int capacity) { elements = new List<V>(capacity); } public SetSnapShot(IEnumerable<V> collection) { elements = new List<V>(collection); } #region ISetSnapshot<V> Members public IEnumerator<V> GetEnumerator() { return elements.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(V item) { elements.Add(item); } public void Clear() { throw new InvalidOperationException(); } public bool Contains(V item) { return elements.Contains(item); } public void CopyTo(V[] array, int arrayIndex) { elements.CopyTo(array, arrayIndex); } public bool Remove(V item) { throw new InvalidOperationException(); } public void CopyTo(Array array, int index) { ((ICollection)elements).CopyTo(array, index); } int ICollection.Count { get { return elements.Count; } } public object SyncRoot { get { return ((ICollection)elements).SyncRoot; } } public bool IsSynchronized { get { return ((ICollection)elements).IsSynchronized; } } int ICollection<V>.Count { get { return elements.Count; } } public bool IsReadOnly { get { return ((ICollection<T>)elements).IsReadOnly; } } public V this[V element] { get { int idx = elements.IndexOf(element); if (idx >= 0) { return elements[idx]; } return default(V); } } #endregion } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xunit; namespace System.Json.Tests { public class JsonObjectTests { [Fact] public void Ctor_EmptyArray_Works() { Assert.Equal(0, new JsonObject(new KeyValuePair<string, JsonValue>[0]).Count); Assert.Equal(0, new JsonObject(Enumerable.Empty<KeyValuePair<string, JsonValue>>()).Count); } [Fact] public void Ctor_Array() { // Workaround xunit/xunit#987: InvalidOperationException thrown if this is in MemberData KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject obj = new JsonObject(items); Assert.Equal(items.Length, obj.Count); for (int i = 0; i < items.Length; i++) { Assert.Equal(items[i].Value.ToString(), obj[items[i].Key].ToString()); JsonValue value; Assert.True(obj.TryGetValue(items[i].Key, out value)); Assert.Equal(items[i].Value.ToString(), value.ToString()); } } [Fact] public void Ctor_IEnumerable() { // Workaround xunit/xunit#987: InvalidOperationException thrown if this is in MemberData KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject obj = new JsonObject((IEnumerable<KeyValuePair<string, JsonValue>>)items); Assert.Equal(items.Length, obj.Count); for (int i = 0; i < items.Length; i++) { Assert.Equal(items[i].Value.ToString(), obj[items[i].Key].ToString()); JsonValue value; Assert.True(obj.TryGetValue(items[i].Key, out value)); Assert.Equal(items[i].Value.ToString(), value.ToString()); } } [Fact] public void Ctor_NullArray_Works() { JsonObject obj = new JsonObject(null); Assert.Equal(0, obj.Count); } [Fact] public void Ctor_NullIEnumerable_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("items", () => new JsonObject((IEnumerable<KeyValuePair<string, JsonValue>>)null)); } [Fact] public void JsonType_ReturnsObject() { Assert.Equal(JsonType.Object, new JsonObject().JsonType); } [Fact] public void IsReadOnly_ReturnsFalse() { ICollection<KeyValuePair<string, JsonValue>> iCollection = new JsonObject(); Assert.False(iCollection.IsReadOnly); } [Fact] public void Item_Set_Get() { JsonObject obj = new JsonObject(); string key = "key"; JsonValue value = new JsonPrimitive(true); obj[key] = value; Assert.Equal(1, obj.Count); Assert.Same(value, obj[key]); } [Fact] public void Item_NoSuchKey_ThrowsKeyNotFoundException() { JsonObject obj = new JsonObject(); Assert.Throws<KeyNotFoundException>(() => obj["no-such-key"]); } [Fact] public void TryGetValue_NoSuchKey_ReturnsNull() { JsonObject obj = new JsonObject(); JsonValue value; Assert.False(obj.TryGetValue("no-such-key", out value)); Assert.Null(value); } [Fact] public void Add() { JsonObject obj = new JsonObject(); KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)); obj.Add(item); Assert.Equal(1, obj.Count); Assert.Equal(item.Key, obj.Keys.First()); Assert.Equal(item.Value.ToString(), obj.Values.First().ToString()); } [Fact] public void Add_NullKey_ThrowsArgumentNullException() { JsonObject obj = new JsonObject(); Assert.Throws<ArgumentNullException>("key", () => obj.Add(null, new JsonPrimitive(true))); } [Fact] public void Add_NullKeyInKeyValuePair_ThrowsArgumentNullException() { JsonObject obj = new JsonObject(); KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>(null, new JsonPrimitive(true)); Assert.Throws<ArgumentNullException>("key", () => obj.Add(item)); } [Fact] public void AddRange_Array() { KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject obj = new JsonObject(); obj.AddRange(items); Assert.Equal(items.Length, obj.Count); for (int i = 0; i < items.Length; i++) { Assert.Equal(items[i].Value.ToString(), obj[items[i].Key].ToString()); } } [Fact] public void AddRange_IEnumerable() { KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject obj = new JsonObject(); obj.AddRange((IEnumerable<KeyValuePair<string, JsonValue>>)items); Assert.Equal(items.Length, obj.Count); for (int i = 0; i < items.Length; i++) { Assert.Equal(items[i].Value.ToString(), obj[items[i].Key].ToString()); } } [Fact] public void AddRange_NullItems_ThrowsArgumentNullException() { JsonObject obj = new JsonObject(); Assert.Throws<ArgumentNullException>("items", () => obj.AddRange(null)); Assert.Throws<ArgumentNullException>("items", () => obj.AddRange((IEnumerable<KeyValuePair<string, JsonValue>>)null)); } [Fact] public void Clear() { JsonObject obj = new JsonObject(new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true))); obj.Clear(); Assert.Equal(0, obj.Count); obj.Clear(); Assert.Equal(0, obj.Count); } [Fact] public void ContainsKey() { KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)); JsonObject obj = new JsonObject(item); Assert.True(obj.ContainsKey(item.Key)); Assert.False(obj.ContainsKey("abc")); ICollection<KeyValuePair<string, JsonValue>> iCollection = obj; Assert.True(iCollection.Contains(item)); Assert.False(iCollection.Contains(new KeyValuePair<string, JsonValue>())); } [Fact] public void ContainsKey_NullKey_ThrowsArgumentNullException() { JsonObject obj = new JsonObject(); Assert.Throws<ArgumentNullException>("key", () => obj.ContainsKey(null)); } [Theory] [InlineData(0)] [InlineData(1)] public void CopyTo(int arrayIndex) { KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject array = new JsonObject(items); KeyValuePair<string, JsonValue>[] copy = new KeyValuePair<string, JsonValue>[array.Count + arrayIndex]; array.CopyTo(copy, arrayIndex); for (int i = 0; i < arrayIndex; i++) { Assert.Equal(default(KeyValuePair<string, JsonValue>), copy[i]); } for (int i = arrayIndex; i < copy.Length; i++) { Assert.Equal(items[i - arrayIndex], copy[i]); } } [Fact] public void Remove() { KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)); JsonObject obj = new JsonObject(item); obj.Remove(item.Key); Assert.Equal(0, obj.Count); Assert.False(obj.ContainsKey(item.Key)); obj.Remove(item.Key); Assert.Equal(0, obj.Count); } [Fact] public void Remove_NullKey_ThrowsArgumentNullException() { JsonObject obj = new JsonObject(); Assert.Throws<ArgumentNullException>("key", () => obj.Remove(null)); } [Fact] public void ICollection_Remove() { KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)); JsonObject obj = new JsonObject(item); ICollection<KeyValuePair<string, JsonValue>> iCollection = obj; iCollection.Remove(item); Assert.Equal(0, obj.Count); Assert.False(obj.ContainsKey(item.Key)); iCollection.Remove(item); Assert.Equal(0, obj.Count); } [Fact] public void Save_Stream() { JsonObject obj = new JsonObject(new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)), new KeyValuePair<string, JsonValue>("key2", null)); using (MemoryStream stream = new MemoryStream()) { obj.Save(stream); string result = Encoding.UTF8.GetString(stream.ToArray()); Assert.Equal("{\"key\", true\"key2\", null}", result); } } [Fact] public void Save_TextWriter() { JsonObject obj = new JsonObject(new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)), new KeyValuePair<string, JsonValue>("key2", null)); using (StringWriter writer = new StringWriter()) { obj.Save(writer); Assert.Equal("{\"key\": true, \"key2\": null}", writer.ToString()); } } [Fact] public void Save_NullStream_ThrowsArgumentNullException() { JsonObject obj = new JsonObject(); Assert.Throws<ArgumentNullException>("stream", () => obj.Save((Stream)null)); Assert.Throws<ArgumentNullException>("textWriter", () => obj.Save((TextWriter)null)); } [Fact] public void GetEnumerator_GenericIEnumerable() { KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject obj = new JsonObject(items); IEnumerator<KeyValuePair<string, JsonValue>> enumerator = ((IEnumerable<KeyValuePair<string, JsonValue>>)obj).GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(items[counter].Key, enumerator.Current.Key); Assert.Equal(items[counter].Value.ToString(), enumerator.Current.Value.ToString()); counter++; } Assert.Equal(obj.Count, counter); enumerator.Reset(); } } [Fact] public void GetEnumerator_NonGenericIEnumerable() { KeyValuePair<string, JsonValue>[] items = new KeyValuePair<string, JsonValue>[] { new KeyValuePair<string, JsonValue>("key", new JsonPrimitive(true)) }; JsonObject obj = new JsonObject(items); IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { KeyValuePair<string, JsonValue> current = (KeyValuePair<string, JsonValue>)enumerator.Current; Assert.Equal(items[counter].Key, current.Key); Assert.Equal(items[counter].Value.ToString(), current.Value.ToString()); counter++; } Assert.Equal(obj.Count, counter); enumerator.Reset(); } } } }
//--------------------------------------------------------------------- // <copyright file="RelationalExpressions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; using System.Data.Common; using System.Data.Metadata.Edm; using System.Data.Common.CommandTrees.Internal; namespace System.Data.Common.CommandTrees { /// <summary> /// Represents an apply operation, which is the invocation of the specified functor for each element in the specified input set. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbApplyExpression : DbExpression { private readonly DbExpressionBinding _input; private readonly DbExpressionBinding _apply; internal DbApplyExpression(DbExpressionKind applyKind, TypeUsage resultRowCollectionTypeUsage, DbExpressionBinding input, DbExpressionBinding apply) : base(applyKind, resultRowCollectionTypeUsage) { Debug.Assert(input != null, "DbApplyExpression input cannot be null"); Debug.Assert(input != null, "DbApplyExpression apply cannot be null"); Debug.Assert(DbExpressionKind.CrossApply == applyKind || DbExpressionKind.OuterApply == applyKind, "Invalid DbExpressionKind for DbApplyExpression"); _input = input; _apply = apply; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the functor that is invoked for each element in the input set. /// </summary> public DbExpressionBinding Apply { get { return _apply; } } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the input set. /// </summary> public DbExpressionBinding Input { get { return _input; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the removal of duplicate elements from the specified set operand. /// </summary> /// <remarks> /// DbDistinctExpression requires that its argument has a collection result type /// with an element type that is equality comparable. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbDistinctExpression : DbUnaryExpression { internal DbDistinctExpression(TypeUsage resultType, DbExpression argument) : base(DbExpressionKind.Distinct, resultType, argument) { Debug.Assert(TypeSemantics.IsCollectionType(argument.ResultType), "DbDistinctExpression argument must have a collection result type"); } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the conversion of the specified set operand to a singleton. /// If the set is empty the conversion will return null, otherwise the conversion will return one of the elements in the set. /// </summary> /// <remarks> /// DbElementExpression requires that its argument has a collection result type /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbElementExpression : DbUnaryExpression { private bool _singlePropertyUnwrapped; internal DbElementExpression(TypeUsage resultType, DbExpression argument) : base(DbExpressionKind.Element, resultType, argument) { this._singlePropertyUnwrapped = false; } internal DbElementExpression(TypeUsage resultType, DbExpression argument, bool unwrapSingleProperty) : base(DbExpressionKind.Element, resultType, argument) { this._singlePropertyUnwrapped = unwrapSingleProperty; } /// <summary> /// Is the result type of the element equal to the result type of the single property /// of the element of its operand? /// </summary> internal bool IsSinglePropertyUnwrapped { get { return _singlePropertyUnwrapped; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the set subtraction operation between the left and right operands. /// </summary> /// <remarks> /// DbExceptExpression requires that its arguments have a common collection result type /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbExceptExpression : DbBinaryExpression { internal DbExceptExpression(TypeUsage resultType, DbExpression left, DbExpression right) : base(DbExpressionKind.Except, resultType, left, right) { Debug.Assert(object.ReferenceEquals(resultType, left.ResultType), "DbExceptExpression result type should be result type of left argument"); } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents a predicate applied to an input set to produce the set of elements that satisfy the predicate. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbFilterExpression : DbExpression { private readonly DbExpressionBinding _input; private readonly DbExpression _predicate; internal DbFilterExpression(TypeUsage resultType, DbExpressionBinding input, DbExpression predicate) : base(DbExpressionKind.Filter, resultType) { Debug.Assert(input != null, "DbFilterExpression input cannot be null"); Debug.Assert(predicate != null, "DbBFilterExpression predicate cannot be null"); Debug.Assert(TypeSemantics.IsPrimitiveType(predicate.ResultType, PrimitiveTypeKind.Boolean), "DbFilterExpression predicate must have a Boolean result type"); _input = input; _predicate = predicate; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the input set. /// </summary> public DbExpressionBinding Input { get { return _input; } } /// <summary> /// Gets the <see cref="DbExpression"/> that specifies the predicate used to filter the input set. /// </summary> public DbExpression Predicate { get { return _predicate; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents a group by operation, which is a grouping of the elements in the input set based on the specified key expressions followed by the application of the specified aggregates. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbGroupByExpression : DbExpression { private readonly DbGroupExpressionBinding _input; private readonly DbExpressionList _keys; private readonly System.Collections.ObjectModel.ReadOnlyCollection<DbAggregate> _aggregates; internal DbGroupByExpression(TypeUsage collectionOfRowResultType, DbGroupExpressionBinding input, DbExpressionList groupKeys, System.Collections.ObjectModel.ReadOnlyCollection<DbAggregate> aggregates) : base(DbExpressionKind.GroupBy, collectionOfRowResultType) { Debug.Assert(input != null, "DbGroupExpression input cannot be null"); Debug.Assert(groupKeys != null, "DbGroupExpression keys cannot be null"); Debug.Assert(aggregates != null, "DbGroupExpression aggregates cannot be null"); Debug.Assert(groupKeys.Count > 0 || aggregates.Count > 0, "At least one key or aggregate is required"); _input = input; _keys = groupKeys; _aggregates = aggregates; } /// <summary> /// Gets the <see cref="DbGroupExpressionBinding"/> that specifies the input set and provides access to the set element and group element variables. /// </summary> public DbGroupExpressionBinding Input { get { return _input; } } /// <summary> /// Gets an <see cref="DbExpression"/> list that provides grouping keys. /// </summary> public IList<DbExpression> Keys { get { return _keys; } } /// <summary> /// Gets an <see cref="DbAggregate"/> list that provides the aggregates to apply. /// </summary> public IList<DbAggregate> Aggregates { get { return _aggregates; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the set intersection operation between the left and right operands. /// </summary> /// <remarks> /// DbIntersectExpression requires that its arguments have a common collection result type /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbIntersectExpression : DbBinaryExpression { internal DbIntersectExpression(TypeUsage resultType, DbExpression left, DbExpression right) : base(DbExpressionKind.Intersect, resultType, left, right) { } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents an unconditional join operation between the given collection arguments /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbCrossJoinExpression : DbExpression { private readonly System.Collections.ObjectModel.ReadOnlyCollection<DbExpressionBinding> _inputs; internal DbCrossJoinExpression(TypeUsage collectionOfRowResultType, System.Collections.ObjectModel.ReadOnlyCollection<DbExpressionBinding> inputs) : base(DbExpressionKind.CrossJoin, collectionOfRowResultType) { Debug.Assert(inputs != null, "DbCrossJoin inputs cannot be null"); Debug.Assert(inputs.Count >= 2, "DbCrossJoin requires at least two inputs"); _inputs = inputs; } /// <summary> /// Gets an <see cref="DbExpressionBinding"/> list that provide the input sets to the join. /// </summary> public IList<DbExpressionBinding> Inputs { get { return _inputs; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents an inner, left outer or full outer join operation between the given collection arguments on the specified join condition. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbJoinExpression : DbExpression { private readonly DbExpressionBinding _left; private readonly DbExpressionBinding _right; private readonly DbExpression _condition; internal DbJoinExpression(DbExpressionKind joinKind, TypeUsage collectionOfRowResultType, DbExpressionBinding left, DbExpressionBinding right, DbExpression condition) : base(joinKind, collectionOfRowResultType) { Debug.Assert(left != null, "DbJoinExpression left cannot be null"); Debug.Assert(right != null, "DbJoinExpression right cannot be null"); Debug.Assert(condition != null, "DbJoinExpression condition cannot be null"); Debug.Assert(DbExpressionKind.InnerJoin == joinKind || DbExpressionKind.LeftOuterJoin == joinKind || DbExpressionKind.FullOuterJoin == joinKind, "Invalid DbExpressionKind specified for DbJoinExpression"); _left = left; _right = right; _condition = condition; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> provides the left input. /// </summary> public DbExpressionBinding Left { get { return _left; } } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> provides the right input. /// </summary> public DbExpressionBinding Right { get { return _right; } } /// <summary> /// Gets the <see cref="DbExpression"/> that defines the join condition to apply. /// </summary> public DbExpression JoinCondition { get { return _condition; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the restriction of the number of elements in the Argument collection to the specified Limit value. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbLimitExpression : DbExpression { private readonly DbExpression _argument; private readonly DbExpression _limit; private readonly bool _withTies; internal DbLimitExpression(TypeUsage resultType, DbExpression argument, DbExpression limit, bool withTies) : base(DbExpressionKind.Limit, resultType) { Debug.Assert(argument != null, "DbLimitExpression argument cannot be null"); Debug.Assert(limit != null, "DbLimitExpression limit cannot be null"); Debug.Assert(object.ReferenceEquals(resultType, argument.ResultType), "DbLimitExpression result type must be the result type of the argument"); this._argument = argument; this._limit = limit; this._withTies = withTies; } /// <summary> /// Gets the expression that specifies the input collection. /// </summary> public DbExpression Argument { get { return this._argument; } } /// <summary> /// Gets the expression that specifies the limit on the number of elements returned from the input collection. /// </summary> public DbExpression Limit { get { return this._limit; } } /// <summary> /// Gets whether the limit operation will include tied results, which could produce more results than specifed by the Limit value if ties are present. /// </summary> public bool WithTies { get { return _withTies; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the projection of a given set of values over the specified input set. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbProjectExpression : DbExpression { private readonly DbExpressionBinding _input; private readonly DbExpression _projection; internal DbProjectExpression(TypeUsage resultType, DbExpressionBinding input, DbExpression projection) : base(DbExpressionKind.Project, resultType) { Debug.Assert(input != null, "DbProjectExpression input cannot be null"); Debug.Assert(projection != null, "DbProjectExpression projection cannot be null"); this._input = input; this._projection = projection; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the input set. /// </summary> public DbExpressionBinding Input { get { return _input; } } /// <summary> /// Gets the <see cref="DbExpression"/> that defines the projection. /// </summary> public DbExpression Projection { get { return _projection; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents a quantifier operation of the specified kind (Any, All) over the elements of the specified input set. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbQuantifierExpression : DbExpression { private readonly DbExpressionBinding _input; private readonly DbExpression _predicate; internal DbQuantifierExpression(DbExpressionKind kind, TypeUsage booleanResultType, DbExpressionBinding input, DbExpression predicate) : base(kind, booleanResultType) { Debug.Assert(input != null, "DbQuantifierExpression input cannot be null"); Debug.Assert(predicate != null, "DbQuantifierExpression predicate cannot be null"); Debug.Assert(TypeSemantics.IsPrimitiveType(booleanResultType, PrimitiveTypeKind.Boolean), "DbQuantifierExpression must have a Boolean result type"); Debug.Assert(TypeSemantics.IsPrimitiveType(predicate.ResultType, PrimitiveTypeKind.Boolean), "DbQuantifierExpression predicate must have a Boolean result type"); this._input = input; this._predicate = predicate; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the input set. /// </summary> public DbExpressionBinding Input { get { return _input; } } /// <summary> /// Gets the Boolean predicate that should be evaluated for each element in the input set. /// </summary> public DbExpression Predicate { get { return _predicate; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Specifies a sort key that can be used as part of the sort order in a DbSortExpression. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbSortClause { private readonly DbExpression _expr; private readonly bool _asc; private readonly string _coll; internal DbSortClause(DbExpression key, bool asc, string collation) { Debug.Assert(key != null, "DbSortClause key cannot be null"); _expr = key; _asc = asc; _coll = collation; } /// <summary> /// Gets a Boolean value indicating whether or not this sort key is sorted ascending. /// </summary> public bool Ascending { get { return _asc; } } /// <summary> /// Gets a string value that specifies the collation for this sort key. /// </summary> public string Collation { get { return _coll; } } /// <summary> /// Gets the <see cref="DbExpression"/> that provides the value for this sort key. /// </summary> public DbExpression Expression { get { return _expr; } } } /// <summary> /// Represents a skip operation of the specified number of elements of the input set after the ordering described in the given sort keys is applied. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbSkipExpression : DbExpression { private readonly DbExpressionBinding _input; private readonly System.Collections.ObjectModel.ReadOnlyCollection<DbSortClause> _keys; private readonly DbExpression _count; internal DbSkipExpression(TypeUsage resultType, DbExpressionBinding input, System.Collections.ObjectModel.ReadOnlyCollection<DbSortClause> sortOrder, DbExpression count) : base(DbExpressionKind.Skip, resultType) { Debug.Assert(input != null, "DbSkipExpression input cannot be null"); Debug.Assert(sortOrder != null, "DbSkipExpression sort order cannot be null"); Debug.Assert(count != null, "DbSkipExpression count cannot be null"); Debug.Assert(TypeSemantics.IsCollectionType(resultType), "DbSkipExpression requires a collection result type"); this._input = input; this._keys = sortOrder; this._count = count; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the input set. /// </summary> public DbExpressionBinding Input { get { return _input; } } /// <summary> /// Gets a <see cref="DbSortClause"/> list that defines the sort order. /// </summary> public IList<DbSortClause> SortOrder { get { return _keys; } } /// <summary> /// Gets the expression that specifies the number of elements from the input collection to skip. /// </summary> public DbExpression Count { get { return _count; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents a sort operation applied to the elements of the specified input set based on the given sort keys. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbSortExpression : DbExpression { private readonly DbExpressionBinding _input; private readonly System.Collections.ObjectModel.ReadOnlyCollection<DbSortClause> _keys; internal DbSortExpression(TypeUsage resultType, DbExpressionBinding input, System.Collections.ObjectModel.ReadOnlyCollection<DbSortClause> sortOrder) : base(DbExpressionKind.Sort, resultType) { Debug.Assert(input != null, "DbSortExpression input cannot be null"); Debug.Assert(sortOrder != null, "DbSortExpression sort order cannot be null"); Debug.Assert(TypeSemantics.IsCollectionType(resultType), "DbSkipExpression requires a collection result type"); this._input = input; this._keys = sortOrder; } /// <summary> /// Gets the <see cref="DbExpressionBinding"/> that specifies the input set. /// </summary> public DbExpressionBinding Input { get { return _input; } } /// <summary> /// Gets a <see cref="DbSortClause"/> list that defines the sort order. /// </summary> public IList<DbSortClause> SortOrder { get { return _keys; } } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } /// <summary> /// Represents the set union (without duplicate removal) operation between the left and right operands. /// </summary> /// <remarks> /// DbUnionAllExpression requires that its arguments have a common collection result type /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public sealed class DbUnionAllExpression : DbBinaryExpression { internal DbUnionAllExpression(TypeUsage resultType, DbExpression left, DbExpression right) : base(DbExpressionKind.UnionAll, resultType, left, right) { } /// <summary> /// The visitor pattern method for expression visitors that do not produce a result value. /// </summary> /// <param name="visitor">An instance of DbExpressionVisitor.</param> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } /// <summary> /// The visitor pattern method for expression visitors that produce a result value of a specific type. /// </summary> /// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param> /// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam> /// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception> /// <returns>An instance of <typeparamref name="TResultType"/>.</returns> public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection.Emit { using System.Runtime.InteropServices; using System; using System.Reflection; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] internal enum TypeKind { IsArray = 1, IsPointer = 2, IsByRef = 3, } // This is a kind of Type object that will represent the compound expression of a parameter type or field type. internal sealed class SymbolType : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){ if(typeInfo==null) return false; return IsAssignableFrom(typeInfo.AsType()); } #region Static Members internal static Type FormCompoundType(string format, Type baseType, int curIndex) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. // // Example: [2..4] - one dimension array with lower bound 2 and size of 3 // Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6 // Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 for // the first dimension) // Example: []* - pointer to a one dimensional array // Example: *[] - one dimensional array. The element type is a pointer to the baseType // Example: []& - ByRef of a single dimensional array. Only one & is allowed and it must appear the last! // Example: [?] - Array with unknown bound SymbolType symbolType; int iLowerBound; int iUpperBound; if (format == null || curIndex == format.Length) { // we have consumed all of the format string return baseType; } if (format[curIndex] == '&') { // ByRef case symbolType = new SymbolType(TypeKind.IsByRef); symbolType.SetFormat(format, curIndex, 1); curIndex++; if (curIndex != format.Length) // ByRef has to be the last char!! throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); symbolType.SetElementType(baseType); return symbolType; } if (format[curIndex] == '[') { // Array type. symbolType = new SymbolType(TypeKind.IsArray); int startIndex = curIndex; curIndex++; iLowerBound = 0; iUpperBound = -1; // Example: [2..4] - one dimension array with lower bound 2 and size of 3 // Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6 // Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 sepcified) while (format[curIndex] != ']') { if (format[curIndex] == '*') { symbolType.m_isSzArray = false; curIndex++; } // consume, one dimension at a time if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-') { bool isNegative = false; if (format[curIndex] == '-') { isNegative = true; curIndex++; } // lower bound is specified. Consume the low bound while (format[curIndex] >= '0' && format[curIndex] <= '9') { iLowerBound = iLowerBound * 10; iLowerBound += format[curIndex] - '0'; curIndex++; } if (isNegative) { iLowerBound = 0 - iLowerBound; } // set the upper bound to be less than LowerBound to indicate that upper bound it not specified yet! iUpperBound = iLowerBound - 1; } if (format[curIndex] == '.') { // upper bound is specified // skip over ".." curIndex++; if (format[curIndex] != '.') { // bad format!! Throw exception throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); } curIndex++; // consume the upper bound if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-') { bool isNegative = false; iUpperBound = 0; if (format[curIndex] == '-') { isNegative = true; curIndex++; } // lower bound is specified. Consume the low bound while (format[curIndex] >= '0' && format[curIndex] <= '9') { iUpperBound = iUpperBound * 10; iUpperBound += format[curIndex] - '0'; curIndex++; } if (isNegative) { iUpperBound = 0 - iUpperBound; } if (iUpperBound < iLowerBound) { // User specified upper bound less than lower bound, this is an error. // Throw error exception. throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); } } } if (format[curIndex] == ',') { // We have more dimension to deal with. // now set the lower bound, the size, and increase the dimension count! curIndex++; symbolType.SetBounds(iLowerBound, iUpperBound); // clear the lower and upper bound information for next dimension iLowerBound = 0; iUpperBound = -1; } else if (format[curIndex] != ']') { throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); } } // The last dimension information symbolType.SetBounds(iLowerBound, iUpperBound); // skip over ']' curIndex++; symbolType.SetFormat(format, startIndex, curIndex - startIndex); // set the base type of array symbolType.SetElementType(baseType); return FormCompoundType(format, symbolType, curIndex); } else if (format[curIndex] == '*') { // pointer type. symbolType = new SymbolType(TypeKind.IsPointer); symbolType.SetFormat(format, curIndex, 1); curIndex++; symbolType.SetElementType(baseType); return FormCompoundType(format, symbolType, curIndex); } return null; } #endregion #region Data Members internal TypeKind m_typeKind; internal Type m_baseType; internal int m_cRank; // count of dimension // If LowerBound and UpperBound is equal, that means one element. // If UpperBound is less than LowerBound, then the size is not specified. internal int[] m_iaLowerBound; internal int[] m_iaUpperBound; // count of dimension private string m_format; // format string to form the full name. private bool m_isSzArray = true; #endregion #region Constructor internal SymbolType(TypeKind typeKind) { m_typeKind = typeKind; m_iaLowerBound = new int[4]; m_iaUpperBound = new int[4]; } #endregion #region Internal Members internal void SetElementType(Type baseType) { if (baseType == null) throw new ArgumentNullException("baseType"); Contract.EndContractBlock(); m_baseType = baseType; } private void SetBounds(int lower, int upper) { // Increase the rank, set lower and upper bound if (lower != 0 || upper != -1) m_isSzArray = false; if (m_iaLowerBound.Length <= m_cRank) { // resize the bound array int[] iaTemp = new int[m_cRank * 2]; Array.Copy(m_iaLowerBound, 0, iaTemp, 0, m_cRank); m_iaLowerBound = iaTemp; Array.Copy(m_iaUpperBound, 0, iaTemp, 0, m_cRank); m_iaUpperBound = iaTemp; } m_iaLowerBound[m_cRank] = lower; m_iaUpperBound[m_cRank] = upper; m_cRank++; } internal void SetFormat(string format, int curIndex, int length) { // Cache the text display format for this SymbolType m_format = format.Substring(curIndex, length); } #endregion #region Type Overrides internal override bool IsSzArray { get { if (m_cRank > 1) return false; return m_isSzArray; } } public override Type MakePointerType() { return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); string szrank = ""; if (rank == 1) { szrank = "*"; } else { for(int i = 1; i < rank; i++) szrank += ","; } string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] SymbolType st = SymbolType.FormCompoundType(m_format + s, m_baseType, 0) as SymbolType; return st; } public override int GetArrayRank() { if (!IsArray) throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); Contract.EndContractBlock(); return m_cRank; } public override Guid GUID { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } } public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Module Module { get { Type baseType; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType); return baseType.Module; } } public override Assembly Assembly { get { Type baseType; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType); return baseType.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } } public override String Name { get { Type baseType; String sFormat = m_format; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) sFormat = ((SymbolType)baseType).m_format + sFormat; return baseType.Name + sFormat; } } public override String FullName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); } } public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } } public override String ToString() { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); } public override String Namespace { get { return m_baseType.Namespace; } } public override Type BaseType { get { return typeof(System.Array); } } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } [System.Runtime.InteropServices.ComVisible(true)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type GetInterface(String name,bool ignoreCase) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type[] GetInterfaces() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override EventInfo GetEvent(String name,BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override EventInfo[] GetEvents() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } [System.Runtime.InteropServices.ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } protected override TypeAttributes GetAttributeFlagsImpl() { // Return the attribute flags of the base type? Type baseType; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType); return baseType.Attributes; } protected override bool IsArrayImpl() { return m_typeKind == TypeKind.IsArray; } protected override bool IsPointerImpl() { return m_typeKind == TypeKind.IsPointer; } protected override bool IsByRefImpl() { return m_typeKind == TypeKind.IsByRef; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsValueTypeImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override bool IsConstructedGenericType { get { return false; } } public override Type GetElementType() { return m_baseType; } protected override bool HasElementTypeImpl() { return m_baseType != null; } public override Type UnderlyingSystemType { get { return this; } } public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override bool IsDefined (Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Web; using Funq; using ServiceStack.Common.Utils; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; namespace ServiceStack.WebHost.Endpoints.Extensions { public class HttpRequestWrapper : IHttpRequest { private static readonly string physicalFilePath; public Container Container { get; set; } private readonly HttpRequest request; static HttpRequestWrapper() { physicalFilePath = "~".MapHostAbsolutePath(); } public HttpRequest Request { get { return request; } } public object OriginalRequest { get { return request; } } public HttpRequestWrapper(HttpRequest request) : this(null, request) { } public HttpRequestWrapper(string operationName, HttpRequest request) { this.OperationName = operationName; this.request = request; this.Container = Container; } public T TryResolve<T>() { return Container == null ? EndpointHost.AppHost.TryResolve<T>() : Container.TryResolve<T>(); } public string OperationName { get; set; } public string ContentType { get { return request.ContentType; } } private string httpMethod; public string HttpMethod { get { return httpMethod ?? (httpMethod = request.Headers[Common.Web.HttpHeaders.XHttpMethodOverride] ?? request.HttpMethod); } } public string UserAgent { get { return request.UserAgent; } } private Dictionary<string, object> items; public Dictionary<string, object> Items { get { if (items == null) { items = new Dictionary<string, object>(); } return items; } } private string responseContentType; public string ResponseContentType { get { if (responseContentType == null) { responseContentType = this.GetResponseContentType(); } return responseContentType; } set { this.responseContentType = value; } } private Dictionary<string, Cookie> cookies; public IDictionary<string, Cookie> Cookies { get { if (cookies == null) { cookies = new Dictionary<string, Cookie>(); for (var i = 0; i < this.request.Cookies.Count; i++) { var httpCookie = this.request.Cookies[i]; var cookie = new Cookie( httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain) { HttpOnly = httpCookie.HttpOnly, Secure = httpCookie.Secure, Expires = httpCookie.Expires, }; cookies[httpCookie.Name] = cookie; } } return cookies; } } public NameValueCollection Headers { get { return request.Headers; } } public NameValueCollection QueryString { get { return request.QueryString; } } public NameValueCollection FormData { get { return request.Form; } } public string GetRawBody() { using (var reader = new StreamReader(request.InputStream)) { return reader.ReadToEnd(); } } public string RawUrl { get { return request.RawUrl; } } public string AbsoluteUri { get { try { return request.Url.AbsoluteUri.TrimEnd('/'); } catch (Exception) { //fastcgi mono, do a 2nd rounds best efforts return "http://" + request.UserHostName + request.RawUrl; } } } private string userHostAddress; public string UserHostAddress { get { return userHostAddress ?? (userHostAddress = request.Headers[HttpHeaders.XForwardedFor] ?? (request.Headers[HttpHeaders.XRealIp] ?? request.UserHostAddress)); } } public bool IsSecureConnection { get { return request.IsSecureConnection; } } public string[] AcceptTypes { get { return request.AcceptTypes; } } public string PathInfo { get { return request.GetPathInfo(); } } public string UrlHostName { get { return request.GetUrlHostName(); } } public Stream InputStream { get { return request.InputStream; } } public long ContentLength { get { return request.ContentLength; } } private IFile[] files; public IFile[] Files { get { if (files == null) { files = new IFile[request.Files.Count]; for (var i = 0; i < request.Files.Count; i++) { var reqFile = request.Files[i]; files[i] = new HttpFile { ContentType = reqFile.ContentType, ContentLength = reqFile.ContentLength, FileName = reqFile.FileName, InputStream = reqFile.InputStream, }; } } return files; } } public string ApplicationFilePath { get { return physicalFilePath; } } } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Jovian.Compiler { public class QueryEnvironment { private SortedList<string, IPoint> ID2Point; private SortedList<int, IPoint> cell2point; private Jovian.Math.GraphTheory graph; public QueryEnvironment(SortedList<string, IPoint> i2p, Jovian.Math.GraphTheory gt) { ID2Point = i2p; IList<IPoint> v = i2p.Values; graph = gt; cell2point = new SortedList<int, IPoint>(); foreach(IPoint p in v) { cell2point.Add(p.DataCell, p); } } public int GetID(string ido) { string id = ido.Trim().ToLower(); return ID2Point[id].DataCell; } public void MapDepend(int me, int dependon) { IPoint ipME = cell2point[me]; IPoint ipDEP = cell2point[dependon]; if (!ipDEP.NotifyList.Contains(ipME)) { ipDEP.NotifyList.Add(ipME); graph.Map(dependon, me); } //Console.WriteLine("Mapping:" + me + "=>" + dependon); } } public class QueryEnvironment2 { SortedList<string, int> Name2Cell; List<int> Calls; public QueryEnvironment2(SortedList<string, int> name2cell, List<int> calls) { Name2Cell = name2cell; Calls = calls; } public int GetID(string ido) { string key = ido; if (Name2Cell.ContainsKey(key)) { int idx = Name2Cell[key]; if (!Calls.Contains(idx)) Calls.Add(idx); return idx; } return -1; } } public interface Query { string php(QueryEnvironment E); string js(QueryEnvironment E); string js2(QueryEnvironment2 E); void depend(int me, QueryEnvironment E); } public class QueryStr : Query { public string str; public QueryStr(string s) { str = s; } public string php(QueryEnvironment E) { return "'" + str.Replace("'", "\\'") + "'"; } public string js(QueryEnvironment E) { return "\"" + str.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; } public string js2(QueryEnvironment2 E) { return str; } public void depend(int me, QueryEnvironment E) { } } public class QueryRef : Query { public string var; public string param; public QueryRef(string bit) { int Point = bit.IndexOf("."); if(Point < 0) { var = bit.Trim().ToLower(); param = ""; } else { var = bit.Substring(0,Point).Trim().ToLower(); param = bit.Substring(Point+1).Trim().ToLower(); } } public string php(QueryEnvironment E) { if(param.Length == 0 || param.Equals("value")) { return "$this->" + var; //return "CODEFORVALUE"; } return "$this->UnkQuery($this,'" + var + "','"+param+"')"; //return "CODEFORREFERENCE"; } public string js(QueryEnvironment E) { if(param.Length == 0 || param.Equals("value")) { return "o.l(" + E.GetID(var) + ")"; //return "CODEFORVALUE"; } return "o.p(" + E.GetID(var) + ",'"+param+"')"; //return "CODEFORREFERENCE"; } public string js2(QueryEnvironment2 E) { int cell = E.GetID(var); if (cell >= 0) { // If we can find it, then it is the RootEnvironment, else search the stack if (param.Length == 0 || param.Equals("value")) { return "a.val(" + cell + ")"; //return "CODEFORVALUE"; } return "a.fld(" + cell + ",'" + param + "')"; } else { if (param.Length == 0 || param.Equals("value")) { return "o.ev('" + var + "')"; } else { return "o.ev('" + var + "')"; } } //return "CODEFORREFERENCE"; } public void depend(int me, QueryEnvironment E) { E.MapDepend(me,E.GetID(var)); } } public class QueryCompiler { #region Query Parsing public class Result { public string Head; public string QueryBit; public string Tail; public static Result Pull(string X) { int kLeft = X.IndexOf("{"); int kRight = X.IndexOf("}"); Result R = new Result(); if (kLeft >= 0) { R.Head = X.Substring(0, kLeft); R.Tail = X.Substring(kRight + 1); R.QueryBit = X.Substring(kLeft + 1, kRight - kLeft - 1); } else { R.Head = X; R.Tail = ""; R.QueryBit = ""; } return R; } } #endregion Query Parsing #region Query Compilation public static Query[] Pass0(string X) { ArrayList Q = new ArrayList(); string Y = X; //Console.WriteLine("QUERY:" + X); while (Y.Length > 0) { Result R = Result.Pull(Y); if (R.Head.Length > 0) Q.Add(new QueryStr(R.Head)); if (R.QueryBit.Length > 0) Q.Add(new QueryRef(R.QueryBit)); Y = R.Tail; } Query[] A = new Query[Q.Count]; for (int k = 0; k < Q.Count; k++) A[k] = Q[k] as Query; return A; } public static string Pass1(QueryEnvironment E, Query[] Q) { string x = ""; for (int k = 0; k < Q.Length; k++) { if (k > 0) x += "+"; x += Q[k].js(E); } if (x.Equals("")) return "''"; return x; } public static string CompileJS(QueryEnvironment E, string X) { return Pass1(E,Pass0(X)); } #endregion Query Compilation } public class SuperCodeQueryCompiler { #region Query Parsing public class Result { public string Head; public string QueryBit; public string Tail; public static Result Pull(string X) { int kLeft = X.IndexOf("{"); int kRight = X.IndexOf("}"); Result R = new Result(); if (kLeft >= 0) { R.Head = X.Substring(0, kLeft); R.Tail = X.Substring(kRight + 1); R.QueryBit = X.Substring(kLeft + 1, kRight - kLeft - 1); } else { R.Head = X; R.Tail = ""; R.QueryBit = ""; } return R; } } #endregion Query Parsing #region Query Compilation public static Query[] Pass0(string X) { ArrayList Q = new ArrayList(); string Y = X; while (Y.Length > 0) { Result R = Result.Pull(Y); if (R.Head.Length > 0) Q.Add(new QueryStr(R.Head)); if (R.QueryBit.Length > 0) Q.Add(new QueryRef(R.QueryBit)); Y = R.Tail; } Query[] A = new Query[Q.Count]; for (int k = 0; k < Q.Count; k++) A[k] = Q[k] as Query; return A; } public static string Pass1(QueryEnvironment2 E, Query[] Q) { string x = ""; for (int k = 0; k < Q.Length; k++) { x += Q[k].js2(E); } if (x.Equals("")) return "''"; return x; } public static string CompileJS(QueryEnvironment2 E, string X) { return Pass1(E,Pass0(X)); } #endregion Query Compilation } /* public class QueryStr : Query { public string str; #region Query Members public QueryStr(string s) { str = s; } public string js(Env E) { return "\"" + E.IDSub(str).Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; } public string jsD(Env E) { return "\"" + str.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; } public string php() { return "\"" + str.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("" + (char)10, " ").Replace("" + (char)13, " ") + "\""; } public string sample_sql() { return str; } public string pjs() { return str; } #endregion } public class QueryRef : Query { public string var; public int cell; public string param; public bool isOverride; public string Override; public bool verySpecialOverride; public string rezFunc; #region Query Members public QueryRef(Env E, string bito) { string bit = bito; rezFunc = ""; int Point = bit.IndexOf("."); verySpecialOverride = false; if (bit[0] == '!') { isOverride = true; Override = "\"" + CommandCompiler.CompileJs(E, bit.Substring(1).ToLower().Trim()).Replace("\"", "'") + "\""; } else if (bit[0] == '@') { isOverride = true; if (bit[1] == ' ') Override = "zAct(" + CommandCompiler.CompileJsActive(E, bit.Substring(1).ToLower().Trim(), true) + ")"; else { string cmdcmd = bit.Substring(1, bit.IndexOf(" ") - 1); string bit2 = bit.Substring(bit.IndexOf(" ") + 1); Override = "z" + cmdcmd.ToUpper() + "(" + CommandCompiler.CompileJsActive(E, bit2.ToLower().Trim(), true) + ")"; } } else if (bit[0] == '$') { isOverride = true; verySpecialOverride = true; string cmdcmd = bit.Substring(1, bit.IndexOf(" ") - 1).Trim(); string bit2 = bit.Substring(bit.IndexOf(" ") + 1).Trim(); Point = bit2.IndexOf("."); var = bit2.Substring(0, Point).Trim().ToLower(); param = bit2.Substring(Point + 1).Trim(); Override = "z" + cmdcmd.ToUpper() + "('" + var.ToLower() + "')"; } else { if (bit[0] == '#') { rezFunc = "zBRtab"; //rezFunc = bit.Substring(1, bit.IndexOf(" ") - 1).Trim(); bit = bit.Substring(bit.IndexOf(" ") + 1).Trim(); Point = bit.IndexOf("."); } else if (bit[0] == '^') { rezFunc = "zNonZero"; bit = bit.Substring(bit.IndexOf(" ") + 1).Trim(); Point = bit.IndexOf("."); } isOverride = false; if (Point >= 0) { var = bit.Substring(0, Point).Trim().ToLower(); param = bit.Substring(Point + 1).Trim(); } else { var = bit.Trim().ToLower(); param = ""; cell = 0; } } } public string jsD(Env E) { throw new Exception("-1"); } public string js(Env E) { if (isOverride) { return Override; } else { Control C = E.Find(var); string rz = ""; if (C != null) { cell = E.Find(var).DataCell; if (C is DataPanel || C is DataLink) { rz = "zZ(gV(" + cell + ",'" + param.ToLower().Trim() + "'))"; } else if (param.Equals("value") || param.Equals('v') || param.Equals("vle")) { rz = "v(" + cell + ")"; } else { rz = "zZ(" + E.CellArray + "[" + cell + "]." + param + ")"; } if (rezFunc.Length > 0) { rz = rezFunc + "(" + rz + ")"; } return rz; } else { return "gU('" + var + "','" + param + "')"; } } } public string php() { throw new Exception("-1"); } public string sample_sql() { return ""; } public string pjs() { throw new Exception("-1"); } #endregion } public class QueryRefSql : Query { public string var; #region Query Members public QueryRefSql(string bit) { var = bit; } public string js(Env E) { throw new Exception("-1"); } public string jsD(Env E) { if (var[0] == '@') { return "'" + E.FindD(var.Substring(1).Trim()).ID + "'"; } try { return "m.v('" + E.FindD(var).ID + "')"; } catch (Exception eerr) { string fiddle = eerr.Message; return "m.v('" + var + "')"; } } public string php() { try { if (var[0] == '!') { return "SECUREN($inputs[" + (Int32.Parse(var.Substring(1).Trim()) + 1) + "])"; } return "SECURE($inputs[" + (Int32.Parse(var.Trim()) + 1) + "])"; } catch (Exception EEEE) { string HackWarning = EEEE.Message; return "SECURE($inputs['" + var + "'])"; } } public string sample_sql() { return "'1'"; } public string pjs() { return "lV(k,r,'{" + var + "}')"; } #endregion } public class QueryCompiler { #region Query Parsing public class Result { public string Head; public string QueryBit; public string Tail; public static Result Pull(string X) { int kLeft = X.IndexOf("{"); int kRight = X.IndexOf("}"); Result R = new Result(); if (kLeft >= 0) { R.Head = X.Substring(0, kLeft); R.Tail = X.Substring(kRight + 1); R.QueryBit = X.Substring(kLeft + 1, kRight - kLeft - 1); } else { R.Head = X; R.Tail = ""; R.QueryBit = ""; } return R; } } #endregion Query Parsing #region Query Compilation public static Query[] Compile(Env E, string X) { ArrayList Q = new ArrayList(); string Y = X.Trim().Replace(".value", ".vle"); while (Y.Length > 0) { Result R = Result.Pull(Y); if (R.Head.Length > 0) Q.Add(new QueryStr(R.Head)); if (R.QueryBit.Length > 0) Q.Add(new QueryRef(E, R.QueryBit)); Y = R.Tail.Trim(); } Query[] A = new Query[Q.Count]; for (int k = 0; k < Q.Count; k++) A[k] = Q[k] as Query; return A; } public static Query[] CompileSql(string X) { ArrayList Q = new ArrayList(); string Y = X.Trim(); while (Y.Length > 0) { Result R = Result.Pull(Y); if (R.Head.Length > 0) Q.Add(new QueryStr(R.Head)); if (R.QueryBit.Length > 0) Q.Add(new QueryRefSql(R.QueryBit)); Y = R.Tail; } Query[] A = new Query[Q.Count]; for (int k = 0; k < Q.Count; k++) A[k] = Q[k] as Query; return A; } public static Query[] CompilePjs(string X) { ArrayList Q = new ArrayList(); string Y = X.Trim(); while (Y.Length > 0) { Result R = Result.Pull(Y); if (R.Head.Length > 0) Q.Add(new QueryStr(R.Head)); if (R.QueryBit.Length > 0) Q.Add(new QueryRefSql(R.QueryBit)); Y = R.Tail; } Query[] A = new Query[Q.Count]; for (int k = 0; k < Q.Count; k++) A[k] = Q[k] as Query; return A; } public static string BuildJs(Query[] Q, Env E) { string x = ""; for (int k = 0; k < Q.Length; k++) { if (k > 0) x += "+"; x += Q[k].js(E); } if (x.Equals("")) return "''"; return x; } public static string BuildPjs(Query[] Q) { string x = ""; for (int k = 0; k < Q.Length; k++) { x += Q[k].pjs(); } if (x.Equals("")) return "''"; return x + ";"; } public static string BuildSql(Query[] Q) { string x = ""; for (int k = 0; k < Q.Length; k++) { if (k > 0) x += "."; x += Q[k].php(); } if (x.Equals("")) return "''"; return x; } public static string BuildJsD(Query[] Q, Env E) { string x = ""; for (int k = 0; k < Q.Length; k++) { if (k > 0) x += "+"; x += Q[k].jsD(E); } if (x.Equals("")) return "''"; return x; } public static string BuildSqlSample(Query[] Q) { string x = ""; for (int k = 0; k < Q.Length; k++) { x += Q[k].sample_sql(); } return x; } public static string CompileJS(Env E, string X) { return BuildJs(Compile(E, X), E); } public static string CompileJSD(Env E, string X) { return BuildJsD(CompileSql(X), E); } #endregion Query Compilation } */ }
// Copyright 2013, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: thagikura@gmail.com (Takeshi Hagikura) using Google.Api.Ads.Common.Lib; using System; using System.Collections.Generic; using System.Reflection; namespace Google.Api.Ads.AdWords.Lib { /// <summary> /// Lists all the services available through this library. /// </summary> public partial class AdWordsService : AdsService { /// <summary> /// All the services available in v201306. /// </summary> public class v201306 { /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdExtensionOverrideService.html"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature AdExtensionOverrideService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdGroupAdService.html"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature AdGroupAdService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdGroupCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdGroupFeedService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupFeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdGroupService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdGroupBidModifierService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupBidModifierService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdParamService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdParamService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AdwordsUserListService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdwordsUserListService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/AlertService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AlertService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/BiddingStrategyService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BiddingStrategyService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/BudgetService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BudgetService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/BudgetOrderService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BudgetOrderService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CampaignAdExtensionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignAdExtensionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CampaignCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CampaignFeedService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignFeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CampaignService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CampaignSharedSetService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignSharedSetService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/ConstantDataService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ConstantDataService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/ConversionTrackerService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ConversionTrackerService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CustomerService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/CustomerSyncService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerSyncService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/DataService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature DataService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/ExperimentService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ExperimentService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/FeedService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/FeedItemService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedItemService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/FeedMappingService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedMappingService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/GeoLocationService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature GeoLocationService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/LocationCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LocationCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/ManagedCustomerService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ManagedCustomerService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/MediaService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MediaService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/MutateJobService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MutateJobService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/ReportDefinitionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ReportDefinitionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/SharedCriterionService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SharedCriterionService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/SharedSetService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SharedSetService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/TargetingIdeaService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TargetingIdeaService; /// <summary> /// See <a href="http://code.google.com/apis/adwords/docs/reference/v201306/TrafficEstimatorService.html"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TrafficEstimatorService; /// <summary> /// Factory type for v201306 services. /// </summary> public static readonly Type factoryType = typeof(AdWordsServiceFactory); /// <summary> /// Static constructor to initialize the service constants. /// </summary> static v201306() { AdExtensionOverrideService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdExtensionOverrideService"); AdGroupAdService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdGroupAdService"); AdGroupCriterionService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdGroupCriterionService"); AdGroupService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdGroupService"); AdGroupBidModifierService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdGroupBidModifierService"); AdGroupFeedService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdGroupFeedService"); AdParamService = AdWordsService.MakeServiceSignature("v201306", "cm", "AdParamService"); AdwordsUserListService = AdWordsService.MakeServiceSignature("v201306", "rm", "AdWordsUserListService"); AlertService = AdWordsService.MakeServiceSignature("v201306", "mcm", "AlertService"); BiddingStrategyService = AdWordsService.MakeServiceSignature("v201306", "cm", "BiddingStrategyService"); BudgetService = AdWordsService.MakeServiceSignature("v201306", "cm", "BudgetService"); BudgetOrderService = AdWordsService.MakeServiceSignature("v201306", "billing", "BudgetOrderService"); CampaignAdExtensionService = AdWordsService.MakeServiceSignature("v201306", "cm", "CampaignAdExtensionService"); CampaignCriterionService = AdWordsService.MakeServiceSignature("v201306", "cm", "CampaignCriterionService"); CampaignService = AdWordsService.MakeServiceSignature("v201306", "cm", "CampaignService"); CampaignFeedService = AdWordsService.MakeServiceSignature("v201306", "cm", "CampaignFeedService"); CampaignSharedSetService = AdWordsService.MakeServiceSignature("v201306", "cm", "CampaignSharedSetService"); ConstantDataService = AdWordsService.MakeServiceSignature("v201306", "cm", "ConstantDataService"); ConversionTrackerService = AdWordsService.MakeServiceSignature("v201306", "cm", "ConversionTrackerService"); CustomerService = AdWordsService.MakeServiceSignature("v201306", "mcm", "CustomerService"); CustomerSyncService = AdWordsService.MakeServiceSignature("v201306", "ch", "CustomerSyncService"); DataService = AdWordsService.MakeServiceSignature( "v201306", "cm", "DataService"); ExperimentService = AdWordsService.MakeServiceSignature("v201306", "cm", "ExperimentService"); FeedService = AdWordsService.MakeServiceSignature("v201306", "cm", "FeedService"); FeedItemService = AdWordsService.MakeServiceSignature("v201306", "cm", "FeedItemService"); FeedMappingService = AdWordsService.MakeServiceSignature("v201306", "cm", "FeedMappingService"); GeoLocationService = AdWordsService.MakeServiceSignature("v201306", "cm", "GeoLocationService"); LocationCriterionService = AdWordsService.MakeServiceSignature("v201306", "cm", "LocationCriterionService"); ManagedCustomerService = AdWordsService.MakeServiceSignature("v201306", "mcm", "ManagedCustomerService"); MediaService = AdWordsService.MakeServiceSignature("v201306", "cm", "MediaService"); MutateJobService = AdWordsService.MakeServiceSignature("v201306", "cm", "MutateJobService"); ReportDefinitionService = AdWordsService.MakeServiceSignature("v201306", "cm", "ReportDefinitionService"); SharedCriterionService = AdWordsService.MakeServiceSignature("v201306", "cm", "SharedCriterionService"); SharedSetService = AdWordsService.MakeServiceSignature("v201306", "cm", "SharedSetService"); TargetingIdeaService = AdWordsService.MakeServiceSignature("v201306", "o", "TargetingIdeaService"); TrafficEstimatorService = AdWordsService.MakeServiceSignature("v201306", "o", "TrafficEstimatorService"); } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.Runtime.Serialization; using System.Collections.Generic; namespace System.Patterns.Caching { /// <summary> /// DataStore /// </summary> [DataContract(Name = "dataStore")] public class DataStore { private object _data; /// <summary> /// Initializes a new instance of the <see cref="DataStore"/> class. /// </summary> public DataStore() { Channel = new ChannelIndex(this); } #region Channel /// <summary> /// Gets the index base class instance associated with the current instance of the Channel class. /// </summary> /// <value>The channel.</value> public Collections.CollectionIndexer<string, DataStore> Channel { get; private set; } /// <summary> /// ChannelIndex /// </summary> private class ChannelIndex : Collections.CollectionIndexer<string, DataStore> { private DataStore _parent; private Dictionary<string, DataStore> _channelHash; /// <summary> /// Initializes a new instance of the <see cref="ChannelIndex"/> class. /// </summary> /// <param name="parent">The parent.</param> public ChannelIndex(DataStore parent) : base() { _parent = parent; } /// <summary> /// Gets or sets the <see cref="TChannel"/> with the specified key. /// </summary> /// <value></value> public override DataStore this[string key] { get { if ((string.IsNullOrEmpty(key)) || (key == CoreEx.Scope)) return _parent; if (key.StartsWith(CoreEx.Scope)) key = key.Substring(2); int scopeIndex = key.IndexOf(CoreEx.Scope); string channelKey = (scopeIndex == -1 ? key : key.Substring(0, scopeIndex)); if (_channelHash == null) _channelHash = new Dictionary<string, DataStore>(); DataStore channel2; if (!_channelHash.TryGetValue(key, out channel2)) _channelHash[key] = channel2 = new DataStore(); return (scopeIndex == -1 ? channel2 : channel2.Channel[key.Substring(scopeIndex + CoreEx.ScopeLength)]); } set { throw new NotSupportedException(); } } /// <summary> /// Clears this instance. /// </summary> public override void Clear() { if (_channelHash != null) _channelHash.Clear(); } /// <summary> /// Gets the count of the items in collection. /// </summary> /// <value>The count.</value> public override int Count { get { return (_channelHash == null ? 0 : _channelHash.Count); } } ///// <summary> ///// Gets the generic <paramref name="TChannel"/> value associated with the specified <c>key</c>. ///// </summary> ///// <param name="key">The key whose value to get or set.</param> ///// <param name="defaultValue">The default value to return if no value is found associated with <c>key</c>.</param> ///// <returns></returns> ///// <value>Returns the generic <paramref name="TValue"/> value associated with the specified <c>key</c>.</value> //public override DataStore GetValue(string key, DataStore defaultValue) //{ // if ((string.IsNullOrEmpty(key)) || (key == CoreEx.Scope)) // return _parent; // if (key.StartsWith(CoreEx.Scope)) // key = key.Substring(CoreEx.ScopeLength); // int scopeIndex = key.IndexOf(CoreEx.Scope); // string channelKey = (scopeIndex == -1 ? key : key.Substring(0, scopeIndex)); // if (_channelHash == null) // _channelHash = new Dictionary<string, DataStore>(); // DataStore channel2; // if (!_channelHash.TryGetValue(key, out channel2)) // _channelHash[key] = channel2 = new DataStore(); // return (scopeIndex == -1 ? channel2 : channel2.Channel[key.Substring(scopeIndex + CoreEx.ScopeLength)]); //} ///// <summary> ///// Gets the generic <paramref name="TChannel"/> value associated with the specified <c>key</c>. ///// </summary> ///// <param name="index">The index whose value to get or set.</param> ///// <returns></returns> ///// <value>Returns the generic <paramref name="TValue"/> value associated with the specified <c>key</c>.</value> //public override DataStore GetValueAt(int index) //{ // throw new NotSupportedException(); // //if ((_channelHash == null) || (index >= _channelHash.Count)) // // throw new ArgumentOutOfRangeException("key"); // //return _channelHash.GetValue(index); //} /// <summary> /// Determines whether the item in collection with specified key exists. /// </summary> /// <param name="key">The key to check.</param> /// <returns> /// <c>true</c> if the specified item exists; otherwise, <c>false</c>. /// </returns> public override bool ContainsKey(string key) { if (key == null) throw new ArgumentNullException("key"); return (_channelHash == null ? false : _channelHash.ContainsKey(key)); } /// <summary> /// Return an instance of <see cref="System.Collections.Generic.ICollection{TKey}"/> representing the collection of /// keys in the indexed collection. /// </summary> /// <value> /// The <see cref="System.Collections.Generic.ICollection{TKey}"/> instance containing the collection of keys. /// </value> public override ICollection<string> Keys { get { return (_channelHash == null ? null : _channelHash.Keys); } } /// <summary> /// Removes the item with the specified key. /// </summary> /// <param name="key">The key to use.</param> /// <returns></returns> public override bool Remove(string key) { if (key == null) throw new ArgumentNullException("key"); return (_channelHash == null ? false : _channelHash.Remove(key)); } /// <summary> /// Tries the get value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns></returns> public override bool TryGetValue(string key, out DataStore value) { if (key == null) throw new ArgumentNullException("key"); if (_channelHash == null) { value = null; return false; } return _channelHash.TryGetValue(key, out value); } /// <summary> /// Tries the get value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns></returns> public override bool TryGetValueAt(int index, out DataStore value) { value = null; return false; } /// <summary> /// Return an instance of <see cref="System.Collections.Generic.ICollection{TValue}"/> representing the collection of /// values in the indexed collection. /// </summary> /// <value> /// The <see cref="System.Collections.Generic.ICollection{TValue}"/> instance containing the collection of values. /// </value> public override ICollection<DataStore> Values { get { return (_channelHash == null ? null : _channelHash.Values); } } } #endregion Channel /// <summary> /// Gets or sets the data. /// </summary> /// <value>The data.</value> public object Data { get { var builder = (_data as DataStoreBuilder); if (builder != null) { bool replaceData; object data = builder(out replaceData); if (replaceData) _data = data; return data; } return _data; } set { _data = value; } } /// <summary> /// Gets or sets the key. /// </summary> /// <value>The key.</value> [DataMember(Name = "key")] /// <summary> /// Gets or sets the key. /// </summary> /// <value>The key.</value> public string Key { get; protected set; } /// <summary> /// Gets or sets the tag. /// </summary> /// <value>The tag.</value> [DataMember(Name = "tag")] public object Tag { get; set; } } }
/****************************************************************************** * 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.LdapAttributeSet.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Collections; using System.Text; namespace Novell.Directory.Ldap { /// <summary> /// A set of {@link LdapAttribute} objects. /// An <code>LdapAttributeSet</code> is a collection of <code>LdapAttribute</code> /// classes as returned from an <code>LdapEntry</code> on a search or read /// operation. <code>LdapAttributeSet</code> may be also used to contruct an entry /// to be added to a directory. If the <code>add()</code> or <code>addAll()</code> /// methods are called and one or more of the objects to be added is not /// an <code>LdapAttribute, ClassCastException</code> is thrown (as discussed in the /// documentation for <code>java.util.Collection</code>). /// </summary> /// <seealso cref="LdapAttribute"> /// </seealso> /// <seealso cref="LdapEntry"> /// </seealso> public class LdapAttributeSet : SupportClass.AbstractSetSupport //, SupportClass.SetSupport { /// <summary> /// Returns the number of attributes in this set. /// </summary> /// <returns> /// number of attributes in this set. /// </returns> public override int Count { get { return map.Count; } } /// <summary> /// This is the underlying data structure for this set. /// HashSet is similar to the functionality of this set. The difference /// is we use the name of an attribute as keys in the Map and LdapAttributes /// as the values. We also do not declare the map as transient, making the /// map serializable. /// </summary> private readonly Hashtable map; /// <summary> Constructs an empty set of attributes.</summary> public LdapAttributeSet() { map = new Hashtable(); } // --- methods not defined in Set --- /// <summary> /// Returns a deep copy of this attribute set. /// </summary> /// <returns> /// A deep copy of this attribute set. /// </returns> public override object Clone() { try { var newObj = MemberwiseClone(); var i = GetEnumerator(); while (i.MoveNext()) { ((LdapAttributeSet) newObj).Add(((LdapAttribute) i.Current).Clone()); } return newObj; } catch (Exception ce) { throw new Exception("Internal error, cannot create clone", ce); } } /// <summary> /// Returns the attribute matching the specified attrName. /// For example: /// <ul> /// <li><code>getAttribute("cn")</code> returns only the "cn" attribute</li> /// <li> /// <code>getAttribute("cn;lang-en")</code> returns only the "cn;lang-en" /// attribute. /// </li> /// </ul> /// In both cases, <code>null</code> is returned if there is no exact match to /// the specified attrName. /// Note: Novell eDirectory does not currently support language subtypes. /// It does support the "binary" subtype. /// </summary> /// <param name="attrName"> /// The name of an attribute to retrieve, with or without /// subtype specifications. For example, "cn", "cn;phonetic", and /// "cn;binary" are valid attribute names. /// </param> /// <returns> /// The attribute matching the specified attrName, or <code>null</code> /// if there is no exact match. /// </returns> public virtual LdapAttribute getAttribute(string attrName) { return (LdapAttribute) map[attrName.ToUpper()]; } /// <summary> /// Returns a single best-match attribute, or <code>null</code> if no match is /// available in the entry. /// Ldap version 3 allows adding a subtype specification to an attribute /// name. For example, "cn;lang-ja" indicates a Japanese language /// subtype of the "cn" attribute and "cn;lang-ja-JP-kanji" may be a subtype /// of "cn;lang-ja". This feature may be used to provide multiple /// localizations in the same directory. For attributes which do not vary /// among localizations, only the base attribute may be stored, whereas /// for others there may be varying degrees of specialization. /// For example, <code>getAttribute(attrName,lang)</code> returns the /// <code>LdapAttribute</code> that exactly matches attrName and that /// best matches lang. /// If there are subtypes other than "lang" subtypes included /// in attrName, for example, "cn;binary", only attributes with all of /// those subtypes are returned. If lang is <code>null</code> or empty, the /// method behaves as getAttribute(attrName). If there are no matching /// attributes, <code>null</code> is returned. /// Assume the entry contains only the following attributes: /// <ul> /// <li>cn;lang-en</li> /// <li>cn;lang-ja-JP-kanji</li> /// <li>sn</li> /// </ul> /// Examples: /// <ul> /// <li><code>getAttribute( "cn" )</code> returns <code>null</code>.</li> /// <li><code>getAttribute( "sn" )</code> returns the "sn" attribute.</li> /// <li> /// <code>getAttribute( "cn", "lang-en-us" )</code> /// returns the "cn;lang-en" attribute. /// </li> /// <li> /// <code>getAttribute( "cn", "lang-en" )</code> /// returns the "cn;lang-en" attribute. /// </li> /// <li> /// <code>getAttribute( "cn", "lang-ja" )</code> /// returns <code>null</code>. /// </li> /// <li> /// <code>getAttribute( "sn", "lang-en" )</code> /// returns the "sn" attribute. /// </li> /// </ul> /// Note: Novell eDirectory does not currently support language subtypes. /// It does support the "binary" subtype. /// </summary> /// <param name="attrName"> /// The name of an attribute to retrieve, with or without /// subtype specifications. For example, "cn", "cn;phonetic", and /// cn;binary" are valid attribute names. /// </param> /// <param name="lang"> /// A language specification with optional subtypes /// appended using "-" as separator. For example, "lang-en", "lang-en-us", /// "lang-ja", and "lang-ja-JP-kanji" are valid language specification. /// </param> /// <returns> /// A single best-match <code>LdapAttribute</code>, or <code>null</code> /// if no match is found in the entry. /// </returns> public virtual LdapAttribute getAttribute(string attrName, string lang) { var key = attrName + ";" + lang; return (LdapAttribute) map[key.ToUpper()]; } /// <summary> /// Creates a new attribute set containing only the attributes that have /// the specified subtypes. /// For example, suppose an attribute set contains the following /// attributes: /// <ul> /// <li> cn</li> /// <li> cn;lang-ja</li> /// <li> sn;phonetic;lang-ja</li> /// <li> sn;lang-us</li> /// </ul> /// Calling the <code>getSubset</code> method and passing lang-ja as the /// argument, the method returns an attribute set containing the following /// attributes: /// <ul> /// <li>cn;lang-ja</li> /// <li>sn;phonetic;lang-ja</li> /// </ul> /// </summary> /// <param name="subtype"> /// Semi-colon delimited list of subtypes to include. For /// example: /// <ul> /// <li> "lang-ja" specifies only Japanese language subtypes</li> /// <li> "binary" specifies only binary subtypes</li> /// <li> /// "binary;lang-ja" specifies only Japanese language subtypes /// which also are binary /// </li> /// </ul> /// Note: Novell eDirectory does not currently support language subtypes. /// It does support the "binary" subtype. /// </param> /// <returns> /// An attribute set containing the attributes that match the /// specified subtype. /// </returns> public virtual LdapAttributeSet getSubset(string subtype) { // Create a new tempAttributeSet var tempAttributeSet = new LdapAttributeSet(); var i = GetEnumerator(); // Cycle throught this.attributeSet while (i.MoveNext()) { var attr = (LdapAttribute) i.Current; // Does this attribute have the subtype we are looking for. If // yes then add it to our AttributeSet, else next attribute if (attr.hasSubtype(subtype)) tempAttributeSet.Add(attr.Clone()); } return tempAttributeSet; } // --- methods defined in set --- /// <summary> /// Returns an iterator over the attributes in this set. The attributes /// returned from this iterator are not in any particular order. /// </summary> /// <returns> /// iterator over the attributes in this set /// </returns> public override IEnumerator GetEnumerator() { return map.Values.GetEnumerator(); } /// <summary> /// Returns <code>true</code> if this set contains no elements /// </summary> /// <returns> /// <code>true</code> if this set contains no elements /// </returns> public override bool IsEmpty() { return map.Count == 0; } /// <summary> /// Returns <code>true</code> if this set contains an attribute of the same name /// as the specified attribute. /// </summary> /// <param name="attr"> /// Object of type <code>LdapAttribute</code> /// </param> /// <returns> /// true if this set contains the specified attribute /// @throws ClassCastException occurs the specified Object /// is not of type LdapAttribute. /// </returns> public override bool Contains(object attr) { var attribute = (LdapAttribute) attr; return map.ContainsKey(attribute.Name.ToUpper()); } /// <summary> /// Adds the specified attribute to this set if it is not already present. /// If an attribute with the same name already exists in the set then the /// specified attribute will not be added. /// </summary> /// <param name="attr"> /// Object of type <code>LdapAttribute</code> /// </param> /// <returns> /// true if the attribute was added. /// @throws ClassCastException occurs the specified Object /// is not of type <code>LdapAttribute</code>. /// </returns> public override bool Add(object attr) { //We must enforce that attr is an LdapAttribute var attribute = (LdapAttribute) attr; var name = attribute.Name.ToUpper(); if (map.ContainsKey(name)) return false; SupportClass.PutElement(map, name, attribute); return true; } /// <summary> /// Removes the specified object from this set if it is present. /// If the specified object is of type <code>LdapAttribute</code>, the /// specified attribute will be removed. If the specified object is of type /// <code>String</code>, the attribute with a name that matches the string will /// be removed. /// </summary> /// <param name="object"> /// LdapAttribute to be removed or <code>String</code> naming /// the attribute to be removed. /// </param> /// <returns> /// true if the object was removed. /// @throws ClassCastException occurs the specified Object /// is not of type <code>LdapAttribute</code> or of type <code>String</code>. /// </returns> public override bool Remove(object object_Renamed) { string attributeName; //the name is the key to object in the HashMap if (object_Renamed is string) { attributeName = (string) object_Renamed; } else { attributeName = ((LdapAttribute) object_Renamed).Name; } if ((object) attributeName == null) { return false; } return SupportClass.HashtableRemove(map, attributeName.ToUpper()) != null; } /// <summary> Removes all of the elements from this set.</summary> public override void Clear() { map.Clear(); } /// <summary> /// Adds all <code>LdapAttribute</code> objects in the specified collection to /// this collection. /// </summary> /// <param name="c"> /// Collection of <code>LdapAttribute</code> objects. /// @throws ClassCastException occurs when an element in the /// collection is not of type <code>LdapAttribute</code>. /// </param> /// <returns> /// true if this set changed as a result of the call. /// </returns> public override bool AddAll(ICollection c) { var setChanged = false; var i = c.GetEnumerator(); while (i.MoveNext()) { // we must enforce that everything in c is an LdapAttribute // add will return true if the attribute was added if (Add(i.Current)) { setChanged = true; } } return setChanged; } /// <summary> /// Returns a string representation of this LdapAttributeSet /// </summary> /// <returns> /// a string representation of this LdapAttributeSet /// </returns> public override string ToString() { var retValue = new StringBuilder("LdapAttributeSet: "); var attrs = GetEnumerator(); var first = true; while (attrs.MoveNext()) { if (!first) { retValue.Append(" "); } first = false; var attr = (LdapAttribute) attrs.Current; retValue.Append(attr); } return retValue.ToString(); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// EndUserResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Numbers.V2.RegulatoryCompliance { public class EndUserResource : Resource { public sealed class TypeEnum : StringEnum { private TypeEnum(string value) : base(value) {} public TypeEnum() {} public static implicit operator TypeEnum(string value) { return new TypeEnum(value); } public static readonly TypeEnum Individual = new TypeEnum("individual"); public static readonly TypeEnum Business = new TypeEnum("business"); } private static Request BuildCreateRequest(CreateEndUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/EndUsers", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new End User. /// </summary> /// <param name="options"> Create EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static EndUserResource Create(CreateEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new End User. /// </summary> /// <param name="options"> Create EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<EndUserResource> CreateAsync(CreateEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new End User. /// </summary> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="type"> The type of end user of the Bundle resource </param> /// <param name="attributes"> The set of parameters that compose the End User resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static EndUserResource Create(string friendlyName, EndUserResource.TypeEnum type, object attributes = null, ITwilioRestClient client = null) { var options = new CreateEndUserOptions(friendlyName, type){Attributes = attributes}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new End User. /// </summary> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="type"> The type of end user of the Bundle resource </param> /// <param name="attributes"> The set of parameters that compose the End User resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<EndUserResource> CreateAsync(string friendlyName, EndUserResource.TypeEnum type, object attributes = null, ITwilioRestClient client = null) { var options = new CreateEndUserOptions(friendlyName, type){Attributes = attributes}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadEndUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/EndUsers", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all End User for an account. /// </summary> /// <param name="options"> Read EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static ResourceSet<EndUserResource> Read(ReadEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<EndUserResource>.FromJson("results", response.Content); return new ResourceSet<EndUserResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all End User for an account. /// </summary> /// <param name="options"> Read EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<ResourceSet<EndUserResource>> ReadAsync(ReadEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<EndUserResource>.FromJson("results", response.Content); return new ResourceSet<EndUserResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all End User for an account. /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static ResourceSet<EndUserResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadEndUserOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all End User for an account. /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<ResourceSet<EndUserResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadEndUserOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<EndUserResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<EndUserResource>.FromJson("results", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<EndUserResource> NextPage(Page<EndUserResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Numbers) ); var response = client.Request(request); return Page<EndUserResource>.FromJson("results", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<EndUserResource> PreviousPage(Page<EndUserResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Numbers) ); var response = client.Request(request); return Page<EndUserResource>.FromJson("results", response.Content); } private static Request BuildFetchRequest(FetchEndUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/EndUsers/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch specific End User Instance. /// </summary> /// <param name="options"> Fetch EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static EndUserResource Fetch(FetchEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch specific End User Instance. /// </summary> /// <param name="options"> Fetch EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<EndUserResource> FetchAsync(FetchEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch specific End User Instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static EndUserResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchEndUserOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch specific End User Instance. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<EndUserResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchEndUserOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateEndUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/EndUsers/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update an existing End User. /// </summary> /// <param name="options"> Update EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static EndUserResource Update(UpdateEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update an existing End User. /// </summary> /// <param name="options"> Update EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<EndUserResource> UpdateAsync(UpdateEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update an existing End User. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="attributes"> The set of parameters that compose the End User resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static EndUserResource Update(string pathSid, string friendlyName = null, object attributes = null, ITwilioRestClient client = null) { var options = new UpdateEndUserOptions(pathSid){FriendlyName = friendlyName, Attributes = attributes}; return Update(options, client); } #if !NET35 /// <summary> /// Update an existing End User. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> The string that you assigned to describe the resource </param> /// <param name="attributes"> The set of parameters that compose the End User resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<EndUserResource> UpdateAsync(string pathSid, string friendlyName = null, object attributes = null, ITwilioRestClient client = null) { var options = new UpdateEndUserOptions(pathSid){FriendlyName = friendlyName, Attributes = attributes}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteEndUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Numbers, "/v2/RegulatoryCompliance/EndUsers/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific End User. /// </summary> /// <param name="options"> Delete EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static bool Delete(DeleteEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific End User. /// </summary> /// <param name="options"> Delete EndUser parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteEndUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific End User. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of EndUser </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteEndUserOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific End User. /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of EndUser </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteEndUserOptions(pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a EndUserResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> EndUserResource object represented by the provided JSON </returns> public static EndUserResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<EndUserResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The type of end user of the Bundle resource /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public EndUserResource.TypeEnum Type { get; private set; } /// <summary> /// The set of parameters that compose the End Users resource /// </summary> [JsonProperty("attributes")] public object Attributes { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the End User resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private EndUserResource() { } } }
using UnityEngine; using System.Collections; [RequireComponent (typeof (Detonator))] [AddComponentMenu("Detonator/Fireball")] public class DetonatorFireball : DetonatorComponent { private float _baseSize = 1f; private float _baseDuration = 3f; private Color _baseColor = new Color(1f, .423f, 0f, .5f); private Vector3 _baseVelocity = new Vector3(60f, 60f, 60f); // private float _baseDamping = 0.1300004f; private float _scaledDuration; private GameObject _fireballA; private DetonatorBurstEmitter _fireballAEmitter; public Material fireballAMaterial; private GameObject _fireballB; private DetonatorBurstEmitter _fireballBEmitter; public Material fireballBMaterial; private GameObject _fireShadow; private DetonatorBurstEmitter _fireShadowEmitter; public Material fireShadowMaterial; public bool drawFireballA = true; public bool drawFireballB = true; public bool drawFireShadow = true; override public void Init() { //make sure there are materials at all FillMaterials(false); BuildFireballA(); BuildFireballB(); BuildFireShadow(); } //if materials are empty fill them with defaults public void FillMaterials(bool wipe) { if (!fireballAMaterial || wipe) { fireballAMaterial = MyDetonator().fireballAMaterial; } if (!fireballBMaterial || wipe) { fireballBMaterial = MyDetonator().fireballBMaterial; } if (!fireShadowMaterial || wipe) { if (Random.value > 0.5) { fireShadowMaterial = MyDetonator().smokeAMaterial; } else { fireShadowMaterial = MyDetonator().smokeBMaterial; } } } private Color _detailAdjustedColor; //Build these to look correct at the stock Detonator size of 10m... then let the size parameter //cascade through to the emitters and let them do the scaling work... keep these absolute. public void BuildFireballA() { _fireballA = new GameObject("FireballA"); _fireballAEmitter = (DetonatorBurstEmitter)_fireballA.AddComponent<DetonatorBurstEmitter>(); _fireballA.transform.parent = this.transform; _fireballA.transform.localRotation = Quaternion.identity; _fireballAEmitter.material = fireballAMaterial; _fireballAEmitter.useWorldSpace = MyDetonator().useWorldSpace; _fireballAEmitter.upwardsBias = MyDetonator().upwardsBias; } public void UpdateFireballA() { _fireballA.transform.localPosition = Vector3.Scale(localPosition,(new Vector3(size, size, size))); _fireballAEmitter.color = color; _fireballAEmitter.duration = duration * .5f; _fireballAEmitter.durationVariation = duration * .5f; _fireballAEmitter.count = 2f; _fireballAEmitter.timeScale = timeScale; _fireballAEmitter.detail = detail; _fireballAEmitter.particleSize = 14f; _fireballAEmitter.sizeVariation = 3f; _fireballAEmitter.velocity = velocity; _fireballAEmitter.startRadius = 4f; _fireballAEmitter.size = size; _fireballAEmitter.useExplicitColorAnimation = true; //make the starting colors more intense, towards white Color fadeWhite = new Color(1f, 1f, 1f, .5f); Color fadeRed = new Color(.6f, .15f, .15f, .3f); Color fadeBlue = new Color(.1f, .2f, .45f, 0f); _fireballAEmitter.colorAnimation[0] = Color.Lerp(color, fadeWhite, .8f); _fireballAEmitter.colorAnimation[1] = Color.Lerp(color, fadeWhite, .5f); _fireballAEmitter.colorAnimation[2] = color; _fireballAEmitter.colorAnimation[3] = Color.Lerp(color, fadeRed, .7f); _fireballAEmitter.colorAnimation[4] = fadeBlue; _fireballAEmitter.explodeDelayMin = explodeDelayMin; _fireballAEmitter.explodeDelayMax = explodeDelayMax; } public void BuildFireballB() { _fireballB = new GameObject("FireballB"); _fireballBEmitter = (DetonatorBurstEmitter)_fireballB.AddComponent<DetonatorBurstEmitter>(); _fireballB.transform.parent = this.transform; _fireballB.transform.localRotation = Quaternion.identity; _fireballBEmitter.material = fireballBMaterial; _fireballBEmitter.useWorldSpace = MyDetonator().useWorldSpace; _fireballBEmitter.upwardsBias = MyDetonator().upwardsBias; } public void UpdateFireballB() { _fireballB.transform.localPosition = Vector3.Scale(localPosition,(new Vector3(size, size, size))); _fireballBEmitter.color = color; _fireballBEmitter.duration = duration * .5f; _fireballBEmitter.durationVariation = duration * .5f; _fireballBEmitter.count = 2f; _fireballBEmitter.timeScale = timeScale; _fireballBEmitter.detail = detail; _fireballBEmitter.particleSize = 10f; _fireballBEmitter.sizeVariation = 6f; _fireballBEmitter.velocity = velocity; _fireballBEmitter.startRadius = 4f; _fireballBEmitter.size = size; _fireballBEmitter.useExplicitColorAnimation = true; //make the starting colors more intense, towards white Color fadeWhite = new Color(1f, 1f, 1f, .5f); Color fadeRed = new Color(.6f, .15f, .15f, .3f); Color fadeBlue = new Color(.1f, .2f, .45f, 0f); _fireballBEmitter.colorAnimation[0] = Color.Lerp(color, fadeWhite, .8f); _fireballBEmitter.colorAnimation[1] = Color.Lerp(color, fadeWhite, .5f); _fireballBEmitter.colorAnimation[2] = color; _fireballBEmitter.colorAnimation[3] = Color.Lerp(color, fadeRed, .7f); _fireballBEmitter.colorAnimation[4] = fadeBlue; _fireballBEmitter.explodeDelayMin = explodeDelayMin; _fireballBEmitter.explodeDelayMax = explodeDelayMax; } public void BuildFireShadow() { _fireShadow = new GameObject("FireShadow"); _fireShadowEmitter = (DetonatorBurstEmitter)_fireShadow.AddComponent<DetonatorBurstEmitter>(); _fireShadow.transform.parent = this.transform; _fireShadow.transform.localRotation = Quaternion.identity; _fireShadowEmitter.material = fireShadowMaterial; _fireShadowEmitter.useWorldSpace = MyDetonator().useWorldSpace; _fireShadowEmitter.upwardsBias = MyDetonator().upwardsBias; } public void UpdateFireShadow() { _fireShadow.transform.localPosition = Vector3.Scale(localPosition,(new Vector3(size, size, size))); //move slightly towards the main camera so it sorts properly _fireShadow.transform.LookAt(Camera.main.transform); _fireShadow.transform.localPosition = -(Vector3.forward * 1f); _fireShadowEmitter.color = new Color(.1f, .1f, .1f, .6f); _fireShadowEmitter.duration = duration * .5f; _fireShadowEmitter.durationVariation = duration * .5f; _fireShadowEmitter.timeScale = timeScale; _fireShadowEmitter.detail = 1; //don't scale up count _fireShadowEmitter.particleSize = 13f; _fireShadowEmitter.velocity = velocity; _fireShadowEmitter.sizeVariation = 1f; _fireShadowEmitter.count = 4; _fireShadowEmitter.startRadius = 6f; _fireShadowEmitter.size = size; _fireShadowEmitter.explodeDelayMin = explodeDelayMin; _fireShadowEmitter.explodeDelayMax = explodeDelayMax; } public void Reset() { FillMaterials(true); on = true; size = _baseSize; duration = _baseDuration; explodeDelayMin = 0f; explodeDelayMax = 0f; color = _baseColor; velocity = _baseVelocity; } override public void Explode() { if (detailThreshold > detail) return; if (on) { UpdateFireballA(); UpdateFireballB(); UpdateFireShadow(); if (drawFireballA) _fireballAEmitter.Explode(); if (drawFireballB) _fireballBEmitter.Explode(); if (drawFireShadow) _fireShadowEmitter.Explode(); } } }
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. // // This material may not be duplicated in whole or in part, except for // personal use, without the express written consent of the author. // // Email: ianier@hotmail.com // // Copyright (C) 1999-2003 Ianier Munoz. All Rights Reserved. // The methods commented with <summary> tags have been inserted by // Corinna John, EMail: picturekey@binary-universe.net // Anybody who knows a little about the wave format could have // written these enhancements, so I don't claim any rights, // do whatever you want with them. using System; using System.IO; namespace SoundCatcher { internal class WaveStream : Stream { private readonly Stream _mStream; private long _mDataPos; private int _mLength; private WaveFormat Format { get; set; } private static string ReadChunk(BinaryReader reader) { byte[] ch = new byte[4]; reader.Read(ch, 0, ch.Length); return System.Text.Encoding.ASCII.GetString(ch); } private void ReadHeader() { BinaryReader reader = new BinaryReader(_mStream); if (ReadChunk(reader) != "RIFF") throw new Exception("Invalid file format"); reader.ReadInt32(); // File length minus first 8 bytes of RIFF description, we don't use it if (ReadChunk(reader) != "WAVE") throw new Exception("Invalid file format"); if (ReadChunk(reader) != "fmt ") throw new Exception("Invalid file format"); int len = reader.ReadInt32(); if (len < 16) // bad format chunk length throw new Exception("Invalid file format"); Format = new WaveFormat(22050, 16, 2) {wFormatTag = reader.ReadInt16(), nChannels = reader.ReadInt16(), nSamplesPerSec = reader.ReadInt32(), nAvgBytesPerSec = reader.ReadInt32(), nBlockAlign = reader.ReadInt16(), wBitsPerSample = reader.ReadInt16()}; // initialize to any format // advance in the stream to skip the wave format block len -= 16; // minimum format size while (len > 0) { reader.ReadByte(); len--; } // assume the data chunk is aligned while (_mStream.Position < _mStream.Length && ReadChunk(reader) != "data") { } if (_mStream.Position >= _mStream.Length) throw new Exception("Invalid file format"); _mLength = reader.ReadInt32(); _mDataPos = _mStream.Position; Position = 0; } /// <summary>ReadChunk(reader) - Changed to CopyChunk(reader, writer)</summary> /// <param name="reader">source stream</param> /// <param name="writer"></param> /// <returns>four characters</returns> private static string CopyChunk(BinaryReader reader, BinaryWriter writer) { byte[] ch = new byte[4]; reader.Read(ch, 0, ch.Length); //copy the chunk writer.Write(ch); return System.Text.Encoding.ASCII.GetString(ch); } /// <summary>ReadHeader() - Changed to CopyHeader(destination)</summary> private void CopyHeader(Stream destinationStream) { BinaryReader reader = new BinaryReader(_mStream); BinaryWriter writer = new BinaryWriter(destinationStream); if (CopyChunk(reader, writer) != "RIFF") throw new Exception("Invalid file format"); writer.Write(reader.ReadInt32()); // File length minus first 8 bytes of RIFF description if (CopyChunk(reader, writer) != "WAVE") throw new Exception("Invalid file format"); if (CopyChunk(reader, writer) != "fmt ") throw new Exception("Invalid file format"); int len = reader.ReadInt32(); if (len < 16) { // bad format chunk length throw new Exception("Invalid file format"); } writer.Write(len); Format = new WaveFormat(22050, 16, 2) { wFormatTag = reader.ReadInt16(), nChannels = reader.ReadInt16(), nSamplesPerSec = reader.ReadInt32(), nAvgBytesPerSec = reader.ReadInt32(), nBlockAlign = reader.ReadInt16(), wBitsPerSample = reader.ReadInt16() }; // initialize to any format //copy format information writer.Write(Format.wFormatTag); writer.Write(Format.nChannels); writer.Write(Format.nSamplesPerSec); writer.Write(Format.nAvgBytesPerSec); writer.Write(Format.nBlockAlign); writer.Write(Format.wBitsPerSample); // advance in the stream to skip the wave format block len -= 16; // minimum format size writer.Write(reader.ReadBytes(len)); /*while (len > 0) { reader.ReadByte(); len--; }*/ // assume the data chunk is aligned while (_mStream.Position < _mStream.Length && CopyChunk(reader, writer) != "data") { } if (_mStream.Position >= _mStream.Length) throw new Exception("Invalid file format"); _mLength = reader.ReadInt32(); writer.Write(_mLength); _mDataPos = _mStream.Position; Position = 0; } /// <summary>Write a new header</summary> public static Stream CreateStream(Stream waveData, WaveFormat format) { MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); writer.Write(System.Text.Encoding.ASCII.GetBytes("RIFF".ToCharArray())); writer.Write((Int32)(waveData.Length + 36)); //File length minus first 8 bytes of RIFF description writer.Write(System.Text.Encoding.ASCII.GetBytes("WAVEfmt ".ToCharArray())); writer.Write(16); //length of following chunk: 16 writer.Write(format.wFormatTag); writer.Write(format.nChannels); writer.Write(format.nSamplesPerSec); writer.Write(format.nAvgBytesPerSec); writer.Write(format.nBlockAlign); writer.Write(format.wBitsPerSample); writer.Write(System.Text.Encoding.ASCII.GetBytes("data".ToCharArray())); writer.Write((Int32)waveData.Length); waveData.Seek(0, SeekOrigin.Begin); byte[] b = new byte[waveData.Length]; waveData.Read(b, 0, (int)waveData.Length); writer.Write(b); writer.Seek(0, SeekOrigin.Begin); return stream; } public WaveStream(Stream sourceStream, Stream destinationStream) { _mStream = sourceStream; CopyHeader(destinationStream); } public WaveStream(Stream sourceStream) { _mStream = sourceStream; ReadHeader(); } ~WaveStream() { Dispose(); } //public void Dispose() //{ // if (m_Stream != null) // m_Stream.Close(); // GC.SuppressFinalize(this); //} public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _mLength; } } /// <summary>Length of the data (in samples)</summary> public long CountSamples { get { return (_mLength - _mDataPos) / (Format.wBitsPerSample / 8); } } public override long Position { get { return _mStream.Position - _mDataPos; } set { Seek(value, SeekOrigin.Begin); } } public override void Close() { Dispose(); } public override void Flush() { } public override void SetLength(long len) { throw new InvalidOperationException(); } public override long Seek(long pos, SeekOrigin o) { switch (o) { case SeekOrigin.Begin: _mStream.Position = pos + _mDataPos; break; case SeekOrigin.Current: _mStream.Seek(pos, SeekOrigin.Current); break; case SeekOrigin.End: _mStream.Position = _mDataPos + _mLength - pos; break; } return Position; } public override int Read(byte[] buf, int ofs, int count) { int toread = (int)Math.Min(count, _mLength - Position); return _mStream.Read(buf, ofs, toread); } /// <summary>Read - Changed to Copy</summary> /// <param name="buf">Buffer to receive the data</param> /// <param name="ofs">Offset</param> /// <param name="count">Count of bytes to read</param> /// <param name="destination">Where to copy the buffer</param> /// <returns>Count of bytes actually read</returns> public int Copy(byte[] buf, int ofs, int count, Stream destination) { int toread = (int)Math.Min(count, _mLength - Position); int read = _mStream.Read(buf, ofs, toread); destination.Write(buf, ofs, read); if (_mStream.Position != destination.Position) Console.WriteLine(); return read; } public override void Write(byte[] buf, int ofs, int count) { throw new InvalidOperationException(); } } }
// Copyright 2016, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Logging.V2 { /// <summary> /// Settings for a <see cref="ConfigServiceV2Client"/>. /// </summary> public sealed partial class ConfigServiceV2Settings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="ConfigServiceV2Settings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="ConfigServiceV2Settings"/>. /// </returns> public static ConfigServiceV2Settings GetDefault() => new ConfigServiceV2Settings(); /// <summary> /// Constructs a new <see cref="ConfigServiceV2Settings"/> object with default settings. /// </summary> public ConfigServiceV2Settings() { } private ConfigServiceV2Settings(ConfigServiceV2Settings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListSinksSettings = existing.ListSinksSettings; GetSinkSettings = existing.GetSinkSettings; CreateSinkSettings = existing.CreateSinkSettings; UpdateSinkSettings = existing.UpdateSinkSettings; DeleteSinkSettings = existing.DeleteSinkSettings; } /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="ConfigServiceV2Client"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="ConfigServiceV2Client"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="ConfigServiceV2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="ConfigServiceV2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="ConfigServiceV2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 1000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.2</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(1000), delayMultiplier: 1.2 ); /// <summary> /// "Default" timeout backoff for <see cref="ConfigServiceV2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="ConfigServiceV2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="ConfigServiceV2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 2000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Maximum timeout: 30000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(2000), maxDelay: TimeSpan.FromMilliseconds(30000), delayMultiplier: 1.5 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ConfigServiceV2Client.ListSinks</c> and <c>ConfigServiceV2Client.ListSinksAsync</c>. /// </summary> /// <remarks> /// The default <c>ConfigServiceV2Client.ListSinks</c> and /// <c>ConfigServiceV2Client.ListSinksAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 2000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings ListSinksSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ConfigServiceV2Client.GetSink</c> and <c>ConfigServiceV2Client.GetSinkAsync</c>. /// </summary> /// <remarks> /// The default <c>ConfigServiceV2Client.GetSink</c> and /// <c>ConfigServiceV2Client.GetSinkAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 2000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings GetSinkSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ConfigServiceV2Client.CreateSink</c> and <c>ConfigServiceV2Client.CreateSinkAsync</c>. /// </summary> /// <remarks> /// The default <c>ConfigServiceV2Client.CreateSink</c> and /// <c>ConfigServiceV2Client.CreateSinkAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 2000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings CreateSinkSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ConfigServiceV2Client.UpdateSink</c> and <c>ConfigServiceV2Client.UpdateSinkAsync</c>. /// </summary> /// <remarks> /// The default <c>ConfigServiceV2Client.UpdateSink</c> and /// <c>ConfigServiceV2Client.UpdateSinkAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 2000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings UpdateSinkSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ConfigServiceV2Client.DeleteSink</c> and <c>ConfigServiceV2Client.DeleteSinkAsync</c>. /// </summary> /// <remarks> /// The default <c>ConfigServiceV2Client.DeleteSink</c> and /// <c>ConfigServiceV2Client.DeleteSinkAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.2</description></item> /// <item><description>Retry maximum delay: 1000 milliseconds</description></item> /// <item><description>Initial timeout: 2000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.5</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 45000 milliseconds. /// </remarks> public CallSettings DeleteSinkSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="ConfigServiceV2Settings"/> object.</returns> public ConfigServiceV2Settings Clone() => new ConfigServiceV2Settings(this); } /// <summary> /// ConfigServiceV2 client wrapper, for convenient use. /// </summary> public abstract partial class ConfigServiceV2Client { /// <summary> /// The default endpoint for the ConfigServiceV2 service, which is a host of "logging.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("logging.googleapis.com", 443); /// <summary> /// The default ConfigServiceV2 scopes. /// </summary> /// <remarks> /// The default ConfigServiceV2 scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// <item><description>"https://www.googleapis.com/auth/cloud-platform.read-only"</description></item> /// <item><description>"https://www.googleapis.com/auth/logging.admin"</description></item> /// <item><description>"https://www.googleapis.com/auth/logging.read"</description></item> /// <item><description>"https://www.googleapis.com/auth/logging.write"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read", "https://www.googleapis.com/auth/logging.write", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); /// <summary> /// Path template for a parent resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// </list> /// </summary> public static PathTemplate ParentTemplate { get; } = new PathTemplate("projects/{project}"); /// <summary> /// Creates a parent resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <returns> /// The full parent resource name. /// </returns> public static string FormatParentName(string projectId) => ParentTemplate.Expand(projectId); /// <summary> /// Path template for a sink resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// <item><description>sink</description></item> /// </list> /// </summary> public static PathTemplate SinkTemplate { get; } = new PathTemplate("projects/{project}/sinks/{sink}"); /// <summary> /// Creates a sink resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <param name="sinkId">The sink ID.</param> /// <returns> /// The full sink resource name. /// </returns> public static string FormatSinkName(string projectId, string sinkId) => SinkTemplate.Expand(projectId, sinkId); /// <summary> /// Path template for a metric resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// <item><description>metric</description></item> /// </list> /// </summary> public static PathTemplate MetricTemplate { get; } = new PathTemplate("projects/{project}/metrics/{metric}"); /// <summary> /// Creates a metric resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <param name="metricId">The metric ID.</param> /// <returns> /// The full metric resource name. /// </returns> public static string FormatMetricName(string projectId, string metricId) => MetricTemplate.Expand(projectId, metricId); /// <summary> /// Path template for a log resource. Parameters: /// <list type="bullet"> /// <item><description>project</description></item> /// <item><description>log</description></item> /// </list> /// </summary> public static PathTemplate LogTemplate { get; } = new PathTemplate("projects/{project}/logs/{log}"); /// <summary> /// Creates a log resource name from its component IDs. /// </summary> /// <param name="projectId">The project ID.</param> /// <param name="logId">The log ID.</param> /// <returns> /// The full log resource name. /// </returns> public static string FormatLogName(string projectId, string logId) => LogTemplate.Expand(projectId, logId); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="ConfigServiceV2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ConfigServiceV2Settings"/>.</param> /// <returns>The task representing the created <see cref="ConfigServiceV2Client"/>.</returns> public static async Task<ConfigServiceV2Client> CreateAsync(ServiceEndpoint endpoint = null, ConfigServiceV2Settings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="ConfigServiceV2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ConfigServiceV2Settings"/>.</param> /// <returns>The created <see cref="ConfigServiceV2Client"/>.</returns> public static ConfigServiceV2Client Create(ServiceEndpoint endpoint = null, ConfigServiceV2Settings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="ConfigServiceV2Client"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ConfigServiceV2Settings"/>.</param> /// <returns>The created <see cref="ConfigServiceV2Client"/>.</returns> public static ConfigServiceV2Client Create(Channel channel, ConfigServiceV2Settings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); ConfigServiceV2.ConfigServiceV2Client grpcClient = new ConfigServiceV2.ConfigServiceV2Client(channel); return new ConfigServiceV2ClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ConfigServiceV2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ConfigServiceV2Settings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ConfigServiceV2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ConfigServiceV2Settings)"/> 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 Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC ConfigServiceV2 client. /// </summary> public virtual ConfigServiceV2.ConfigServiceV2Client GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Lists sinks. /// </summary> /// <param name="parent"> /// Required. The cloud resource containing the sinks. /// Example: `"projects/my-logging-project"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="LogSink"/> resources. /// </returns> public virtual IPagedAsyncEnumerable<ListSinksResponse, LogSink> ListSinksAsync( string parent, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists sinks. /// </summary> /// <param name="parent"> /// Required. The cloud resource containing the sinks. /// Example: `"projects/my-logging-project"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="LogSink"/> resources. /// </returns> public virtual IPagedEnumerable<ListSinksResponse, LogSink> ListSinks( string parent, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to return. /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogSink> GetSinkAsync( string sinkName, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to return. /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogSink> GetSinkAsync( string sinkName, CancellationToken cancellationToken) => GetSinkAsync( sinkName, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to return. /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogSink GetSink( string sinkName, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates a sink. /// </summary> /// <param name="parent"> /// Required. The resource in which to create the sink. /// Example: `"projects/my-project-id"`. /// The new sink must be provided in the request. /// </param> /// <param name="sink"> /// Required. The new sink, whose `name` parameter is a sink identifier that /// is not already in use. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogSink> CreateSinkAsync( string parent, LogSink sink, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Creates a sink. /// </summary> /// <param name="parent"> /// Required. The resource in which to create the sink. /// Example: `"projects/my-project-id"`. /// The new sink must be provided in the request. /// </param> /// <param name="sink"> /// Required. The new sink, whose `name` parameter is a sink identifier that /// is not already in use. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogSink> CreateSinkAsync( string parent, LogSink sink, CancellationToken cancellationToken) => CreateSinkAsync( parent, sink, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a sink. /// </summary> /// <param name="parent"> /// Required. The resource in which to create the sink. /// Example: `"projects/my-project-id"`. /// The new sink must be provided in the request. /// </param> /// <param name="sink"> /// Required. The new sink, whose `name` parameter is a sink identifier that /// is not already in use. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogSink CreateSink( string parent, LogSink sink, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Updates or creates a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to update, including the parent /// resource and the sink identifier. If the sink does not exist, this method /// creates the sink. Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="sink"> /// Required. The updated sink, whose name is the same identifier that appears /// as part of `sinkName`. If `sinkName` does not exist, then /// this method creates a new sink. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogSink> UpdateSinkAsync( string sinkName, LogSink sink, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Updates or creates a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to update, including the parent /// resource and the sink identifier. If the sink does not exist, this method /// creates the sink. Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="sink"> /// Required. The updated sink, whose name is the same identifier that appears /// as part of `sinkName`. If `sinkName` does not exist, then /// this method creates a new sink. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<LogSink> UpdateSinkAsync( string sinkName, LogSink sink, CancellationToken cancellationToken) => UpdateSinkAsync( sinkName, sink, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates or creates a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to update, including the parent /// resource and the sink identifier. If the sink does not exist, this method /// creates the sink. Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="sink"> /// Required. The updated sink, whose name is the same identifier that appears /// as part of `sinkName`. If `sinkName` does not exist, then /// this method creates a new sink. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual LogSink UpdateSink( string sinkName, LogSink sink, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to delete, including the parent /// resource and the sink identifier. Example: /// `"projects/my-project-id/sinks/my-sink-id"`. It is an error if the sink /// does not exist. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteSinkAsync( string sinkName, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to delete, including the parent /// resource and the sink identifier. Example: /// `"projects/my-project-id/sinks/my-sink-id"`. It is an error if the sink /// does not exist. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteSinkAsync( string sinkName, CancellationToken cancellationToken) => DeleteSinkAsync( sinkName, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to delete, including the parent /// resource and the sink identifier. Example: /// `"projects/my-project-id/sinks/my-sink-id"`. It is an error if the sink /// does not exist. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteSink( string sinkName, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// ConfigServiceV2 client wrapper implementation, for convenient use. /// </summary> public sealed partial class ConfigServiceV2ClientImpl : ConfigServiceV2Client { private readonly ClientHelper _clientHelper; private readonly ApiCall<ListSinksRequest, ListSinksResponse> _callListSinks; private readonly ApiCall<GetSinkRequest, LogSink> _callGetSink; private readonly ApiCall<CreateSinkRequest, LogSink> _callCreateSink; private readonly ApiCall<UpdateSinkRequest, LogSink> _callUpdateSink; private readonly ApiCall<DeleteSinkRequest, Empty> _callDeleteSink; /// <summary> /// Constructs a client wrapper for the ConfigServiceV2 service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ConfigServiceV2Settings"/> used within this client </param> public ConfigServiceV2ClientImpl(ConfigServiceV2.ConfigServiceV2Client grpcClient, ConfigServiceV2Settings settings) { this.GrpcClient = grpcClient; ConfigServiceV2Settings effectiveSettings = settings ?? ConfigServiceV2Settings.GetDefault(); _clientHelper = new ClientHelper(effectiveSettings); _callListSinks = _clientHelper.BuildApiCall<ListSinksRequest, ListSinksResponse>( GrpcClient.ListSinksAsync, GrpcClient.ListSinks, effectiveSettings.ListSinksSettings); _callGetSink = _clientHelper.BuildApiCall<GetSinkRequest, LogSink>( GrpcClient.GetSinkAsync, GrpcClient.GetSink, effectiveSettings.GetSinkSettings); _callCreateSink = _clientHelper.BuildApiCall<CreateSinkRequest, LogSink>( GrpcClient.CreateSinkAsync, GrpcClient.CreateSink, effectiveSettings.CreateSinkSettings); _callUpdateSink = _clientHelper.BuildApiCall<UpdateSinkRequest, LogSink>( GrpcClient.UpdateSinkAsync, GrpcClient.UpdateSink, effectiveSettings.UpdateSinkSettings); _callDeleteSink = _clientHelper.BuildApiCall<DeleteSinkRequest, Empty>( GrpcClient.DeleteSinkAsync, GrpcClient.DeleteSink, effectiveSettings.DeleteSinkSettings); } /// <summary> /// The underlying gRPC ConfigServiceV2 client. /// </summary> public override ConfigServiceV2.ConfigServiceV2Client GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_ListSinksRequest(ref ListSinksRequest request, ref CallSettings settings); partial void Modify_GetSinkRequest(ref GetSinkRequest request, ref CallSettings settings); partial void Modify_CreateSinkRequest(ref CreateSinkRequest request, ref CallSettings settings); partial void Modify_UpdateSinkRequest(ref UpdateSinkRequest request, ref CallSettings settings); partial void Modify_DeleteSinkRequest(ref DeleteSinkRequest request, ref CallSettings settings); /// <summary> /// Lists sinks. /// </summary> /// <param name="parent"> /// Required. The cloud resource containing the sinks. /// Example: `"projects/my-logging-project"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="LogSink"/> resources. /// </returns> public override IPagedAsyncEnumerable<ListSinksResponse, LogSink> ListSinksAsync( string parent, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { ListSinksRequest request = new ListSinksRequest { Parent = parent, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListSinksRequest(ref request, ref callSettings); return new PagedAsyncEnumerable<ListSinksRequest, ListSinksResponse, LogSink>(_callListSinks, request, callSettings); } /// <summary> /// Lists sinks. /// </summary> /// <param name="parent"> /// Required. The cloud resource containing the sinks. /// Example: `"projects/my-logging-project"`. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="LogSink"/> resources. /// </returns> public override IPagedEnumerable<ListSinksResponse, LogSink> ListSinks( string parent, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { ListSinksRequest request = new ListSinksRequest { Parent = parent, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListSinksRequest(ref request, ref callSettings); return new PagedEnumerable<ListSinksRequest, ListSinksResponse, LogSink>(_callListSinks, request, callSettings); } /// <summary> /// Gets a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to return. /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<LogSink> GetSinkAsync( string sinkName, CallSettings callSettings = null) { GetSinkRequest request = new GetSinkRequest { SinkName = sinkName, }; Modify_GetSinkRequest(ref request, ref callSettings); return _callGetSink.Async(request, callSettings); } /// <summary> /// Gets a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to return. /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override LogSink GetSink( string sinkName, CallSettings callSettings = null) { GetSinkRequest request = new GetSinkRequest { SinkName = sinkName, }; Modify_GetSinkRequest(ref request, ref callSettings); return _callGetSink.Sync(request, callSettings); } /// <summary> /// Creates a sink. /// </summary> /// <param name="parent"> /// Required. The resource in which to create the sink. /// Example: `"projects/my-project-id"`. /// The new sink must be provided in the request. /// </param> /// <param name="sink"> /// Required. The new sink, whose `name` parameter is a sink identifier that /// is not already in use. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<LogSink> CreateSinkAsync( string parent, LogSink sink, CallSettings callSettings = null) { CreateSinkRequest request = new CreateSinkRequest { Parent = parent, Sink = sink, }; Modify_CreateSinkRequest(ref request, ref callSettings); return _callCreateSink.Async(request, callSettings); } /// <summary> /// Creates a sink. /// </summary> /// <param name="parent"> /// Required. The resource in which to create the sink. /// Example: `"projects/my-project-id"`. /// The new sink must be provided in the request. /// </param> /// <param name="sink"> /// Required. The new sink, whose `name` parameter is a sink identifier that /// is not already in use. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override LogSink CreateSink( string parent, LogSink sink, CallSettings callSettings = null) { CreateSinkRequest request = new CreateSinkRequest { Parent = parent, Sink = sink, }; Modify_CreateSinkRequest(ref request, ref callSettings); return _callCreateSink.Sync(request, callSettings); } /// <summary> /// Updates or creates a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to update, including the parent /// resource and the sink identifier. If the sink does not exist, this method /// creates the sink. Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="sink"> /// Required. The updated sink, whose name is the same identifier that appears /// as part of `sinkName`. If `sinkName` does not exist, then /// this method creates a new sink. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<LogSink> UpdateSinkAsync( string sinkName, LogSink sink, CallSettings callSettings = null) { UpdateSinkRequest request = new UpdateSinkRequest { SinkName = sinkName, Sink = sink, }; Modify_UpdateSinkRequest(ref request, ref callSettings); return _callUpdateSink.Async(request, callSettings); } /// <summary> /// Updates or creates a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to update, including the parent /// resource and the sink identifier. If the sink does not exist, this method /// creates the sink. Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </param> /// <param name="sink"> /// Required. The updated sink, whose name is the same identifier that appears /// as part of `sinkName`. If `sinkName` does not exist, then /// this method creates a new sink. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override LogSink UpdateSink( string sinkName, LogSink sink, CallSettings callSettings = null) { UpdateSinkRequest request = new UpdateSinkRequest { SinkName = sinkName, Sink = sink, }; Modify_UpdateSinkRequest(ref request, ref callSettings); return _callUpdateSink.Sync(request, callSettings); } /// <summary> /// Deletes a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to delete, including the parent /// resource and the sink identifier. Example: /// `"projects/my-project-id/sinks/my-sink-id"`. It is an error if the sink /// does not exist. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task DeleteSinkAsync( string sinkName, CallSettings callSettings = null) { DeleteSinkRequest request = new DeleteSinkRequest { SinkName = sinkName, }; Modify_DeleteSinkRequest(ref request, ref callSettings); return _callDeleteSink.Async(request, callSettings); } /// <summary> /// Deletes a sink. /// </summary> /// <param name="sinkName"> /// Required. The resource name of the sink to delete, including the parent /// resource and the sink identifier. Example: /// `"projects/my-project-id/sinks/my-sink-id"`. It is an error if the sink /// does not exist. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void DeleteSink( string sinkName, CallSettings callSettings = null) { DeleteSinkRequest request = new DeleteSinkRequest { SinkName = sinkName, }; Modify_DeleteSinkRequest(ref request, ref callSettings); _callDeleteSink.Sync(request, callSettings); } } // Partial classes to enable page-streaming public partial class ListSinksRequest : IPageRequest { } public partial class ListSinksResponse : IPageResponse<LogSink> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<LogSink> GetEnumerator() => Sinks.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
using System; using System.Collections; using System.IO; // C# Translation of GoldParser, by Marcus Klimstra <klimstra@home.nl>. // Based on GOLDParser by Devin Cook <http://www.devincook.com/goldparser>. namespace Alachisoft.NosDB.Common.Queries.Parser { /// This is the main class in the GoldParser Engine and is used to perform /// all duties required to the parsing of a source text string. This class /// contains the LALR(1) State Machine code, the DFA State Machine code, /// character table (used by the DFA algorithm) and all other structures and /// methods needed to interact with the developer. public class Parser { private Hashtable m_parameters; private Symbol[] m_symbols; private String[] m_charsets; private Rule[] m_rules; private FAState[] m_DfaStates; private LRActionTable[] m_LalrTables; private bool m_initialized; private bool m_caseSensitive; private int m_startSymbol; private int m_initDfaState; private Symbol m_errorSymbol; private Symbol m_endSymbol; private LookAheadReader m_source; private int m_lineNumber; private bool m_haveReduction; private bool m_trimReductions; private int m_commentLevel; private int m_initLalrState; private int m_LalrState; private TokenStack m_inputTokens; // Stack of tokens to be analyzed private TokenStack m_outputTokens; // The set of tokens for 1. Expecting during error, 2. Reduction private TokenStack m_tempStack; // I often dont know what to call variables. /* constructor */ public Parser() { } /// <summary>Creates a new <c>Parser</c> object for the specified /// CGT file.</summary> /// <param name="p_filename">The name of the CGT file.</param> public Parser(String p_filename) { LoadGrammar(p_filename); } /// <summary>Creates a new <c>Parser</c> object for the specified /// CGT file.</summary> /// <param name="p_filename">The name of the CGT file.</param> public Parser(Stream stream) { LoadGrammar(stream); } public void LoadGrammar(String p_filename) { m_parameters = new Hashtable(); m_inputTokens = new TokenStack(); m_outputTokens = new TokenStack(); m_tempStack = new TokenStack(); m_initialized = false; m_trimReductions = false; LoadTables(new GrammarReader(p_filename)); } public void LoadGrammar(Stream stream) { m_parameters = new Hashtable(); m_inputTokens = new TokenStack(); m_outputTokens = new TokenStack(); m_tempStack = new TokenStack(); m_initialized = false; m_trimReductions = false; LoadTables(new GrammarReader(stream)); } /* properties */ /// Gets or sets whether or not to trim reductions which contain /// only one non-terminal. public bool TrimReductions { get { return m_trimReductions; } set { m_trimReductions = value; } } /// Gets the current token. public Token CurrentToken { get { return m_inputTokens.PeekToken(); } } /// <summary>Gets the <c>Reduction</c> made by the parsing engine.</summary> /// <remarks>The value of this property is only valid when the Parse-method /// returns <c>ParseMessage.Reduction</c>.</remarks> public Reduction CurrentReduction { get { if (m_haveReduction) { Token token = m_tempStack.PeekToken(); return (token.Data as Reduction); } else return null; } set { if (m_haveReduction) { m_tempStack.PeekToken().Data = value; } } } /// Gets the line number that is currently being processed. public int CurrentLineNumber { get { return m_lineNumber; } } /* public methods */ /// Pushes the specified token onto the internal input queue. /// It will be the next token analyzed by the parsing engine. public void PushInputToken(Token p_token) { m_inputTokens.PushToken(p_token); } /// Pops the next token from the internal input queue. public Token PopInputToken() { return m_inputTokens.PopToken(); } /* /// Returns the token at the specified index. public Token GetToken(int p_index) { return m_outputTokens.GetToken(p_index); } */ /// Returns a <c>TokenStack</c> containing the tokens for the reduced rule or /// the tokens that where expected when a syntax error occures. public TokenStack GetTokens() { return m_outputTokens; } /// <summary>Returns a string containing the value of the specified parameter.</summary> /// <remarks>These parameters include: Name, Version, Author, About, Case Sensitive /// and Start Symbol. If the name specified is invalid, this method will /// return an empty string.</remarks> public String GetParameter(String p_name) { String result = (String)m_parameters[p_name]; return (result != null ? result : ""); } /// Opens the file with the specified name for parsing. public void OpenFile(String p_filename) { Reset(); m_source = new LookAheadReader( new StreamReader(new FileStream(p_filename, FileMode.Open))); PrepareToParse(); } /// Opens the file with the specified name for parsing. public void OpenStream(TextReader stream) { Reset(); m_source = new LookAheadReader(stream); PrepareToParse(); } /// Closes the file opened with <c>OpenFile</c>. public void CloseFile() { // This will automaticly close the FileStream (I think :)) if (m_source != null) m_source.Close(); m_source = null; } /// <summary>Executes a parse-action.</summary> /// <remarks>When this method is called, the parsing engine /// reads information from the source text and then reports what action was taken. /// This ranges from a token being read and recognized from the source, a parse /// reduction, or some type of error.</remarks> public ParseMessage Parse() { while (true) { if (m_inputTokens.Count == 0) { // we must read a token. Token token = RetrieveToken(); if (token == null) throw new ParserException("RetrieveToken returned null"); if (token.Kind != SymbolType.Whitespace) { m_inputTokens.PushToken(token); if (m_commentLevel == 0 && ! CommentToken(token)) return ParseMessage.TokenRead; } } else if (m_commentLevel > 0) { // we are in a block comment. Token token = m_inputTokens.PopToken(); switch (token.Kind) { case SymbolType.CommentStart: m_commentLevel++; break; case SymbolType.CommentEnd: m_commentLevel--; break; case SymbolType.End: return ParseMessage.CommentError; } } else { // we are ready to parse. Token token = m_inputTokens.PeekToken(); switch (token.Kind) { case SymbolType.CommentStart: m_inputTokens.PopToken(); m_commentLevel++; break; case SymbolType.CommentLine: m_inputTokens.PopToken(); DiscardLine(); break; default: ParseResult result = ParseToken(token); switch (result) { case ParseResult.Accept: return ParseMessage.Accept; case ParseResult.InternalError: return ParseMessage.InternalError; case ParseResult.ReduceNormal: return ParseMessage.Reduction; case ParseResult.Shift: m_inputTokens.PopToken(); break; case ParseResult.SyntaxError: return ParseMessage.SyntaxError; } break; } // switch } // else } // while } /* private methods */ private char FixCase(char p_char) { if (m_caseSensitive) return p_char; return Char.ToLower(p_char); } private String FixCase(String p_string) { if (m_caseSensitive) return p_string; return p_string.ToLower(); } private void AddSymbol(Symbol p_symbol) { if (! m_initialized) throw new ParserException("Table sizes not initialized"); int index = p_symbol.TableIndex; m_symbols[index] = p_symbol; } private void AddCharset(int p_index, String p_charset) { if (! m_initialized) throw new ParserException("Table sizes not initialized"); m_charsets[p_index] = FixCase(p_charset); } private void AddRule(Rule p_rule) { if (! m_initialized) throw new ParserException("Table sizes not initialized"); int index = p_rule.TableIndex; m_rules[index] = p_rule; } private void AddDfaState(int p_index, FAState p_fastate) { if (! m_initialized) throw new ParserException("Table sizes not initialized"); m_DfaStates[p_index] = p_fastate; } private void AddLalrTable(int p_index, LRActionTable p_table) { if (! m_initialized) throw new ParserException("Table counts not initialized"); m_LalrTables[p_index] = p_table; } private void LoadTables(GrammarReader reader) { Object obj; Int16 index; while (reader.MoveNext()) { byte id = (byte)reader.RetrieveNext(); switch ((RecordId)id) { case RecordId.Parameters: m_parameters["Name"] = (String)reader.RetrieveNext(); m_parameters["Version"] = (String)reader.RetrieveNext(); m_parameters["Author"] = (String)reader.RetrieveNext(); m_parameters["About"] = (String)reader.RetrieveNext(); m_caseSensitive = (Boolean)reader.RetrieveNext(); m_startSymbol = (Int16)reader.RetrieveNext(); break; case RecordId.TableCounts: m_symbols = new Symbol[(Int16)reader.RetrieveNext()]; m_charsets = new String[(Int16)reader.RetrieveNext()]; m_rules = new Rule[(Int16)reader.RetrieveNext()]; m_DfaStates = new FAState[(Int16)reader.RetrieveNext()]; m_LalrTables = new LRActionTable[(Int16)reader.RetrieveNext()]; m_initialized = true; break; case RecordId.Initial: m_initDfaState = (Int16)reader.RetrieveNext(); m_initLalrState = (Int16)reader.RetrieveNext(); break; case RecordId.Symbols: index = (Int16)reader.RetrieveNext(); String name = (String)reader.RetrieveNext(); SymbolType kind = (SymbolType)(Int16)reader.RetrieveNext(); Symbol symbol = new Symbol(index, name, kind); AddSymbol(symbol); break; case RecordId.CharSets: index = (Int16)reader.RetrieveNext(); String charset = (String)reader.RetrieveNext(); AddCharset(index, charset); break; case RecordId.Rules: index = (Int16)reader.RetrieveNext(); Symbol head = m_symbols[(Int16)reader.RetrieveNext()]; Rule rule = new Rule(index, head); reader.RetrieveNext(); // reserved while ((obj = reader.RetrieveNext()) != null) rule.AddItem(m_symbols[(Int16)obj]); AddRule(rule); break; case RecordId.DFAStates: FAState fastate = new FAState(); index = (Int16)reader.RetrieveNext(); if ((bool)reader.RetrieveNext()) fastate.AcceptSymbol = (Int16)reader.RetrieveNext(); else reader.RetrieveNext(); reader.RetrieveNext(); // reserverd while (! reader.RetrieveDone()) { Int16 ci = (Int16)reader.RetrieveNext(); Int16 ti = (Int16)reader.RetrieveNext(); reader.RetrieveNext(); // reserved fastate.AddEdge(m_charsets[ci], ti); } AddDfaState(index, fastate); break; case RecordId.LRTables: LRActionTable table = new LRActionTable(); index = (Int16)reader.RetrieveNext(); reader.RetrieveNext(); // reserverd while (! reader.RetrieveDone()) { Int16 sid = (Int16)reader.RetrieveNext(); Int16 action = (Int16)reader.RetrieveNext(); Int16 tid = (Int16)reader.RetrieveNext(); reader.RetrieveNext(); // reserved table.AddItem(m_symbols[sid], (Action)action, tid); } AddLalrTable(index, table); break; case RecordId.Comment: Console.WriteLine("Comment record encountered"); break; default: throw new ParserException("Wrong id for record"); } } } private void Reset() { foreach (Symbol symbol in m_symbols) { if (symbol.Kind == SymbolType.Error) m_errorSymbol = symbol; else if (symbol.Kind == SymbolType.End) m_endSymbol = symbol; } m_haveReduction = false; m_LalrState = m_initLalrState; m_lineNumber = 1; m_commentLevel = 0; m_inputTokens.Clear(); m_outputTokens.Clear(); m_tempStack.Clear(); } private void PrepareToParse() { Token token = new Token(); token.State = m_initLalrState; token.SetParent(m_symbols[m_startSymbol]); m_tempStack.PushToken(token); } private void DiscardLine() { m_source.DiscardLine(); m_lineNumber++; } /// Returns true if the specified token is a CommentLine or CommentStart-symbol. private bool CommentToken(Token p_token) { return (p_token.Kind == SymbolType.CommentLine) || (p_token.Kind == SymbolType.CommentStart); } /// This function analyzes a token and either: /// 1. Makes a SINGLE reduction and pushes a complete Reduction object on the stack /// 2. Accepts the token and shifts /// 3. Errors and places the expected symbol indexes in the Tokens list /// The Token is assumed to be valid and WILL be checked private ParseResult ParseToken(Token p_token) { ParseResult result = ParseResult.InternalError; LRActionTable table = m_LalrTables[m_LalrState]; LRAction action = table.GetActionForSymbol(p_token.TableIndex); if (action != null) { m_haveReduction = false; m_outputTokens.Clear(); switch (action.Action) { case Action.Accept: m_haveReduction = true; result = ParseResult.Accept; break; case Action.Shift: p_token.State = m_LalrState = action.Value; m_tempStack.PushToken(p_token); result = ParseResult.Shift; break; case Action.Reduce: result = Reduce(m_rules[action.Value]); break; } } else { // syntax error - fill expected tokens. m_outputTokens.Clear(); foreach (LRAction a in table.Members) { SymbolType kind = a.Symbol.Kind; if (kind == SymbolType.Terminal || kind == SymbolType.End) m_outputTokens.PushToken(new Token(a.Symbol)); } result = ParseResult.SyntaxError; } return result; } /// <summary>Produces a reduction.</summary> /// <remarks>Removes as many tokens as members in the rule and pushes a /// non-terminal token.</remarks> private ParseResult Reduce(Rule p_rule) { ParseResult result; Token head; if (m_trimReductions && p_rule.ContainsOneNonTerminal) { // The current rule only consists of a single nonterminal and can be trimmed from the // parse tree. Usually we create a new Reduction, assign it to the Data property // of Head and push it on the stack. However, in this case, the Data property of the // Head will be assigned the Data property of the reduced token (i.e. the only one // on the stack). In this case, to save code, the value popped of the stack is changed // into the head. head = m_tempStack.PopToken(); head.SetParent(p_rule.RuleNonTerminal); result = ParseResult.ReduceEliminated; } else { Reduction reduction = new Reduction(); reduction.ParentRule = p_rule; m_tempStack.PopTokensInto(reduction, p_rule.SymbolCount); head = new Token(); head.Data = reduction; head.SetParent(p_rule.RuleNonTerminal); m_haveReduction = true; result = ParseResult.ReduceNormal; } int index = m_tempStack.PeekToken().State; LRAction action = m_LalrTables[index].GetActionForSymbol(p_rule.RuleNonTerminal.TableIndex); if (action != null) { head.State = m_LalrState = action.Value;; m_tempStack.PushToken(head); } else throw new ParserException("Action for LALR state is null"); return result; } /// This method implements the DFA algorithm and returns a token /// to the LALR state machine. private Token RetrieveToken() { Token result; int currentPos = 0; int lastAcceptState = -1; int lastAcceptPos = -1; FAState currentState = m_DfaStates[m_initDfaState]; try { while (true) { // This code searches all the branches of the current DFA state for the next // character in the input LookaheadStream. If found the target state is returned. // The InStr() function searches the string pCharacterSetTable.Member(CharSetIndex) // starting at position 1 for ch. The pCompareMode variable determines whether // the search is case sensitive. int target = -1; char ch = FixCase(m_source.LookAhead(currentPos)); foreach (FAEdge edge in currentState.Edges) { String chars = edge.Characters; if (chars.IndexOf(ch) != -1) { target = edge.TargetIndex; break; } } // This block-if statement checks whether an edge was found from the current state. // If so, the state and current position advance. Otherwise it is time to exit the main loop // and report the token found (if there was it fact one). If the LastAcceptState is -1, // then we never found a match and the Error Token is created. Otherwise, a new token // is created using the Symbol in the Accept State and all the characters that // comprise it. if (target != -1) { // This code checks whether the target state accepts a token. If so, it sets the // appropiate variables so when the algorithm is done, it can return the proper // token and number of characters. if (m_DfaStates[target].AcceptSymbol != -1) { lastAcceptState = target; lastAcceptPos = currentPos; } currentState = m_DfaStates[target]; currentPos++; } else { if (lastAcceptState == -1) { result = new Token(m_errorSymbol); result.Data = m_source.Read(1); } else { Symbol symbol = m_symbols[m_DfaStates[lastAcceptState].AcceptSymbol]; result = new Token(symbol); result.Data = m_source.Read(lastAcceptPos + 1); } break; } } } catch (EndOfStreamException) { result = new Token(m_endSymbol); result.Data = ""; } UpdateLineNumber((String)result.Data); return result; } private void UpdateLineNumber(String p_string) { int index, pos = 0; while ((index = p_string.IndexOf('\n', pos)) != -1) { pos = index + 1; m_lineNumber++; } } } }
// 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.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.CompletionProviders.XmlDocCommentCompletion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.Completion.CompletionProviders.XmlDocCommentCompletion { [ExportCompletionProvider("DocCommentCompletionProvider", LanguageNames.CSharp)] internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider { public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options) { return text[characterPosition] == '<'; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>(); if (parentTrivia == null) { return null; } var items = new List<CompletionItem>(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var span = CompletionUtilities.GetTextChangeSpan(text, position); var attachedToken = parentTrivia.ParentTrivia.Token; if (attachedToken.Kind() == SyntaxKind.None) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false); ISymbol declaredSymbol = null; var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken); } else { var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); } } if (declaredSymbol != null) { items.AddRange(GetTagsForSymbol(declaredSymbol, span, parentTrivia, token)); } if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText || (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) || (token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement))) { if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement) { items.AddRange(GetNestedTags(span)); } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "list") { items.AddRange(GetListItems(span)); } if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { var element = (XmlElementSyntax)token.Parent.Parent.Parent; if (element.StartTag.Name.LocalName.ValueText == "list") { items.AddRange(GetListItems(span)); } } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "listheader") { items.AddRange(GetListHeaderItems(span)); } if (token.Parent.Parent is DocumentationCommentTriviaSyntax) { items.AddRange(GetTopLevelSingleUseNames(parentTrivia, span)); items.AddRange(GetTopLevelRepeatableItems(span)); } } if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag) { var startTag = (XmlElementStartTagSyntax)token.Parent; if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "list") { items.AddRange(GetListItems(span)); } if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "listheader") { items.AddRange(GetListHeaderItems(span)); } } items.AddRange(GetAlwaysVisibleItems(span)); return items; } private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia, TextSpan span) { var names = new HashSet<string>(new[] { "summary", "remarks", "example", "completionlist" }); RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText); return names.Select(n => GetItem(n, span)); } private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector) { if (parentTrivia != null) { foreach (var node in parentTrivia.Content) { var element = node as XmlElementSyntax; if (element != null) { names.Remove(selector(element)); } } } } private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { if (symbol is IMethodSymbol) { return GetTagsForMethod((IMethodSymbol)symbol, filterSpan, trivia, token); } if (symbol is IPropertySymbol) { return GetTagsForProperty((IPropertySymbol)symbol, filterSpan, trivia, token); } if (symbol is INamedTypeSymbol) { return GetTagsForType((INamedTypeSymbol)symbol, filterSpan, trivia); } return SpecializedCollections.EmptyEnumerable<CompletionItem>(); } private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet(); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam")); items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("typeparam", t), GetCompletionItemRules()))); return items; } private string AttributeSelector(XmlElementSyntax element, string attribute) { if (!element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == "name"); if (nameAttribute != null) { if (startTag.Name.LocalName.ValueText == attribute) { return nameAttribute.Identifier.Identifier.ValueText; } } } return null; } private IEnumerable<XmlDocCommentCompletionItem> GetTagsForProperty(IPropertySymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<XmlDocCommentCompletionItem>(); if (symbol.IsIndexer) { var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref if (parentElementName == "paramref") { items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, p, GetCompletionItemRules()))); } return items; } RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, "param")); items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("param", p), GetCompletionItemRules()))); } var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet(); items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, "typeparam", "name", t, GetCompletionItemRules()))); items.Add(new XmlDocCommentCompletionItem(this, filterSpan, "value", GetCompletionItemRules())); return items; } private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<CompletionItem>(); var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref or typeparamref if (parentElementName == "paramref") { items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, p, GetCompletionItemRules()))); } else if (parentElementName == "typeparamref") { items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, t, GetCompletionItemRules()))); } return items; } var returns = true; RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, "param")); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam")); foreach (var node in trivia.Content) { var element = node as XmlElementSyntax; if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; if (startTag.Name.LocalName.ValueText == "returns") { returns = false; break; } } } items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("param", p), GetCompletionItemRules()))); items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("typeparam", t), GetCompletionItemRules()))); if (returns && !symbol.ReturnsVoid) { items.Add(new XmlDocCommentCompletionItem(this, filterSpan, "returns", GetCompletionItemRules())); } return items; } protected override AbstractXmlDocCommentCompletionItemRules GetCompletionItemRules() { return XmlDocCommentCompletionItemRules.Instance; } } }
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2004-2005 Novell, Inc. // // Authors: // Duncan Mak duncan@ximian.com // Nick Drochak ndrochak@gol.com // Paolo Molaro lupus@ximian.com // Peter Bartok pbartok@novell.com // Gert Driesen drieseng@users.sourceforge.net // Olivier Dufour olivier.duff@gmail.com // Gary Barnett gary.barnett.mono@gmail.com using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Design; using System.Drawing; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.Serialization; using System.Xml; namespace simpleresgen.mono { #if INSIDE_SYSTEM_WEB internal #else public #endif class ResXResourceReader : IResourceReader, IDisposable { #region Local Variables private string fileName; private Stream stream; private TextReader reader; private OrderedDictionary hasht; private ITypeResolutionService typeresolver; private XmlTextReader xmlReader; private string basepath; private bool useResXDataNodes; private AssemblyName [] assemblyNames; private OrderedDictionary hashtm; #endregion // Local Variables #region Constructors & Destructor public ResXResourceReader (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead) throw new ArgumentException ("Stream was not readable."); this.stream = stream; } public ResXResourceReader (Stream stream, ITypeResolutionService typeResolver) : this (stream) { this.typeresolver = typeResolver; } public ResXResourceReader (string fileName) { this.fileName = fileName; } public ResXResourceReader (string fileName, ITypeResolutionService typeResolver) : this (fileName) { this.typeresolver = typeResolver; } public ResXResourceReader (TextReader reader) { this.reader = reader; } public ResXResourceReader (TextReader reader, ITypeResolutionService typeResolver) : this (reader) { this.typeresolver = typeResolver; } public ResXResourceReader (Stream stream, AssemblyName [] assemblyNames) : this (stream) { this.assemblyNames = assemblyNames; } public ResXResourceReader (string fileName, AssemblyName [] assemblyNames) : this (fileName) { this.assemblyNames = assemblyNames; } public ResXResourceReader (TextReader reader, AssemblyName [] assemblyNames) : this (reader) { this.assemblyNames = assemblyNames; } ~ResXResourceReader () { Dispose (false); } #endregion // Constructors & Destructor public string BasePath { get { return basepath; } set { basepath = value; } } public bool UseResXDataNodes { get { return useResXDataNodes; } set { if (xmlReader != null) throw new InvalidOperationException (); useResXDataNodes = value; } } #region Private Methods private void LoadData () { hasht = new OrderedDictionary (); hashtm = new OrderedDictionary (); if (fileName != null) { stream = File.OpenRead (fileName); } try { xmlReader = null; if (stream != null) { xmlReader = new XmlTextReader (stream); } else if (reader != null) { xmlReader = new XmlTextReader (reader); } if (xmlReader == null) { throw new InvalidOperationException ("ResourceReader is closed."); } xmlReader.WhitespaceHandling = WhitespaceHandling.None; ResXHeader header = new ResXHeader (); try { while (xmlReader.Read ()) { if (xmlReader.NodeType != XmlNodeType.Element) continue; switch (xmlReader.LocalName) { case "resheader": ParseHeaderNode (header); break; case "data": ParseDataNode (false); break; case "metadata": ParseDataNode (true); break; } } } catch (XmlException ex) { throw new ArgumentException ("Invalid ResX input.", ex); } catch (SerializationException ex) { throw ex; } catch (TargetInvocationException ex) { throw ex; } catch (Exception ex) { XmlException xex = new XmlException (ex.Message, ex, xmlReader.LineNumber, xmlReader.LinePosition); throw new ArgumentException ("Invalid ResX input.", xex); } header.Verify (); } finally { if (fileName != null) { stream.Close (); stream = null; } xmlReader = null; } } private void ParseHeaderNode (ResXHeader header) { string v = GetAttribute ("name"); if (v == null) return; if (String.Compare (v, "resmimetype", true) == 0) { header.ResMimeType = GetHeaderValue (); } else if (String.Compare (v, "reader", true) == 0) { header.Reader = GetHeaderValue (); } else if (String.Compare (v, "version", true) == 0) { header.Version = GetHeaderValue (); } else if (String.Compare (v, "writer", true) == 0) { header.Writer = GetHeaderValue (); } } private string GetHeaderValue () { string value = null; xmlReader.ReadStartElement (); if (xmlReader.NodeType == XmlNodeType.Element) { value = xmlReader.ReadElementString (); } else { value = xmlReader.Value.Trim (); } return value; } private string GetAttribute (string name) { if (!xmlReader.HasAttributes) return null; for (int i = 0; i < xmlReader.AttributeCount; i++) { xmlReader.MoveToAttribute (i); if (String.Compare (xmlReader.Name, name, true) == 0) { string v = xmlReader.Value; xmlReader.MoveToElement (); return v; } } xmlReader.MoveToElement (); return null; } private string GetDataValue (bool meta, out string comment) { string value = null; comment = null; while (xmlReader.Read ()) { if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == (meta ? "metadata" : "data")) break; if (xmlReader.NodeType == XmlNodeType.Element) { if (xmlReader.Name.Equals ("value")) { xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; value = xmlReader.ReadString (); xmlReader.WhitespaceHandling = WhitespaceHandling.None; } else if (xmlReader.Name.Equals ("comment")) { xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; comment = xmlReader.ReadString (); xmlReader.WhitespaceHandling = WhitespaceHandling.None; if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == (meta ? "metadata" : "data")) break; } } else value = xmlReader.Value.Trim (); } return value; } private void ParseDataNode (bool meta) { OrderedDictionary hashtable = ((meta && ! useResXDataNodes) ? hashtm : hasht); Point pos = new Point (xmlReader.LineNumber, xmlReader.LinePosition); string name = GetAttribute ("name"); string type_name = GetAttribute ("type"); string mime_type = GetAttribute ("mimetype"); string comment = null; string value = GetDataValue (meta, out comment); ResXDataNode node = new ResXDataNode (name, mime_type, type_name, value, comment, pos, BasePath); if (useResXDataNodes) { hashtable [name] = node; return; } if (name == null) throw new ArgumentException (string.Format (CultureInfo.CurrentCulture, "Could not find a name for a resource. The resource value was '{0}'.", node.GetValue ((AssemblyName []) null).ToString())); // useResXDataNodes is false, add to dictionary of values if (assemblyNames != null) { try { hashtable [name] = node.GetValue (assemblyNames); } catch (TypeLoadException ex) { // different error messages depending on type of resource, hacky solution if (node.handler is TypeConverterFromResXHandler) hashtable [name] = null; else throw ex; } } else { // there is a typeresolver or its null try { hashtable [name] = node.GetValue (typeresolver); } catch (TypeLoadException ex) { if (node.handler is TypeConverterFromResXHandler) hashtable [name] = null; else throw ex; } } } #endregion // Private Methods #region Public Methods public void Close () { if (reader != null) { reader.Close (); reader = null; } } public IDictionaryEnumerator GetEnumerator () { if (hasht == null) { LoadData (); } return hasht.GetEnumerator (); } IEnumerator IEnumerable.GetEnumerator () { return ((IResourceReader) this).GetEnumerator (); } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (disposing) { Close (); } } public static ResXResourceReader FromFileContents (string fileContents) { return new ResXResourceReader (new StringReader (fileContents)); } public static ResXResourceReader FromFileContents (string fileContents, ITypeResolutionService typeResolver) { return new ResXResourceReader (new StringReader (fileContents), typeResolver); } public static ResXResourceReader FromFileContents (string fileContents, AssemblyName [] assemblyNames) { return new ResXResourceReader (new StringReader (fileContents), assemblyNames); } public IDictionaryEnumerator GetMetadataEnumerator () { if (hashtm == null) LoadData (); return hashtm.GetEnumerator (); } #endregion // Public Methods #region Internal Classes private class ResXHeader { private string resMimeType; private string reader; private string version; private string writer; public string ResMimeType { get { return resMimeType; } set { resMimeType = value; } } public string Reader { get { return reader; } set { reader = value; } } public string Version { get { return version; } set { version = value; } } public string Writer { get { return writer; } set { writer = value; } } public void Verify () { if (!IsValid) throw new ArgumentException ("Invalid ResX input. Could " + "not find valid \"resheader\" tags for the ResX " + "reader & writer type names."); } public bool IsValid { get { if (string.Compare (ResMimeType, ResXResourceWriter.ResMimeType) != 0) return false; if (Reader == null || Writer == null) return false; string readerType = Reader.Split (',') [0].Trim (); readerType = readerType.Replace("System.Resources", "simpleresgen.mono"); if (readerType != typeof (ResXResourceReader).FullName) return false; string writerType = Writer.Split (',') [0].Trim (); writerType = writerType.Replace("System.Resources", "simpleresgen.mono"); if (writerType != typeof (ResXResourceWriter).FullName) return false; return true; } } } #endregion } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\ExtractTensors.tcl // output file is AVExtractTensors.cs /// <summary> /// The testing class derived from AVExtractTensors /// </summary> public class AVExtractTensorsClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVExtractTensors(String [] argv) { //Prefix Content is: "" // create tensor ellipsoids[] // Create the RenderWindow, Renderer and interactive renderer[] //[] ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); ptLoad = new vtkPointLoad(); ptLoad.SetLoadValue((double)100.0); ptLoad.SetSampleDimensions((int)30,(int)30,(int)30); ptLoad.ComputeEffectiveStressOn(); ptLoad.SetModelBounds((double)-10,(double)10,(double)-10,(double)10,(double)-10,(double)10); extractTensor = new vtkExtractTensorComponents(); extractTensor.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort()); extractTensor.ScalarIsEffectiveStress(); extractTensor.ScalarIsComponent(); extractTensor.ExtractScalarsOn(); extractTensor.ExtractVectorsOn(); extractTensor.ExtractNormalsOff(); extractTensor.ExtractTCoordsOn(); contour = new vtkContourFilter(); contour.SetInputConnection((vtkAlgorithmOutput)extractTensor.GetOutputPort()); contour.SetValue((int)0,(double)0); probe = new vtkProbeFilter(); probe.SetInputConnection((vtkAlgorithmOutput)contour.GetOutputPort()); probe.SetSourceConnection(ptLoad.GetOutputPort()); su = new vtkLoopSubdivisionFilter(); su.SetInputConnection((vtkAlgorithmOutput)probe.GetOutputPort()); su.SetNumberOfSubdivisions((int)1); s1Mapper = vtkPolyDataMapper.New(); s1Mapper.SetInputConnection((vtkAlgorithmOutput)probe.GetOutputPort()); // s1Mapper SetInputConnection [su GetOutputPort][] s1Actor = new vtkActor(); s1Actor.SetMapper((vtkMapper)s1Mapper); //[] // plane for context[] //[] g = new vtkImageDataGeometryFilter(); g.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort()); g.SetExtent((int)0,(int)100,(int)0,(int)100,(int)0,(int)0); g.Update(); //for scalar range[] gm = vtkPolyDataMapper.New(); gm.SetInputConnection((vtkAlgorithmOutput)g.GetOutputPort()); gm.SetScalarRange((double)((vtkDataSet)g.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)g.GetOutput()).GetScalarRange()[1]); ga = new vtkActor(); ga.SetMapper((vtkMapper)gm); s1Mapper.SetScalarRange((double)((vtkDataSet)g.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)g.GetOutput()).GetScalarRange()[1]); //[] // Create outline around data[] //[] outline = new vtkOutlineFilter(); outline.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort()); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)outlineMapper); outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0); //[] // Create cone indicating application of load[] //[] coneSrc = new vtkConeSource(); coneSrc.SetRadius((double).5); coneSrc.SetHeight((double)2); coneMap = vtkPolyDataMapper.New(); coneMap.SetInputConnection((vtkAlgorithmOutput)coneSrc.GetOutputPort()); coneActor = new vtkActor(); coneActor.SetMapper((vtkMapper)coneMap); coneActor.SetPosition((double)0,(double)0,(double)11); coneActor.RotateY((double)90); coneActor.GetProperty().SetColor((double)1,(double)0,(double)0); camera = new vtkCamera(); camera.SetFocalPoint((double)0.113766,(double)-1.13665,(double)-1.01919); camera.SetPosition((double)-29.4886,(double)-63.1488,(double)26.5807); camera.SetViewAngle((double)24.4617); camera.SetViewUp((double)0.17138,(double)0.331163,(double)0.927879); camera.SetClippingRange((double)1,(double)100); ren1.AddActor((vtkProp)s1Actor); ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)coneActor); ren1.AddActor((vtkProp)ga); ren1.SetBackground((double)1.0,(double)1.0,(double)1.0); ren1.SetActiveCamera((vtkCamera)camera); renWin.SetSize((int)300,(int)300); renWin.Render(); // prevent the tk window from showing up then start the event loop[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkPointLoad ptLoad; static vtkExtractTensorComponents extractTensor; static vtkContourFilter contour; static vtkProbeFilter probe; static vtkLoopSubdivisionFilter su; static vtkPolyDataMapper s1Mapper; static vtkActor s1Actor; static vtkImageDataGeometryFilter g; static vtkPolyDataMapper gm; static vtkActor ga; static vtkOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkConeSource coneSrc; static vtkPolyDataMapper coneMap; static vtkActor coneActor; static vtkCamera camera; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPointLoad GetptLoad() { return ptLoad; } ///<summary> A Set Method for Static Variables </summary> public static void SetptLoad(vtkPointLoad toSet) { ptLoad = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkExtractTensorComponents GetextractTensor() { return extractTensor; } ///<summary> A Set Method for Static Variables </summary> public static void SetextractTensor(vtkExtractTensorComponents toSet) { extractTensor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkContourFilter Getcontour() { return contour; } ///<summary> A Set Method for Static Variables </summary> public static void Setcontour(vtkContourFilter toSet) { contour = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkProbeFilter Getprobe() { return probe; } ///<summary> A Set Method for Static Variables </summary> public static void Setprobe(vtkProbeFilter toSet) { probe = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkLoopSubdivisionFilter Getsu() { return su; } ///<summary> A Set Method for Static Variables </summary> public static void Setsu(vtkLoopSubdivisionFilter toSet) { su = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper Gets1Mapper() { return s1Mapper; } ///<summary> A Set Method for Static Variables </summary> public static void Sets1Mapper(vtkPolyDataMapper toSet) { s1Mapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Gets1Actor() { return s1Actor; } ///<summary> A Set Method for Static Variables </summary> public static void Sets1Actor(vtkActor toSet) { s1Actor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageDataGeometryFilter Getg() { return g; } ///<summary> A Set Method for Static Variables </summary> public static void Setg(vtkImageDataGeometryFilter toSet) { g = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper Getgm() { return gm; } ///<summary> A Set Method for Static Variables </summary> public static void Setgm(vtkPolyDataMapper toSet) { gm = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getga() { return ga; } ///<summary> A Set Method for Static Variables </summary> public static void Setga(vtkActor toSet) { ga = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetoutlineMapper() { return outlineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineMapper(vtkPolyDataMapper toSet) { outlineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkConeSource GetconeSrc() { return coneSrc; } ///<summary> A Set Method for Static Variables </summary> public static void SetconeSrc(vtkConeSource toSet) { coneSrc = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetconeMap() { return coneMap; } ///<summary> A Set Method for Static Variables </summary> public static void SetconeMap(vtkPolyDataMapper toSet) { coneMap = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetconeActor() { return coneActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetconeActor(vtkActor toSet) { coneActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCamera Getcamera() { return camera; } ///<summary> A Set Method for Static Variables </summary> public static void Setcamera(vtkCamera toSet) { camera = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(ptLoad!= null){ptLoad.Dispose();} if(extractTensor!= null){extractTensor.Dispose();} if(contour!= null){contour.Dispose();} if(probe!= null){probe.Dispose();} if(su!= null){su.Dispose();} if(s1Mapper!= null){s1Mapper.Dispose();} if(s1Actor!= null){s1Actor.Dispose();} if(g!= null){g.Dispose();} if(gm!= null){gm.Dispose();} if(ga!= null){ga.Dispose();} if(outline!= null){outline.Dispose();} if(outlineMapper!= null){outlineMapper.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(coneSrc!= null){coneSrc.Dispose();} if(coneMap!= null){coneMap.Dispose();} if(coneActor!= null){coneActor.Dispose();} if(camera!= null){camera.Dispose();} } } //--- end of script --//
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Runtime.Serialization; using Apache.Ignite.Core.Compute; using NUnit.Framework; /// <summary> /// Closure execution tests for serializable objects. /// </summary> public class SerializableClosureTaskTest : ClosureTaskTest { /// <summary> /// Constructor. /// </summary> public SerializableClosureTaskTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected SerializableClosureTaskTest(bool fork) : base(fork) { } /** <inheritDoc /> */ protected override IComputeFunc<object> OutFunc(bool err) { return new SerializableOutFunc(err); } /** <inheritDoc /> */ protected override IComputeFunc<object, object> Func(bool err) { return new SerializableFunc(err); } /** <inheritDoc /> */ protected override void CheckResult(object res) { Assert.IsTrue(res != null); SerializableResult res0 = res as SerializableResult; Assert.IsTrue(res0 != null); Assert.AreEqual(1, res0.Res); } /** <inheritDoc /> */ protected override void CheckError(Exception err) { Assert.IsTrue(err != null); var aggregate = err as AggregateException; if (aggregate != null) err = aggregate.InnerException; SerializableException err0 = err as SerializableException; Assert.IsTrue(err0 != null); Assert.AreEqual(ErrMsg, err0.Msg); } /// <summary> /// /// </summary> [Serializable] private class SerializableOutFunc : IComputeFunc<object> { /** Error. */ private bool _err; /// <summary> /// /// </summary> public SerializableOutFunc() { // No-op. } /// <summary> /// /// </summary> /// <param name="err"></param> public SerializableOutFunc(bool err) { _err = err; } /** <inheritDoc /> */ public object Invoke() { if (_err) throw new SerializableException(ErrMsg); return new SerializableResult(1); } } /// <summary> /// /// </summary> [Serializable] private class SerializableFunc : IComputeFunc<object, object> { /** Error. */ private bool _err; /// <summary> /// /// </summary> public SerializableFunc() { // No-op. } /// <summary> /// /// </summary> /// <param name="err"></param> public SerializableFunc(bool err) { _err = err; } /** <inheritDoc /> */ public object Invoke(object arg) { Console.WriteLine("INVOKED!"); if (_err) throw new SerializableException(ErrMsg); return new SerializableResult(1); } } /// <summary> /// /// </summary> [Serializable] private class SerializableException : Exception { /** */ public string Msg; /// <summary> /// /// </summary> public SerializableException() { // No-op. } /// <summary> /// /// </summary> /// <param name="msg"></param> public SerializableException(string msg) : this() { Msg = msg; } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> public SerializableException(SerializationInfo info, StreamingContext context) : base(info, context) { Msg = info.GetString("msg"); } /** <inheritDoc /> */ public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("msg", Msg); base.GetObjectData(info, context); } } /// <summary> /// /// </summary> [Serializable] private class SerializableResult { public int Res; /// <summary> /// /// </summary> public SerializableResult() { // No-op. } /// <summary> /// /// </summary> /// <param name="res"></param> public SerializableResult(int res) { Res = res; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml.Serialization { using System.IO; using System.Collections; using System.Text; using System; using Microsoft.Xml.Schema; internal class XmlCountingReader : XmlReader, IXmlTextParser, IXmlLineInfo { private XmlReader _innerReader; private int _advanceCount; internal XmlCountingReader(XmlReader xmlReader) { if (xmlReader == null) throw new ArgumentNullException("xmlReader"); _innerReader = xmlReader; _advanceCount = 0; } internal int AdvanceCount { get { return _advanceCount; } } private void IncrementCount() { if (_advanceCount == Int32.MaxValue) _advanceCount = 0; else _advanceCount++; } // Properties (non-advancing) public override XmlReaderSettings Settings { get { return _innerReader.Settings; } } public override XmlNodeType NodeType { get { return _innerReader.NodeType; } } public override string Name { get { return _innerReader.Name; } } public override string LocalName { get { return _innerReader.LocalName; } } public override string NamespaceURI { get { return _innerReader.NamespaceURI; } } public override string Prefix { get { return _innerReader.Prefix; } } public override bool HasValue { get { return _innerReader.HasValue; } } public override string Value { get { return _innerReader.Value; } } public override int Depth { get { return _innerReader.Depth; } } public override string BaseURI { get { return _innerReader.BaseURI; } } public override bool IsEmptyElement { get { return _innerReader.IsEmptyElement; } } public override bool IsDefault { get { return _innerReader.IsDefault; } } public override char QuoteChar { get { return _innerReader.QuoteChar; } } public override XmlSpace XmlSpace { get { return _innerReader.XmlSpace; } } public override string XmlLang { get { return _innerReader.XmlLang; } } public override IXmlSchemaInfo SchemaInfo { get { return _innerReader.SchemaInfo; } } public override Type ValueType { get { return _innerReader.ValueType; } } public override int AttributeCount { get { return _innerReader.AttributeCount; } } public override string this[int i] { get { return _innerReader[i]; } } public override string this[string name] { get { return _innerReader[name]; } } public override string this[string name, string namespaceURI] { get { return _innerReader[name, namespaceURI]; } } public override bool EOF { get { return _innerReader.EOF; } } public override ReadState ReadState { get { return _innerReader.ReadState; } } public override XmlNameTable NameTable { get { return _innerReader.NameTable; } } public override bool CanResolveEntity { get { return _innerReader.CanResolveEntity; } } public override bool CanReadBinaryContent { get { return _innerReader.CanReadBinaryContent; } } public override bool CanReadValueChunk { get { return _innerReader.CanReadValueChunk; } } public override bool HasAttributes { get { return _innerReader.HasAttributes; } } // Methods (non-advancing) // Reader tends to under-count rather than over-count public override void Close() { _innerReader.Close(); } public override string GetAttribute(string name) { return _innerReader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceURI) { return _innerReader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { return _innerReader.GetAttribute(i); } public override bool MoveToAttribute(string name) { return _innerReader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { return _innerReader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { _innerReader.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { return _innerReader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return _innerReader.MoveToNextAttribute(); } public override bool MoveToElement() { return _innerReader.MoveToElement(); } public override string LookupNamespace(string prefix) { return _innerReader.LookupNamespace(prefix); } public override bool ReadAttributeValue() { return _innerReader.ReadAttributeValue(); } public override void ResolveEntity() { _innerReader.ResolveEntity(); } public override bool IsStartElement() { return _innerReader.IsStartElement(); } public override bool IsStartElement(string name) { return _innerReader.IsStartElement(name); } public override bool IsStartElement(string localname, string ns) { return _innerReader.IsStartElement(localname, ns); } public override XmlReader ReadSubtree() { return _innerReader.ReadSubtree(); } public override XmlNodeType MoveToContent() { return _innerReader.MoveToContent(); } // Methods (advancing) public override bool Read() { IncrementCount(); return _innerReader.Read(); } public override void Skip() { IncrementCount(); _innerReader.Skip(); } public override string ReadInnerXml() { if (_innerReader.NodeType != XmlNodeType.Attribute) IncrementCount(); return _innerReader.ReadInnerXml(); } public override string ReadOuterXml() { if (_innerReader.NodeType != XmlNodeType.Attribute) IncrementCount(); return _innerReader.ReadOuterXml(); } public override object ReadContentAsObject() { IncrementCount(); return _innerReader.ReadContentAsObject(); } public override bool ReadContentAsBoolean() { IncrementCount(); return _innerReader.ReadContentAsBoolean(); } public override DateTime ReadContentAsDateTime() { IncrementCount(); return _innerReader.ReadContentAsDateTime(); } public override double ReadContentAsDouble() { IncrementCount(); return _innerReader.ReadContentAsDouble(); } public override int ReadContentAsInt() { IncrementCount(); return _innerReader.ReadContentAsInt(); } public override long ReadContentAsLong() { IncrementCount(); return _innerReader.ReadContentAsLong(); } public override string ReadContentAsString() { IncrementCount(); return _innerReader.ReadContentAsString(); } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { IncrementCount(); return _innerReader.ReadContentAs(returnType, namespaceResolver); } public override object ReadElementContentAsObject() { IncrementCount(); return _innerReader.ReadElementContentAsObject(); } public override object ReadElementContentAsObject(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsObject(localName, namespaceURI); } public override bool ReadElementContentAsBoolean() { IncrementCount(); return _innerReader.ReadElementContentAsBoolean(); } public override bool ReadElementContentAsBoolean(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsBoolean(localName, namespaceURI); } public override DateTime ReadElementContentAsDateTime() { IncrementCount(); return _innerReader.ReadElementContentAsDateTime(); } public override DateTime ReadElementContentAsDateTime(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsDateTime(localName, namespaceURI); } public override double ReadElementContentAsDouble() { IncrementCount(); return _innerReader.ReadElementContentAsDouble(); } public override double ReadElementContentAsDouble(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsDouble(localName, namespaceURI); } public override int ReadElementContentAsInt() { IncrementCount(); return _innerReader.ReadElementContentAsInt(); } public override int ReadElementContentAsInt(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsInt(localName, namespaceURI); } public override long ReadElementContentAsLong() { IncrementCount(); return _innerReader.ReadElementContentAsLong(); } public override long ReadElementContentAsLong(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsLong(localName, namespaceURI); } public override string ReadElementContentAsString() { IncrementCount(); return _innerReader.ReadElementContentAsString(); } public override string ReadElementContentAsString(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsString(localName, namespaceURI); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { IncrementCount(); return _innerReader.ReadElementContentAs(returnType, namespaceResolver); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI); } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadContentAsBase64(buffer, index, count); } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadElementContentAsBase64(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadContentAsBinHex(buffer, index, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadElementContentAsBinHex(buffer, index, count); } public override int ReadValueChunk(char[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadValueChunk(buffer, index, count); } public override string ReadString() { IncrementCount(); return _innerReader.ReadString(); } public override void ReadStartElement() { IncrementCount(); _innerReader.ReadStartElement(); } public override void ReadStartElement(string name) { IncrementCount(); _innerReader.ReadStartElement(name); } public override void ReadStartElement(string localname, string ns) { IncrementCount(); _innerReader.ReadStartElement(localname, ns); } public override string ReadElementString() { IncrementCount(); return _innerReader.ReadElementString(); } public override string ReadElementString(string name) { IncrementCount(); return _innerReader.ReadElementString(name); } public override string ReadElementString(string localname, string ns) { IncrementCount(); return _innerReader.ReadElementString(localname, ns); } public override void ReadEndElement() { IncrementCount(); _innerReader.ReadEndElement(); } public override bool ReadToFollowing(string name) { IncrementCount(); return ReadToFollowing(name); } public override bool ReadToFollowing(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadToFollowing(localName, namespaceURI); } public override bool ReadToDescendant(string name) { IncrementCount(); return _innerReader.ReadToDescendant(name); } public override bool ReadToDescendant(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadToDescendant(localName, namespaceURI); } public override bool ReadToNextSibling(string name) { IncrementCount(); return _innerReader.ReadToNextSibling(name); } public override bool ReadToNextSibling(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadToNextSibling(localName, namespaceURI); } // IDisposable interface protected override void Dispose(bool disposing) { try { if (disposing) { IDisposable disposableReader = _innerReader as IDisposable; if (disposableReader != null) disposableReader.Dispose(); } } finally { base.Dispose(disposing); } } // IXmlTextParser members bool IXmlTextParser.Normalized { get { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; return (xmlTextParser == null) ? false : xmlTextParser.Normalized; } else return xmlTextReader.Normalization; } set { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.Normalized = value; } else xmlTextReader.Normalization = value; } } WhitespaceHandling IXmlTextParser.WhitespaceHandling { get { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; } else return xmlTextReader.WhitespaceHandling; } set { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.WhitespaceHandling = value; } else xmlTextReader.WhitespaceHandling = value; } } // IXmlLineInfo members bool IXmlLineInfo.HasLineInfo() { IXmlLineInfo iXmlLineInfo = _innerReader as IXmlLineInfo; return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo(); } int IXmlLineInfo.LineNumber { get { IXmlLineInfo iXmlLineInfo = _innerReader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber; } } int IXmlLineInfo.LinePosition { get { IXmlLineInfo iXmlLineInfo = _innerReader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition; } } } }
/* * Copyright (c)2007-2008, Dustin Spicuzza * 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. * * The name of the Dustin Spicuzza may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY Dustin Spicuzza ``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 Dustin Spicuzza 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.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using System.Threading; namespace ReadDataFromDAQNavi { internal delegate void VoidInvoke(); /// <summary> /// Oscilloscope drawing control. :) /// </summary> public partial class ScopeControl : UserControl { // variables needed for drawing stuff Graphics realGraphic = null; Pen backPen; Pen gridBackPen; Pen gridPen; RectangleF gridLocation; // background image Bitmap bgImage; // image currently being displayed Bitmap currentScopeImage; PointF zeroPosition; // where to align the controls on the left.. or something like that. float leftAlign = 10; Stopwatch traceTime = new Stopwatch(); // locks // don't allow the timer to reenter itself object timerLock = new object(); // this locks starting, stopping, and adding points object traceLock = new object(); /// <summary> /// Constructor the ScopeControl /// </summary> public ScopeControl() { // these reduce flicker, which is definitely a good thing SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // these initializations don't matter at this point zeroPosition = new PointF(0, 0); // initialize pens backPen = new Pen(BackColor); gridBackPen = new Pen(gridBackColor); gridPen = new Pen(gridColor); // initialize event handler Traces.OnChange += new ListChangedEventHandler(Traces_OnChange); InitializeComponent(); InitTimeDivision(); } /// <summary> /// Called anytime a trace is added/removed /// </summary> void Traces_OnChange(object sender, ListChangedEventArgs e) { if ( InvokeRequired ) { Invoke(new ListChangedEventHandler(Traces_OnChange), sender, e); return; } switch ( e.ListChangedType ) { case ListChangedType.ItemDeleted: Controls.Remove(Traces[e.NewIndex].traceLabel); Traces[e.NewIndex].OnChange -= new VoidInvoke(ReinitializeScopeControl); break; case ListChangedType.ItemAdded: Controls.Add(Traces[e.NewIndex].traceLabel); Traces[e.NewIndex].OnChange += new VoidInvoke(ReinitializeScopeControl); break; } // reposition anything that needs to be repositioned ReinitializeScopeControl(); } private void Scope_Load(object sender, EventArgs e) { realGraphic = this.CreateGraphics(); ReinitializeScopeControl(); } /// <summary> /// Call this to begin sending points to the scope. This flushes the internal /// buffers and begins drawing traces from t=0 /// </summary> public void Start() { lock ( traceLock ) { if ( IsRunning ) return; foreach ( Trace trace in Traces ) trace.TracePoints.Clear(); } Interlocked.Exchange(ref isRunning, 1); historyScrollBar.Visible = false; traceTime.Reset(); traceTime.Start(); drawTimer.Start(); } /// <summary> /// Call this to signal the end of incoming points to the scope /// </summary> public void Stop() { Interlocked.Exchange(ref isRunning, 0); lock ( traceLock ) { drawTimer.Stop(); traceTime.Stop(); } if ( enableHistory && Traces.Count > 0) { // this needs to be thought through some more, I think // note: the scrollbar can never get to its maximum position, its always // maximum - largechange // this depends on the count - itemwindow being positive // TODO: This needs to be fixed, badly!! try { historyScrollBar.Maximum = historyScrollBar.LargeChange + Traces[0].TracePoints.Count - Traces[0].TraceItemWindow; historyScrollBar.Value = historyScrollBar.Maximum - historyScrollBar.LargeChange; historyScrollBar.Visible = true; } catch { // screw it. } } } private void drawTimer_Tick(object sender, EventArgs e) { // don't let calls overlap -- yes, this can happen lock ( timerLock ) { DrawTraces(); } } /// <summary> /// Call this to draw the trace(s) that are currently enabled /// </summary> private void DrawTraces() { Graphics bufferGraphic; int i,j; PointF[] points; long currentMilliseconds; int tracePointsCount = 0; double usPerPoint; int calculatedPoints; int pointsToPlot; // points that should be plotted int maxPointsToPlot; // ensure this doesn't exceed that number int bufferWindow; // the range inside the buffer that will be plotted int bufferIncrement; // the number of items that should be skipped float traceYmult; // constants per trace, calculate only once instead of many times float traceYaddend; float incrementX; float X; lock ( traceLock ) { // milliseconds should be good enough currentMilliseconds = traceTime.ElapsedMilliseconds; // get count under lock if ( Traces.Count > 0 ) tracePointsCount = Traces[0].TracePoints.Count; } if ( currentScopeImage != null ) currentScopeImage.Dispose(); currentScopeImage = new Bitmap(bgImage); bufferGraphic = Graphics.FromImage(currentScopeImage); if ( Traces == null ) return; // don't draw too many points, skip some in that case maxPointsToPlot = (int)(gridLocation.Width * 2); for ( j = 0; j < Traces.Count; j++ ) { Trace trace = Traces[j]; if ( j == 0 ) lblSamples.Text = tracePointsCount.ToString() + " / " + currentMilliseconds.ToString() + " = " + ( (double)tracePointsCount / (double)currentMilliseconds ).ToString("f"); if ( !trace.Visible && trace.TraceItemWindow > 0 ) continue; // if there are no points, theres nothing to draw if ( tracePointsCount < 1 ) continue; // figure out what needs to be drawn, and scale it properly // the challenge here is that we should draw *something* at all times // and that the something should always stretch across the whole screen // another problem is that for some reason the tracing freezes when we're // drawing, and that needs to be fixed too // find the number of microseconds per point -- for obvious reasons // we're going to be doing quite horribly at microsecond resolution, but // it will have to be good enough usPerPoint = ( currentMilliseconds * 1000 ) / tracePointsCount; // find out how many points we could plot calculatedPoints = pointsToPlot = bufferWindow = (int)Math.Ceiling(( microSecondsPerUnit * UnitsX ) / usPerPoint); // this is always left justified if ( pointsToPlot >= tracePointsCount ) pointsToPlot = bufferWindow = tracePointsCount; else // otherwise, move this over one pointsToPlot = bufferWindow += 1; // if its too many, then we need to adjust it if ( pointsToPlot > maxPointsToPlot ) { // adjust the buffer increment value bufferIncrement = (int)Math.Ceiling((double)calculatedPoints / maxPointsToPlot); // set this to the max pointsToPlot = (int)Math.Ceiling((double)pointsToPlot / bufferIncrement); } else { bufferIncrement = 1; } incrementX = (float)( ( gridLocation.Width * bufferIncrement ) / calculatedPoints ); // find the starting X value X = gridLocation.Left;// -someOffset; if ( tracePointsCount < bufferWindow ) throw new Exception("Hmm"); // if its running if ( isRunning == 1) { trace.TraceStartIndex = tracePointsCount - bufferWindow; trace.TraceEndIndex = tracePointsCount; // or if the time window isn't correct } else if ( trace.TraceItemWindow != bufferWindow ) { // expand/shrink to the right, its more intuitive trace.TraceEndIndex = bufferWindow + trace.TraceStartIndex; // if its too big, then shift the window to the left if ( trace.TraceEndIndex > tracePointsCount ) { trace.TraceEndIndex = tracePointsCount; trace.TraceStartIndex = trace.TraceEndIndex - bufferWindow; // ensure that it wasn't too small if ( trace.TraceStartIndex < 0 ) trace.TraceStartIndex = 0; } } // these save time on calculations traceYmult = ( -1000F * unitLength ) / trace.MilliPerUnit; traceYaddend = zeroPosition.Y + trace.ZeroPositionY * unitLength; if ( pointsToPlot < 2 ) { // if theres only one point to draw, then draw a straight line, its // a pretty good approximation. :p points = new PointF[2]; points[0].X = gridLocation.Left; points[1].X = gridLocation.Right; points[0].Y = points[1].Y = DrawTraces_ClipY(trace.TracePoints[trace.TraceEndIndex - 1] * traceYmult + traceYaddend); } else { // points to plot should always be at least two points = new PointF[pointsToPlot]; int k = 0; for ( i = trace.TraceStartIndex; i < trace.TraceEndIndex; i += bufferIncrement ) { points[k].X = X; points[k].Y = trace.TracePoints[i] * traceYmult + traceYaddend; // TODO: sometimes we interpolate the first value (not values!) // TODO: not sure if this actually works, it may not if ( points[k].X < gridLocation.Left ) { // we have to calculate this again at the next iteration, but I can live with that float y1 = trace.TracePoints[i + bufferIncrement] * traceYmult + traceYaddend; // y0 = (y1-y0)*((x1-z)/(x1-x0)) points[k].Y = ( y1 - points[k].Y ) * ( ( X + incrementX - gridLocation.Left ) / ( incrementX ) ); points[k].X = gridLocation.Left; } // ensure valid Y values points[k].Y = DrawTraces_ClipY(points[k].Y); k += 1; X += incrementX; } } // this should not fail, most of the time if ( points.Length > 1 ) bufferGraphic.DrawCurve(trace.Pen, points); } // draw the scope on the control if ( this.ParentForm != null ) { if ( realGraphic == null ) realGraphic = this.CreateGraphics(); realGraphic.DrawImage(currentScopeImage, 0, 0); } else if (realGraphic != null ){ realGraphic.Dispose(); realGraphic = null; } bufferGraphic.Dispose(); // draw the left time buffer (TODO: this needs to be refined) timeLeftLabel.Visible = false; timeRightLabel.Visible = false; if ( tracePointsCount != 0 ) { // left side first double leftSide = ( (double)( Traces[0].TraceStartIndex * currentMilliseconds ) / 1000 ) / ( (double)tracePointsCount ); timeLeftLabel.Text = String.Format("{0:0.###}s", leftSide); // right side second timeRightLabel.Text = String.Format("{0:0.###}s", leftSide + ( (double)(microSecondsPerUnit * UnitsX)) / 1000000.0); timeRightLabel.Left = (int)gridLocation.Right - timeRightLabel.Width; }else{ timeLeftLabel.Text = ""; timeRightLabel.Text = ""; } } /// <summary> /// Don't call this from anywhere except DrawTraces. Ensures the Y /// value is valid. /// </summary> /// <param name="y"></param> /// <returns></returns> private float DrawTraces_ClipY(float y) { if (y < gridLocation.Top) return gridLocation.Top; if (y > gridLocation.Bottom) return gridLocation.Bottom; if (float.IsNaN(y)) return zeroPosition.Y; return y; } /// <summary> /// This recalculates all of the grid parameters whenever one of the attributes /// have been changed. You should only write the grid parameters through the /// associated properties, otherwise things get out of sync. /// </summary> private void recalculateGridParameters() { unitLength = Math.Max(0,gridLocation.Height / unitsY); zeroPosition.Y = ( UnitsY / 2 ) * unitLength + gridLocation.Top; zeroPosition.X = ( UnitsX / 2 ) * unitLength + gridLocation.Left; ReinitializeScopeControl(); } /// <summary> /// Repositions controls on the form /// </summary> void ReinitializeScopeControl() { // do this first CreateControlBackground(); timeUnitLabel.Font = Font; timeUnitLabel.ForeColor = ForeColor; timeUnitLabel.BackColor = BackColor; // position the history scrollbar historyScrollBar.Top = (int)Math.Ceiling(gridLocation.Bottom) + 3; historyScrollBar.Left = (int)Math.Ceiling(gridLocation.Left); historyScrollBar.Width = (int)Math.Ceiling(gridLocation.Width); historyScrollBar.Height = timeUnitLabel.Height; // position the trace controls and such int spacer = historyScrollBar.Height / 4; int nextLeft = historyScrollBar.Left; int nextTop = historyScrollBar.Top + historyScrollBar.Height + spacer; int rightLimit; // first, position the time timeUnitLabel.Top = nextTop; timeUnitLabel.Left = historyScrollBar.Right - timeUnitLabel.Width; rightLimit = timeUnitLabel.Left - spacer; for ( int i = 0; i < Traces.Count; i++ ) { Trace td = Traces[i]; Label label = td.traceLabel; if (td.MilliPerUnit < 500) label.Text = String.Format("Ch{0}: {1}m{2}", i, td.MilliPerUnit, td.UnitName); else label.Text = String.Format("Ch{0}: {1:.###}{2}", i, ((double)td.MilliPerUnit)/1000, td.UnitName); if ( td.Visible ) label.BackColor = td.TraceColor; else label.BackColor = Color.Gray; label.ForeColor = BackColor; label.Font = Font; if ( nextLeft + label.Width > rightLimit ) { nextTop += label.Height + spacer; nextLeft = historyScrollBar.Left; } label.Top = nextTop; label.Left = nextLeft; nextLeft = label.Right + spacer; } DrawTraces(); } /// <summary> /// This creates the background bitmap and scales it properly. Only /// call this from ReinitializeScopeControl /// </summary> private void CreateControlBackground() { Graphics graphic; if ( realGraphic == null || Width < 1 || Height < 1) return; // create the background image for it, setup buffers and such bgImage = new Bitmap((int)Width,(int)Height); // TODO: add margins, text, and such graphic = Graphics.FromImage(bgImage); // control background graphic.FillRectangle(backPen.Brush, this.ClientRectangle); // grid background graphic.FillRectangle(gridBackPen.Brush, gridLocation.X, gridLocation.Y, gridLocation.Width + 1, gridLocation.Height + 1); // grid border graphic.DrawRectangle(gridPen, gridLocation.X - 1, gridLocation.Y - 1, gridLocation.Width + 2, gridLocation.Height + 2); // draw the grid if ( gridVisible) DrawGrid(graphic, gridLocation, gridPen); // finish this off, don't need it anymore graphic.Dispose(); // draw any traces that need to be drawn DrawTraces(); } /// <summary> /// Draws a grid, starting from the center /// </summary> private void DrawGrid(Graphics graphic, RectangleF location, Pen pen) { int xunits, yunits, ix, iy, k; float x, y, xstart, t, xt, yt; bool AtTopEdge, AtBottomEdge, AtLeftEdge, AtRightEdge, AtCenterX, AtCenterY; // dash length float majorHalfLength = 4, minorHalfLength = 2; // dot size float dotW = 1, dotH = 1, dotX = 0.5F, dotY = 0.5F; // draw X direction, except for the edges and center // Xunits xunits = (int)Math.Ceiling(( zeroPosition.X - location.Left ) / unitLength); yunits = (int)Math.Ceiling(( zeroPosition.Y - location.Top ) / unitLength); // X starting position xstart = zeroPosition.X - xunits * unitLength; y = zeroPosition.Y - yunits * unitLength; t = unitLength / 5; iy = 0; // draw from the top left corner.. while ( iy <= yunits * 2 ) { // more efficient to calculate this here AtTopEdge = y <= location.Top + majorHalfLength ? true : false; AtBottomEdge = y >= location.Bottom - majorHalfLength ? true : false; AtCenterY = iy == yunits; ix = 0; x = xstart; while ( ix <= xunits * 2 ) { // more efficient to calculate this here AtLeftEdge = x <= location.Left + majorHalfLength ? true : false; AtRightEdge = x >= location.Right - majorHalfLength ? true : false; AtCenterX = ix == xunits; // draw minor points in Y direction for ( k = 0; k < 5; k++ ) { // value of y for this increment yt = y + t * k; // skip certain values if ((k == 0 && AtCenterY && !AtCenterX && !AtRightEdge && !AtLeftEdge) || yt < location.Top || yt > location.Bottom) continue; // left lines else if (AtLeftEdge){ if ( k == 0 ) graphic.DrawLine(pen, location.Left, yt, location.Left + majorHalfLength, yt); else graphic.DrawLine(pen, location.Left, yt, location.Left + minorHalfLength, yt); // right lines }else if (AtRightEdge){ if ( k == 0 ) graphic.DrawLine(pen, location.Right - majorHalfLength, yt, location.Right, yt); else graphic.DrawLine(pen, location.Right - minorHalfLength, yt, location.Right, yt); // middle lines } else if (AtCenterX) { if (k == 0) graphic.DrawLine(pen, x - majorHalfLength, yt, x + majorHalfLength, yt); else graphic.DrawLine(pen, x - minorHalfLength, yt, x + minorHalfLength, yt); // anything else } else graphic.DrawEllipse(pen, x - dotX, yt - dotY, dotW, dotH); } // draw minor points in X direction for ( k = 0; k < 5; k++ ) { // value of x for this increment xt = x + t * k; // skip certain values if ((k == 0 && AtCenterX && !AtCenterY && !AtTopEdge && !AtBottomEdge) || xt < location.Left || xt > location.Right) continue; // top lines else if (AtTopEdge) { if (k == 0) graphic.DrawLine(pen, xt, location.Top, xt, location.Top + majorHalfLength); else graphic.DrawLine(pen, xt, location.Top, xt, location.Top + minorHalfLength); // bottom lines }else if (AtBottomEdge) { if (k == 0) graphic.DrawLine(pen, xt, location.Bottom - majorHalfLength, xt, location.Bottom); else graphic.DrawLine(pen, xt, location.Bottom - minorHalfLength, xt, location.Bottom); // middle line }else if (AtCenterY) { if ( k == 0 ) graphic.DrawLine(pen, xt, y - majorHalfLength, xt, y + majorHalfLength); else graphic.DrawLine(pen, xt, y - minorHalfLength, xt, y + minorHalfLength); // anything else } else graphic.DrawEllipse(pen, xt - dotX, y - dotY, dotW, dotH); } // next X line x += unitLength; ix += 1; } // next Y line y += unitLength; iy += 1; } } // this needs to be far more intelligent than it is currently private void SetGridLocation() { timeRightLabel.Top = timeLeftLabel.Top = (int)leftAlign/2; timeLeftLabel.Left = (int)leftAlign; timeRightLabel.Left = (int)gridLocation.Right - timeRightLabel.Width; float b = timeLeftLabel.Bottom + leftAlign / 2; gridLocation = new RectangleF(leftAlign, b, Width -20, Height - b - (3 + timeLeftLabel.Height * 4)); recalculateGridParameters(); } /// <summary> /// Called on resize /// </summary> protected override void OnResize(EventArgs e) { Graphics old = realGraphic; // need to get a different graphics handle realGraphic = this.CreateGraphics(); // get rid of the old one if (old != null) old.Dispose(); SetGridLocation(); ReinitializeScopeControl(); } /// <summary> /// Called to paint /// </summary> protected override void OnPaint(PaintEventArgs e) { if ( currentScopeImage != null && realGraphic != null ) //realGraphic.DrawImage(currentScopeImage, e.ClipRectangle, e.ClipRectangle, GraphicsUnit.Pixel); e.Graphics.DrawImageUnscaled(currentScopeImage, 0, 0); } #region Overridden control default properties /// <summary> /// Gets or sets the primary background color of control /// </summary> public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; if ( backPen != null ) backPen.Dispose(); backPen = new Pen(value); ReinitializeScopeControl(); } } /// <summary> /// Gets or sets the primary text color of control /// </summary> public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; ReinitializeScopeControl(); } } /// <summary> /// Gets or sets the primary font for the control /// </summary> public override Font Font { get { return base.Font; } set { base.Font = value; SetGridLocation(); } } #endregion #region Properties Color gridBackColor = Color.Black; /// <summary> /// Background color of the grid /// </summary> [DefaultValue(typeof(Color), "Black")] public Color GridBackColor { get { return gridBackColor; } set { gridBackColor = value; if ( gridBackPen != null ) gridBackPen.Dispose(); gridBackPen = new Pen(value); CreateControlBackground(); } } Color gridColor = Color.White; /// <summary> /// Color of major grid lines /// </summary> [DefaultValue(typeof(Color), "GreenYellow")] public Color GridColor { get { return gridColor; } set { gridColor = value; if ( gridPen != null ) gridPen.Dispose(); gridPen = new Pen(value); CreateControlBackground(); } } int microSecondsPerUnit = 100000; /// <summary> /// How many microseconds are represented by an X unit /// </summary> [DefaultValue(100000)] public int MicroSecondsPerUnit { get { return microSecondsPerUnit; } set { microSecondsPerUnit = value; InitTimeDivision(); } } private void InitTimeDivision() { if ( InvokeRequired ) { Invoke(new VoidInvoke(InitTimeDivision)); return; } if ( microSecondsPerUnit < 1000 ) timeUnitLabel.Text = microSecondsPerUnit.ToString() + "\u00B5" + "s"; else if ( microSecondsPerUnit < 1000000 ) timeUnitLabel.Text = ( microSecondsPerUnit / 1000 ).ToString() + "ms"; else timeUnitLabel.Text = ( microSecondsPerUnit / 1000000 ).ToString() + "s"; timeUnitLabel.Visible = false; // redraw the traces DrawTraces(); ReinitializeScopeControl(); } float gridSpacing = 1; /// <summary> /// Number of units major gridlines are spaced at /// </summary> [DefaultValue(1)] public float GridSpacing{ get { return gridSpacing; } set { gridSpacing = value; CreateControlBackground(); } } bool gridVisible = true; /// <summary> /// Set this to true to show major grid lines /// </summary> [DefaultValue(true)] public bool GridVisible { get { return gridVisible; } set { gridVisible = value; CreateControlBackground(); } } float unitLength = 1; float unitsY = 8; /// <summary> /// Gets or Sets the number of vertical units that are drawn by the scope. This should be a multiple of two. /// </summary> [DefaultValue(8)] public float UnitsY { get { return unitsY; } set { unitsY = value; recalculateGridParameters(); } } /// <summary> /// Gets the number of units across that are drawn by the scope /// </summary> [ReadOnly(true)] public float UnitsX { get { if ( unitLength == 0 ) return 0; return gridLocation.Width / unitLength; } } bool enableHistory = true; /// <summary> /// Enables the ability to go back and forth with the last /// oscope trace /// </summary> [DefaultValue(true)] public bool EnableHistory { get { return enableHistory; } set { enableHistory = value; ReinitializeScopeControl(); } } private int isRunning = 0; /// <summary> /// This is set to true when the scope is "running", ie., you can call addpoints /// </summary> [ReadOnly(true)] public bool IsRunning { get { return isRunning == 1; } } #endregion //private void ScopeControl_MouseMove(object sender, MouseEventArgs e) { // locLabel.Text = e.X.ToString() + ", " + e.Y.ToString(); //} // makes the history function work private void historyScrollBar_ValueChanged(object sender, EventArgs e) { Trace t = Traces[0]; int val = historyScrollBar.Value; // TODO: Validate this function foreach ( Trace td in Traces ) { // the order matters! this one should be first td.TraceEndIndex = val + t.TraceItemWindow; if ( td.TraceEndIndex > td.TracePoints.Count ) td.TraceEndIndex = td.TracePoints.Count; td.TraceStartIndex = val; if ( td.TraceStartIndex > td.TraceEndIndex ) td.TraceStartIndex = td.TraceEndIndex - 1; } timeLeftLabel.Text = val.ToString() + " " + historyScrollBar.Maximum.ToString(); DrawTraces(); } #region Trace manipulation // Note: having this as a property causes problems /// <summary> /// This is an array of all traces, and their attributes /// </summary> public TraceCollection Traces = new TraceCollection(); List<float> tempAddPoint = new List<float>(); // the point of this is to ensure that all points have // the same number of nodes in them. This makes a lot of // things easier. /// <summary> /// Begins an 'addpoint' operation /// </summary> public void BeginAddPoint() { if ( tempAddPoint.Count != Traces.Count ) { tempAddPoint = new List<float>(Traces.Count); for ( int i = 0; i < Traces.Count; i++ ) tempAddPoint.Add(0); } else for ( int i = 0; i < Traces.Count; i++ ) tempAddPoint[i] = 0; } /// <summary> /// Add a point related to a specific trace to the display. This should be /// preceded with BeginAddPoint and ended with EndAddPoint /// </summary> /// <param name="traceIndex"></param> /// <param name="point"></param> public void AddPoint(int traceIndex, float point) { tempAddPoint[traceIndex] = point; } /// <summary> /// Commits the last set of points added with addpoint /// </summary> public void EndAddPoint() { lock ( traceLock ) { if ( isRunning == 1) for ( int i = 0; i < tempAddPoint.Count; i++ ) Traces[i].TracePoints.Add(tempAddPoint[i]); } } /// <summary> /// Add data to all traces simultaeneously. This does not require /// BeginAddPoint or EndAddPoint /// </summary> /// <param name="points"></param> public void AddPoints(params float[] points) { // don't bother checking for exceptions.. // if it throws an exception, then apparently you forgot to add // traces to the scope. :) lock ( traceLock ) { if ( isRunning == 1 ) for ( int i = 0; i < points.Length; i++ ) Traces[i].TracePoints.Add(points[i]); } } #endregion } }
#region Namespaces using System; using System.Runtime.InteropServices; using System.Threading; #endregion namespace ArdanStudios.Common { #region Structure - OVERLAPPED /// <summary> This is the WIN32 OVERLAPPED structure </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public unsafe struct OVERLAPPED { UInt32* ulpInternal; UInt32* ulpInternalHigh; Int32 lOffset; Int32 lOffsetHigh; UInt32 hEvent; } #endregion #region Class - IOCPThreadPool /// <summary> This class provides the ability to create a thread pool to manage work. The /// class abstracts the Win32 IOCompletionPort API so it requires the use of /// unmanaged code. Unfortunately the .NET framework does not provide this functionality </summary> public sealed class IOCPThreadPool { #region Win32 Function Prototypes /// <summary> Win32Func: Create an IO Completion Port Thread Pool </summary> [DllImport("Kernel32", CharSet = CharSet.Auto)] private unsafe static extern UInt32 CreateIoCompletionPort(UInt32 hFile, UInt32 hExistingCompletionPort, UInt32* puiCompletionKey, UInt32 uiNumberOfConcurrentThreads); /// <summary> Win32Func: Closes an IO Completion Port Thread Pool </summary> [DllImport("Kernel32", CharSet = CharSet.Auto)] private unsafe static extern Boolean CloseHandle(UInt32 hObject); /// <summary> Win32Func: Posts a context based event into an IO Completion Port Thread Pool </summary> [DllImport("Kernel32", CharSet = CharSet.Auto)] private unsafe static extern Boolean PostQueuedCompletionStatus(UInt32 hCompletionPort, UInt32 uiSizeOfArgument, UInt32* puiUserArg, OVERLAPPED* pOverlapped); /// <summary> Win32Func: Waits on a context based event from an IO Completion Port Thread Pool. /// All threads in the pool wait in this Win32 Function </summary> [DllImport("Kernel32", CharSet = CharSet.Auto)] private unsafe static extern Boolean GetQueuedCompletionStatus(UInt32 hCompletionPort, UInt32* pSizeOfArgument, UInt32* puiUserArg, OVERLAPPED** ppOverlapped, UInt32 uiMilliseconds); #endregion #region Constants /// <summary> SimTypeConst: This represents the Win32 Invalid Handle Value Macro </summary> private const UInt32 INVALID_HANDLE_VALUE = 0xffffffff; /// <summary> SimTypeConst: This represents the Win32 INFINITE Macro </summary> private const UInt32 INIFINITE = 0xffffffff; /// <summary> SimTypeConst: This tells the IOCP Function to shutdown </summary> private const Int32 SHUTDOWN_IOCPTHREAD = 0x7fffffff; #endregion #region Delegate Function Types /// <summary> DelType: This is the type of user function to be supplied for the thread pool </summary> public delegate void USER_FUNCTION(Int32 iValue); #endregion #region Private Properties /// <summary> SimType: Contains the IO Completion Port Thread Pool handle for this instance </summary> private UInt32 Handle; /// <summary> SimType: The maximum number of threads that may be running at the same time </summary> private Int32 MaxConcurrency; /// <summary> SimType: The minimal number of threads the thread pool maintains </summary> private Int32 MinThreadsInPool; /// <summary> SimType: The maximum number of threads the thread pool maintains </summary> private Int32 MaxThreadsInPool; /// <summary> RefType: A serialization object to protect the class state </summary> private Object CriticalSection; /// <summary> DelType: A reference to a user specified function to be call by the thread pool </summary> private USER_FUNCTION UserFunction; /// <summary> SimType: Flag to indicate if the class is disposing </summary> private Boolean IsDisposed; #endregion #region Public Properties private long _CurThreadsInPool = 0; /// <summary> SimType: The current number of threads in the thread pool </summary> public long CurThreadsInPool { get { return Interlocked.Read(ref _CurThreadsInPool); } } /// <summary> SimType: Increment current number of threads in the thread pool </summary> private long IncCurThreadsInPool() { return Interlocked.Increment(ref _CurThreadsInPool); } /// <summary> SimType: Decrement current number of threads in the thread pool </summary> private long DecCurThreadsInPool() { return Interlocked.Decrement(ref _CurThreadsInPool); } private long _ActThreadsInPool = 0; /// <summary> SimType: The current number of active threads in the thread pool </summary> public long ActThreadsInPool { get { return Interlocked.Read(ref _ActThreadsInPool); } } /// <summary> SimType: Increment current number of active threads in the thread pool </summary> private long IncActThreadsInPool() { return Interlocked.Increment(ref _ActThreadsInPool); } /// <summary> SimType: Decrement current number of active threads in the thread pool </summary> private long DecActThreadsInPool() { return Interlocked.Decrement(ref _ActThreadsInPool); } private long _CurWorkInPool = 0; /// <summary> SimType: The current number of Work posted in the thread pool </summary> public long CurWorkInPool { get { return Interlocked.Read(ref _CurWorkInPool); } } /// <summary> SimType: Increment current number of Work posted in the thread pool </summary> private long IncCurWorkInPool() { return Interlocked.Increment(ref _CurWorkInPool); } /// <summary> SimType: Decrement current number of Work posted in the thread pool </summary> private long DecCurWorkInPool() { return Interlocked.Decrement(ref _CurWorkInPool); } #endregion #region Constructor /// <summary> Constructor </summary> /// <param name = "iMaxConcurrency"> SimType: Max number of running threads allowed </param> /// <param name = "iMinThreadsInPool"> SimType: Min number of threads in the pool </param> /// <param name = "iMaxThreadsInPool"> SimType: Max number of threads in the pool </param> /// <param name = "pfnUserFunction"> DelType: Reference to a function to call to perform work </param> /// <param name="threadPriority"></param> /// <exception cref = "Exception"> Unhandled Exception </exception> public IOCPThreadPool(Int32 iMaxConcurrency, Int32 iMinThreadsInPool, Int32 iMaxThreadsInPool, USER_FUNCTION pfnUserFunction, ThreadPriority threadPriority=ThreadPriority.Normal) { try { // Set initial class state MaxConcurrency = iMaxConcurrency; MinThreadsInPool = iMinThreadsInPool; MaxThreadsInPool = iMaxThreadsInPool; UserFunction = pfnUserFunction; // Initialize the Monitor Object CriticalSection = new Object(); // Set the disposing flag to false IsDisposed = false; unsafe { // Create an IO Completion Port for Thread Pool use Handle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, null, (UInt32)MaxConcurrency); } // Test to make sure the IO Completion Port was created if (Handle == 0) throw new Exception("Unable To Create IO Completion Port"); // Allocate and start the Minimum number of threads specified long iStartingCount = CurThreadsInPool; ThreadStart tsThread = new ThreadStart(IOCPFunction); for (long iThread = 0; iThread < MinThreadsInPool; ++iThread) { // Create a thread and start it Thread thThread = new Thread(tsThread); thThread.Name = "IOCP"; thThread.Priority = threadPriority; thThread.Start(); // Increment the thread pool count IncCurThreadsInPool(); } } catch { throw new Exception("Unhandled Exception"); } } //******************************************************************** /// <summary> Called when the object will be shutdown. This /// function will wait for all of the work to be completed /// inside the queue before completing </summary> public void Dispose() { try { // Flag that we are disposing this object IsDisposed = true; // Get the current number of threads in the pool long iCurThreadsInPool = CurThreadsInPool; // Shutdown all thread in the pool for (long iThread = 0; iThread < iCurThreadsInPool; ++iThread) { unsafe { bool bret = PostQueuedCompletionStatus(Handle, 4, (UInt32*)SHUTDOWN_IOCPTHREAD, null); } } // Wait here until all the threads are gone while (CurThreadsInPool != 0) Thread.Sleep(100); unsafe { // Close the IOCP Handle CloseHandle(Handle); } } catch { } } #endregion #region Private Methods /// <summary> IOCP Worker Function that calls the specified user function </summary> private void IOCPFunction() { UInt32 uiNumberOfBytes; Int32 iValue; try { while (true) { unsafe { OVERLAPPED* pOv; // Wait for an event GetQueuedCompletionStatus(Handle, &uiNumberOfBytes, (UInt32*)&iValue, &pOv, INIFINITE); } // Decrement the number of events in queue DecCurWorkInPool(); // Should this thread shutdown if ((IsDisposed == true) || (iValue == SHUTDOWN_IOCPTHREAD)) break; // Increment the number of active threads IncActThreadsInPool(); try { // Call the user function UserFunction(iValue); } catch { } // Get a lock lock (CriticalSection) { // If we have less than max threads currently in the pool if (CurThreadsInPool < MaxThreadsInPool) { // Should we add a new thread to the pool if (ActThreadsInPool == CurThreadsInPool) { if (IsDisposed == false) { // Create a thread and start it ThreadStart tsThread = new ThreadStart(IOCPFunction); Thread thThread = new Thread(tsThread); thThread.Name = string.Format("IOCP {0}", thThread.GetHashCode()); thThread.Start(); // Increment the thread pool count IncCurThreadsInPool(); } } } } // Increment the number of active threads DecActThreadsInPool(); } } catch { } // Decrement the thread pool count DecCurThreadsInPool(); } #endregion #region Public Methods /// <summary> IOCP Worker Function that calls the specified user function </summary> /// <exception cref = "Exception"> Unhandled Exception </exception> public void PostEvent() { try { // Only add work if we are not disposing if (IsDisposed == false) { unsafe { // Post an event into the IOCP Thread Pool PostQueuedCompletionStatus(Handle, 0, null, null); } // Increment the number of item of work IncCurWorkInPool(); // Get a lock lock (CriticalSection) { // If we have less than max threads currently in the pool if (CurThreadsInPool < MaxThreadsInPool) { // Should we add a new thread to the pool if (ActThreadsInPool == CurThreadsInPool) { if (IsDisposed == false) { // Create a thread and start it ThreadStart tsThread = new ThreadStart(IOCPFunction); Thread thThread = new Thread(tsThread); thThread.Name = string.Format("IOCP {0}", thThread.GetHashCode()); thThread.Start(); // Increment the thread pool count IncCurThreadsInPool(); } } } } } } catch (Exception e) { throw e; } } //******************************************************************** /// <summary> IOCP Worker Function that calls the specified user function </summary> /// <param name="iValue"> SimType: A value to be passed with the event </param> /// <exception cref = "Exception"> Unhandled Exception </exception> public void PostEvent(Int32 iValue) { try { // Only add work if we are not disposing if (IsDisposed == false) { unsafe { // Post an event into the IOCP Thread Pool PostQueuedCompletionStatus(Handle, 4, (UInt32*)iValue, null); } // Increment the number of item of work IncCurWorkInPool(); // Get a lock lock (CriticalSection) { // If we have less than max threads currently in the pool if (CurThreadsInPool < MaxThreadsInPool) { // Should we add a new thread to the pool if (ActThreadsInPool == CurThreadsInPool) { if (IsDisposed == false) { // Create a thread and start it ThreadStart tsThread = new ThreadStart(IOCPFunction); Thread thThread = new Thread(tsThread); thThread.Name = string.Format("IOCP {0}", thThread.GetHashCode()); thThread.Start(); // Increment the thread pool count IncCurThreadsInPool(); } } } } } } catch (Exception e) { throw e; } } #endregion } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Orleans.Streams; namespace Orleans.Runtime.Host { /// <summary> /// Interfacse exposed by ServiceRuntimeWrapper for functionality provided /// by Microsoft.WindowsAzure.ServiceRuntime. /// </summary> public interface IServiceRuntimeWrapper { /// <summary> /// Deployment ID of the hosted service /// </summary> string DeploymentId { get; } /// <summary> /// Name of the role instance /// </summary> string InstanceName { get; } /// <summary> /// Name of the worker/web role /// </summary> string RoleName { get; } /// <summary> /// Update domain of the role instance /// </summary> int UpdateDomain { get; } /// <summary> /// Fault domain of the role instance /// </summary> int FaultDomain { get; } /// <summary> /// Number of instances in the worker/web role /// </summary> int RoleInstanceCount { get; } /// <summary> /// Returns IP endpoint by name /// </summary> /// <param name="endpointName">Name of the IP endpoint</param> /// <returns></returns> IPEndPoint GetIPEndpoint(string endpointName); /// <summary> /// Returns value of the given configuration setting /// </summary> /// <param name="configurationSettingName"></param> /// <returns></returns> string GetConfigurationSettingValue(string configurationSettingName); /// <summary> /// Subscribes given even handler for role instance Stopping event /// </summary> /// /// <param name="handlerObject">Object that handler is part of, or null for a static method</param> /// <param name="handler">Handler to subscribe</param> void SubscribeForStoppingNotifcation(object handlerObject, EventHandler<object> handler); /// <summary> /// Unsubscribes given even handler from role instance Stopping event /// </summary> /// /// <param name="handlerObject">Object that handler is part of, or null for a static method</param> /// <param name="handler">Handler to unsubscribe</param> void UnsubscribeFromStoppingNotifcation(object handlerObject, EventHandler<object> handler); } /// <summary> /// The purpose of this class is to wrap the functionality provided /// by Microsoft.WindowsAzure.ServiceRuntime.dll, so that we can access it via Reflection, /// and not have a compile-time dependency on it. /// Microsoft.WindowsAzure.ServiceRuntime.dll doesn't have an official NuGet package. /// By loading it via Reflection we solve this problem, and do not need an assembly /// binding redirect for it, as we can call any compatible version. /// Microsoft.WindowsAzure.ServiceRuntime.dll hasn't changed in years, so the chance of a breaking change /// is relatively low. /// </summary> internal class ServiceRuntimeWrapper : IServiceRuntimeWrapper, IDeploymentConfiguration { private readonly TraceLogger logger; private Assembly assembly; private Type roleEnvironmentType; private EventInfo stoppingEvent; private MethodInfo stoppingEventAdd; private MethodInfo stoppingEventRemove; private Type roleInstanceType; private dynamic currentRoleInstance; private dynamic instanceEndpoints; private dynamic role; public ServiceRuntimeWrapper() { logger = TraceLogger.GetLogger("ServiceRuntimeWrapper"); Initialize(); } public string DeploymentId { get; private set; } public string InstanceId { get; private set; } public string RoleName { get; private set; } public int UpdateDomain { get; private set; } public int FaultDomain { get; private set; } public string InstanceName { get { return ExtractInstanceName(InstanceId, DeploymentId); } } public int RoleInstanceCount { get { dynamic instances = role.Instances; return instances.Count; } } public IList<string> GetAllSiloNames() { dynamic instances = role.Instances; var list = new List<string>(); foreach(dynamic instance in instances) list.Add(ExtractInstanceName(instance.Id,DeploymentId)); return list; } public IPEndPoint GetIPEndpoint(string endpointName) { try { dynamic ep = instanceEndpoints.GetType() .GetProperty("Item") .GetMethod.Invoke(instanceEndpoints, new object[] {endpointName}); return ep.IPEndpoint; } catch (Exception exc) { var errorMsg = string.Format("Unable to obtain endpoint info for role {0} from role config parameter {1} -- Endpoints defined = [{2}]", RoleName, endpointName, string.Join(", ", instanceEndpoints)); logger.Error(ErrorCode.SiloEndpointConfigError, errorMsg, exc); throw new OrleansException(errorMsg, exc); } } public string GetConfigurationSettingValue(string configurationSettingName) { return (string) roleEnvironmentType.GetMethod("GetConfigurationSettingValue").Invoke(null, new object[] {configurationSettingName}); } public void SubscribeForStoppingNotifcation(object handlerObject, EventHandler<object> handler) { var handlerDelegate = handler.GetMethodInfo().CreateDelegate(stoppingEvent.EventHandlerType, handlerObject); stoppingEventAdd.Invoke(null, new object[] { handlerDelegate }); } public void UnsubscribeFromStoppingNotifcation(object handlerObject, EventHandler<object> handler) { var handlerDelegate = handler.GetMethodInfo().CreateDelegate(stoppingEvent.EventHandlerType, handlerObject); stoppingEventRemove.Invoke(null, new[] { handlerDelegate }); } private void Initialize() { assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault( a => a.FullName.StartsWith("Microsoft.WindowsAzure.ServiceRuntime")); // If we are runing within a worker role Microsoft.WindowsAzure.ServiceRuntime should already be loaded if (assembly == null) { const string msg1 = "Microsoft.WindowsAzure.ServiceRuntime is not loaded. Trying to load it with Assembly.LoadWithPartialName()."; logger.Warn(ErrorCode.AzureServiceRuntime_NotLoaded, msg1); // Microsoft.WindowsAzure.ServiceRuntime isn't loaded. We may be running within a web role or not in Azure. // Trying to load by partial name, so that we are not version specific. // Assembly.LoadWithPartialName has been deprecated. Is there a better way to load any version of a known assembly? #pragma warning disable 618 assembly = Assembly.LoadWithPartialName("Microsoft.WindowsAzure.ServiceRuntime"); #pragma warning restore 618 if (assembly == null) { const string msg2 = "Failed to find or load Microsoft.WindowsAzure.ServiceRuntime."; logger.Error(ErrorCode.AzureServiceRuntime_FailedToLoad, msg2); throw new OrleansException(msg2); } } roleEnvironmentType = assembly.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment"); stoppingEvent = roleEnvironmentType.GetEvent("Stopping"); stoppingEventAdd = stoppingEvent.GetAddMethod(); stoppingEventRemove = stoppingEvent.GetRemoveMethod(); roleInstanceType = assembly.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleInstance"); DeploymentId = (string) roleEnvironmentType.GetProperty("DeploymentId").GetValue(null); if (string.IsNullOrWhiteSpace(DeploymentId)) throw new OrleansException("DeploymentId is null or whitespace."); currentRoleInstance = roleEnvironmentType.GetProperty("CurrentRoleInstance").GetValue(null); if (currentRoleInstance == null) throw new OrleansException("CurrentRoleInstance is null."); InstanceId = currentRoleInstance.Id; UpdateDomain = currentRoleInstance.UpdateDomain; FaultDomain = currentRoleInstance.FaultDomain; instanceEndpoints = currentRoleInstance.InstanceEndpoints; role = currentRoleInstance.Role; RoleName = role.Name; } private static string ExtractInstanceName(string instanceId, string deploymentId) { return instanceId.Length > deploymentId.Length && instanceId.StartsWith(deploymentId) ? instanceId.Substring(deploymentId.Length + 1) : instanceId; } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class LinearLayout : android.view.ViewGroup { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static LinearLayout() { InitJNI(); } protected LinearLayout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class LayoutParams : android.view.ViewGroup.MarginLayoutParams { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static LayoutParams() { InitJNI(); } protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _debug11484; public virtual global::java.lang.String debug(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.LinearLayout.LayoutParams._debug11484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._debug11484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _LayoutParams11485; public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._LayoutParams11485, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11486; public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._LayoutParams11486, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11487; public LayoutParams(int arg0, int arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._LayoutParams11487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11488; public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._LayoutParams11488, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11489; public LayoutParams(android.view.ViewGroup.MarginLayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.LayoutParams.staticClass, global::android.widget.LinearLayout.LayoutParams._LayoutParams11489, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _weight11490; public float weight { get { return default(float); } set { } } internal static global::MonoJavaBridge.FieldId _gravity11491; public int gravity { get { return default(int); } set { } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.LinearLayout.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/LinearLayout$LayoutParams")); global::android.widget.LinearLayout.LayoutParams._debug11484 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "debug", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.widget.LinearLayout.LayoutParams._LayoutParams11485 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.LinearLayout.LayoutParams._LayoutParams11486 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(II)V"); global::android.widget.LinearLayout.LayoutParams._LayoutParams11487 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(IIF)V"); global::android.widget.LinearLayout.LayoutParams._LayoutParams11488 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V"); global::android.widget.LinearLayout.LayoutParams._LayoutParams11489 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$MarginLayoutParams;)V"); } } internal static global::MonoJavaBridge.MethodId _setGravity11492; public virtual void setGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setGravity11492, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setGravity11492, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onLayout11493; protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._onLayout11493, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._onLayout11493, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _getBaseline11494; public override int getBaseline() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.LinearLayout._getBaseline11494); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._getBaseline11494); } internal static global::MonoJavaBridge.MethodId _onMeasure11495; protected override void onMeasure(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._onMeasure11495, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._onMeasure11495, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _checkLayoutParams11496; protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.LinearLayout._checkLayoutParams11496, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._checkLayoutParams11496, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11497; public virtual new global::android.widget.LinearLayout.LayoutParams generateLayoutParams(android.util.AttributeSet arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.LinearLayout._generateLayoutParams11497, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.LinearLayout.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._generateLayoutParams11497, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.LinearLayout.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11498; protected virtual new global::android.widget.LinearLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.LinearLayout._generateLayoutParams11498, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.LinearLayout.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._generateLayoutParams11498, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.LinearLayout.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateDefaultLayoutParams11499; protected virtual new global::android.widget.LinearLayout.LayoutParams generateDefaultLayoutParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.LinearLayout._generateDefaultLayoutParams11499)) as android.widget.LinearLayout.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._generateDefaultLayoutParams11499)) as android.widget.LinearLayout.LayoutParams; } internal static global::MonoJavaBridge.MethodId _isBaselineAligned11500; public virtual bool isBaselineAligned() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.LinearLayout._isBaselineAligned11500); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._isBaselineAligned11500); } internal static global::MonoJavaBridge.MethodId _setBaselineAligned11501; public virtual void setBaselineAligned(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setBaselineAligned11501, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setBaselineAligned11501, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getBaselineAlignedChildIndex11502; public virtual int getBaselineAlignedChildIndex() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.LinearLayout._getBaselineAlignedChildIndex11502); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._getBaselineAlignedChildIndex11502); } internal static global::MonoJavaBridge.MethodId _setBaselineAlignedChildIndex11503; public virtual void setBaselineAlignedChildIndex(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setBaselineAlignedChildIndex11503, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setBaselineAlignedChildIndex11503, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getWeightSum11504; public virtual float getWeightSum() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.widget.LinearLayout._getWeightSum11504); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._getWeightSum11504); } internal static global::MonoJavaBridge.MethodId _setWeightSum11505; public virtual void setWeightSum(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setWeightSum11505, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setWeightSum11505, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOrientation11506; public virtual void setOrientation(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setOrientation11506, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setOrientation11506, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getOrientation11507; public virtual int getOrientation() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.LinearLayout._getOrientation11507); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._getOrientation11507); } internal static global::MonoJavaBridge.MethodId _setHorizontalGravity11508; public virtual void setHorizontalGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setHorizontalGravity11508, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setHorizontalGravity11508, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setVerticalGravity11509; public virtual void setVerticalGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.LinearLayout._setVerticalGravity11509, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._setVerticalGravity11509, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _LinearLayout11510; public LinearLayout(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._LinearLayout11510, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LinearLayout11511; public LinearLayout(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.LinearLayout.staticClass, global::android.widget.LinearLayout._LinearLayout11511, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int HORIZONTAL { get { return 0; } } public static int VERTICAL { get { return 1; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.LinearLayout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/LinearLayout")); global::android.widget.LinearLayout._setGravity11492 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setGravity", "(I)V"); global::android.widget.LinearLayout._onLayout11493 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "onLayout", "(ZIIII)V"); global::android.widget.LinearLayout._getBaseline11494 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "getBaseline", "()I"); global::android.widget.LinearLayout._onMeasure11495 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "onMeasure", "(II)V"); global::android.widget.LinearLayout._checkLayoutParams11496 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z"); global::android.widget.LinearLayout._generateLayoutParams11497 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/LinearLayout$LayoutParams;"); global::android.widget.LinearLayout._generateLayoutParams11498 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/widget/LinearLayout$LayoutParams;"); global::android.widget.LinearLayout._generateDefaultLayoutParams11499 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "generateDefaultLayoutParams", "()Landroid/widget/LinearLayout$LayoutParams;"); global::android.widget.LinearLayout._isBaselineAligned11500 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "isBaselineAligned", "()Z"); global::android.widget.LinearLayout._setBaselineAligned11501 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setBaselineAligned", "(Z)V"); global::android.widget.LinearLayout._getBaselineAlignedChildIndex11502 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "getBaselineAlignedChildIndex", "()I"); global::android.widget.LinearLayout._setBaselineAlignedChildIndex11503 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setBaselineAlignedChildIndex", "(I)V"); global::android.widget.LinearLayout._getWeightSum11504 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "getWeightSum", "()F"); global::android.widget.LinearLayout._setWeightSum11505 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setWeightSum", "(F)V"); global::android.widget.LinearLayout._setOrientation11506 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setOrientation", "(I)V"); global::android.widget.LinearLayout._getOrientation11507 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "getOrientation", "()I"); global::android.widget.LinearLayout._setHorizontalGravity11508 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setHorizontalGravity", "(I)V"); global::android.widget.LinearLayout._setVerticalGravity11509 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "setVerticalGravity", "(I)V"); global::android.widget.LinearLayout._LinearLayout11510 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.LinearLayout._LinearLayout11511 = @__env.GetMethodIDNoThrow(global::android.widget.LinearLayout.staticClass, "<init>", "(Landroid/content/Context;)V"); } } }
using System; using System.IO; using Cake.Core.IO; using Path = Cake.Core.IO.Path; namespace Cake.Testing { /// <summary> /// Represents a fake file. /// </summary> public sealed class FakeFile : IFile { private readonly FakeFileSystemTree _tree; private readonly FilePath _path; private readonly object _contentLock = new object(); private byte[] _content = new byte[4096]; /// <summary> /// Gets the path to the file. /// </summary> /// <value>The path.</value> public FilePath Path { get { return _path; } } Path IFileSystemInfo.Path { get { return _path; } } /// <summary> /// Gets a value indicating whether this <see cref="IFileSystemInfo" /> exists. /// </summary> /// <value> /// <c>true</c> if the entry exists; otherwise, <c>false</c>. /// </value> public bool Exists { get; internal set; } /// <summary> /// Gets a value indicating whether this <see cref="IFileSystemInfo" /> is hidden. /// </summary> /// <value> /// <c>true</c> if the entry is hidden; otherwise, <c>false</c>. /// </value> public bool Hidden { get; internal set; } /// <summary> /// Gets the length of the file. /// </summary> /// <value> /// The length of the file. /// </value> public long Length { get; private set; } /// <summary> /// Gets the date and time the file was last modified. /// </summary> /// <value>The date and time the file was last modified.</value> public DateTimeOffset LastModified { get; private set; } internal object ContentLock { get { return _contentLock; } } /// <summary> /// Gets the length of the content. /// </summary> /// <value> /// The length of the content. /// </value> public long ContentLength { get { return Length; } internal set { Length = value; } } /// <summary> /// Gets the content. /// </summary> /// <value>The content.</value> public byte[] Content { get { return _content; } internal set { _content = value; } } internal FakeFile(FakeFileSystemTree tree, FilePath path) { _tree = tree; _path = path; Exists = false; Hidden = false; } /// <summary> /// Copies the file to the specified destination path. /// </summary> /// <param name="destination">The destination path.</param> /// <param name="overwrite">Will overwrite existing destination file if set to <c>true</c>.</param> public void Copy(FilePath destination, bool overwrite) { _tree.CopyFile(this, destination, overwrite); } /// <summary> /// Moves the file to the specified destination path. /// </summary> /// <param name="destination">The destination path.</param> public void Move(FilePath destination) { _tree.MoveFile(this, destination); } /// <summary> /// Opens the file using the specified options. /// </summary> /// <param name="fileMode">The file mode.</param> /// <param name="fileAccess">The file access.</param> /// <param name="fileShare">The file share.</param> /// <returns>A <see cref="Stream" /> to the file.</returns> public Stream Open(FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { bool fileWasCreated; var position = GetPosition(fileMode, out fileWasCreated); if (fileWasCreated) { _tree.CreateFile(this); } return new FakeFileStream(this) { Position = position }; } /// <summary> /// Deletes the file. /// </summary> public void Delete() { _tree.DeleteFile(this); } /// <summary> /// Resizes the file. /// </summary> /// <param name="offset">The offset.</param> public void Resize(long offset) { if (Length < offset) { Length = offset; } if (_content.Length >= Length) { return; } var buffer = new byte[Length * 2]; Buffer.BlockCopy(_content, 0, buffer, 0, _content.Length); _content = buffer; } private long GetPosition(FileMode fileMode, out bool fileWasCreated) { fileWasCreated = false; if (Exists) { switch (fileMode) { case FileMode.CreateNew: throw new IOException(); case FileMode.Create: case FileMode.Truncate: Length = 0; return 0; case FileMode.Open: case FileMode.OpenOrCreate: return 0; case FileMode.Append: return Length; } } else { switch (fileMode) { case FileMode.Create: case FileMode.Append: case FileMode.CreateNew: case FileMode.OpenOrCreate: fileWasCreated = true; Exists = true; return Length; case FileMode.Open: case FileMode.Truncate: throw new FileNotFoundException(); } } throw new NotSupportedException(); } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { partial class WsatControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WsatControl)); this.textBoxNetworkDtcAccess = new System.Windows.Forms.TextBox(); this.groupBoxTracing = new System.Windows.Forms.GroupBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.buttonTracingOptions = new System.Windows.Forms.Button(); this.groupBoxTimeouts = new System.Windows.Forms.GroupBox(); this.textBoxDefaultTimeout = new System.Windows.Forms.TextBox(); this.textBoxMaxTimeout = new System.Windows.Forms.TextBox(); this.labelSeconds2 = new System.Windows.Forms.Label(); this.labelSeconds1 = new System.Windows.Forms.Label(); this.labelMaxTimeout = new System.Windows.Forms.Label(); this.labelDefaultTimeout = new System.Windows.Forms.Label(); this.groupBoxNetwork = new System.Windows.Forms.GroupBox(); this.textBoxHttpsPort = new System.Windows.Forms.TextBox(); this.labelHttpsPort = new System.Windows.Forms.Label(); this.labelEndpointCert = new System.Windows.Forms.Label(); this.textBoxEndpointCert = new System.Windows.Forms.TextBox(); this.buttonSelectEndpointCert = new System.Windows.Forms.Button(); this.buttonSelectAuthorizedAccounts = new System.Windows.Forms.Button(); this.buttonSelectAuthorizedCerts = new System.Windows.Forms.Button(); this.labelAuthorizedCerts = new System.Windows.Forms.Label(); this.labelAuthorizedAccounts = new System.Windows.Forms.Label(); this.checkBoxEnableNetworkSupport = new System.Windows.Forms.CheckBox(); this.groupBoxTracing.SuspendLayout(); this.groupBoxTimeouts.SuspendLayout(); this.groupBoxNetwork.SuspendLayout(); this.SuspendLayout(); // // textBoxNetworkDtcAccess // this.textBoxNetworkDtcAccess.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.textBoxNetworkDtcAccess, "textBoxNetworkDtcAccess"); this.textBoxNetworkDtcAccess.Name = "textBoxNetworkDtcAccess"; this.textBoxNetworkDtcAccess.ReadOnly = true; this.textBoxNetworkDtcAccess.TabStop = false; // // groupBoxTracing // this.groupBoxTracing.Controls.Add(this.textBox1); this.groupBoxTracing.Controls.Add(this.buttonTracingOptions); resources.ApplyResources(this.groupBoxTracing, "groupBoxTracing"); this.groupBoxTracing.Name = "groupBoxTracing"; this.groupBoxTracing.TabStop = false; // // textBox1 // this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.textBox1, "textBox1"); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.TabStop = false; // // buttonTracingOptions // resources.ApplyResources(this.buttonTracingOptions, "buttonTracingOptions"); this.buttonTracingOptions.Name = "buttonTracingOptions"; this.buttonTracingOptions.UseVisualStyleBackColor = true; this.buttonTracingOptions.Click += new System.EventHandler(this.buttonTracingOptions_Click); // // groupBoxTimeouts // this.groupBoxTimeouts.Controls.Add(this.labelDefaultTimeout); this.groupBoxTimeouts.Controls.Add(this.textBoxDefaultTimeout); this.groupBoxTimeouts.Controls.Add(this.labelMaxTimeout); this.groupBoxTimeouts.Controls.Add(this.textBoxMaxTimeout); this.groupBoxTimeouts.Controls.Add(this.labelSeconds2); this.groupBoxTimeouts.Controls.Add(this.labelSeconds1); resources.ApplyResources(this.groupBoxTimeouts, "groupBoxTimeouts"); this.groupBoxTimeouts.Name = "groupBoxTimeouts"; this.groupBoxTimeouts.TabStop = false; // // textBoxDefaultTimeout // resources.ApplyResources(this.textBoxDefaultTimeout, "textBoxDefaultTimeout"); this.textBoxDefaultTimeout.Name = "textBoxDefaultTimeout"; this.textBoxDefaultTimeout.TextChanged += new System.EventHandler(this.textBoxDefaultTimeout_TextChanged); // // textBoxMaxTimeout // resources.ApplyResources(this.textBoxMaxTimeout, "textBoxMaxTimeout"); this.textBoxMaxTimeout.Name = "textBoxMaxTimeout"; this.textBoxMaxTimeout.TextChanged += new System.EventHandler(this.textBoxMaxTimeout_TextChanged); // // labelSeconds2 // resources.ApplyResources(this.labelSeconds2, "labelSeconds2"); this.labelSeconds2.Name = "labelSeconds2"; // // labelSeconds1 // resources.ApplyResources(this.labelSeconds1, "labelSeconds1"); this.labelSeconds1.Name = "labelSeconds1"; // // labelMaxTimeout // resources.ApplyResources(this.labelMaxTimeout, "labelMaxTimeout"); this.labelMaxTimeout.Name = "labelMaxTimeout"; // // labelDefaultTimeout // resources.ApplyResources(this.labelDefaultTimeout, "labelDefaultTimeout"); this.labelDefaultTimeout.Name = "labelDefaultTimeout"; // // groupBoxNetwork // this.groupBoxNetwork.Controls.Add(this.labelHttpsPort); this.groupBoxNetwork.Controls.Add(this.textBoxHttpsPort); this.groupBoxNetwork.Controls.Add(this.labelEndpointCert); this.groupBoxNetwork.Controls.Add(this.textBoxEndpointCert); this.groupBoxNetwork.Controls.Add(this.buttonSelectEndpointCert); this.groupBoxNetwork.Controls.Add(this.buttonSelectAuthorizedAccounts); this.groupBoxNetwork.Controls.Add(this.buttonSelectAuthorizedCerts); this.groupBoxNetwork.Controls.Add(this.labelAuthorizedCerts); this.groupBoxNetwork.Controls.Add(this.labelAuthorizedAccounts); resources.ApplyResources(this.groupBoxNetwork, "groupBoxNetwork"); this.groupBoxNetwork.Name = "groupBoxNetwork"; this.groupBoxNetwork.TabStop = false; // // textBoxHttpsPort // resources.ApplyResources(this.textBoxHttpsPort, "textBoxHttpsPort"); this.textBoxHttpsPort.Name = "textBoxHttpsPort"; this.textBoxHttpsPort.TextChanged += new System.EventHandler(this.textBoxHttpsPort_TextChanged); // // labelHttpsPort // resources.ApplyResources(this.labelHttpsPort, "labelHttpsPort"); this.labelHttpsPort.Name = "labelHttpsPort"; // // labelEndpointCert // resources.ApplyResources(this.labelEndpointCert, "labelEndpointCert"); this.labelEndpointCert.Name = "labelEndpointCert"; // // textBoxEndpointCert // this.textBoxEndpointCert.BackColor = System.Drawing.SystemColors.Control; this.textBoxEndpointCert.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; resources.ApplyResources(this.textBoxEndpointCert, "textBoxEndpointCert"); this.textBoxEndpointCert.Name = "textBoxEndpointCert"; this.textBoxEndpointCert.ReadOnly = true; // // buttonSelectEndpointCert // resources.ApplyResources(this.buttonSelectEndpointCert, "buttonSelectEndpointCert"); this.buttonSelectEndpointCert.Name = "buttonSelectEndpointCert"; this.buttonSelectEndpointCert.UseVisualStyleBackColor = true; this.buttonSelectEndpointCert.Click += new System.EventHandler(this.buttonSelectEndpointCert_Click); // // buttonSelectAuthorizedAccounts // resources.ApplyResources(this.buttonSelectAuthorizedAccounts, "buttonSelectAuthorizedAccounts"); this.buttonSelectAuthorizedAccounts.Name = "buttonSelectAuthorizedAccounts"; this.buttonSelectAuthorizedAccounts.UseVisualStyleBackColor = true; this.buttonSelectAuthorizedAccounts.Click += new System.EventHandler(this.buttonSelectAuthorizedAccounts_Click); // // buttonSelectAuthorizedCerts // resources.ApplyResources(this.buttonSelectAuthorizedCerts, "buttonSelectAuthorizedCerts"); this.buttonSelectAuthorizedCerts.Name = "buttonSelectAuthorizedCerts"; this.buttonSelectAuthorizedCerts.UseVisualStyleBackColor = true; this.buttonSelectAuthorizedCerts.Click += new System.EventHandler(this.buttonSelectAuthorizedCerts_Click); // // labelAuthorizedCerts // resources.ApplyResources(this.labelAuthorizedCerts, "labelAuthorizedCerts"); this.labelAuthorizedCerts.Name = "labelAuthorizedCerts"; // // labelAuthorizedAccounts // resources.ApplyResources(this.labelAuthorizedAccounts, "labelAuthorizedAccounts"); this.labelAuthorizedAccounts.Name = "labelAuthorizedAccounts"; // // checkBoxEnableNetworkSupport // resources.ApplyResources(this.checkBoxEnableNetworkSupport, "checkBoxEnableNetworkSupport"); this.checkBoxEnableNetworkSupport.Name = "checkBoxEnableNetworkSupport"; this.checkBoxEnableNetworkSupport.UseVisualStyleBackColor = true; this.checkBoxEnableNetworkSupport.CheckedChanged += new System.EventHandler(this.checkBoxEnableNetworkSupport_CheckedChanged); // // WsatControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.textBoxNetworkDtcAccess); this.Controls.Add(this.checkBoxEnableNetworkSupport); this.Controls.Add(this.groupBoxNetwork); this.Controls.Add(this.groupBoxTimeouts); this.Controls.Add(this.groupBoxTracing); this.Name = "WsatControl"; this.groupBoxTracing.ResumeLayout(false); this.groupBoxTracing.PerformLayout(); this.groupBoxTimeouts.ResumeLayout(false); this.groupBoxTimeouts.PerformLayout(); this.groupBoxNetwork.ResumeLayout(false); this.groupBoxNetwork.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBoxNetworkDtcAccess; private System.Windows.Forms.GroupBox groupBoxNetwork; private System.Windows.Forms.Label labelHttpsPort; private System.Windows.Forms.GroupBox groupBoxTimeouts; private System.Windows.Forms.Label labelEndpointCert; private System.Windows.Forms.Label labelAuthorizedCerts; private System.Windows.Forms.Label labelAuthorizedAccounts; private System.Windows.Forms.TextBox textBoxHttpsPort; private System.Windows.Forms.Button buttonSelectEndpointCert; private System.Windows.Forms.TextBox textBoxEndpointCert; private System.Windows.Forms.Label labelMaxTimeout; private System.Windows.Forms.Label labelDefaultTimeout; private System.Windows.Forms.CheckBox checkBoxEnableNetworkSupport; private System.Windows.Forms.Button buttonSelectAuthorizedCerts; private System.Windows.Forms.TextBox textBoxDefaultTimeout; private System.Windows.Forms.Label labelSeconds2; private System.Windows.Forms.Label labelSeconds1; private System.Windows.Forms.TextBox textBoxMaxTimeout; private System.Windows.Forms.Button buttonTracingOptions; private System.Windows.Forms.GroupBox groupBoxTracing; private System.Windows.Forms.Button buttonSelectAuthorizedAccounts; private System.Windows.Forms.TextBox textBox1; } }
using System; #if SILVERLIGHT using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.ComponentModel; #else using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.Foundation; using Windows.UI.Input; #endif namespace Microsoft.PlayerFramework { /// <summary> /// Represents a control that shows a visual indicator of the duration of the current media and current position. /// </summary> /// <remarks> /// The Timeline keeps track of the current position, start position, and end position. /// </remarks> public partial class SeekableSlider : Slider { private bool pointerCaptured; private Action pointerReleaseAction; private bool ignoreValueChanged; private bool inboundValue; /// <summary> /// Instantiates a new instance of the SeekableSlider class. /// </summary> public SeekableSlider() { DefaultStyleKey = typeof(SeekableSlider); this.SizeChanged += SeekableSlider_SizeChanged; } /// <summary> /// Gets or sets whether the timeline is scrubbing. /// </summary> public bool IsScrubbing { get { return pointerCaptured || (Thumb != null && Thumb.IsDragging); } } /// <summary> /// Occurs when the user seeked. /// </summary> public event EventHandler<ValueRoutedEventArgs> Seeked; /// <summary> /// Occurs when the user begins scrubbing. /// </summary> public event EventHandler<ValueRoutedEventArgs> ScrubbingStarted; /// <summary> /// Occurs when the user scrubs. /// </summary> public event EventHandler<ValueRoutedEventArgs> Scrubbing; /// <summary> /// Occurs when the user completes scrubbing. /// </summary> public event EventHandler<ValueRoutedEventArgs> ScrubbingCompleted; /// <summary> /// Invokes the Seeked event. /// </summary> /// <param name="e">EventArgs used to provide info about the event</param> protected void OnSeeked(ValueRoutedEventArgs e) { if (Seeked != null) { ignoreValueChanged = true; try { Seeked(this, e); } finally { ignoreValueChanged = false; } } } /// <summary> /// Invokes the ScrubbingCompleted event. /// </summary> /// <param name="e">EventArgs used to provide info about the event</param> protected void OnScrubbingCompleted(ValueRoutedEventArgs e) { VisualStateManager.GoToState(this, "NotScrubbing", true); if (ScrubbingCompleted != null) { ignoreValueChanged = true; try { ScrubbingCompleted(this, e); } finally { ignoreValueChanged = false; } } } /// <summary> /// Invokes the Scrubbing event. /// </summary> /// <param name="e">EventArgs used to provide info about the event</param> protected void OnScrubbing(ValueRoutedEventArgs e) { if (Scrubbing != null) { ignoreValueChanged = true; try { Scrubbing(this, e); } finally { ignoreValueChanged = false; } } } /// <summary> /// Invokes the ScrubbingStarted event. /// </summary> /// <param name="e">EventArgs used to provide info about the event</param> protected void OnScrubbingStarted(ValueRoutedEventArgs e) { VisualStateManager.GoToState(this, "Scrubbing", true); if (ScrubbingStarted != null) { ignoreValueChanged = true; try { ScrubbingStarted(this, e); } finally { ignoreValueChanged = false; } } } /// <inheritdoc /> protected override void OnValueChanged(double oldValue, double newValue) { if (!ignoreValueChanged) { var value = Math.Min(newValue, Max); if (inboundValue || !IsEnabled) { base.OnValueChanged(oldValue, value); } else { var args = new ValueRoutedEventArgs(value); if (IsScrubbing) { OnScrubbing(args); } else { OnSeeked(args); } if (!args.Canceled) { base.OnValueChanged(oldValue, value); } else { inboundValue = true; try { Value = oldValue; } finally { inboundValue = false; } } } } } /// <inheritdoc /> protected override void OnMaximumChanged(double oldMaximum, double newMaximum) { base.OnMaximumChanged(oldMaximum, newMaximum); RestrictAvailability(); RefreshStepFrequency(); } /// <inheritdoc /> protected override void OnMinimumChanged(double oldMinimum, double newMinimum) { base.OnMinimumChanged(oldMinimum, newMinimum); RestrictAvailability(); RefreshStepFrequency(); } void SeekableSlider_SizeChanged(object sender, SizeChangedEventArgs e) { RefreshStepFrequency(); } void RefreshStepFrequency() { #if !SILVERLIGHT var length = Orientation == Orientation.Horizontal ? RenderSize.Width : RenderSize.Height; if (length > 0) { StepFrequency = (Maximum - Minimum) / length; } #endif } private void RestrictAvailability() { double range = Maximum - Minimum; // convert the available unit to a pixel width if (AvailableBar != null) { if (Orientation == Orientation.Horizontal) { if (Panel != null && Panel.ActualWidth > 0 && range > 0) { var thumbWidth = ThumbElement == null ? 0 : ThumbElement.ActualWidth; // calculate the pixel width of the available bar, need to take into // account the _horizontalThumb width, otherwise the _horizontalThumb position is calculated differently // then the available bar (the _horizontalThumb position takes into account the _horizontalThumb width) double availableRange = Max - Minimum; double pixelValue = (availableRange / range) * (Panel.ActualWidth - thumbWidth); // want the width of the available bar to be aligned with the right of the _horizontalThumb, this // allows the maxposition indictor to be correctly positioned to the right of the _horizontalThumb pixelValue += thumbWidth; // make sure within range, Available can be negative when it first starts pixelValue = Math.Min(Panel.ActualWidth, pixelValue); pixelValue = Math.Max(0, pixelValue); AvailableBar.Width = pixelValue; } else { AvailableBar.Width = Panel.ActualWidth; } } else { if (Panel != null && Panel.ActualHeight > 0 && range > 0) { var thumbHeight = ThumbElement == null ? 0 : ThumbElement.ActualHeight; // calculate the pixel width of the available bar, need to take into // account the Thumb width, otherwise the Thumb position is calculated differently // then the available bar (the Thumb position takes into account the Thumb width) double availableRange = Max - Minimum; double pixelValue = (availableRange / range) * (Panel.ActualHeight - thumbHeight); // want the width of the available bar to be aligned with the right of the Thumb, this // allows the maxposition indictor to be correctly positioned to the right of the Thumb pixelValue += thumbHeight; // make sure within range, Available can be negative when it first starts pixelValue = Math.Min(Panel.ActualHeight, pixelValue); pixelValue = Math.Max(0, pixelValue); AvailableBar.Height = pixelValue; } else { AvailableBar.Height = 0; } } } } #if SILVERLIGHT private double? GetHorizontalPanelMousePosition(MouseEventArgs e) #else private double? GetHorizontalPanelMousePosition(PointerRoutedEventArgs e) #endif { // take into account the scrubber _horizontalThumb size double thumbWidth = (ThumbElement == null) ? 0 : ThumbElement.ActualWidth; double panelWidth = Panel.ActualWidth - thumbWidth; if (panelWidth > 0) { double range = Maximum - Minimum; // calculate the new newValue based on mouse position #if SILVERLIGHT Point mousePosition = e.GetPosition(Panel); #else Point mousePosition = e.GetCurrentPoint(Panel).Position; #endif double x = mousePosition.X - thumbWidth / 2; x = Math.Min(Math.Max(0, x), panelWidth); double value = (x * range) / panelWidth; // offset from the min newValue value += Minimum; return value; } else return null; } #if SILVERLIGHT private double? GetVerticalPanelMousePosition(MouseEventArgs e) #else private double? GetVerticalPanelMousePosition(PointerRoutedEventArgs e) #endif { // take into account the scrubber _horizontalThumb size double thumbHeight = (ThumbElement == null) ? 0 : ThumbElement.ActualHeight; double panelHeight = Panel.ActualHeight - thumbHeight; if (panelHeight > 0) { double range = Maximum - Minimum; // calculate the new newValue based on mouse position #if SILVERLIGHT Point mousePosition = e.GetPosition(Panel); #else Point mousePosition = e.GetCurrentPoint(Panel).Position; #endif double y = mousePosition.Y - thumbHeight / 2; y = Math.Min(Math.Max(0, y), panelHeight); double value = ((panelHeight - y) * range) / panelHeight; // offset from the min newValue value += Minimum; return value; } else return null; } } /// <summary> /// EventArgs class to return a double. /// </summary> public class ValueRoutedEventArgs : RoutedEventArgs { internal ValueRoutedEventArgs(double Value) { this.Value = Value; } /// <summary> /// The value associated with the event. /// </summary> public double Value { get; internal set; } /// <summary> /// The value associated with the event. /// </summary> public bool Canceled { get; set; } } }
/* ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ namespace System.Data.SQLite { public partial class Sqlite3 { //#define TK_SEMI 1 //#define TK_EXPLAIN 2 //#define TK_QUERY 3 //#define TK_PLAN 4 //#define TK_BEGIN 5 //#define TK_TRANSACTION 6 //#define TK_DEFERRED 7 //#define TK_IMMEDIATE 8 //#define TK_EXCLUSIVE 9 //#define TK_COMMIT 10 //#define TK_END 11 //#define TK_ROLLBACK 12 //#define TK_SAVEPOINT 13 //#define TK_RELEASE 14 //#define TK_TO 15 //#define TK_TABLE 16 //#define TK_CREATE 17 //#define TK_IF 18 //#define TK_NOT 19 //#define TK_EXISTS 20 //#define TK_TEMP 21 //#define TK_LP 22 //#define TK_RP 23 //#define TK_AS 24 //#define TK_COMMA 25 //#define TK_ID 26 //#define TK_INDEXED 27 //#define TK_ABORT 28 //#define TK_ACTION 29 //#define TK_AFTER 30 //#define TK_ANALYZE 31 //#define TK_ASC 32 //#define TK_ATTACH 33 //#define TK_BEFORE 34 //#define TK_BY 35 //#define TK_CASCADE 36 //#define TK_CAST 37 //#define TK_COLUMNKW 38 //#define TK_CONFLICT 39 //#define TK_DATABASE 40 //#define TK_DESC 41 //#define TK_DETACH 42 //#define TK_EACH 43 //#define TK_FAIL 44 //#define TK_FOR 45 //#define TK_IGNORE 46 //#define TK_INITIALLY 47 //#define TK_INSTEAD 48 //#define TK_LIKE_KW 49 //#define TK_MATCH 50 //#define TK_NO 51 //#define TK_KEY 52 //#define TK_OF 53 //#define TK_OFFSET 54 //#define TK_PRAGMA 55 //#define TK_RAISE 56 //#define TK_REPLACE 57 //#define TK_RESTRICT 58 //#define TK_ROW 59 //#define TK_TRIGGER 60 //#define TK_VACUUM 61 //#define TK_VIEW 62 //#define TK_VIRTUAL 63 //#define TK_REINDEX 64 //#define TK_RENAME 65 //#define TK_CTIME_KW 66 //#define TK_ANY 67 //#define TK_OR 68 //#define TK_AND 69 //#define TK_IS 70 //#define TK_BETWEEN 71 //#define TK_IN 72 //#define TK_ISNULL 73 //#define TK_NOTNULL 74 //#define TK_NE 75 //#define TK_EQ 76 //#define TK_GT 77 //#define TK_LE 78 //#define TK_LT 79 //#define TK_GE 80 //#define TK_ESCAPE 81 //#define TK_BITAND 82 //#define TK_BITOR 83 //#define TK_LSHIFT 84 //#define TK_RSHIFT 85 //#define TK_PLUS 86 //#define TK_MINUS 87 //#define TK_STAR 88 //#define TK_SLASH 89 //#define TK_REM 90 //#define TK_CONCAT 91 //#define TK_COLLATE 92 //#define TK_BITNOT 93 //#define TK_STRING 94 //#define TK_JOIN_KW 95 //#define TK_CONSTRAINT 96 //#define TK_DEFAULT 97 //#define TK_NULL 98 //#define TK_PRIMARY 99 //#define TK_UNIQUE 100 //#define TK_CHECK 101 //#define TK_REFERENCES 102 //#define TK_AUTOINCR 103 //#define TK_ON 104 //#define TK_INSERT 105 //#define TK_DELETE 106 //#define TK_UPDATE 107 //#define TK_SET 108 //#define TK_DEFERRABLE 109 //#define TK_FOREIGN 110 //#define TK_DROP 111 //#define TK_UNION 112 //#define TK_ALL 113 //#define TK_EXCEPT 114 //#define TK_INTERSECT 115 //#define TK_SELECT 116 //#define TK_DISTINCT 117 //#define TK_DOT 118 //#define TK_FROM 119 //#define TK_JOIN 120 //#define TK_USING 121 //#define TK_ORDER 122 //#define TK_GROUP 123 //#define TK_HAVING 124 //#define TK_LIMIT 125 //#define TK_WHERE 126 //#define TK_INTO 127 //#define TK_VALUES 128 //#define TK_INTEGER 129 //#define TK_FLOAT 130 //#define TK_BLOB 131 //#define TK_REGISTER 132 //#define TK_VARIABLE 133 //#define TK_CASE 134 //#define TK_WHEN 135 //#define TK_THEN 136 //#define TK_ELSE 137 //#define TK_INDEX 138 //#define TK_ALTER 139 //#define TK_ADD 140 //#define TK_TO_TEXT 141 //#define TK_TO_BLOB 142 //#define TK_TO_NUMERIC 143 //#define TK_TO_INT 144 //#define TK_TO_REAL 145 //#define TK_ISNOT 146 //#define TK_END_OF_FILE 147 //#define TK_ILLEGAL 148 //#define TK_SPACE 149 //#define TK_UNCLOSED_STRING 150 //#define TK_FUNCTION 151 //#define TK_COLUMN 152 //#define TK_AGG_FUNCTION 153 //#define TK_AGG_COLUMN 154 //#define TK_CONST_FUNC 155 //#define TK_UMINUS 156 //#define TK_UPLUS 157 public const int TK_SEMI = 1; public const int TK_EXPLAIN = 2; public const int TK_QUERY = 3; public const int TK_PLAN = 4; public const int TK_BEGIN = 5; public const int TK_TRANSACTION = 6; public const int TK_DEFERRED = 7; public const int TK_IMMEDIATE = 8; public const int TK_EXCLUSIVE = 9; public const int TK_COMMIT = 10; public const int TK_END = 11; public const int TK_ROLLBACK = 12; public const int TK_SAVEPOINT = 13; public const int TK_RELEASE = 14; public const int TK_TO = 15; public const int TK_TABLE = 16; public const int TK_CREATE = 17; public const int TK_IF = 18; public const int TK_NOT = 19; public const int TK_EXISTS = 20; public const int TK_TEMP = 21; public const int TK_LP = 22; public const int TK_RP = 23; public const int TK_AS = 24; public const int TK_COMMA = 25; public const int TK_ID = 26; public const int TK_INDEXED = 27; public const int TK_ABORT = 28; public const int TK_ACTION = 29; public const int TK_AFTER = 30; public const int TK_ANALYZE = 31; public const int TK_ASC = 32; public const int TK_ATTACH = 33; public const int TK_BEFORE = 34; public const int TK_BY = 35; public const int TK_CASCADE = 36; public const int TK_CAST = 37; public const int TK_COLUMNKW = 38; public const int TK_CONFLICT = 39; public const int TK_DATABASE = 40; public const int TK_DESC = 41; public const int TK_DETACH = 42; public const int TK_EACH = 43; public const int TK_FAIL = 44; public const int TK_FOR = 45; public const int TK_IGNORE = 46; public const int TK_INITIALLY = 47; public const int TK_INSTEAD = 48; public const int TK_LIKE_KW = 49; public const int TK_MATCH = 50; public const int TK_NO = 51; public const int TK_KEY = 52; public const int TK_OF = 53; public const int TK_OFFSET = 54; public const int TK_PRAGMA = 55; public const int TK_RAISE = 56; public const int TK_REPLACE = 57; public const int TK_RESTRICT = 58; public const int TK_ROW = 59; public const int TK_TRIGGER = 60; public const int TK_VACUUM = 61; public const int TK_VIEW = 62; public const int TK_VIRTUAL = 63; public const int TK_REINDEX = 64; public const int TK_RENAME = 65; public const int TK_CTIME_KW = 66; public const int TK_ANY = 67; public const int TK_OR = 68; public const int TK_AND = 69; public const int TK_IS = 70; public const int TK_BETWEEN = 71; public const int TK_IN = 72; public const int TK_ISNULL = 73; public const int TK_NOTNULL = 74; public const int TK_NE = 75; public const int TK_EQ = 76; public const int TK_GT = 77; public const int TK_LE = 78; public const int TK_LT = 79; public const int TK_GE = 80; public const int TK_ESCAPE = 81; public const int TK_BITAND = 82; public const int TK_BITOR = 83; public const int TK_LSHIFT = 84; public const int TK_RSHIFT = 85; public const int TK_PLUS = 86; public const int TK_MINUS = 87; public const int TK_STAR = 88; public const int TK_SLASH = 89; public const int TK_REM = 90; public const int TK_CONCAT = 91; public const int TK_COLLATE = 92; public const int TK_BITNOT = 93; public const int TK_STRING = 94; public const int TK_JOIN_KW = 95; public const int TK_CONSTRAINT = 96; public const int TK_DEFAULT = 97; public const int TK_NULL = 98; public const int TK_PRIMARY = 99; public const int TK_UNIQUE = 100; public const int TK_CHECK = 101; public const int TK_REFERENCES = 102; public const int TK_AUTOINCR = 103; public const int TK_ON = 104; public const int TK_INSERT = 105; public const int TK_DELETE = 106; public const int TK_UPDATE = 107; public const int TK_SET = 108; public const int TK_DEFERRABLE = 109; public const int TK_FOREIGN = 110; public const int TK_DROP = 111; public const int TK_UNION = 112; public const int TK_ALL = 113; public const int TK_EXCEPT = 114; public const int TK_INTERSECT = 115; public const int TK_SELECT = 116; public const int TK_DISTINCT = 117; public const int TK_DOT = 118; public const int TK_FROM = 119; public const int TK_JOIN = 120; public const int TK_USING = 121; public const int TK_ORDER = 122; public const int TK_GROUP = 123; public const int TK_HAVING = 124; public const int TK_LIMIT = 125; public const int TK_WHERE = 126; public const int TK_INTO = 127; public const int TK_VALUES = 128; public const int TK_INTEGER = 129; public const int TK_FLOAT = 130; public const int TK_BLOB = 131; public const int TK_REGISTER = 132; public const int TK_VARIABLE = 133; public const int TK_CASE = 134; public const int TK_WHEN = 135; public const int TK_THEN = 136; public const int TK_ELSE = 137; public const int TK_INDEX = 138; public const int TK_ALTER = 139; public const int TK_ADD = 140; public const int TK_TO_TEXT = 141; public const int TK_TO_BLOB = 142; public const int TK_TO_NUMERIC = 143; public const int TK_TO_INT = 144; public const int TK_TO_REAL = 145; public const int TK_ISNOT = 146; public const int TK_END_OF_FILE = 147; public const int TK_ILLEGAL = 148; public const int TK_SPACE = 149; public const int TK_UNCLOSED_STRING = 150; public const int TK_FUNCTION = 151; public const int TK_COLUMN = 152; public const int TK_AGG_FUNCTION = 153; public const int TK_AGG_COLUMN = 154; public const int TK_CONST_FUNC = 155; public const int TK_UMINUS = 156; public const int TK_UPLUS = 157; } }
//------------------------------------------------------------------------------ // <copyright file="WeakHashtable.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.ComponentModel { using System; using System.Collections; using System.Security.Permissions; /// <devdoc> /// This is a hashtable that stores object keys as weak references. /// It monitors memory usage and will periodically scavenge the /// hash table to clean out dead references. /// </devdoc> [HostProtection(SharedState = true)] internal sealed class WeakHashtable : Hashtable { private static IEqualityComparer _comparer = new WeakKeyComparer(); private long _lastGlobalMem; private int _lastHashCount; internal WeakHashtable() : base(_comparer) { } /// <devdoc> /// Override of clear that performs a scavenge. /// </devdoc> public override void Clear() { base.Clear(); } /// <devdoc> /// Override of remove that performs a scavenge. /// </devdoc> public override void Remove(object key) { base.Remove(key); } /// <devdoc> /// Override of Item that wraps a weak reference around the /// key and performs a scavenge. /// </devdoc> public void SetWeak(object key, object value) { ScavengeKeys(); this[new EqualityWeakReference(key)] = value; } /// <devdoc> /// This method checks to see if it is necessary to /// scavenge keys, and if it is it performs a scan /// of all keys to see which ones are no longer valid. /// To determine if we need to scavenge keys we need to /// try to track the current GC memory. Our rule of /// thumb is that if GC memory is decreasing and our /// key count is constant we need to scavenge. We /// will need to see if this is too often for extreme /// use cases like the CompactFramework (they add /// custom type data for every object at design time). /// </devdoc> private void ScavengeKeys() { int hashCount = Count; if (hashCount == 0) { return; } if (_lastHashCount == 0) { _lastHashCount = hashCount; return; } long globalMem = GC.GetTotalMemory(false); if (_lastGlobalMem == 0) { _lastGlobalMem = globalMem; return; } float memDelta = (float)(globalMem - _lastGlobalMem) / (float)_lastGlobalMem; float hashDelta = (float)(hashCount - _lastHashCount) / (float)_lastHashCount; if (memDelta < 0 && hashDelta >= 0) { // Perform a scavenge through our keys, looking // for dead references. // ArrayList cleanupList = null; foreach(object o in Keys) { WeakReference wr = o as WeakReference; if (wr != null && !wr.IsAlive) { if (cleanupList == null) { cleanupList = new ArrayList(); } cleanupList.Add(wr); } } if (cleanupList != null) { foreach(object o in cleanupList) { Remove(o); } } } _lastGlobalMem = globalMem; _lastHashCount = hashCount; } private class WeakKeyComparer : IEqualityComparer { bool IEqualityComparer.Equals(Object x, Object y) { if (x == null) { return y == null; } if (y != null && x.GetHashCode() == y.GetHashCode()) { WeakReference wX = x as WeakReference; WeakReference wY = y as WeakReference; if (wX != null) { if (!wX.IsAlive) { return false; } x = wX.Target; } if (wY != null) { if (!wY.IsAlive) { return false; } y = wY.Target; } return object.ReferenceEquals(x, y); } return false; } int IEqualityComparer.GetHashCode (Object obj) { return obj.GetHashCode(); } } /// <devdoc> /// A subclass of WeakReference that overrides GetHashCode and /// Equals so that the weak reference returns the same equality /// semantics as the object it wraps. This will always return /// the object's hash code and will return True for a Equals /// comparison of the object it is wrapping. If the object /// it is wrapping has finalized, Equals always returns false. /// </devdoc> private sealed class EqualityWeakReference : WeakReference { private int _hashCode; internal EqualityWeakReference(object o) : base(o) { _hashCode = o.GetHashCode(); } public override bool Equals(object o) { if (o == null) { return false; } if (o.GetHashCode() != _hashCode) { return false; } if (o == this || (IsAlive && object.ReferenceEquals(o, Target))) { return true; } return false; } public override int GetHashCode() { return _hashCode; } } /* The folowing code has been removed to prevent FXCOP violation It is left here incase it needs to be resurected /// <devdoc> /// Override of add that wraps a weak reference around the /// key and performs a scavenge. /// </devdoc> public void AddWeak(object key, object value) { ScavengeKeys(); base.Add(new EqualityWeakReference(key), value); } */ } }
//================================================================================================= // Copyright 2017 Dirk Lemstra <https://graphicsmagick.codeplex.com/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing permissions and // limitations under the License. //================================================================================================= using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Text; using System.Windows.Media.Imaging; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Fasterflect; namespace GraphicsMagick { public sealed class PathArc: IDisposable { internal object _Instance; internal PathArc(object instance) { _Instance = instance; } public static object GetInstance(PathArc obj) { if (ReferenceEquals(obj, null)) return null; return obj._Instance; } public static object GetInstance(object obj) { if (ReferenceEquals(obj, null)) return null; PathArc casted = obj as PathArc; if (ReferenceEquals(casted, null)) return obj; return casted._Instance; } internal static object CastIEnumerable(IEnumerable<PathArc> list) { if (ReferenceEquals(list, null)) return null; Type listType = typeof(List<>).MakeGenericType(Types.PathArc); object result = listType.CreateInstance(); foreach (PathArc item in list) result.CallMethod("Add", PathArc.GetInstance(item)); return result; } public PathArc(Double x, Double y, Double radiusX, Double radiusY, Double rotationX, Boolean useLargeArc, Boolean useSweep) : this(AssemblyHelper.CreateInstance(Types.PathArc, new Type[] {typeof(Double), typeof(Double), typeof(Double), typeof(Double), typeof(Double), typeof(Boolean), typeof(Boolean)}, x, y, radiusX, radiusY, rotationX, useLargeArc, useSweep)) { } public PathArc() : this(AssemblyHelper.CreateInstance(Types.PathArc)) { } public Double RadiusX { get { object result; try { result = _Instance.GetPropertyValue("RadiusX"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("RadiusX", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double RadiusY { get { object result; try { result = _Instance.GetPropertyValue("RadiusY"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("RadiusY", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double RotationX { get { object result; try { result = _Instance.GetPropertyValue("RotationX"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("RotationX", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Boolean UseLargeArc { get { object result; try { result = _Instance.GetPropertyValue("UseLargeArc"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Boolean)result; } set { try { _Instance.SetPropertyValue("UseLargeArc", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Boolean UseSweep { get { object result; try { result = _Instance.GetPropertyValue("UseSweep"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Boolean)result; } set { try { _Instance.SetPropertyValue("UseSweep", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double X { get { object result; try { result = _Instance.GetPropertyValue("X"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("X", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double Y { get { object result; try { result = _Instance.GetPropertyValue("Y"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("Y", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public void Dispose() { try { _Instance.CallMethod("Dispose"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Xml; using System.Text; using System.Reflection; using fyiReporting.RDL; namespace fyiReporting.RdlDesign { /// <summary> /// DialogListOfStrings: puts up a dialog that lets a user enter a list of strings /// </summary> public class DialogExprEditor : System.Windows.Forms.Form { Type[] BASE_TYPES = new Type[] { typeof(string), typeof(double), typeof(Single), typeof(decimal), typeof(DateTime), typeof(char), typeof(bool), typeof(int), typeof(short), typeof(long), typeof(byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) }; private DesignXmlDraw _Draw; // design draw private bool _Color; // true if color list should be displayed private SplitContainer splitContainer1; private Button bCopy; private Label lOp; private TextBox tbExpr; private Label lExpr; private TreeView tvOp; private Panel panel1; private Button bCancel; private Button bOK; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node) : this(dxDraw, expr, node, false) { } internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node, bool bColor) { _Draw = dxDraw; _Color = bColor; // // Required for Windows Form Designer support // InitializeComponent(); tbExpr.Text = expr; // Fill out the fields list string[] fields = null; // Find the dataregion that contains the item (if any) for (XmlNode pNode = node; pNode != null; pNode = pNode.ParentNode) { if (pNode.Name == "List" || pNode.Name == "Table" || pNode.Name == "Matrix" || pNode.Name == "Chart") { string dsname = _Draw.GetDataSetNameValue(pNode); if (dsname != null) // found it { fields = _Draw.GetFields(dsname, true); } } } BuildTree(fields); return; } void BuildTree(string[] flds) { // suppress redraw until tree view is complete tvOp.BeginUpdate(); //AJM GJL Adding Missing 'User' Menu // Handle the user TreeNode ndRoot = new TreeNode("User"); tvOp.Nodes.Add(ndRoot); foreach (string item in StaticLists.UserList) { // Add the node to the tree TreeNode aRoot = new TreeNode(item.StartsWith("=") ? item.Substring(1) : item); ndRoot.Nodes.Add(aRoot); } // Handle the globals ndRoot = new TreeNode("Globals"); tvOp.Nodes.Add(ndRoot); foreach (string item in StaticLists.GlobalList) { // Add the node to the tree TreeNode aRoot = new TreeNode(item.StartsWith("=")? item.Substring(1): item); ndRoot.Nodes.Add(aRoot); } // Fields - only when a dataset is specified if (flds != null && flds.Length > 0) { ndRoot = new TreeNode("Fields"); tvOp.Nodes.Add(ndRoot); foreach (string f in flds) { TreeNode aRoot = new TreeNode(f.StartsWith("=")? f.Substring(1): f); ndRoot.Nodes.Add(aRoot); } } // Report parameters InitReportParameters(); // Handle the functions ndRoot = new TreeNode("Functions"); tvOp.Nodes.Add(ndRoot); InitFunctions(ndRoot); // Aggregate functions ndRoot = new TreeNode("Aggregate Functions"); tvOp.Nodes.Add(ndRoot); foreach (string item in StaticLists.AggrFunctionList) { // Add the node to the tree TreeNode aRoot = new TreeNode(item); ndRoot.Nodes.Add(aRoot); } // Operators ndRoot = new TreeNode("Operators"); tvOp.Nodes.Add(ndRoot); foreach (string item in StaticLists.OperatorList) { // Add the node to the tree TreeNode aRoot = new TreeNode(item); ndRoot.Nodes.Add(aRoot); } // Colors (if requested) if (_Color) { ndRoot = new TreeNode("Colors"); tvOp.Nodes.Add(ndRoot); foreach (string item in StaticLists.ColorList) { // Add the node to the tree TreeNode aRoot = new TreeNode(item); ndRoot.Nodes.Add(aRoot); } } tvOp.EndUpdate(); } /// <summary> /// Populate tree view with the report parameters (if any) /// </summary> void InitReportParameters() { string[] ps = _Draw.GetReportParameters(true); if (ps == null || ps.Length == 0) return; TreeNode ndRoot = new TreeNode("Parameters"); tvOp.Nodes.Add(ndRoot); foreach (string p in ps) { TreeNode aRoot = new TreeNode(p.StartsWith("=")?p.Substring(1): p); ndRoot.Nodes.Add(aRoot); } return; } void InitFunctions(TreeNode ndRoot) { List<string> ar = new List<string>(); ar.AddRange(StaticLists.FunctionList); // Build list of methods in the VBFunctions class fyiReporting.RDL.FontStyleEnum fsi = FontStyleEnum.Italic; // just want a class from RdlEngine.dll assembly Assembly a = Assembly.GetAssembly(fsi.GetType()); if (a == null) return; Type ft = a.GetType("fyiReporting.RDL.VBFunctions"); BuildMethods(ar, ft, ""); // build list of financial methods in Financial class ft = a.GetType("fyiReporting.RDL.Financial"); BuildMethods(ar, ft, "Financial."); a = Assembly.GetAssembly("".GetType()); ft = a.GetType("System.Math"); BuildMethods(ar, ft, "Math."); ft = a.GetType("System.Convert"); BuildMethods(ar, ft, "Convert."); ft = a.GetType("System.String"); BuildMethods(ar, ft, "String."); ar.Sort(); string previous=""; foreach (string item in ar) { if (item != previous) // don't add duplicates { // Add the node to the tree TreeNode aRoot = new TreeNode(item); ndRoot.Nodes.Add(aRoot); } previous = item; } } void BuildMethods(List<string> ar, Type ft, string prefix) { if (ft == null) return; MethodInfo[] mis = ft.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo mi in mis) { // Add the node to the tree string name = BuildMethodName(mi); if (name != null) ar.Add(prefix + name); } } string BuildMethodName(MethodInfo mi) { StringBuilder sb = new StringBuilder(mi.Name); sb.Append("("); ParameterInfo[] pis = mi.GetParameters(); bool bFirst=true; foreach (ParameterInfo pi in pis) { if (!IsBaseType(pi.ParameterType)) return null; if (bFirst) bFirst = false; else sb.Append(", "); sb.Append(pi.Name); } sb.Append(")"); return sb.ToString(); } // Determines if underlying type is a primitive bool IsBaseType(Type t) { foreach (Type bt in BASE_TYPES) { if (bt == t) return true; } return false; } public string Expression { get {return tbExpr.Text; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.bCancel = new System.Windows.Forms.Button(); this.bOK = new System.Windows.Forms.Button(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.tvOp = new System.Windows.Forms.TreeView(); this.bCopy = new System.Windows.Forms.Button(); this.lOp = new System.Windows.Forms.Label(); this.tbExpr = new System.Windows.Forms.TextBox(); this.lExpr = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add(this.bCancel); this.panel1.Controls.Add(this.bOK); this.panel1.Location = new System.Drawing.Point(0, 208); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(463, 40); this.panel1.TabIndex = 15; // // bCancel // this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Location = new System.Drawing.Point(374, 9); this.bCancel.Name = "bCancel"; this.bCancel.Size = new System.Drawing.Size(75, 23); this.bCancel.TabIndex = 5; this.bCancel.Text = "Cancel"; // // bOK // this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.bOK.Location = new System.Drawing.Point(293, 9); this.bOK.Name = "bOK"; this.bOK.Size = new System.Drawing.Size(75, 23); this.bOK.TabIndex = 4; this.bOK.Text = "OK"; // // splitContainer1 // this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.tvOp); this.splitContainer1.Panel1.Controls.Add(this.bCopy); this.splitContainer1.Panel1.Controls.Add(this.lOp); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.tbExpr); this.splitContainer1.Panel2.Controls.Add(this.lExpr); this.splitContainer1.Size = new System.Drawing.Size(463, 203); this.splitContainer1.SplitterDistance = 154; this.splitContainer1.TabIndex = 14; // // tvOp // this.tvOp.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tvOp.Location = new System.Drawing.Point(0, 29); this.tvOp.Name = "tvOp"; this.tvOp.Size = new System.Drawing.Size(151, 171); this.tvOp.TabIndex = 1; // // bCopy // this.bCopy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bCopy.Location = new System.Drawing.Point(119, 0); this.bCopy.Name = "bCopy"; this.bCopy.Size = new System.Drawing.Size(32, 23); this.bCopy.TabIndex = 2; this.bCopy.Text = ">>"; this.bCopy.Click += new System.EventHandler(this.bCopy_Click); // // lOp // this.lOp.Location = new System.Drawing.Point(0, 0); this.lOp.Name = "lOp"; this.lOp.Size = new System.Drawing.Size(106, 23); this.lOp.TabIndex = 14; this.lOp.Text = "Select and hit \'>>\'"; // // tbExpr // this.tbExpr.AcceptsReturn = true; this.tbExpr.AcceptsTab = true; this.tbExpr.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbExpr.Location = new System.Drawing.Point(6, 32); this.tbExpr.Multiline = true; this.tbExpr.Name = "tbExpr"; this.tbExpr.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.tbExpr.Size = new System.Drawing.Size(296, 168); this.tbExpr.TabIndex = 0; this.tbExpr.WordWrap = false; // // lExpr // this.lExpr.Location = new System.Drawing.Point(3, 3); this.lExpr.Name = "lExpr"; this.lExpr.Size = new System.Drawing.Size(134, 20); this.lExpr.TabIndex = 13; this.lExpr.Text = "Expressions start with \'=\'"; // // DialogExprEditor // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(463, 248); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogExprEditor"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Edit Expression"; this.panel1.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.Panel2.PerformLayout(); this.splitContainer1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void bCopy_Click(object sender, System.EventArgs e) { if (tvOp.SelectedNode == null || tvOp.SelectedNode.Parent == null) return; // this is the top level nodes (Fields, Parameters, ...) TreeNode node = tvOp.SelectedNode; string t = node.Text; if (tbExpr.Text.Length == 0) t = "=" + t; tbExpr.SelectedText = t; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Globalization; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; namespace Newtonsoft.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerInternalReader _serializerReader; private readonly JsonSerializerInternalWriter _serializerWriter; private readonly JsonSerializer _serializer; public override event EventHandler<ErrorEventArgs> Error { add { _serializer.Error += value; } remove { _serializer.Error -= value; } } public override IReferenceResolver ReferenceResolver { get { return _serializer.ReferenceResolver; } set { _serializer.ReferenceResolver = value; } } public override ITraceWriter TraceWriter { get { return _serializer.TraceWriter; } set { _serializer.TraceWriter = value; } } public override IEqualityComparer EqualityComparer { get { return _serializer.EqualityComparer; } set { _serializer.EqualityComparer = value; } } public override JsonConverterCollection Converters { get { return _serializer.Converters; } } public override DefaultValueHandling DefaultValueHandling { get { return _serializer.DefaultValueHandling; } set { _serializer.DefaultValueHandling = value; } } public override IContractResolver ContractResolver { get { return _serializer.ContractResolver; } set { _serializer.ContractResolver = value; } } public override MissingMemberHandling MissingMemberHandling { get { return _serializer.MissingMemberHandling; } set { _serializer.MissingMemberHandling = value; } } public override NullValueHandling NullValueHandling { get { return _serializer.NullValueHandling; } set { _serializer.NullValueHandling = value; } } public override ObjectCreationHandling ObjectCreationHandling { get { return _serializer.ObjectCreationHandling; } set { _serializer.ObjectCreationHandling = value; } } public override ReferenceLoopHandling ReferenceLoopHandling { get { return _serializer.ReferenceLoopHandling; } set { _serializer.ReferenceLoopHandling = value; } } public override PreserveReferencesHandling PreserveReferencesHandling { get { return _serializer.PreserveReferencesHandling; } set { _serializer.PreserveReferencesHandling = value; } } public override TypeNameHandling TypeNameHandling { get { return _serializer.TypeNameHandling; } set { _serializer.TypeNameHandling = value; } } public override MetadataPropertyHandling MetadataPropertyHandling { get { return _serializer.MetadataPropertyHandling; } set { _serializer.MetadataPropertyHandling = value; } } public override FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _serializer.TypeNameAssemblyFormat; } set { _serializer.TypeNameAssemblyFormat = value; } } public override ConstructorHandling ConstructorHandling { get { return _serializer.ConstructorHandling; } set { _serializer.ConstructorHandling = value; } } public override SerializationBinder Binder { get { return _serializer.Binder; } set { _serializer.Binder = value; } } public override StreamingContext Context { get { return _serializer.Context; } set { _serializer.Context = value; } } public override Formatting Formatting { get { return _serializer.Formatting; } set { _serializer.Formatting = value; } } public override DateFormatHandling DateFormatHandling { get { return _serializer.DateFormatHandling; } set { _serializer.DateFormatHandling = value; } } public override DateTimeZoneHandling DateTimeZoneHandling { get { return _serializer.DateTimeZoneHandling; } set { _serializer.DateTimeZoneHandling = value; } } public override DateParseHandling DateParseHandling { get { return _serializer.DateParseHandling; } set { _serializer.DateParseHandling = value; } } public override FloatFormatHandling FloatFormatHandling { get { return _serializer.FloatFormatHandling; } set { _serializer.FloatFormatHandling = value; } } public override FloatParseHandling FloatParseHandling { get { return _serializer.FloatParseHandling; } set { _serializer.FloatParseHandling = value; } } public override StringEscapeHandling StringEscapeHandling { get { return _serializer.StringEscapeHandling; } set { _serializer.StringEscapeHandling = value; } } public override string DateFormatString { get { return _serializer.DateFormatString; } set { _serializer.DateFormatString = value; } } public override CultureInfo Culture { get { return _serializer.Culture; } set { _serializer.Culture = value; } } public override int? MaxDepth { get { return _serializer.MaxDepth; } set { _serializer.MaxDepth = value; } } public override bool CheckAdditionalContent { get { return _serializer.CheckAdditionalContent; } set { _serializer.CheckAdditionalContent = value; } } internal JsonSerializerInternalBase GetInternalSerializer() { if (_serializerReader != null) { return _serializerReader; } else { return _serializerWriter; } } public JsonSerializerProxy(JsonSerializerInternalReader serializerReader) { ValidationUtils.ArgumentNotNull(serializerReader, nameof(serializerReader)); _serializerReader = serializerReader; _serializer = serializerReader.Serializer; } public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter) { ValidationUtils.ArgumentNotNull(serializerWriter, nameof(serializerWriter)); _serializerWriter = serializerWriter; _serializer = serializerWriter.Serializer; } internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) { return _serializerReader.Deserialize(reader, objectType, false); } else { return _serializer.Deserialize(reader, objectType); } } internal override void PopulateInternal(JsonReader reader, object target) { if (_serializerReader != null) { _serializerReader.Populate(reader, target); } else { _serializer.Populate(reader, target); } } internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) { _serializerWriter.Serialize(jsonWriter, value, rootType); } else { _serializer.Serialize(jsonWriter, value); } } } }
// 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> /// InheritanceOperations operations. /// </summary> internal partial class InheritanceOperations : IServiceOperations<AzureCompositeModel>, IInheritanceOperations { /// <summary> /// Initializes a new instance of the InheritanceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal InheritanceOperations(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 extend others /// </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<Siamese>> 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/inheritance/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 HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new 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 (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<Siamese>(); _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<Siamese>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that extend others /// </summary> /// <param name='complexBody'> /// Please put a siamese with id=2, name="Siameee", color=green, breed=persion, /// which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato", /// and the 2nd one named "Tomato" with id=-1 and food="french fries". /// </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(Siamese complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // 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/inheritance/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 HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new 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 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 (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; } } }
#region File Description //----------------------------------------------------------------------------- // Ship.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace VectorRumble { /// <summary> /// The ship, which is the primary playing-piece in the game. /// </summary> class Ship : Actor { #region Constants /// <summary> /// The value of the spawn timer set when the ship dies. /// </summary> const float respawnTimerOnDeath = 5f; /// <summary> /// How long, in seconds, for the ship to fade in. /// </summary> const float fadeInTimerMaximum = 0.5f; /// <summary> /// The maximum value of the "safe" timer. /// </summary> const float safeTimerMaximum = 4f; /// <summary> /// The amount of drag applied to velocity per second, /// as a percentage of velocity. /// </summary> const float dragPerSecond = 0.9f; /// <summary> /// The amount that the right-stick must be pressed to fire, squared so that /// we can use LengthSquared instead of Length, which has a square-root in it. /// </summary> const float fireThresholdSquared = 0.25f; /// <summary> /// The number of radians that the ship can turn in a second at full left-stick. /// </summary> const float rotationRadiansPerSecond = 6f; /// <summary> /// The maximum length of the velocity vector on a ship. /// </summary> const float velocityLengthMaximum = 320f; /// <summary> /// The maximum strength of the shield. /// </summary> const float shieldMaximum = 100f; /// <summary> /// How much the shield recharges per second. /// </summary> const float shieldRechargePerSecond = 50f; /// <summary> /// The duration of the shield-recharge timer when the ship is hit. /// </summary> const float shieldRechargeTimerOnDamage = 2.5f; /// <summary> /// The amount at which to vibrate the large motor if the timer is active. /// </summary> const float largeMotorSpeed = 0.5f; /// <summary> /// The amount at which to vibrate the small motor if the timer is active. /// </summary> const float smallMotorSpeed = 0.5f; /// <summary> /// The amount of time that the A button must be held to join the game. /// </summary> const float aButtonHeldToPlay = 2f; /// <summary> /// The amount of time that the B button must be held to leave the game. /// </summary> const float bButtonHeldToLeave = 2f; /// <summary> /// The number of radians that the shield rotates per second. /// </summary> const float shieldRotationPeriodPerSecond = 2f; /// <summary> /// The relationship between the shield rotation and it's scale. /// </summary> const float shieldRotationToScaleScalar = 0.025f; /// <summary> /// The relationship between the shield rotation and it's scale period. /// </summary> const float shieldRotationToScalePeriodScalar = 4f; /// <summary> /// The colors used for each ship, given it's player-index. /// </summary> static readonly Color[] shipColorsByPlayerIndex = { Color.Lime, Color.CornflowerBlue, Color.Fuchsia, Color.Red }; /// <summary> /// Particle system colors for the ship-explosion effect. /// </summary> static readonly Color[] explosionColors = { Color.Red, Color.Red, Color.Silver, Color.Gray, Color.Orange, Color.Yellow }; #endregion #region Fields /// <summary> /// If true, this ship is active in-game. /// </summary> private bool playing = false; /// <summary> /// The current score for this ship. /// </summary> private int score = 0; /// <summary> /// The speed at which the ship moves. /// </summary> private float speed = 480f; /// <summary> /// The strength of the shield. /// </summary> private float shield = 0f; /// <summary> /// The rotation of the shield effect. /// </summary> private float shieldRotation = 0f; /// <summary> /// The polygon used to render the shield effect /// </summary> private VectorPolygon shieldPolygon = null; /// <summary> /// The ship's current weapon. /// </summary> private Weapon weapon = null; /// <summary> /// The ship's additional mine-laying weapon. /// </summary> private MineWeapon mineWeapon = null; /// <summary> /// The Gamepad player index that is controlling this ship. /// </summary> private PlayerIndex playerIndex; /// <summary> /// The current state of the Gamepad that is controlling this ship. /// </summary> private GamePadState currentGamePadState; /// <summary> /// The previous state of the Gamepad that is controlling this ship. /// </summary> private GamePadState lastGamePadState; /// <summary> /// Timer for how long the player has been holding the A button (to join). /// </summary> private float aButtonTimer = 0f; /// <summary> /// Timer for how long the player has been holding the B button (to leave). /// </summary> private float bButtonTimer = 0f; /// <summary> /// Timer for how much longer to vibrate the small motor. /// </summary> private float smallMotorTimer = 0f; /// <summary> /// Timer for how much longer to vibrate the large motor. /// </summary> private float largeMotorTimer = 0f; /// <summary> /// Timer for how much longer the player has to wait for the ship to respawn. /// </summary> private float respawnTimer = 0f; /// <summary> /// Timer for how long until the shield starts to recharge. /// </summary> private float shieldRechargeTimer = 0f; /// <summary> /// Timer for how long the player is safe after spawning. /// </summary> private float safeTimer = 0f; /// <summary> /// Timer for how long the player has been spawned for, to fade in /// </summary> private float fadeInTimer = 0f; #endregion #region Properties public bool Playing { get { return playing; } } public bool Safe { get { return (safeTimer > 0f); } set { if (value) { safeTimer = safeTimerMaximum; } else { safeTimer = 0f; } } } public int Score { get { return score; } set { score = value; } } #endregion #region Initialization /// <summary> /// Construct a new ship, for the given player. /// </summary> /// <param name="world">The world that this ship belongs to.</param> /// <param name="playerIndex"> /// The Gamepad player index that controls this ship. /// </param> public Ship(World world, PlayerIndex playerIndex) : base(world) { this.playerIndex = playerIndex; this.radius = 20f; this.mass = 32f; this.color = shipColorsByPlayerIndex[(int)this.playerIndex]; this.polygon = VectorPolygon.CreatePlayer(); this.shieldPolygon = VectorPolygon.CreateCircle(Vector2.Zero, 20f, 16); } #endregion #region Update /// <summary> /// Update the ship. /// </summary> /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param> public override void Update(float elapsedTime) { // process all input ProcessInput(elapsedTime, false); // if this player isn't in the game, then quit now if (playing == false) { return; } if (dead == true) { // if we've died, then we're counting down to respawning if (respawnTimer > 0f) { respawnTimer = Math.Max(respawnTimer - elapsedTime, 0f); } if (respawnTimer <= 0f) { Spawn(true); } } else { // apply drag to the velocity velocity -= velocity * (elapsedTime * dragPerSecond); if (velocity.LengthSquared() <= 0f) { velocity = Vector2.Zero; } // decrement the heal timer if necessary if (shieldRechargeTimer > 0f) { shieldRechargeTimer = Math.Max(shieldRechargeTimer - elapsedTime, 0f); } // recharge the shields if the timer has come up if (shieldRechargeTimer <= 0f) { if (shield < 100f) { shield = Math.Min(100f, shield + shieldRechargePerSecond * elapsedTime); } } } // update the weapons if (weapon != null) { weapon.Update(elapsedTime); } if (mineWeapon != null) { mineWeapon.Update(elapsedTime); } // decrement the safe timer if (safeTimer > 0f) { safeTimer = Math.Max(safeTimer - elapsedTime, 0f); } // update the radius based on the shield radius = (shield > 0f) ? 20f : 14f; // update the spawn-in timer if (fadeInTimer < fadeInTimerMaximum) { fadeInTimer = Math.Min(fadeInTimer + elapsedTime, fadeInTimerMaximum); } // update and apply the vibration smallMotorTimer -= elapsedTime; largeMotorTimer -= elapsedTime; GamePad.SetVibration(playerIndex, (largeMotorTimer > 0f) ? largeMotorSpeed : 0f, (smallMotorTimer > 0f) ? smallMotorSpeed : 0f); base.Update(elapsedTime); } #endregion #region Drawing /// <summary> /// Render the ship. /// </summary> /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param> /// <param name="lineBatch">The LineBatch to render to.</param> public override void Draw(float elapsedTime, LineBatch lineBatch) { // if the ship isn't in the game, or it's dead, don't draw if ((playing == false) || (dead == true)) { return; } // update the shield rotation shieldRotation += elapsedTime * shieldRotationPeriodPerSecond; // calculate the current color color = new Color(color.R, color.G, color.B, (byte)(255f * fadeInTimer / fadeInTimerMaximum)); // transform the shield polygon Matrix translationMatrix = Matrix.CreateTranslation(position.X, position.Y, 0f); shieldPolygon.Transform(Matrix.CreateScale(1f + shieldRotationToScaleScalar * (float)Math.Cos(shieldRotation * shieldRotationToScalePeriodScalar)) * Matrix.CreateRotationZ(shieldRotation) * translationMatrix); // draw the shield if (Safe) { lineBatch.DrawPolygon(shieldPolygon, color); } else if (shield > 0f) { lineBatch.DrawPolygon(shieldPolygon, new Color(color.R, color.G, color.B, (byte)(255f * shield / shieldMaximum)), true); } base.Draw(elapsedTime, lineBatch); } #endregion #region Interaction /// <summary> /// Set the ship up to join the game, if it's not in it already. /// </summary> public void JoinGame() { if (playing == false) { playing = true; score = 0; Spawn(true); } } /// <summary> /// Remove the ship from the game, if it's in it. /// </summary> public void LeaveGame() { if (playing == true) { playing = false; Die(null); } } /// <summary> /// Assigns the new weapon to the ship. /// </summary> /// <param name="weapon">The new weapon.</param> public void SetWeapon(Weapon weapon) { if (weapon != null) { this.weapon = weapon; } } /// <summary> /// Damage this ship by the amount provided. /// </summary> /// <remarks> /// This function is provided in lieu of a Life mutation property to allow /// classes of objects to restrict which kinds of objects may damage them, /// and under what circumstances they may be damaged. /// </remarks> /// <param name="source">The actor responsible for the damage.</param> /// <param name="damageAmount">The amount of damage.</param> /// <returns>If true, this object was damaged.</returns> public override bool Damage(Actor source, float damageAmount) { // if the safe timer hasn't yet gone off, then the ship can't be hurt if (safeTimer > 0f) { return false; } // tickle the gamepad vibration motors FireGamepadMotors(0f, 0.25f); // once you're hit, the shield-recharge timer starts over shieldRechargeTimer = 2.5f; // damage the shield first, then life if (shield <= 0f) { life -= damageAmount; } else { shield -= damageAmount; if (shield < 0f) { // shield has the overflow value as a negative value, just add it life += shield; shield = 0f; } } // if the ship is out of life, it dies if (life < 0f) { Die(source); } return true; } /// <summary> /// Kills this ship, in response to the given actor. /// </summary> /// <param name="source">The actor responsible for the kill.</param> public override void Die(Actor source) { if (dead == false) { // hit the gamepad vibration motors FireGamepadMotors(0.75f, 0.25f); // play several explosion cues world.AudioManager.PlayCue("playerDeath"); // add several particle systems for effect world.ParticleSystems.Add(new ParticleSystem(this.position, Vector2.Zero, 128, 64f, 256f, 3f, 0.05f, explosionColors)); world.ParticleSystems.Add(new ParticleSystem(this.position, Vector2.Zero, 64, 256f, 1024f, 3f, 0.05f, explosionColors)); // reset the respawning timer respawnTimer = respawnTimerOnDeath; // change the score Ship ship = source as Ship; if (ship == null) { Projectile projectile = source as Projectile; if (projectile != null) { ship = projectile.Owner; } } if (ship != null) { if (ship == this) { // reduce the score, since i blew myself up ship.Score--; } else { // add score to the ship who shot this object ship.Score++; } } else { // if it wasn't a ship, then this object loses score this.Score--; } // ships should not be added to the garbage list, so just set dead dead = true; } } /// <summary> /// Place this ship in the world. /// </summary> /// <param name="findSpawnPoint"> /// If true, the actor's position is changed to a valid, non-colliding point. /// </param> public override void Spawn(bool findSpawnPoint) { // do not call the base Spawn, as the actor never is added or removed when // dying or respawning, because we always need to be processing input // respawn this actor if (dead == true) { // I LIVE dead = false; // find a new spawn point if requested if (findSpawnPoint) { position = world.FindSpawnPoint(this); } // reset the velocity velocity = Vector2.Zero; // reset the shield and life values life = 25f; shield = shieldMaximum; // reset the safety timers safeTimer = safeTimerMaximum; // create the default weapons weapon = new LaserWeapon(this); mineWeapon = new MineWeapon(this); // play the ship-spawn cue world.AudioManager.PlayCue("playerSpawn"); // add a particle effect at the ship's new location world.ParticleSystems.Add(new ParticleSystem(this.position, Vector2.Zero, 32, 32f, 64f, 2f, 0.1f, new Color[] { this.color })); // remind the player that we're spawning FireGamepadMotors(0.25f, 0f); } } #endregion #region Input Methods /// <summary> /// Vibrate the gamepad motors for the given period of time. /// </summary> /// <param name="largeMotorTime">The time to run the large motor.</param> /// <param name="smallMotorTime">The time to run the small motor.</param> public void FireGamepadMotors(float largeMotorTime, float smallMotorTime) { // use the maximum timer value this.largeMotorTimer = Math.Max(this.largeMotorTimer, largeMotorTime); this.smallMotorTimer = Math.Max(this.smallMotorTimer, smallMotorTime); } /// <summary> /// Process the input for this ship, from the gamepad assigned to it. /// </summary> /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param> /// <para public virtual void ProcessInput(float elapsedTime, bool overlayPresent) { currentGamePadState = GamePad.GetState(playerIndex); if (overlayPresent == false) { if (playing == false) { // trying to join - update the a-button timer if (currentGamePadState.Buttons.A == ButtonState.Pressed) { aButtonTimer += elapsedTime; } else { aButtonTimer = 0f; } // if the timer has exceeded the expected value, join the game if (aButtonTimer > aButtonHeldToPlay) { JoinGame(); } } else { // check if we're trying to leave if (currentGamePadState.Buttons.B == ButtonState.Pressed) { bButtonTimer += elapsedTime; } else { bButtonTimer = 0f; } // if the timer has exceeded the expected value, leave the game if (bButtonTimer > bButtonHeldToLeave) { LeaveGame(); } else if (dead == false) { // // the ship is alive, so process movement and firing // // calculate the current forward vector Vector2 forward = new Vector2((float)Math.Sin(Rotation), -(float)Math.Cos(Rotation)); Vector2 right = new Vector2(-forward.Y, forward.X); // calculate the current left stick value Vector2 leftStick = currentGamePadState.ThumbSticks.Left; leftStick.Y *= -1f; if (leftStick.LengthSquared() > 0f) { Vector2 wantedForward = Vector2.Normalize(leftStick); float angleDiff = (float)Math.Acos( Vector2.Dot(wantedForward, forward)); float facing = (Vector2.Dot(wantedForward, right) > 0f) ? 1f : -1f; if (angleDiff > 0f) { Rotation += Math.Min(angleDiff, facing * elapsedTime * rotationRadiansPerSecond); } // add velocity Velocity += leftStick * (elapsedTime * speed); if (Velocity.Length() > velocityLengthMaximum) { Velocity = Vector2.Normalize(Velocity) * velocityLengthMaximum; } } // check for firing with the right stick Vector2 rightStick = currentGamePadState.ThumbSticks.Right; rightStick.Y *= -1f; if (rightStick.LengthSquared() > fireThresholdSquared) { weapon.Fire(Vector2.Normalize(rightStick)); } // check for laying mines if ((currentGamePadState.Buttons.B == ButtonState.Pressed) && (lastGamePadState.Buttons.B == ButtonState.Released)) { // fire behind the ship mineWeapon.Fire(-forward); } } } } // update the gamepad state lastGamePadState = currentGamePadState; return; } #endregion } }
#region License /* Copyright (c) 2003-2015 Llewellyn Pritchard * All rights reserved. * This source code is subject to terms and conditions of the BSD License. * See license.txt. */ #endregion using System.Reflection; using System.Drawing; using System.Collections; using System.Windows.Forms; namespace IronScheme.Editor.Controls { /// <summary> /// Summary description for DialogInvokeActionForm. /// </summary> class DialogInvokeActionForm : System.Windows.Forms.Form { private System.Windows.Forms.Panel panel1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public DialogInvokeActionForm() : this(null) { } delegate void MethodNameHandler(string p1, int p2, Color p3, AnchorStyles p4); public void MethodName(string p1, int p2, Color p3, AnchorStyles p4){} public DialogInvokeActionForm(MethodInfo mi) { if (mi == null) { mi = new MethodNameHandler(MethodName).Method; } // // Required for Windows Form Designer support // InitializeComponent(); ShowInTaskbar = false; groupBox1.Text = mi.DeclaringType.Name + " : " + mi.ToString(); int c = 0; int h = 0; foreach (ParameterInfo pi in mi.GetParameters()) { GenericTypeEditor gte = new GenericTypeEditor(); gte.Info = pi; gte.TabIndex = c; gte.Dock = DockStyle.Top; h = gte.Height; groupBox1.Controls.Add(gte); c++; if (c == 1) { gte.Focus(); } } Height = c * h + 58; } public object[] GetValues() { ArrayList values = new ArrayList(); foreach (Control c in groupBox1.Controls) { if ( c is GenericTypeEditor) { values.Add(((GenericTypeEditor)c).Value); } } return values.ToArray(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button3 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.groupBox1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.DockPadding.All = 4; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(254, 206); this.panel1.TabIndex = 0; // // groupBox1 // this.groupBox1.BackColor = System.Drawing.SystemColors.Window; this.groupBox1.Controls.Add(this.button3); this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.button1); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBox1.Location = new System.Drawing.Point(4, 4); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(244, 196); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "groupBox1"; // // button3 // this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button3.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button3.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button3.Location = new System.Drawing.Point(4, 169); this.button3.Name = "button3"; this.button3.TabIndex = 3; this.button3.TabStop = false; this.button3.Text = "OK"; this.button3.Visible = false; // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button2.Location = new System.Drawing.Point(164, 169); this.button2.Name = "button2"; this.button2.TabIndex = 12; this.button2.Text = "Cancel"; this.button2.Click += new System.EventHandler(this.button2_Click); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button1.Location = new System.Drawing.Point(84, 169); this.button1.Name = "button1"; this.button1.TabIndex = 11; this.button1.Text = "OK"; this.button1.Click += new System.EventHandler(this.button1_Click); // // DialogInvokeActionForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.SystemColors.Window; this.ClientSize = new System.Drawing.Size(254, 206); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogInvokeActionForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Info required"; this.panel1.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void button2_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
/* * PrinterSettings.cs - Implementation of the * "System.Drawing.Printing.PrinterSettings" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing.Printing { using System.Drawing.Toolkit; using System.Text; using System.Runtime.InteropServices; using System.ComponentModel; using System.Collections; #if !ECMA_COMPAT [Serializable] [ComVisible(false)] #endif public class PrinterSettings : ICloneable { // Internal state. private bool collate; private short copies; [NonSerializedAttribute] private PageSettings defaultPageSettings; private Duplex duplex; private int fromPage; private int landscapeAngle; private int maximumCopies; private int maximumPage; private int minimumPage; [NonSerializedAttribute] private String printerName; private PrintRange printRange; private bool printToFile; private int toPage; private IToolkitPrinter toolkitPrinter; // Constructor. public PrinterSettings() { collate = false; copies = 1; duplex = Duplex.Default; fromPage = 0; landscapeAngle = 0; maximumCopies = 1; maximumPage = 9999; minimumPage = 0; printerName = null; printRange = PrintRange.AllPages; printToFile = false; toPage = 0; toolkitPrinter = null; } // Get or set this object's properties. public bool CanDuplex { get { return ToolkitPrinter.CanDuplex; } } public bool Collate { get { return collate; } set { collate = value; } } public short Copies { get { return copies; } set { if(value < 0) { throw new ArgumentException (S._("ArgRange_NonNegative")); } copies = value; } } public PageSettings DefaultPageSettings { get { if(defaultPageSettings == null) { LoadDefaults(); } return defaultPageSettings; } } public Duplex Duplex { get { return duplex; } set { duplex = value; } } public int FromPage { get { return fromPage; } set { if(value < 0) { throw new ArgumentException (S._("ArgRange_NonNegative")); } fromPage = value; } } public bool IsDefaultPrinter { get { return (printerName == null); } } public bool IsPlotter { get { return ToolkitPrinter.IsPlotter; } } public bool IsValid { get { lock(this) { if(toolkitPrinter != null) { return true; } toolkitPrinter = ToolkitManager.PrintingSystem.GetPrinter (printerName); return (toolkitPrinter != null); } } } public int LandscapeAngle { get { return landscapeAngle; } set { landscapeAngle = value; } } public int MaximumCopies { get { return maximumCopies; } } public int MaximumPage { get { return maximumPage; } set { if(value < 0) { throw new ArgumentException (S._("ArgRange_NonNegative")); } maximumPage = value; } } public int MinimumPage { get { return minimumPage; } set { if(value < 0) { throw new ArgumentException (S._("ArgRange_NonNegative")); } minimumPage = value; } } public String PrinterName { get { if(printerName == null) { return ToolkitManager.PrintingSystem.DefaultPrinterName; } return printerName; } set { lock(this) { printerName = value; toolkitPrinter = null; } } } public PrintRange PrintRange { get { return printRange; } set { printRange = value; } } public bool PrintToFile { get { return printToFile; } set { printToFile = true; } } public bool SupportsColor { get { return ToolkitPrinter.SupportsColor; } } public int ToPage { get { return toPage; } set { if(value < 0) { throw new ArgumentException (S._("ArgRange_NonNegative")); } toPage = value; } } // Get the toolkit version of a printer. internal IToolkitPrinter ToolkitPrinter { get { lock(this) { if(toolkitPrinter == null) { toolkitPrinter = ToolkitManager.PrintingSystem.GetPrinter (printerName); if(toolkitPrinter == null) { throw new InvalidPrinterException(this); } } return toolkitPrinter; } } } // Get a list of all installed printers on this system. public static StringCollection InstalledPrinters { get { return new StringCollection (ToolkitManager.PrintingSystem.InstalledPrinters); } } // Get a list of all paper sizes that are supported by this printer. public PaperSizeCollection PaperSizes { get { return new PaperSizeCollection(ToolkitPrinter.PaperSizes); } } // Get a list of all paper sources that are supported by this printer. public PaperSourceCollection PaperSources { get { return new PaperSourceCollection (ToolkitPrinter.PaperSources); } } // Get a list of all resolutions that are supported by this printer. public PrinterResolutionCollection PrinterResolutions { get { return new PrinterResolutionCollection (ToolkitPrinter.PrinterResolutions); } } // Clone this object. public Object Clone() { return MemberwiseClone(); } // Create a graphics object that can be used to perform text measurement. public Graphics CreateMeasurementGraphics() { return ToolkitManager.CreateGraphics (ToolkitPrinter.CreateMeasurementGraphics()); } #if !ECMA_COMPAT // Get the Win32-specific DEVMODE information for these printer settings. public IntPtr GetHdevmode() { return GetHdevmode(null); } public IntPtr GetHdevmode(PageSettings pageSettings) { throw new Win32Exception (0, S._("NotSupp_CannotGetDevMode")); } // Get the Win32-specific DEVNAMES information for these printer settings. public IntPtr GetHdevnames() { throw new Win32Exception (0, S._("NotSupp_CannotGetDevNames")); } // Set the DEVMODE information from a Win32-specific structure. public void SetHdevmode(IntPtr hdevmode) { // Not used in this implementation. } // Set the DEVNAMES information from a Win32-specific structure. public void SetHdevnames(IntPtr hdevnames) { // Not used in this implementation. } #endif // Convert this object into a string. public override String ToString() { StringBuilder builder = new StringBuilder(); builder.Append("[PrinterSettings "); builder.Append(PrinterName); builder.Append(" Copies="); builder.Append(Copies.ToString()); builder.Append(" Collate="); builder.Append(Collate.ToString()); builder.Append(" Duplex="); builder.Append(Duplex.ToString()); builder.Append(" FromPage="); builder.Append(FromPage.ToString()); builder.Append(" LandscapeAngle="); builder.Append(LandscapeAngle.ToString()); builder.Append(" MaximumCopies="); builder.Append(MaximumCopies.ToString()); builder.Append(" OutputPort="); builder.Append(ToolkitPrinter.OutputPort.ToString()); builder.Append(" ToPage="); builder.Append(ToPage.ToString()); builder.Append(']'); return builder.ToString(); } // Load the default page settings for the printer. private void LoadDefaults() { // Initialize the defaults object. PageSettings defaults = new PageSettings(); defaults.Color = false; defaults.Landscape = false; defaults.PaperSize = new PaperSize(PaperKind.Letter); defaults.PaperSource = new PaperSource(PaperSourceKind.AutomaticFeed, null); defaults.PrinterResolution = new PrinterResolution (PrinterResolutionKind.Medium, 300, 300); defaultPageSettings = defaults; // Load printer-specific overrides from the system. ToolkitPrinter.LoadDefaults(defaults); } // Collection of paper sizes for a printer. public class PaperSizeCollection : ICollection, IEnumerable { // Internal state. private PaperSize[] array; // Constructor. public PaperSizeCollection(PaperSize[] array) { this.array = array; } // Get a specific element within this collection. public virtual PaperSize this[int index] { get { return array[index]; } } // Implement the ICollection interface. void ICollection.CopyTo(Array array, int index) { this.array.CopyTo(array, index); } public int Count { get { return array.Length; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return array.GetEnumerator(); } }; // class PaperSizeCollection // Collection of paper sources for a printer. public class PaperSourceCollection : ICollection, IEnumerable { // Internal state. private PaperSource[] array; // Constructor. public PaperSourceCollection(PaperSource[] array) { this.array = array; } // Get a specific element within this collection. public virtual PaperSource this[int index] { get { return array[index]; } } // Implement the ICollection interface. void ICollection.CopyTo(Array array, int index) { this.array.CopyTo(array, index); } public int Count { get { return array.Length; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return array.GetEnumerator(); } }; // class PaperSourceCollection // Collection of printer resolutions for a printer. public class PrinterResolutionCollection : ICollection, IEnumerable { // Internal state. private PrinterResolution[] array; // Constructor. public PrinterResolutionCollection(PrinterResolution[] array) { this.array = array; } // Get a specific element within this collection. public virtual PrinterResolution this[int index] { get { return array[index]; } } // Implement the ICollection interface. void ICollection.CopyTo(Array array, int index) { this.array.CopyTo(array, index); } public int Count { get { return array.Length; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return array.GetEnumerator(); } }; // class PrinterResolutionCollection // String collection for printer names. public class StringCollection : ICollection, IEnumerable { // Internal state. private String[] array; // Constructor. public StringCollection(String[] array) { this.array = array; } // Get a specific element within this collection. public virtual String this[int index] { get { return array[index]; } } // Implement the ICollection interface. void ICollection.CopyTo(Array array, int index) { this.array.CopyTo(array, index); } public int Count { get { return array.Length; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return array.GetEnumerator(); } }; // class StringCollection }; // class PrinterSettings }; // namespace System.Drawing.Printing
// // WebRequestTest.cs - NUnit Test Cases for System.Net.WebRequest // // Authors: // Lawrence Pit (loz@cable.a2000.nl) // Martin Willemoes Hansen (mwh@sysrq.dk) // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2003 Martin Willemoes Hansen // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // using NUnit.Framework; using System; using System.Net; using System.Collections; using System.Runtime.Serialization; namespace MonoTests.System.Net { // WebRequest is abstract public class NonAbstractWebRequest : WebRequest { public NonAbstractWebRequest () { } public NonAbstractWebRequest (SerializationInfo si, StreamingContext sc) : base (si, sc) { } } [TestFixture] public class WebRequestTest { private void Callback (IAsyncResult ar) { Assert.Fail ("Callback"); } [Test] public void SerializationConstructor () { NonAbstractWebRequest w = new NonAbstractWebRequest (null, new StreamingContext ()); Assert.IsNotNull (w); } // properties (only test 'get'ter) [Test] [ExpectedException (typeof (NotImplementedException))] public void ConnectionGroupName () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.ConnectionGroupName); } [Test] [ExpectedException (typeof (NotImplementedException))] public void ContentLength () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.ContentLength); } [Test] [ExpectedException (typeof (NotImplementedException))] public void ContentType () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.ContentType); } [Test] [ExpectedException (typeof (NotImplementedException))] public void Credentials () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.Credentials); } [Test] [ExpectedException (typeof (NotImplementedException))] public void Headers () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.Headers); } [Test] [ExpectedException (typeof (NotImplementedException))] public void Method () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.Method); } [Test] [ExpectedException (typeof (NotImplementedException))] public void PreAuthenticate () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsTrue (w.PreAuthenticate); } [Test] [ExpectedException (typeof (NotImplementedException))] public void Proxy () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.Proxy); } [Test] [ExpectedException (typeof (NotImplementedException))] public void RequestUri () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.RequestUri); } [Test] [ExpectedException (typeof (NotImplementedException))] public void Timeout () { NonAbstractWebRequest w = new NonAbstractWebRequest (); Assert.IsNull (w.Timeout); } // methods [Test] [ExpectedException (typeof (NotImplementedException))] public void Abort () { NonAbstractWebRequest w = new NonAbstractWebRequest (); w.Abort (); } [Test] [ExpectedException (typeof (NotImplementedException))] public void BeginGetRequestStream () { NonAbstractWebRequest w = new NonAbstractWebRequest (); IAsyncResult r = w.BeginGetRequestStream (new AsyncCallback (Callback), w); } [Test] [ExpectedException (typeof (NotImplementedException))] public void BeginGetResponse () { NonAbstractWebRequest w = new NonAbstractWebRequest (); IAsyncResult r = w.BeginGetResponse (new AsyncCallback (Callback), w); } [Test] [ExpectedException (typeof (NotImplementedException))] public void EndGetRequestStream () { NonAbstractWebRequest w = new NonAbstractWebRequest (); w.EndGetRequestStream (null); } [Test] [ExpectedException (typeof (NotImplementedException))] public void EndGetResponse () { NonAbstractWebRequest w = new NonAbstractWebRequest (); w.EndGetResponse (null); } [Test] [ExpectedException (typeof (NotImplementedException))] public void GetRequestStream () { NonAbstractWebRequest w = new NonAbstractWebRequest (); w.GetRequestStream (); } [Test] [ExpectedException (typeof (NotImplementedException))] public void GetResponse () { NonAbstractWebRequest w = new NonAbstractWebRequest (); w.GetResponse (); } [Test] public void All () { WebRequest req = WebRequest.Create ("http://www.contoso.com"); Assertion.Assert ("#1", req is HttpWebRequest); req = WebRequest.Create ("https://www.contoso.com"); Assertion.Assert ("#2", req is HttpWebRequest); req = WebRequest.Create ("file://www.contoso.com"); Assertion.Assert ("#3", req is FileWebRequest); WebRequest.RegisterPrefix ("http://www.contoso.com", new TestWebRequestCreator ()); bool ret = WebRequest.RegisterPrefix ("http://WWW.contoso.com", new TestWebRequestCreator ()); Assertion.AssertEquals ("#4a", false, ret); ret = WebRequest.RegisterPrefix ("http://www.contoso.com/foo/bar", new TestWebRequestCreator2 ()); Assertion.AssertEquals ("#4b", true, ret); ret = WebRequest.RegisterPrefix ("http://www", new TestWebRequestCreator3 ()); Assertion.AssertEquals ("#4c", true, ret); req = WebRequest.Create ("http://WWW.contoso.com"); Assertion.Assert ("#5", req is TestWebRequest); req = WebRequest.Create ("http://WWW.contoso.com/foo/bar/index.html"); Assertion.Assert ("#6", req is TestWebRequest2); req = WebRequest.Create ("http://WWW.x.com"); Assertion.Assert ("#7", req is TestWebRequest3); req = WebRequest.Create ("http://WWW.c"); Assertion.Assert ("#8", req is TestWebRequest3); req = WebRequest.CreateDefault (new Uri("http://WWW.contoso.com")); Assertion.Assert ("#9", req is HttpWebRequest); try { req = WebRequest.Create ("tcp://www.contoso.com"); Assertion.Fail ("#10 should have failed with NotSupportedException"); } catch (NotSupportedException) { } } internal class TestWebRequestCreator : IWebRequestCreate { internal TestWebRequestCreator () { } public WebRequest Create (Uri uri) { return new TestWebRequest (); } } internal class TestWebRequest : WebRequest { internal TestWebRequest () { } } internal class TestWebRequestCreator2 : IWebRequestCreate { internal TestWebRequestCreator2 () { } public WebRequest Create (Uri uri) { return new TestWebRequest2 (); } } internal class TestWebRequest2 : WebRequest { internal TestWebRequest2 () { } } internal class TestWebRequestCreator3 : IWebRequestCreate { internal TestWebRequestCreator3 () { } public WebRequest Create (Uri uri) { return new TestWebRequest3 (); } } internal class TestWebRequest3 : WebRequest { internal TestWebRequest3 () { } } } }
//////////////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2014 Paul Louth // // 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 Monad.Utility; using System; using System.Collections.Generic; namespace Monad { /// <summary> /// Either monad /// </summary> public delegate EitherPair<L, R> Either<L, R>(); public struct EitherPair<L, R> { public readonly R Right; public readonly L Left; public readonly bool IsRight; public readonly bool IsLeft; public EitherPair(R r) { Right = r; Left = default(L); IsRight = true; IsLeft = false; } public EitherPair(L l) { Left = l; Right = default(R); IsLeft = true; IsRight = false; } public static implicit operator EitherPair<L, R>(L value) { return new EitherPair<L, R>(value); } public static implicit operator EitherPair<L, R>(R value) { return new EitherPair<L, R>(value); } } /// <summary> /// Either constructor methods /// </summary> public class Either { /// <summary> /// Construct an Either Left monad /// </summary> public static Either<L, R> Left<L, R>(Func<L> left) { if (left == null) throw new ArgumentNullException("left"); return () => new EitherPair<L, R>(left()); } /// <summary> /// Construct an Either Right monad /// </summary> public static Either<L, R> Right<L, R>(Func<R> right) { if (right == null) throw new ArgumentNullException("right"); return () => new EitherPair<L, R>(right()); } /// <summary> /// Construct an either Left or Right /// </summary> public static Either<L, R> Return<L, R>(Func<EitherPair<L, R>> either) { if (either == null) throw new ArgumentNullException("either"); return () => either(); } /// <summary> /// Monadic zero /// </summary> public static Either<L, R> Mempty<L, R>() { return () => new EitherPair<L, R>(default(R)); } } /// <summary> /// The Either monad represents values with two possibilities: a value of Left or Right /// Either is sometimes used to represent a value which is either correct or an error, /// by convention, 'Left' is used to hold an error value 'Right' is used to hold a /// correct value. /// So you can see that Either has a very close relationship to the Error monad. However, /// the Either monad won't capture exceptions. Either would primarily be used for /// known error values rather than exceptional ones. /// Once the Either monad is in the Left state it cancels the monad bind function and /// returns immediately. /// </summary> public static class EitherExt { /// <summary> /// Returns true if the monad object is in the Right state /// </summary> public static bool IsRight<L, R>(this Either<L, R> m) { return m().IsRight; } /// <summary> /// Get the Left value /// NOTE: This throws an InvalidOperationException if the object is in the /// Right state /// </summary> public static bool IsLeft<L, R>(this Either<L, R> m) { return m().IsLeft; } /// <summary> /// Get the Right value /// NOTE: This throws an InvalidOperationException if the object is in the /// Left state /// </summary> public static R Right<L, R>(this Either<L, R> m) { var res = m(); if (res.IsLeft) throw new InvalidOperationException("Not in the Right state"); return res.Right; } /// <summary> /// Get the Left value /// NOTE: This throws an InvalidOperationException if the object is in the /// Right state /// </summary> public static L Left<L, R>(this Either<L, R> m) { var res = m(); if (res.IsRight) throw new InvalidOperationException("Not in the Left state"); return res.Left; } /// <summary> /// Pattern matching method for a branching expression /// </summary> /// <param name="Right">Action to perform if the monad is in the Right state</param> /// <param name="Left">Action to perform if the monad is in the Left state</param> /// <returns>T</returns> public static Func<T> Match<R, L, T>(this Either<L, R> m, Func<R, T> Right, Func<L, T> Left) { if (Right == null) throw new ArgumentNullException("Right"); if (Left == null) throw new ArgumentNullException("Left"); return () => { var res = m(); return res.IsLeft ? Left(res.Left) : Right(res.Right); }; } /// <summary> /// Pattern matching method for a branching expression /// NOTE: This throws an InvalidOperationException if the object is in the /// Left state /// </summary> /// <param name="right">Action to perform if the monad is in the Right state</param> /// <returns>T</returns> public static Func<T> MatchRight<R, L, T>(this Either<L, R> m, Func<R, T> right) { if (right == null) throw new ArgumentNullException("right"); return () => { return right(m.Right()); }; } /// <summary> /// Pattern matching method for a branching expression /// NOTE: This throws an InvalidOperationException if the object is in the /// Right state /// </summary> /// <param name="left">Action to perform if the monad is in the Left state</param> /// <returns>T</returns> public static Func<T> MatchLeft<R, L, T>(this Either<L, R> m, Func<L, T> left) { if (left == null) throw new ArgumentNullException("left"); return () => { return left(m.Left()); }; } /// <summary> /// Pattern matching method for a branching expression /// Returns the defaultValue if the monad is in the Left state /// </summary> /// <param name="right">Action to perform if the monad is in the Right state</param> /// <returns>T</returns> public static Func<T> MatchRight<R, L, T>(this Either<L, R> m, Func<R, T> right, T defaultValue) { if (right == null) throw new ArgumentNullException("right"); return () => { var res = m(); if (res.IsLeft) return defaultValue; return right(res.Right); }; } /// <summary> /// Pattern matching method for a branching expression /// Returns the defaultValue if the monad is in the Right state /// </summary> /// <param name="left">Action to perform if the monad is in the Left state</param> /// <returns>T</returns> public static Func<T> MatchLeft<R, L, T>(this Either<L, R> m, Func<L, T> left, T defaultValue) { if (left == null) throw new ArgumentNullException("left"); return () => { var res = m(); if (res.IsRight) return defaultValue; return left(res.Left); }; } /// <summary> /// Pattern matching method for a branching expression /// </summary> /// <param name="Right">Action to perform if the monad is in the Right state</param> /// <param name="Left">Action to perform if the monad is in the Left state</param> /// <returns>Unit</returns> public static Func<Unit> Match<L, R>(this Either<L, R> m, Action<R> Right, Action<L> Left) { if (Left == null) throw new ArgumentNullException("Left"); if (Right == null) throw new ArgumentNullException("Right"); return () => { var res = m(); if (res.IsLeft) Left(res.Left); else Right(res.Right); return Unit.Default; }; } /// <summary> /// Pattern matching method for a branching expression /// NOTE: This throws an InvalidOperationException if the object is in the /// Left state /// </summary> /// <param name="right">Action to perform if the monad is in the Right state</param> /// <returns>Unit</returns> public static Func<Unit> MatchRight<L, R>(this Either<L, R> m, Action<R> right) { if (right == null) throw new ArgumentNullException("right"); return () => { right(m.Right()); return Unit.Default; }; } /// <summary> /// Pattern matching method for a branching expression /// NOTE: This throws an InvalidOperationException if the object is in the /// Right state /// </summary> /// <param name="left">Action to perform if the monad is in the Left state</param> /// <returns>Unit</returns> public static Func<Unit> MatchLeft<L, R>(this Either<L, R> m, Action<L> left) { if (left == null) throw new ArgumentNullException("left"); return () => { left(m.Left()); return Unit.Default; }; } /// <summary> /// Monadic append /// If the left-hand side or right-hand side are in a Left state, then Left propagates /// </summary> public static Either<L, R> Mappend<L, R>(this Either<L, R> lhs, Either<L, R> rhs) { if (rhs == null) throw new ArgumentNullException("rhs"); return () => { var lhsV = lhs(); if (lhsV.IsLeft) { return lhsV; } else { var rhsV = rhs(); if (rhsV.IsLeft) { return rhsV; } else { if (lhsV.Right is IAppendable<R>) { var lhsApp = lhsV.Right as IAppendable<R>; return new EitherPair<L, R>(lhsApp.Append(rhsV.Right)); } else { // TODO: Consider replacing this with a static Reflection.Emit which does this job efficiently. switch (typeof(R).ToString()) { case "System.Int64": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToInt64(lhsV.Right) + Convert.ToInt64(rhsV.Right)), typeof(R))); case "System.UInt64": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToUInt64(lhsV.Right) + Convert.ToUInt64(rhsV.Right)), typeof(R))); case "System.Int32": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToInt32(lhsV.Right) + Convert.ToInt32(rhsV.Right)), typeof(R))); case "System.UInt32": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToUInt32(lhsV.Right) + Convert.ToUInt32(rhsV.Right)), typeof(R))); case "System.Int16": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToInt16(lhsV.Right) + Convert.ToInt16(rhsV.Right)), typeof(R))); case "System.UInt16": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToUInt16(lhsV.Right) + Convert.ToUInt16(rhsV.Right)), typeof(R))); case "System.Decimal": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToDecimal(lhsV.Right) + Convert.ToDecimal(rhsV.Right)), typeof(R))); case "System.Double": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToDouble(lhsV.Right) + Convert.ToDouble(rhsV.Right)), typeof(R))); case "System.Single": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToSingle(lhsV.Right) + Convert.ToSingle(rhsV.Right)), typeof(R))); case "System.Char": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToChar(lhsV.Right) + Convert.ToChar(rhsV.Right)), typeof(R))); case "System.Byte": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToByte(lhsV.Right) + Convert.ToByte(rhsV.Right)), typeof(R))); case "System.String": return new EitherPair<L, R>((R)Convert.ChangeType((Convert.ToString(lhsV.Right) + Convert.ToString(rhsV.Right)), typeof(R))); default: throw new InvalidOperationException("Type " + typeof(R).Name + " is not appendable. Consider implementing the IAppendable interface."); } } } } }; } /// <summary> /// Converts the Either to an enumerable of R /// </summary> /// <returns> /// Right: A list with one R in /// Left: An empty list /// </returns> public static IEnumerable<R> AsEnumerable<L, R>(this Either<L, R> self) { var res = self(); if (res.IsRight) yield return res.Right; else yield break; } /// <summary> /// Converts the Either to an infinite enumerable /// </summary> /// <returns> /// Just: An infinite list of R /// Nothing: An empty list /// </returns> public static IEnumerable<R> AsEnumerableInfinite<L, R>(this Either<L, R> self) { var res = self(); if (res.IsRight) while (true) yield return res.Right; else yield break; } /// <summary> /// Select /// </summary> public static Either<L, UR> Select<L, TR, UR>( this Either<L, TR> self, Func<TR, UR> selector) { if (selector == null) throw new ArgumentNullException("selector"); return () => { var resT = self(); if (resT.IsLeft) return new EitherPair<L, UR>(resT.Left); return new EitherPair<L, UR>(selector(resT.Right)); }; } /// <summary> /// SelectMany /// </summary> public static Either<L, VR> SelectMany<L, TR, UR, VR>( this Either<L, TR> self, Func<TR, Either<L, UR>> selector, Func<TR, UR, VR> projector) { if (selector == null) throw new ArgumentNullException("selector"); if (projector == null) throw new ArgumentNullException("projector"); return () => { var resT = self(); if (resT.IsLeft) return new EitherPair<L, VR>(resT.Left); var resU = selector(resT.Right)(); if (resU.IsLeft) return new EitherPair<L, VR>(resU.Left); return new EitherPair<L, VR>(projector(resT.Right, resU.Right)); }; } /// <summary> /// Mconcat /// </summary> public static Either<L, R> Mconcat<L, R>(this IEnumerable<Either<L, R>> ms) { return () => { var value = ms.Head(); foreach (var m in ms.Tail()) { var res = value(); if (res.IsLeft) return res; value = value.Mappend(m); } return value(); }; } /// <summary> /// Memoize the result /// </summary> public static Func<EitherPair<L, R>> Memo<L, R>(this Either<L, R> self) { var res = self(); return () => res; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using log4net; using Newtonsoft.Json.Linq; using Ripple.Core; using Ripple.Core.Enums; using Ripple.Core.Types; using Ripple.Testing.Client; using Ripple.Testing.Server; using Ripple.TxSigning; namespace Ripple.Testing.Utils { public abstract partial class RippledFixtureBase { public static readonly ILog Log = Logging.ForContext(); public MultiThreadedFailures MultiThreadedFailures = new MultiThreadedFailures(); public Thread TestThread; public Rippled Rippled; public Connection Ws; public abstract ITestFrameworkAbstraction TestHelper(); public abstract string RippledBasePath { get; } public abstract string RippledBinaryPath { get; } public abstract void PerformOneTimeSetUp(); public abstract void PerformSetUp(); public abstract void PerformOneTimeTearDown(); public abstract void PerformTearDown(); // ReSharper disable InconsistentNaming [AutoFilled] public Currency USD , EUR , KHR , XRP ; [AutoFilled] public TestAccount ROOT , MARY , GW1 , GW2 , BOB , ALICE , JOE ; // ReSharper restore InconsistentNaming static RippledFixtureBase() { if (Environment.GetEnvironmentVariable("CI") != null) { Logging.ConfigureConsoleLogging(); } } private void SetupNamedMembers() { SetUpAccounts(); AutoFilled.Set(this, Currency.FromString); } protected Func<object, string> Alias; private void SetUpAccounts() { var testAccounts = AutoFilled.Set(this, TestAccount.FromAlias); var lookup = testAccounts.ToDictionary(a => a.Id.ToString()); var pattern = string.Join("|", testAccounts.Select(a => a.Id)); Alias = o => Regex.Replace(o.ToString(), pattern, match => lookup[match.Groups[0].Value].Alias); } public void SetupRippled() { TestThread = Thread.CurrentThread; FixtureScopedRippledBase.Log.DebugFormat("{1}() tid={0}", TestThread.ManagedThreadId, nameof(SetupRippled)); SetupNamedMembers(); var conf = RippledConfig.PrepareWithDefault(RippledBasePath); var execConf = conf.ExecutionConfig(RippledBinaryPath) .WithVerbosity(false); Rippled = new Rippled(execConf).Start(); Ws = new Connection(conf.AdminWebSocketUrl()); TestHelper().RunAsyncAction(Ws.ConnectAndSubscribe); if (Rippled.Proc.HasExited) { throw new InvalidOperationException("probably connected to a rippled that " + "wasn't torn down properly"); } } public void TearDownRippled() { FixtureScopedRippledBase.Log.DebugFormat(nameof(TearDownRippled)); Ws.Disconnect(); Rippled.Proc.Kill(); Rippled.Proc.WaitForExit(); } public async Task<JObject> GetValidatedLedger() { var args = new {ledger_index = "validated", full = true}; var ledger = await Ws.RequestAsync("ledger", args); return (JObject) ledger["ledger"]; } public async Task<TxSubmission> Pay( TestAccount src, TestAccount dest, Amount amt, TxConfigurator[] configure = null) { var payment = new StObject { [Field.TransactionType] = TransactionType.Payment, [Field.Amount] = amt, [Field.Destination] = dest.Id }; var signed = SignAndConfigure(src, payment, configure); return await Ws.Submit(signed.TxBlob); } public async Task<TxSubmission> Trust( TestAccount src, Amount amt, TxConfigurator[] configure = null) { var trustSet = new StObject { [Field.TransactionType] = TransactionType.TrustSet, [Field.LimitAmount] = amt }; var signed = SignAndConfigure(src, trustSet, configure); return await Ws.Submit(signed.TxBlob); } public async Task<TxSubmission> Offer( TestAccount src, Amount pays, Amount gets, TxConfigurator[] configure = null) { var offer = new StObject { [Field.TransactionType] = TransactionType.OfferCreate, [Field.TakerPays] = pays, [Field.TakerGets] = gets }; var signed = SignAndConfigure(src, offer, configure); return await Ws.Submit(signed.TxBlob); } public async Task<TxSubmission> OfferCancel( TestAccount src, Uint32 cancel, TxConfigurator[] configure = null) { var offer = new StObject { [Field.TransactionType] = TransactionType.OfferCreate, [Field.OfferSequence] = cancel }; var signed = SignAndConfigure(src, offer, configure); return await Ws.Submit(signed.TxBlob); } public async Task<TxSubmission> AccountSet( TestAccount src, TxConfigurator[] configure = null) { var offer = new StObject { [Field.TransactionType] = TransactionType.AccountSet }; var signed = SignAndConfigure(src, offer, configure); return await Ws.Submit(signed.TxBlob); } public SignedTx SignAndConfigure(TestAccount src, StObject tx, TxConfigurator[] configure = null) { AutoPopulateFields(src, tx); configure = configure ?? new TxConfigurator[0]; foreach (var conf in configure) { conf.PreSubmit?.Invoke(tx); } var signed = GetSignedTx(tx, src); foreach (var conf in configure) { conf.AfterSigning?.Invoke(signed); } return signed; } private static SignedTx GetSignedTx(StObject tx, TestAccount src) { if (tx.Has(Field.Signers) || tx.Has(Field.TxnSignature)) { return TxSigner.ValidateAndEncode(tx); } return src.Signer.SignStObject(tx); } public void AutoPopulateFields(TestAccount src, StObject tx) { if (!tx.Has(Field.Sequence)) { tx[Field.Sequence] = src.NextSequence++; } if (!tx.Has(Field.Fee)) { tx[Field.Fee] = DefaultFee; } if (!tx.Has(Field.Account)) { tx[Field.Account] = src.Id; } } public async Task<int> LedgerAccept() { return await Ws.LedgerAccept(); } public static Action<StObject> SetFlag(uint flag) => o => o.SetFlag(flag); public static Action<StObject> SetIndexedFlag(uint flag) => o => o[Field.SetFlag] = flag; public static Action<StObject> ClearIndexedFlag(uint flag) => o => o[Field.ClearFlag] = flag; public static Action<StObject> PartialPaymentFlag = SetFlag(TxFlag.PartialPayment) , SellFlag = SetFlag(TxFlag.Sell) , FillOrKillFlag = SetFlag(TxFlag.FillOrKill) , DisallowXrpFlag = SetFlag(TxFlag.DisallowXrp) , NoRippleFlag = SetFlag(TxFlag.SetNoRipple) , ClearDefaultRipple = ClearIndexedFlag(TxFlag.AsfDefaultRipple) , SetDefaultRipple = SetIndexedFlag(TxFlag.AsfDefaultRipple) ; protected Amount DefaultFee = "1000"; public static Action<StObject> Replaces(Uint32 offerSequence) => o => o[Field.OfferSequence] = offerSequence; public Action<StObject> Debug => tx => Console.WriteLine(Alias(tx.ToJson())); public Action<SignedTx> DebugSigned => tx => Console.WriteLine(Alias(tx.TxJson)); /// <summary> /// Paths DSL Hop creation helper /// </summary> /// <param name="trickResharper">First positional is ignored and only /// here to make other keyword args /// non redundant. /// </param> /// <param name="c">currency</param> /// <param name="a">account</param> /// <param name="i">issuer</param> /// <returns></returns> protected static PathHop Hop(bool? trickResharper=null, Currency c = null, AccountId a = null, AccountId i = null) { return new PathHop(a, i, c); } protected static Path Path(params PathHop[] hops) { return new Path(hops); } protected static Action<StObject> SendMax(Amount s) { return t => t[Field.SendMax] = s; } protected static Action<StObject> Paths(params Path[] paths) { return t => t[Field.Paths] = new PathSet(paths); } protected static Action<StObject> Paths(params PathHop[] hops) { return t => t[Field.Paths] = new PathSet(new[] {new Path(hops)}); } protected async Task<TxResult> RequestTxResult(Hash256 hash) { return await Ws.RequestTxResult(hash); } // ReSharper disable once InconsistentNaming protected async Task<TxSubmission> Expect( Task<TxSubmission> future, CallerInfo caller) { return await Expect(future, // ReSharper disable ExplicitCallerInfoArgument caller.MemberName, caller.SourceFilePath, caller.SourceLineNumber); // ReSharper restore ExplicitCallerInfoArgument } // ReSharper disable once InconsistentNaming protected async Task<TxSubmission> Expect( Task<TxSubmission> future, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0 ) { return await Expect(EngineResult.tesSUCCESS, future, // ReSharper disable ExplicitCallerInfoArgument memberName, sourceFilePath, sourceLineNumber); // ReSharper restore ExplicitCallerInfoArgument } protected async Task<TxSubmission> Expect( EngineResult ter, Task<TxSubmission> future, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { TxSubmission result; try { result = await future; } catch (InvalidOperationException e) { throw new UnexpectedEngineResultException( $"In {memberName} @ {sourceFilePath}:{sourceLineNumber} you " + $"expected {ter} submit response, got:\n" + $"{Alias(e.Message)}"); } if (ter != result.EngineResult) { throw new UnexpectedEngineResultException( $"In {memberName} @ {sourceFilePath}:{sourceLineNumber} you " + $"expected {ter} submit response, got {result.EngineResult}:\n" + $"{Alias(result.ResultJson.ToString())}"); } // For checking the final result result.ExpectedFinalResult = new ResultExpectation { EngineResult = ter, MemberName = memberName, SourceFilePath = sourceFilePath, SourceLineNumber = sourceLineNumber }; return result; } protected async Task<TxResult[]> SubmitAndClose( IEnumerable<Task<TxSubmission>> fut) { return await SubmitAndClose(fut.ToArray()); } protected async Task<TxResult[]> SubmitAndClose(params Task<TxSubmission>[] fut) { var submissions = await Task.WhenAll(fut); await LedgerAccept(); return (await Task.WhenAll( submissions.Select(async s => { try { return await RequestTxResult(s.Hash); } catch (TxNotFound e) { if (s.ExpectedFinalResult.EngineResult.ShouldClaimFee()) { throw new UnexpectedEngineResultException( "Transaction was expected to be in closed ledger, " + "but wasn't found", e); } return null; } } ))).Where(tx => true).ToArray(); } protected TxConfigurator[] With(params TxConfigurator[] conf) { return conf; } protected static async Task Future(params Task[] tasks) { await Task.WhenAll(tasks); } protected async Task<JObject[]> GetAccountData(AccountId testAccount) { // ReSharper disable once InconsistentNaming const string ledger_index = "validated"; var account = testAccount.ToString(); var parameters = new {ledger_index, account}; var lines = Ws.RequestAsync("account_lines", parameters); var info = Ws.RequestAsync("account_info", parameters); var offers = Ws.RequestAsync("account_offers", parameters); return await Task.WhenAll(info, lines, offers); } } }
//----------------------------------------------------------------------- // <copyright file="Constants.cs" company="Microsoft"> // Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <summary> // Contains code for the Constants class. // </summary> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure.StorageClient.Protocol { using System; /// <summary> /// Contains storage constants. /// </summary> internal class Constants { /// <summary> /// Maximum number of shared access policy identifiers supported by server. /// </summary> public const int MaxSharedAccessPolicyIdentifiers = 5; /// <summary> /// Default client side timeout for all service clients. /// </summary> public static readonly TimeSpan DefaultClientSideTimeout = TimeSpan.FromSeconds(90); /// <summary> /// Default Write Block Size used by Blob stream. /// </summary> public const long DefaultWriteBlockSizeBytes = 4 * Constants.MB; /// <summary> /// Default Read Ahead Size used by Blob stream. /// </summary> public const long DefaultReadAheadSizeBytes = 512 * Constants.KB; /// <summary> /// The maximum size of a blob before it must be separated into blocks. /// </summary> public const long MaxSingleUploadBlobSize = 64 * MB; /// <summary> /// The maximum size of a blob with blocks. /// </summary> public const long MaxBlobSize = 200 * GB; /// <summary> /// The maximum size of a single block. /// </summary> public const long MaxBlockSize = 4 * 1024 * 1024; /// <summary> /// The maximum number of blocks. /// </summary> public const long MaxBlockNumber = 50000; /// <summary> /// Default size of buffer for unknown sized requests. /// </summary> internal const int DefaultBufferSize = 84000; /// <summary> /// This is used to create V1 BlockIDs. The prefix must be Base64 compatible. /// </summary> internal static readonly string V1BlockPrefix = "MD5/"; /// <summary> /// This is the offset of the V2 MD5 string where the MD5/ tag resides. /// </summary> internal static readonly int V1MD5blockIdExpectedLength = 28; /// <summary> /// This is used to create BlockIDs. The prefix must be Base64 compatible. /// </summary> internal const string V2blockPrefix = "V2/"; /// <summary> /// This is used to create BlockIDs. The prefix must be Base64 compatible. /// </summary> internal static readonly string V2MD5blockIdFormat = V2blockPrefix + "{0}/{1}"; /// <summary> /// This is the offset of the V2 MD5 string where the hash value resides. /// </summary> internal static readonly int V2MD5blockIdMD5Offset = V2blockPrefix.Length + 8 + 1; /// <summary> /// This is the expected length of a V2 MD5 Block ID string. /// </summary> internal static readonly int V2MD5blockIdExpectedLength = V2MD5blockIdMD5Offset + 24; /// <summary> /// The size of a page in a PageBlob. /// </summary> internal const long PageSize = 512; /// <summary> /// A constant representing a kilo-byte (Non-SI version). /// </summary> internal const long KB = 1024; /// <summary> /// A constant representing a megabyte (Non-SI version). /// </summary> internal const long MB = 1024 * KB; /// <summary> /// A constant representing a megabyte (Non-SI version). /// </summary> internal const long GB = 1024 * MB; /// <summary> /// XML element for committed blocks. /// </summary> internal const string CommittedBlocksElement = "CommittedBlocks"; /// <summary> /// XML element for uncommitted blocks. /// </summary> internal const string UncommittedBlocksElement = "UncommittedBlocks"; /// <summary> /// XML element for blocks. /// </summary> internal const string BlockElement = "Block"; /// <summary> /// XML element for names. /// </summary> internal const string NameElement = "Name"; /// <summary> /// XML element for sizes. /// </summary> internal const string SizeElement = "Size"; /// <summary> /// XML element for block lists. /// </summary> internal const string BlockListElement = "BlockList"; /// <summary> /// XML element for queue message lists. /// </summary> internal const string MessagesElement = "QueueMessagesList"; /// <summary> /// XML element for queue messages. /// </summary> internal const string MessageElement = "QueueMessage"; /// <summary> /// XML element for message IDs. /// </summary> internal const string MessageIdElement = "MessageId"; /// <summary> /// XML element for insertion times. /// </summary> internal const string InsertionTimeElement = "InsertionTime"; /// <summary> /// XML element for expiration times. /// </summary> internal const string ExpirationTimeElement = "ExpirationTime"; /// <summary> /// XML element for pop receipts. /// </summary> internal const string PopReceiptElement = "PopReceipt"; /// <summary> /// XML element for the time next visible fields. /// </summary> internal const string TimeNextVisibleElement = "TimeNextVisible"; /// <summary> /// XML element for message texts. /// </summary> internal const string MessageTextElement = "MessageText"; /// <summary> /// XML element for dequeue counts. /// </summary> internal const string DequeueCountElement = "DequeueCount"; /// <summary> /// XML element for page ranges. /// </summary> internal const string PageRangeElement = "PageRange"; /// <summary> /// XML element for page list elements. /// </summary> internal const string PageListElement = "PageListElement"; /// <summary> /// XML element for page range start elements. /// </summary> internal const string StartElement = "Start"; /// <summary> /// XML element for page range end elements. /// </summary> internal const string EndElement = "End"; /// <summary> /// XML element for delimiters. /// </summary> internal const string DelimiterElement = "Delimiter"; /// <summary> /// XML element for blob prefixes. /// </summary> internal const string BlobPrefixElement = "BlobPrefix"; /// <summary> /// XML element for content type fields. /// </summary> internal const string ContentTypeElement = "Content-Type"; /// <summary> /// XML element for content encoding fields. /// </summary> internal const string ContentEncodingElement = "Content-Encoding"; /// <summary> /// XML element for content language fields. /// </summary> internal const string ContentLanguageElement = "Content-Language"; /// <summary> /// XML element for content length fields. /// </summary> internal const string ContentLengthElement = "Content-Length"; /// <summary> /// XML element for content MD5 fields. /// </summary> internal const string ContentMD5Element = "Content-MD5"; /// <summary> /// XML element for blobs. /// </summary> internal const string BlobsElement = "Blobs"; /// <summary> /// XML element for prefixes. /// </summary> internal const string PrefixElement = "Prefix"; /// <summary> /// XML element for maximum results. /// </summary> internal const string MaxResultsElement = "MaxResults"; /// <summary> /// XML element for markers. /// </summary> internal const string MarkerElement = "Marker"; /// <summary> /// XML element for the next marker. /// </summary> internal const string NextMarkerElement = "NextMarker"; /// <summary> /// XML element for the ETag. /// </summary> internal const string EtagElement = "Etag"; /// <summary> /// XML element for the last modified date. /// </summary> internal const string LastModifiedElement = "Last-Modified"; /// <summary> /// XML element for the Url. /// </summary> internal const string UrlElement = "Url"; /// <summary> /// XML element for blobs. /// </summary> internal const string BlobElement = "Blob"; /// <summary> /// Constant signalling a page blob. /// </summary> internal const string PageBlobValue = "PageBlob"; /// <summary> /// Constant signalling a block blob. /// </summary> internal const string BlockBlobValue = "BlockBlob"; /// <summary> /// Constant signalling the blob is locked. /// </summary> internal const string LockedValue = "Locked"; /// <summary> /// Constant signalling the blob is unlocked. /// </summary> internal const string UnlockedValue = "Unlocked"; /// <summary> /// XML element for blob types. /// </summary> internal const string BlobTypeElement = "BlobType"; /// <summary> /// XML element for the lease status. /// </summary> internal const string LeaseStatusElement = "LeaseStatus"; /// <summary> /// XML element for snapshots. /// </summary> internal const string SnapshotElement = "Snapshot"; /// <summary> /// XML element for containers. /// </summary> internal const string ContainersElement = "Containers"; /// <summary> /// XML element for a container. /// </summary> internal const string ContainerElement = "Container"; /// <summary> /// XML element for queues. /// </summary> internal const string QueuesElement = "Queues"; /// <summary> /// XML element for the queue name. /// </summary> internal const string QueueNameElement = "QueueName"; /// <summary> /// Version 2 of the XML element for the queue name. /// </summary> internal const string QueueNameElementVer2 = "Name"; /// <summary> /// XML element for the queue. /// </summary> internal const string QueueElement = "Queue"; /// <summary> /// XML element for the metadata. /// </summary> internal const string MetadataElement = "Metadata"; /// <summary> /// XML element for an invalid metadata name. /// </summary> internal const string InvalidMetadataName = "x-ms-invalid-name"; /// <summary> /// XPath query for error codes. /// </summary> internal const string ErrorCodeQuery = "//Error/Code"; /// <summary> /// XPath query for error messages. /// </summary> internal const string ErrorMessageQuery = "//Error/Message"; /// <summary> /// XML element for maximum results. /// </summary> internal const string MaxResults = "MaxResults"; /// <summary> /// XML element for committed blocks. /// </summary> internal const string CommittedElement = "Committed"; /// <summary> /// XML element for uncommitted blocks. /// </summary> internal const string UncommittedElement = "Uncommitted"; /// <summary> /// XML element for the latest. /// </summary> internal const string LatestElement = "Latest"; /// <summary> /// XML element for signed identifiers. /// </summary> internal const string SignedIdentifiers = "SignedIdentifiers"; /// <summary> /// XML element for a signed identifier. /// </summary> internal const string SignedIdentifier = "SignedIdentifier"; /// <summary> /// XML element for access policies. /// </summary> internal const string AccessPolicy = "AccessPolicy"; /// <summary> /// XML attribute for IDs. /// </summary> internal const string Id = "Id"; /// <summary> /// XML element for the start time of an access policy. /// </summary> internal const string Start = "Start"; /// <summary> /// XML element for the end of an access policy. /// </summary> internal const string Expiry = "Expiry"; /// <summary> /// XML element for the permissions of an access policy. /// </summary> internal const string Permission = "Permission"; /// <summary> /// The maximum size of a string property for the table service in bytes. /// </summary> internal const int TableServiceMaxStringPropertySizeInBytes = 64 * 1024; /// <summary> /// The maximum size of a string property for the table service in chars. /// </summary> internal const int TableServiceMaxStringPropertySizeInChars = TableServiceMaxStringPropertySizeInBytes / 2; /// <summary> /// The minimum supported <see cref="DateTime"/> value for the table service. /// </summary> internal static readonly DateTime TableServiceMinSupportedDateTime = DateTime.FromFileTime(0).ToUniversalTime().AddYears(200); /// <summary> /// The name of the special table used to store tables. /// </summary> internal const string TableServiceTablesName = "Tables"; /// <summary> /// The timeout after which the WCF Data Services bug workaround kicks in. This should be greater than the timeout we pass to DataServiceContext (90 seconds). /// </summary> internal static readonly TimeSpan TableWorkaroundTimeout = TimeSpan.FromSeconds(120); /// <summary> /// The Uri path component to access the messages in a queue. /// </summary> internal const string Messages = "messages"; /// <summary> /// XML root element for errors. /// </summary> internal const string ErrorRootElement = "Error"; /// <summary> /// XML element for error codes. /// </summary> internal const string ErrorCode = "Code"; /// <summary> /// XML element for error messages. /// </summary> internal const string ErrorMessage = "Message"; /// <summary> /// XML element for exception details. /// </summary> internal const string ErrorException = "ExceptionDetails"; /// <summary> /// XML element for exception messages. /// </summary> internal const string ErrorExceptionMessage = "ExceptionMessage"; /// <summary> /// XML element for stack traces. /// </summary> internal const string ErrorExceptionStackTrace = "StackTrace"; /// <summary> /// XML element for the authentication error details. /// </summary> internal const string AuthenticationErrorDetail = "AuthenticationErrorDetail"; /// <summary> /// XML namespace for the WCF Data Services metadata. /// </summary> internal const string DataWebMetadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; /// <summary> /// XML element for table error codes. /// </summary> internal const string TableErrorCodeElement = "code"; /// <summary> /// XML element for table error messages. /// </summary> internal const string TableErrorMessageElement = "message"; /// <summary> /// Constants for HTTP headers. /// </summary> internal class HeaderConstants { /// <summary> /// Master Windows Azure Storage header prefix. /// </summary> internal const string PrefixForStorageHeader = "x-ms-"; /// <summary> /// Header prefix for properties. /// </summary> internal const string PrefixForStorageProperties = "x-ms-prop-"; /// <summary> /// Header prefix for metadata. /// </summary> internal const string PrefixForStorageMetadata = "x-ms-meta-"; /// <summary> /// Header for data ranges. /// </summary> internal const string StorageRangeHeader = PrefixForStorageHeader + "range"; /// <summary> /// Header for storage version. /// </summary> internal const string StorageVersionHeader = PrefixForStorageHeader + "version"; /// <summary> /// Header for copy source. /// </summary> internal const string CopySourceHeader = PrefixForStorageHeader + "copy-source"; /// <summary> /// Header for the If-Match condition. /// </summary> internal const string SourceIfMatchHeader = PrefixForStorageHeader + "source-if-match"; /// <summary> /// Header for the If-Modified-Since condition. /// </summary> internal const string SourceIfModifiedSinceHeader = PrefixForStorageHeader + "source-if-modified-since"; /// <summary> /// Header for the If-None-Match condition. /// </summary> internal const string SourceIfNoneMatchHeader = PrefixForStorageHeader + "source-if-none-match"; /// <summary> /// Header for the If-Unmodified-Since condition. /// </summary> internal const string SourceIfUnmodifiedSinceHeader = PrefixForStorageHeader + "source-if-unmodified-since"; /// <summary> /// Header for the blob content length. /// </summary> internal const string Size = PrefixForStorageHeader + "blob-content-length"; /// <summary> /// Header for the blob type. /// </summary> internal const string BlobType = PrefixForStorageHeader + "blob-type"; /// <summary> /// Header for snapshots. /// </summary> internal const string SnapshotHeader = PrefixForStorageHeader + "snapshot"; /// <summary> /// Header to delete snapshots. /// </summary> internal const string DeleteSnapshotHeader = PrefixForStorageHeader + "delete-snapshots"; /// <summary> /// Header that specifies approximate message count of a queue. /// </summary> internal const string ApproximateMessagesCount = PrefixForStorageHeader + "approximate-messages-count"; /// <summary> /// Header that specifies a range. /// </summary> internal const string RangeHeader = PrefixForStorageHeader + "range"; /// <summary> /// Header that specifies blob caching control. /// </summary> internal const string CacheControlHeader = PrefixForStorageHeader + "blob-cache-control"; /// <summary> /// Header that specifies blob content encoding. /// </summary> internal const string ContentEncodingHeader = PrefixForStorageHeader + "blob-content-encoding"; /// <summary> /// Header that specifies blob content language. /// </summary> internal const string ContentLanguageHeader = PrefixForStorageHeader + "blob-content-language"; /// <summary> /// Header that specifies blob content MD5. /// </summary> internal const string BlobContentMD5Header = PrefixForStorageHeader + "blob-content-md5"; /// <summary> /// Header that specifies blob content type. /// </summary> internal const string ContentTypeHeader = PrefixForStorageHeader + "blob-content-type"; /// <summary> /// Header that specifies blob content length. /// </summary> internal const string ContentLengthHeader = PrefixForStorageHeader + "blob-content-length"; /// <summary> /// Header that specifies lease ID. /// </summary> internal const string LeaseIdHeader = PrefixForStorageHeader + "lease-id"; /// <summary> /// Header that specifies lease status. /// </summary> internal const string LeaseStatus = PrefixForStorageHeader + "lease-status"; /// <summary> /// Header that specifies page write mode. /// </summary> internal const string PageWrite = PrefixForStorageHeader + "page-write"; /// <summary> /// Header that specifies the date. /// </summary> internal const string Date = PrefixForStorageHeader + "date"; /// <summary> /// Header indicating the request ID. /// </summary> internal const string RequestIdHeader = PrefixForStorageHeader + "request-id"; /// <summary> /// Header that specifies public access to blobs. /// </summary> internal const string BlobPublicAccess = PrefixForStorageHeader + "blob-public-access"; /// <summary> /// Format string for specifying ranges. /// </summary> internal const string RangeHeaderFormat = "bytes={0}-{1}"; /// <summary> /// Current storage version header value. /// </summary> internal const string TargetStorageVersion = "2011-08-18"; /// <summary> /// Specifies the page blob type. /// </summary> internal const string PageBlob = "PageBlob"; /// <summary> /// Specifies the block blob type. /// </summary> internal const string BlockBlob = "BlockBlob"; /// <summary> /// Specifies only snapshots are to be included. /// </summary> internal const string SnapshotsOnlyValue = "only"; /// <summary> /// Specifies snapshots are to be included. /// </summary> internal const string IncludeSnapshotsValue = "include"; /// <summary> /// Specifies the value to use for UserAgent header. /// </summary> internal const string UserAgent = "WA-Storage/1.6.0"; /// <summary> /// Specifies the pop receipt for a message. /// </summary> internal const string PopReceipt = PrefixForStorageHeader + "popreceipt"; /// <summary> /// Specifies the next visible time for a message. /// </summary> internal const string NextVisibleTime = PrefixForStorageHeader + "time-next-visible"; } /// <summary> /// Constants for query strings. /// </summary> internal class QueryConstants { /// <summary> /// Query component for snapshot time. /// </summary> internal const string Snapshot = "snapshot"; /// <summary> /// Query component for the signed SAS start time. /// </summary> internal const string SignedStart = "st"; /// <summary> /// Query component for the signed SAS expiry time. /// </summary> internal const string SignedExpiry = "se"; /// <summary> /// Query component for the signed SAS resource. /// </summary> internal const string SignedResource = "sr"; /// <summary> /// Query component for the signed SAS permissions. /// </summary> internal const string SignedPermissions = "sp"; /// <summary> /// Query component for the signed SAS identifier. /// </summary> internal const string SignedIdentifier = "si"; /// <summary> /// Query component for the signed SAS version. /// </summary> internal const string SignedVersion = "sv"; /// <summary> /// Query component for SAS signature. /// </summary> internal const string Signature = "sig"; /// <summary> /// Query component for message time-to-live. /// </summary> internal const string MessageTimeToLive = "messagettl"; /// <summary> /// Query component for message visibility timeout. /// </summary> internal const string VisibilityTimeout = "visibilitytimeout"; /// <summary> /// Query component for message pop receipt. /// </summary> internal const string PopReceipt = "popreceipt"; /// <summary> /// Query component for resource type. /// </summary> internal const string ResourceType = "restype"; /// <summary> /// Query component for the operation (component) to access. /// </summary> internal const string Component = "comp"; } } }
using System; using System.Text; using SimpleJson; using System.Collections; using System.Collections.Generic; namespace Pomelo.Protobuf { public class MsgEncoder { private JsonObject protos { set; get; }//The message format(like .proto file) private Encoder encoder { set; get; } private Util util { set; get; } public MsgEncoder(JsonObject protos) { if (protos == null) protos = new JsonObject(); this.protos = protos; this.util = new Util(); } /// <summary> /// Encode the message from server. /// </summary> /// <param name='route'> /// Route. /// </param> /// <param name='msg'> /// Message. /// </param> public byte[] encode(string route, JsonObject msg) { byte[] returnByte = null; object proto; if (this.protos.TryGetValue(route, out proto)) { if (!checkMsg(msg, (JsonObject)proto)) { return null; } int length = Encoder.byteLength(msg.ToString()) * 2; int offset = 0; byte[] buff = new byte[length]; offset = encodeMsg(buff, offset, (JsonObject)proto, msg); returnByte = new byte[offset]; for (int i = 0; i < offset; i++) { returnByte[i] = buff[i]; } } return returnByte; } /// <summary> /// Check the message. /// </summary> private bool checkMsg(JsonObject msg, JsonObject proto) { ICollection<string> protoKeys = proto.Keys; foreach (string key in protoKeys) { JsonObject value = (JsonObject)proto[key]; object proto_option; if (value.TryGetValue("option", out proto_option)) { switch (proto_option.ToString()) { case "required": if (!msg.ContainsKey(key)) { return false; } else { } break; case "optional": object value_type; JsonObject messages = (JsonObject)proto["__messages"]; value_type = value["type"]; if (msg.ContainsKey(key)) { Object value_proto; if (messages.TryGetValue(value_type.ToString(), out value_proto) || protos.TryGetValue("message " + value_type.ToString(), out value_proto)) { checkMsg((JsonObject)msg[key], (JsonObject)value_proto); } } break; case "repeated": object msg_name; object msg_type; if (value.TryGetValue("type", out value_type) && msg.TryGetValue(key, out msg_name)) { if (((JsonObject)proto["__messages"]).TryGetValue(value_type.ToString(), out msg_type) || protos.TryGetValue("message " + value_type.ToString(), out msg_type)) { List<object> o = (List<object>)msg_name; foreach (object item in o) { if (!checkMsg((JsonObject)item, (JsonObject)msg_type)) { return false; } } } } break; } } } return true; } /// <summary> /// Encode the message. /// </summary> private int encodeMsg(byte[] buffer, int offset, JsonObject proto, JsonObject msg) { ICollection<string> msgKeys = msg.Keys; foreach (string key in msgKeys) { object value; if (proto.TryGetValue(key, out value)) { object value_option; if (((JsonObject)value).TryGetValue("option", out value_option)) { switch (value_option.ToString()) { case "required": case "optional": object value_type, value_tag; if (((JsonObject)value).TryGetValue("type", out value_type) && ((JsonObject)value).TryGetValue("tag", out value_tag)) { offset = this.writeBytes(buffer, offset, this.encodeTag(value_type.ToString(), Convert.ToInt32(value_tag))); offset = this.encodeProp(msg[key], value_type.ToString(), offset, buffer, proto); } break; case "repeated": object msg_key; if (msg.TryGetValue(key, out msg_key)) { if (((List<object>)msg_key).Count > 0) { offset = encodeArray((List<object>)msg_key, (JsonObject)value, offset, buffer, proto); } } break; } } } } return offset; } /// <summary> /// Encode the array type. /// </summary> private int encodeArray(List<object> msg, JsonObject value, int offset, byte[] buffer, JsonObject proto) { object value_type, value_tag; if (value.TryGetValue("type", out value_type) && value.TryGetValue("tag", out value_tag)) { if (this.util.isSimpleType(value_type.ToString())) { offset = this.writeBytes(buffer, offset, this.encodeTag(value_type.ToString(), Convert.ToInt32(value_tag))); offset = this.writeBytes(buffer, offset, Encoder.encodeUInt32((uint)msg.Count)); foreach (object item in msg) { offset = this.encodeProp(item, value_type.ToString(), offset, buffer, null); } } else { foreach (object item in msg) { offset = this.writeBytes(buffer, offset, this.encodeTag(value_type.ToString(), Convert.ToInt32(value_tag))); offset = this.encodeProp(item, value_type.ToString(), offset, buffer, proto); } } } return offset; } /// <summary> /// Encode each item in message. /// </summary> private int encodeProp(object value, string type, int offset, byte[] buffer, JsonObject proto) { switch (type) { case "uInt32": this.writeUInt32(buffer, ref offset, value); break; case "int32": case "sInt32": this.writeInt32(buffer, ref offset, value); break; case "float": this.writeFloat(buffer, ref offset, value); break; case "double": this.writeDouble(buffer, ref offset, value); break; case "string": this.writeString(buffer, ref offset, value); break; default: object __messages; object __message_type; if (proto.TryGetValue("__messages", out __messages)) { if (((JsonObject)__messages).TryGetValue(type, out __message_type) || protos.TryGetValue("message " + type, out __message_type)) { byte[] tembuff = new byte[Encoder.byteLength(value.ToString()) * 3]; int length = 0; length = this.encodeMsg(tembuff, length, (JsonObject)__message_type, (JsonObject)value); offset = writeBytes(buffer, offset, Encoder.encodeUInt32((uint)length)); for (int i = 0; i < length; i++) { buffer[offset] = tembuff[i]; offset++; } } } break; } return offset; } //Encode string. private void writeString(byte[] buffer, ref int offset, object value) { int le = Encoding.UTF8.GetByteCount(value.ToString()); offset = writeBytes(buffer, offset, Encoder.encodeUInt32((uint)le)); byte[] bytes = Encoding.UTF8.GetBytes(value.ToString()); this.writeBytes(buffer, offset, bytes); offset += le; } //Encode double. private void writeDouble(byte[] buffer, ref int offset, object value) { WriteRawLittleEndian64(buffer, offset, (ulong)BitConverter.DoubleToInt64Bits(double.Parse(value.ToString()))); offset += 8; } //Encode float. private void writeFloat(byte[] buffer, ref int offset, object value) { this.writeBytes(buffer, offset, Encoder.encodeFloat(float.Parse(value.ToString()))); offset += 4; } ////Encode UInt32. private void writeUInt32(byte[] buffer, ref int offset, object value) { offset = writeBytes(buffer, offset, Encoder.encodeUInt32(value.ToString())); } //Encode Int32 private void writeInt32(byte[] buffer, ref int offset, object value) { offset = writeBytes(buffer, offset, Encoder.encodeSInt32(value.ToString())); } //Write bytes to buffer. private int writeBytes(byte[] buffer, int offset, byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { buffer[offset] = bytes[i]; offset++; } return offset; } //Encode tag. private byte[] encodeTag(string type, int tag) { int flag = this.util.containType(type); return Encoder.encodeUInt32((uint)(tag << 3 | flag)); } private void WriteRawLittleEndian64(byte[] buffer, int offset, ulong value) { buffer[offset++] = ((byte)value); buffer[offset++] = ((byte)(value >> 8)); buffer[offset++] = ((byte)(value >> 16)); buffer[offset++] = ((byte)(value >> 24)); buffer[offset++] = ((byte)(value >> 32)); buffer[offset++] = ((byte)(value >> 40)); buffer[offset++] = ((byte)(value >> 48)); buffer[offset++] = ((byte)(value >> 56)); } } }
// // MultipartContent.cs // // Authors: // Marek Safar <marek.safar@gmail.com> // // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Threading.Tasks; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net.Http.Headers; using System.Linq; using System.Text; using HttpClientLibrary; namespace System.Net.Http { public class MultipartContent : HttpContent, IEnumerable<HttpContent> { List<HttpContent> nested_content; readonly string boundary; public MultipartContent() : this("mixed") { } public MultipartContent(string subtype) : this(subtype, Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture)) { } public MultipartContent(string subtype, string boundary) { if (StringEx.IsNullOrWhiteSpace(subtype)) throw new ArgumentException("boundary"); // // The only mandatory parameter for the multipart Content-Type is the boundary parameter, which consists // of 1 to 70 characters from a set of characters known to be very robust through email gateways, // and NOT ending with white space // if (StringEx.IsNullOrWhiteSpace(boundary)) throw new ArgumentException("boundary"); if (boundary.Length > 70) throw new ArgumentOutOfRangeException("boundary"); if (boundary.Last() == ' ' || !IsValidRFC2049(boundary)) throw new ArgumentException("boundary"); this.boundary = boundary; this.nested_content = new List<HttpContent>(2); Headers.ContentType = new MediaTypeHeaderValue("multipart/" + subtype) { Parameters = { new NameValueHeaderValue("boundary", "\"" + boundary + "\"") } }; } static bool IsValidRFC2049(string s) { foreach (char c in s) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) continue; switch (c) { case '\'': case '(': case ')': case '+': case ',': case '-': case '.': case '/': case ':': case '=': case '?': continue; } return false; } return true; } public virtual void Add(HttpContent content) { if (content == null) throw new ArgumentNullException("content"); if (nested_content == null) nested_content = new List<HttpContent>(); nested_content.Add(content); } protected override void Dispose(bool disposing) { if (disposing) { foreach (var item in nested_content) { item.Dispose(); } nested_content = null; } base.Dispose(disposing); } protected internal override Task SerializeToStreamAsync(Stream stream, TransportContext context) { // RFC 2046 // // The Content-Type field for multipart entities requires one parameter, // "boundary". The boundary delimiter line is then defined as a line // consisting entirely of two hyphen characters ("-", decimal value 45) // followed by the boundary parameter value from the Content-Type header // field, optional linear whitespace, and a terminating CRLF. // byte[] buffer; var sb = new StringBuilder(); sb.Append('-').Append('-'); sb.Append(boundary); sb.Append('\r').Append('\n'); int i = 0; Func<bool> condition = () => i < nested_content.Count; Func<Task> body = () => { var c = nested_content[i]; foreach (var h in c.Headers) { sb.Append(h.Key); sb.Append(':').Append(' '); foreach (var v in h.Value) { sb.Append(v); } sb.Append('\r').Append('\n'); } sb.Append('\r').Append('\n'); buffer = Encoding.ASCII.GetBytes(sb.ToString()); sb.Length = 0; return stream.WriteAsync(buffer, 0, buffer.Length) .Then(_ => c.SerializeToStreamAsync(stream, context)) .Select( _ => { if (i != nested_content.Count - 1) { sb.Append('\r').Append('\n'); sb.Append('-').Append('-'); sb.Append(boundary); sb.Append('\r').Append('\n'); } i++; }); }; Func<Task, Task> continuationFunction = task => { sb.Append('\r').Append('\n'); sb.Append('-').Append('-'); sb.Append(boundary); sb.Append('-').Append('-'); sb.Append('\r').Append('\n'); buffer = Encoding.ASCII.GetBytes(sb.ToString()); return stream.WriteAsync(buffer, 0, buffer.Length); }; return TaskBlocks.While(condition, body) .Then(continuationFunction); } protected internal override bool TryComputeLength(out long length) { length = 12 + 2 * boundary.Length; for (int i = 0; i < nested_content.Count; i++) { var c = nested_content[i]; foreach (var h in c.Headers) { length += h.Key.Length; length += 4; foreach (var v in h.Value) { length += v.Length; } } long l; if (!c.TryComputeLength(out l)) return false; length += 2; length += l; if (i != nested_content.Count - 1) { length += 6; length += boundary.Length; } } return true; } public IEnumerator<HttpContent> GetEnumerator() { return nested_content.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return nested_content.GetEnumerator(); } } }
/* * Pen.cs - Implementation of the "System.Drawing.Pen" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing { using System.Drawing.Drawing2D; using System.Drawing.Toolkit; public sealed class Pen : MarshalByRefObject, ICloneable, IDisposable { // Internal state. private Brush brush; private Color color; private float width; private PenAlignment alignment; private float[] compoundArray; private CustomLineCap customEndCap; private CustomLineCap customStartCap; private DashCap dashCap; private float dashOffset; private float[] dashPattern; private DashStyle dashStyle; private LineCap endCap; private LineJoin lineJoin; private float miterLimit; private LineCap startCap; private Matrix transform; private IToolkit toolkit; private IToolkitPen toolkitPen; // Constructors. public Pen(Brush brush) { if(brush == null) { throw new ArgumentNullException("brush"); } this.brush = brush; this.width = 1.0f; this.miterLimit = 10.0f; } public Pen(Color color) { this.color = color; this.width = 1.0f; this.miterLimit = 10.0f; } public Pen(Brush brush, float width) { if(brush == null) { throw new ArgumentNullException("brush"); } this.brush = brush; this.width = width; this.miterLimit = 10.0f; } public Pen(Color color, float width) { this.color = color; this.width = width; this.miterLimit = 10.0f; } // Destructor. ~Pen() { Dispose(); } // Get or set the pen properties. public PenAlignment Alignment { get { return alignment; } set { if(alignment != value) { Dispose(); alignment = value; } } } public Brush Brush { get { if(brush == null) { brush = new SolidBrush(color); } return brush; } set { if(brush != value) { Dispose(); brush = value; } } } public Color Color { get { if(brush is SolidBrush) { return ((SolidBrush)brush).Color; } return color; } set { if(color != value) { Dispose(); color = value; brush = null; } } } public float[] CompoundArray { get { return compoundArray; } set { Dispose(); compoundArray = value; } } public CustomLineCap CustomEndCap { get { return customEndCap; } set { Dispose(); customEndCap = value; } } public CustomLineCap CustomStartCap { get { return customStartCap; } set { Dispose(); customStartCap = value; } } public DashCap DashCap { get { return dashCap; } set { if(dashCap != value) { Dispose(); dashCap = value; } } } public float DashOffset { get { return dashOffset; } set { if(dashOffset != value) { Dispose(); dashOffset = value; } } } public float[] DashPattern { get { return dashPattern; } set { Dispose(); dashPattern = value; } } public DashStyle DashStyle { get { return dashStyle; } set { if(dashStyle != value) { Dispose(); dashStyle = value; } } } public LineCap EndCap { get { return endCap; } set { if(endCap != value) { Dispose(); endCap = value; } } } public LineJoin LineJoin { get { return lineJoin; } set { if(lineJoin != value) { Dispose(); lineJoin = value; } } } public float MiterLimit { get { return miterLimit; } set { if(miterLimit != value) { Dispose(); miterLimit = value; } } } public PenType PenType { get { if(brush == null || brush is SolidBrush) { return PenType.SolidColor; } else if(brush is TextureBrush) { return PenType.TextureFill; } else if(brush is HatchBrush) { return PenType.HatchFill; } else if(brush is PathGradientBrush) { return PenType.PathGradient; } else if(brush is LinearGradientBrush) { return PenType.LinearGradient; } else { return PenType.SolidColor; } } } public LineCap StartCap { get { return startCap; } set { if(startCap != value) { Dispose(); startCap = value; } } } public Matrix Transform { get { return transform; } set { Dispose(); if(value != null) { // Make a copy of the matrix so that modifications // to the original don't affect the pen settings. transform = Matrix.Clone(value); } else { transform = null; } } } public float Width { get { return width; } set { if(width != value) { Dispose(); width = value; } } } // Clone this pen. public Object Clone() { lock(this) { Pen pen = (Pen)(MemberwiseClone()); pen.toolkit = null; pen.toolkitPen = null; return pen; } } // Dispose of this pen. public void Dispose() { lock(this) { if(toolkitPen != null) { toolkitPen.Dispose(); toolkitPen = null; } toolkit = null; if(brush != null) { brush.Modified(); } } } // Set the line capabilities. public void SetLineCap(LineCap startCap, LineCap endCap, DashCap dashCap) { Dispose(); this.startCap = startCap; this.endCap = endCap; this.dashCap = dashCap; } // Get the toolkit version of this pen for a specific toolkit. internal IToolkitPen GetPen(IToolkit toolkit) { lock(this) { if(this.toolkitPen == null) { // We don't yet have a toolkit pen yet. this.toolkitPen = toolkit.CreatePen(this); this.toolkit = toolkit; return this.toolkitPen; } else if(this.toolkit == toolkit) { // Same toolkit - return the cached pen information. return this.toolkitPen; } else { // We have a pen for another toolkit, // so dispose it and create for this toolkit. // We null out "toolkitPen" before calling // "CreatePen()" just in case an exception // is thrown while creating the toolkit pen. this.toolkitPen.Dispose(); this.toolkitPen = null; this.toolkitPen = toolkit.CreatePen(this); this.toolkit = toolkit; return this.toolkitPen; } } } }; // class Pen }; // namespace System.Drawing
// Copyright 2014 Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; #if !NO_SERIALIZATION using System.Runtime.Serialization; #endif using Serilog.Events; using Serilog.Parsing; namespace Serilog.Formatting.Elasticsearch { /// <summary> /// Custom Json formatter that respects the configured property name handling and forces 'Timestamp' to @timestamp /// </summary> public class ElasticsearchJsonFormatter : DefaultJsonFormatter { readonly ISerializer _serializer; readonly bool _inlineFields; readonly bool _formatStackTraceAsArray; /// <summary> /// Render message property name /// </summary> public const string RenderedMessagePropertyName = "message"; /// <summary> /// Message template property name /// </summary> public const string MessageTemplatePropertyName = "messageTemplate"; /// <summary> /// Exception property name /// </summary> public const string ExceptionPropertyName = "Exception"; /// <summary> /// Level property name /// </summary> public const string LevelPropertyName = "level"; /// <summary> /// Timestamp property name /// </summary> public const string TimestampPropertyName = "@timestamp"; /// <summary> /// Construct a <see cref="ElasticsearchJsonFormatter"/>. /// </summary> /// <param name="omitEnclosingObject">If true, the properties of the event will be written to /// the output without enclosing braces. Otherwise, if false, each event will be written as a well-formed /// JSON object.</param> /// <param name="closingDelimiter">A string that will be written after each log event is formatted. /// If null, <see cref="Environment.NewLine"/> will be used. Ignored if <paramref name="omitEnclosingObject"/> /// is true.</param> /// <param name="renderMessage">If true, the message will be rendered and written to the output as a /// property named RenderedMessage.</param> /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param> /// <param name="serializer">Inject a serializer to force objects to be serialized over being ToString()</param> /// <param name="inlineFields">When set to true values will be written at the root of the json document</param> /// <param name="renderMessageTemplate">If true, the message template will be rendered and written to the output as a /// property named RenderedMessageTemplate.</param> /// <param name="formatStackTraceAsArray">If true, splits the StackTrace by new line and writes it as a an array of strings</param> public ElasticsearchJsonFormatter( bool omitEnclosingObject = false, string closingDelimiter = null, bool renderMessage = true, IFormatProvider formatProvider = null, ISerializer serializer = null, bool inlineFields = false, bool renderMessageTemplate = true, bool formatStackTraceAsArray = false) : base(omitEnclosingObject, closingDelimiter, renderMessage, formatProvider, renderMessageTemplate) { _serializer = serializer; _inlineFields = inlineFields; _formatStackTraceAsArray = formatStackTraceAsArray; } /// <summary> /// Writes out individual renderings of attached properties /// </summary> protected override void WriteRenderings(IGrouping<string, PropertyToken>[] tokensWithFormat, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output) { output.Write(",\"{0}\":{{", "renderings"); WriteRenderingsValues(tokensWithFormat, properties, output); output.Write("}"); } /// <summary> /// Writes out the attached properties /// </summary> protected override void WriteProperties(IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output) { if (!_inlineFields) output.Write(",\"{0}\":{{", "fields"); else output.Write(","); WritePropertiesValues(properties, output); if (!_inlineFields) output.Write("}"); } /// <summary> /// Writes out the attached exception /// </summary> protected override void WriteException(Exception exception, ref string delim, TextWriter output) { output.Write(delim); output.Write("\""); output.Write("exceptions"); output.Write("\":["); delim = ""; this.WriteExceptionSerializationInfo(exception, ref delim, output, depth: 0); output.Write("]"); } private void WriteExceptionSerializationInfo(Exception exception, ref string delim, TextWriter output, int depth) { while (true) { output.Write(delim); output.Write("{"); delim = ""; WriteSingleException(exception, ref delim, output, depth); output.Write("}"); delim = ","; if (exception.InnerException != null && depth < 20) { exception = exception.InnerException; depth = ++depth; continue; } break; } } /// <summary> /// Writes the properties of a single exception, without inner exceptions /// Callers are expected to open and close the json object themselves. /// </summary> /// <param name="exception"></param> /// <param name="delim"></param> /// <param name="output"></param> /// <param name="depth"></param> protected void WriteSingleException(Exception exception, ref string delim, TextWriter output, int depth) { #if NO_SERIALIZATION var helpUrl = exception.HelpLink; var stackTrace = exception.StackTrace; var remoteStackTrace = string.Empty; var remoteStackIndex = -1; var exceptionMethod = string.Empty; var hresult = exception.HResult; var source = exception.Source; var className = string.Empty; #else var si = new SerializationInfo(exception.GetType(), new FormatterConverter()); var sc = new StreamingContext(); exception.GetObjectData(si, sc); var helpUrl = si.GetString("HelpURL"); var stackTrace = si.GetString("StackTraceString"); var remoteStackTrace = si.GetString("RemoteStackTraceString"); var remoteStackIndex = si.GetInt32("RemoteStackIndex"); var exceptionMethod = si.GetString("ExceptionMethod"); var hresult = si.GetInt32("HResult"); var source = si.GetString("Source"); var className = si.GetString("ClassName"); #endif //TODO Loop over ISerializable data this.WriteJsonProperty("Depth", depth, ref delim, output); this.WriteJsonProperty("ClassName", className, ref delim, output); this.WriteJsonProperty("Message", exception.Message, ref delim, output); this.WriteJsonProperty("Source", source, ref delim, output); if (_formatStackTraceAsArray) { this.WriteMultilineString("StackTrace", stackTrace, ref delim, output); this.WriteMultilineString("RemoteStackTrace", stackTrace, ref delim, output); } else { this.WriteJsonProperty("StackTraceString", stackTrace, ref delim, output); this.WriteJsonProperty("RemoteStackTraceString", remoteStackTrace, ref delim, output); } this.WriteJsonProperty("RemoteStackIndex", remoteStackIndex, ref delim, output); this.WriteStructuredExceptionMethod(exceptionMethod, ref delim, output); this.WriteJsonProperty("HResult", hresult, ref delim, output); this.WriteJsonProperty("HelpURL", helpUrl, ref delim, output); //writing byte[] will fall back to serializer and they differ in output //JsonNET assumes string, simplejson writes array of numerics. //Skip for now //this.WriteJsonProperty("WatsonBuckets", watsonBuckets, ref delim, output); } private void WriteMultilineString(string name, string value, ref string delimeter, TextWriter output) { var lines = value?.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) ?? new string[] { }; WriteJsonArrayProperty(name, lines, ref delimeter, output); } private void WriteStructuredExceptionMethod(string exceptionMethodString, ref string delim, TextWriter output) { if (string.IsNullOrWhiteSpace(exceptionMethodString)) return; var args = exceptionMethodString.Split('\0', '\n'); if (args.Length != 5) return; var memberType = Int32.Parse(args[0], CultureInfo.InvariantCulture); var name = args[1]; var assemblyName = args[2]; var className = args[3]; var signature = args[4]; var an = new AssemblyName(assemblyName); output.Write(delim); output.Write("\""); output.Write("ExceptionMethod"); output.Write("\":{"); delim = ""; this.WriteJsonProperty("Name", name, ref delim, output); this.WriteJsonProperty("AssemblyName", an.Name, ref delim, output); this.WriteJsonProperty("AssemblyVersion", an.Version.ToString(), ref delim, output); this.WriteJsonProperty("AssemblyCulture", an.CultureName, ref delim, output); this.WriteJsonProperty("ClassName", className, ref delim, output); this.WriteJsonProperty("Signature", signature, ref delim, output); this.WriteJsonProperty("MemberType", memberType, ref delim, output); output.Write("}"); delim = ","; } /// <summary> /// (Optionally) writes out the rendered message /// </summary> protected override void WriteRenderedMessage(string message, ref string delim, TextWriter output) { WriteJsonProperty(RenderedMessagePropertyName, message, ref delim, output); } /// <summary> /// Writes out the message template for the logevent. /// </summary> protected override void WriteMessageTemplate(string template, ref string delim, TextWriter output) { WriteJsonProperty(MessageTemplatePropertyName, template, ref delim, output); } /// <summary> /// Writes out the log level /// </summary> protected override void WriteLevel(LogEventLevel level, ref string delim, TextWriter output) { var stringLevel = Enum.GetName(typeof(LogEventLevel), level); WriteJsonProperty(LevelPropertyName, stringLevel, ref delim, output); } /// <summary> /// Writes out the log timestamp /// </summary> protected override void WriteTimestamp(DateTimeOffset timestamp, ref string delim, TextWriter output) { WriteJsonProperty(TimestampPropertyName, timestamp, ref delim, output); } /// <summary> /// Allows a subclass to write out objects that have no configured literal writer. /// </summary> /// <param name="value">The value to be written as a json construct</param> /// <param name="output">The writer to write on</param> protected override void WriteLiteralValue(object value, TextWriter output) { if (_serializer != null) { string jsonString = _serializer.SerializeToString(value); output.Write(jsonString); return; } base.WriteLiteralValue(value, output); } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; using System.Collections.Generic; public class DebugConsole : DebugLogger { #region Constants public const char ParameterStart = ' '; public delegate void ConsoleCallback(string commandEntered, DebugConsole console); const float MinInputHeight = 24; #endregion #region Variables static DebugConsole _DebugConsole; public float m_PercentageOfScreenTall = 0.4f; //public float m_InputPercentageTall = 0.05f; public int m_NumVisibleLines = 12; public bool m_DrawConsole = false; Dictionary<string, ConsoleCallback> m_CommandFunctionMap = new Dictionary<string, ConsoleCallback>(); // TextArea for command string string m_CommandString = string.Empty; // true draws the console to the screen bool m_bConsoleLoggingEnabled = true; List<string> m_PreviousCommands = new List<string>(); List<string> m_BrokenUpConsoleText = new List<string>(); // used for storage when breaking up text for the console that is too long int m_PreviousCommandIndex = 0; Image m_MainPanel; RectTransform m_LoggedTextContent; InputField m_InputField; ScrollRect m_ScrollRect; float m_PreferredFontSize; #if UNITY_EDITOR float m_TempPercentageOfScreenTall; int m_TempNumVisibleLines; #endif #endregion #region Properties public string CommandString { get { return m_CommandString; } set { m_InputField.text = m_CommandString = value; } } public float PercentageOfScreenTall { get { return m_PercentageOfScreenTall; } set { m_PercentageOfScreenTall = value; #if UNITY_EDITOR m_TempPercentageOfScreenTall = value; #endif m_MainPanel.rectTransform.offsetMax = new Vector2(0, -(Screen.height - (Screen.height * m_PercentageOfScreenTall))); } } public float InputFieldHeight { get { RectTransform fieldRect = m_InputField.GetComponent<RectTransform>(); return fieldRect.sizeDelta.y; } set { value = Mathf.Max(MinInputHeight, value); RectTransform fieldRect = m_InputField.GetComponent<RectTransform>(); fieldRect.sizeDelta = new Vector2(0, value/*m_InputPercentageTall*/); VHUI.StretchToParent(m_ScrollRect.GetComponent<RectTransform>(), 0, value, 0, 0); //m_InputField.textComponent.fontSize = (int)(fieldRect.rect.height * 0.5f); } } public int NumVisibleLines { get { return m_NumVisibleLines; } set { m_NumVisibleLines = value; #if UNITY_EDITOR m_TempNumVisibleLines = value; #endif m_PreferredFontSize = Mathf.Round(m_ScrollRect.GetComponent<RectTransform>().rect.height / (m_NumVisibleLines)); ResizeTextLog(); } } float CalculateInputFieldHeight { get { return m_PreferredFontSize * 1.2f; } } public bool DrawConsole { get { return m_DrawConsole; } } #endregion public static DebugConsole Get() { if (_DebugConsole == null) { _DebugConsole = Object.FindObjectOfType(typeof(DebugConsole)) as DebugConsole; } return _DebugConsole; } public void Awake() { transform.position = Vector3.zero; Canvas canvas = VHUI.CreateCanvas("DebugConsoleCanvas", this.gameObject, m_CanvasSortingOrder); // add ugui elements to the canvas // main panel m_MainPanel = VHUI.CreateImage("DebugConsoleUI", canvas.transform); m_MainPanel.color = new Color(0, 0, 0, 100f / 255f); VHUI.StretchToParent(m_MainPanel.rectTransform, 0, 0, 0, 0); m_MainPanel.rectTransform.pivot = new Vector2(0.5f, 0); PercentageOfScreenTall = m_PercentageOfScreenTall; // create scroll rect m_ScrollRect = VHUI.CreateScrollRect("Scroll View", m_MainPanel.transform, true); m_ScrollRect.scrollSensitivity = 10; VHUI.StretchToParent(m_ScrollRect.GetComponent<RectTransform>(), 0, Screen.height /** m_InputPercentageTall*/, 0, 0); m_ScrollRect.horizontal = false; m_ScrollRect.GetComponent<Image>().color = new Color(0, 0, 0, 100f / 255f); GameObject scrollContentGO = VHUtils.FindChildRecursive(m_ScrollRect.gameObject, "Content"); m_LoggedTextContent = scrollContentGO.GetComponent<RectTransform>(); VerticalLayoutGroup verticalLayout = m_LoggedTextContent.gameObject.AddComponent<VerticalLayoutGroup>(); verticalLayout.padding = new RectOffset(5, 5, 5, 5); verticalLayout.childForceExpandHeight = false; m_LoggedTextContent.GetComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize; // create input field m_InputField = VHUI.CreateInputField("ConsoleInput", m_MainPanel.transform, (string s) => InvokeCommand(s)); m_InputField.caretWidth = 3; RectTransform fieldRect = m_InputField.GetComponent<RectTransform>(); m_InputField.placeholder.GetComponent<Text>().resizeTextForBestFit = true; m_InputField.textComponent.resizeTextForBestFit = true; fieldRect.pivot = new Vector2(0, 0); VHUI.SetAnchors(fieldRect, 0, 0, 1, 0); fieldRect.position = new Vector3(0, 0, 0); NumVisibleLines = m_NumVisibleLines; InputFieldHeight = CalculateInputFieldHeight; m_MainPanel.gameObject.SetActive(m_DrawConsole); // allow unity output logs to go to the console LogCallbackHandler handler = GameObject.FindObjectOfType<LogCallbackHandler>(); if (handler) handler.AddCallback(HandleUnityLog); else Debug.LogWarning("DebugConsole: LogCallbackHandler component not found in the scene. Add one if you wish to display Unity Log() messages"); CreateUIText(m_LoggedTextContent.transform); #if UNITY_EDITOR m_TempPercentageOfScreenTall = m_PercentageOfScreenTall; m_TempNumVisibleLines = m_NumVisibleLines; #endif //StartCoroutine(Test()); AddText(" "); } IEnumerator Test() { yield return new WaitForEndOfFrame(); //yield return new WaitForEndOfFrame(); //yield return new WaitForEndOfFrame(); //yield return new WaitForEndOfFrame(); for (int i = 0; i < m_LoggedText.Length; i++) { m_LoggedText[i].gameObject.SetActive(true); } ResizeTextLog(); //Canvas.ForceUpdateCanvases(); for (int i = 0; i < m_LoggedText.Length; i++) { m_LoggedText[i].gameObject.SetActive(false); } AddText(" "); } public void AddCommandCallback(string commandString, ConsoleCallback cb) { commandString.ToLower(); if (0 == string.Compare(commandString, "help") || 0 == string.Compare(commandString, "?") || 0 == string.Compare(commandString, "clear") || 0 == string.Compare(commandString, "cls") || 0 == string.Compare(commandString, "q") || 0 == string.Compare(commandString, "quit") || 0 == string.Compare(commandString, "exit") || 0 == string.Compare(commandString, "enable_console_logging") ) { // reserved keywords commandString += " is a reserved keyword by the console."; //AddTextToLog(commandString); return; } if (m_CommandFunctionMap.ContainsKey(commandString)) { m_CommandFunctionMap[commandString] = cb; } else { m_CommandFunctionMap.Add(commandString, cb); } } public override void Update() { base.Update(); if (Input.GetKeyDown(KeyCode.BackQuote)) { ToggleConsole(); } if (m_DrawConsole) { if (Input.GetKeyDown(KeyCode.UpArrow)) { if (m_PreviousCommandIndex > 0) { CommandString = m_PreviousCommands[--m_PreviousCommandIndex]; } } else if (Input.GetKeyDown(KeyCode.DownArrow)) { if (m_PreviousCommandIndex < m_PreviousCommands.Count - 1) { CommandString = m_PreviousCommands[++m_PreviousCommandIndex]; } } else if (Input.GetKeyDown(KeyCode.PageUp)) { m_ScrollRect.verticalScrollbar.value += 0.1f; } else if (Input.GetKeyDown(KeyCode.PageDown)) { m_ScrollRect.verticalScrollbar.value -= 0.1f; } else if (Input.GetKeyDown(KeyCode.End)) { m_ScrollRect.verticalScrollbar.value = 0; } else if (Input.GetKeyDown(KeyCode.Home)) { m_ScrollRect.verticalScrollbar.value = 1; } } #if UNITY_EDITOR if (m_TempPercentageOfScreenTall != m_PercentageOfScreenTall) { PercentageOfScreenTall = m_PercentageOfScreenTall; } if (m_TempNumVisibleLines != m_NumVisibleLines) { NumVisibleLines = m_NumVisibleLines; } #endif } public void ToggleConsole() { m_DrawConsole = !m_DrawConsole; CommandString = string.Empty; m_MainPanel.gameObject.SetActive(m_DrawConsole); #if (!UNITY_ANDROID && !UNITY_IOS) || UNITY_EDITOR SelectInputField(); #endif if (m_DrawConsole) { m_ScrollRect.verticalScrollbar.value = 0; } } void SelectInputField() { m_InputField.ActivateInputField(); m_InputField.Select(); } void InvokeCommand(string command) { if (command == null) { return; } else { command = command.Trim(); command = command.Replace("\n", ""); //VHGUI.TextArea(m_CommandStringPosition, m_CommandString, Color.yellow); } #if (!UNITY_ANDROID && !UNITY_IOS) || UNITY_EDITOR SelectInputField(); #endif if (command == string.Empty) { return; } // format the string to get rid of extra ending spaces and multiple spaces in a row int spaceIndex = 0; do { spaceIndex = command.IndexOf(ParameterStart, spaceIndex); if (spaceIndex != -1) { ++spaceIndex; while (spaceIndex < command.Length && command[spaceIndex] == ParameterStart) { command = command.Remove(spaceIndex, 1); } } } while (spaceIndex != -1); if (command[0] == ParameterStart) { command = command.Remove(0, 1); } //bool commandExists = false; string commandStringWithoutParameters = command; string consoleLogString = commandStringWithoutParameters; // used for logging messages to console int uiIndex = commandStringWithoutParameters.IndexOf(ParameterStart); if (uiIndex != -1) { // we don't want to check parameters, we just want the command, commandStringWithoutParameters = commandStringWithoutParameters.Remove(uiIndex, command.Length - uiIndex); commandStringWithoutParameters = commandStringWithoutParameters.ToLower(); } if (m_CommandFunctionMap.ContainsKey(commandStringWithoutParameters)) { // this command string exists, call its function m_CommandFunctionMap[commandStringWithoutParameters](command, this); } else if (0 == string.Compare(command, "clear") || 0 == string.Compare(command, "cls")) { consoleLogString = string.Empty; ClearConsoleLog(true); } else if (0 == string.Compare(command, "help") || 0 == string.Compare(command, "?")) { // show all the commands available to them consoleLogString = "Commands Available: "; foreach (KeyValuePair<string, ConsoleCallback> kvp in m_CommandFunctionMap) { consoleLogString += " " + kvp.Key; } } else if (0 == string.Compare(command, "q") || 0 == string.Compare(command, "quit") || 0 == string.Compare(command, "exit")) { VHUtils.ApplicationQuit(); } else if (0 == string.Compare(commandStringWithoutParameters, "enable_console_logging")) { if (!ParseBool(command, ref m_bConsoleLoggingEnabled)) { AddText(command + " requires parameter '0' or '1'"); } } else { // command doesn't exist consoleLogString = commandStringWithoutParameters + " command doesn't exist. Type ? or help for a list of commands."; } // display what you wrote in the log AddText(consoleLogString); // add it so you can find it again with the arrow keys if (!m_PreviousCommands.Contains(command)) { //for (int i = 0; i < command.Length; i++) //{ // if (command[i] == '\n') // { // command = command.Remove(i, 1); // } //} m_PreviousCommands.Add(command); } m_PreviousCommandIndex = m_PreviousCommands.Count; CommandString = string.Empty; StartCoroutine(ForceScrollerToBottom()); } IEnumerator ForceScrollerToBottom() { // this is a hack to get the vertical scroller value to show the bottom line // unity forces me to wait for a few frames yield return new WaitForEndOfFrame(); yield return new WaitForEndOfFrame(); yield return new WaitForEndOfFrame(); m_ScrollRect.verticalScrollbar.value = 0; } void ClearConsoleLog(bool clearCache) { if (clearCache) { m_CachedText.Clear(); } for (int i = 0; i < m_LoggedTextContent.transform.childCount; i++) { m_LoggedTextContent.transform.GetChild(i).gameObject.SetActive(false); //m_LoggedTextContent.transform.GetChild(i).GetComponent<Text>().text = string.Empty; } } public void AddText(string text) { AddText(text, Color.white); } override public void AddText(string text, Color c, LogType logType) { AddText(text, c); } public void AddText(string text, Color color) { if (text == null || text == string.Empty || !m_bConsoleLoggingEnabled) { return; } m_CachedText.Add(new TextLine(text, color)); m_BrokenUpConsoleText = BreakUpTextLine(text); for (int i = 0; i < m_BrokenUpConsoleText.Count; i++) { string textCopy = m_BrokenUpConsoleText[i].Substring(0, Mathf.Min(m_BrokenUpConsoleText[i].Length, MaxTextLength)); //InputField inputField = m_LoggedText[m_TextCacheIndex]; Text loggedText = m_LoggedText[m_TextCacheIndex]; loggedText.color = color; loggedText.text = textCopy; loggedText.gameObject.SetActive(true); m_TextCacheIndex += 1; m_TextCacheIndex %= m_MaxLogCapacity; loggedText.transform.SetAsLastSibling(); } if (m_ScrollRect.verticalScrollbar.value == 0) { StartCoroutine(ForceScrollerToBottom()); } } protected override void RebuildDisplay() { NumVisibleLines = m_NumVisibleLines; ClearConsoleLog(false); //int w = Screen.width; List<TextLine> temp = new List<TextLine>(m_CachedText); m_CachedText.Clear(); foreach (TextLine ct in temp) { AddText(ct.text.Trim(), ct.color); } //ResizeTextLog(); } void ResizeText(Text loggedText) { //m_HolderText.fontSize = (int)((float)m_PreferredFontSize * m_FontScaler); m_HolderText.GetComponent<LayoutElement>().preferredHeight = m_PreferredFontSize; if (loggedText != null) { //loggedText.GetComponent<LayoutElement>().preferredHeight = m_PreferredFontSize; //loggedText.fontSize = (int)((float)m_PreferredFontSize * m_FontScaler); loggedText.GetComponent<LayoutElement>().preferredHeight = m_PreferredFontSize; } } void ResizeTextLog() { InputFieldHeight = CalculateInputFieldHeight; for (int i = 0; i < m_LoggedTextContent.transform.childCount; i++) { Transform child = m_LoggedTextContent.transform.GetChild(i); ResizeText(child.GetComponent<Text>()); } } // seperates 1 long line into multiple shorter lines in order to fit on the screen List<string> BreakUpTextLine(string text) { m_BrokenUpConsoleText.Clear(); // break up the lines by searching for newlings //Debug.Log("Screen.width: " + Screen.width); text = VHUI.InsertBreaks(text, m_HolderText.font, m_HolderText.fontSize, (int)((float)Screen.width * 0.95f)); string[] newLineSeperatedLines = text.Split('\n'); m_BrokenUpConsoleText.AddRange(newLineSeperatedLines); return m_BrokenUpConsoleText; } void HandleUnityLog(string logString, string stackTrace, LogType type) { switch (type) { case LogType.Error: AddText(logString, Color.red); break; case LogType.Warning: AddText(logString, Color.yellow); break; default: AddText(logString); break; } } #region String Parsing Functions // these are helper functions to get parameters out of the command string that was entered // i.e. in the string enable_lighting 1, 1 is the parameter // these functions return true if they succeeded in finding the respective parameter public bool ParseBool(string commandEntered, ref bool out_value) { bool success = false; string subString = ""; success = ParseSingleParameter(commandEntered, ref subString, 0); if (success) { success = bool.TryParse(subString, out out_value); if (!success) { // try one more time, see if they put a number instead of the words true or false int holder = 0; success = int.TryParse(subString, out holder); if (success) { out_value = holder == 0 ? false : true; } } } return success; } public bool ParseInt(string commandEntered, ref int out_value) { bool success = false; string subString = ""; success = ParseSingleParameter(commandEntered, ref subString, 0); if (success) { success = int.TryParse(subString, out out_value); } return success; } public bool ParseFloat(string commandEntered, ref float out_value) { bool success = false; string subString = ""; success = ParseSingleParameter(commandEntered, ref subString, 0); if (success) { success = float.TryParse(subString, out out_value); } return success; } public bool ParseVector2(string commandEntered, ref Vector2 out_value) { bool success = false; string subString = ""; int uiSearchStartIndex = 0, uiParamStartIndex = 0, uiParamEndIndex = 0; const int NumTimesToLoop = 2; for (int i = 0; i < NumTimesToLoop; i++) { success = ParseSingleParameter(commandEntered, ref subString, ref uiParamStartIndex, ref uiParamEndIndex, uiSearchStartIndex + uiParamEndIndex); if (success) { float val = 0; success = float.TryParse(subString, out val); out_value[i] = val; } if (!success) { break; } } return success; } public bool ParseVector3(string commandEntered, ref Vector3 out_value) { bool success = false; string subString = ""; int uiSearchStartIndex = 0, uiParamStartIndex = 0, uiParamEndIndex = 0; const int NumTimesToLoop = 3; for (int i = 0; i < NumTimesToLoop; i++) { success = ParseSingleParameter(commandEntered, ref subString, ref uiParamStartIndex, ref uiParamEndIndex, uiSearchStartIndex + uiParamEndIndex); if (success) { float val = 0; success = float.TryParse(subString, out val); out_value[i] = val; } if (!success) { break; } } return success; } public bool ParseVHMSG(string commandEntered, ref string out_opName, ref string out_arg) { bool success = false; //string subString = ""; int uiStartIndex = 0, uiEndIndex = 0, uiSearchStartIndex = 0; // start the the beginning of the string and look for the vhmsg opcode success = ParseSingleParameter(commandEntered, ref out_opName, ref uiStartIndex, ref uiEndIndex, uiSearchStartIndex); if (success) { // now try to find the argument if it has one by using the remainder of the string // this second check doesn't have to succeed because not all vhmsg's have arguments, some just use opcodes if (uiEndIndex < commandEntered.Length - 1 && uiEndIndex != -1) { out_arg = commandEntered.Substring(uiEndIndex + 1, commandEntered.Length - uiEndIndex - 1); } } return success; } // these are helper functions for the rest of the Parsing functions. public bool ParseSingleParameter(string commandEntered, ref string out_value, int uiSearchStartIndex) { int uiStartIndex = 0, uiEndIndex = 0; return ParseSingleParameter(commandEntered, ref out_value, ref uiStartIndex, ref uiEndIndex, uiSearchStartIndex); } public bool ParseSingleParameter(string commandEntered, ref string out_value, ref int out_uiParamStartIndex, ref int out_uiParamEndIndex, int uiSearchStartIndex) { bool success = false; // find where the parameter begins using the start delimiter out_uiParamStartIndex = commandEntered.IndexOf(ParameterStart, uiSearchStartIndex); if (out_uiParamStartIndex != -1 && out_uiParamStartIndex != commandEntered.Length - 1) { // now find where it ends out_uiParamEndIndex = commandEntered.IndexOf(ParameterStart, out_uiParamStartIndex + 1); if (out_uiParamEndIndex != -1) { out_value = commandEntered.Substring(out_uiParamStartIndex + 1, out_uiParamEndIndex - out_uiParamStartIndex - 1); } else { // there aren't anymore parameters, you've reached the end of the string out_value = commandEntered.Substring(out_uiParamStartIndex + 1/*, commandEntered.Length*/); } success = true; } return success; } #endregion }
using System; using UnityEngine; namespace InControl { public class InputDevice { public static readonly InputDevice Null = new InputDevice( "None" ); internal int SortOrder = int.MaxValue; public string Name { get; protected set; } public string Meta { get; protected set; } public ulong LastChangeTick { get; protected set; } public InputControl[] Controls { get; protected set; } public OneAxisInputControl LeftStickX { get; protected set; } public OneAxisInputControl LeftStickY { get; protected set; } public TwoAxisInputControl LeftStick { get; protected set; } public OneAxisInputControl RightStickX { get; protected set; } public OneAxisInputControl RightStickY { get; protected set; } public TwoAxisInputControl RightStick { get; protected set; } public OneAxisInputControl DPadX { get; protected set; } public OneAxisInputControl DPadY { get; protected set; } public TwoAxisInputControl DPad { get; protected set; } public InputControl Command { get; protected set; } public bool IsAttached { get; internal set; } internal bool RawSticks { get; set; } public InputDevice( string name ) { Name = name; Meta = ""; LastChangeTick = 0; const int numInputControlTypes = (int) InputControlType.Count + 1; Controls = new InputControl[numInputControlTypes]; LeftStickX = new OneAxisInputControl(); LeftStickY = new OneAxisInputControl(); LeftStick = new TwoAxisInputControl(); RightStickX = new OneAxisInputControl(); RightStickY = new OneAxisInputControl(); RightStick = new TwoAxisInputControl(); DPadX = new OneAxisInputControl(); DPadY = new OneAxisInputControl(); DPad = new TwoAxisInputControl(); Command = AddControl( InputControlType.Command, "Command" ); } public bool HasControl( InputControlType inputControlType ) { return Controls[(int) inputControlType] != null; } public InputControl GetControl( InputControlType inputControlType ) { var control = Controls[(int) inputControlType]; return control ?? InputControl.Null; } // Warning: this is super inefficient. Don't use it unless you have to, m'kay? public static InputControlType GetInputControlTypeByName( string inputControlName ) { return (InputControlType) Enum.Parse( typeof(InputControlType), inputControlName ); } // Warning: this is super inefficient. Don't use it unless you have to, m'kay? public InputControl GetControlByName( string inputControlName ) { var inputControlType = GetInputControlTypeByName( inputControlName ); return GetControl( inputControlType ); } public InputControl AddControl( InputControlType inputControlType, string handle ) { var inputControl = new InputControl( handle, inputControlType ); Controls[(int) inputControlType] = inputControl; return inputControl; } public InputControl AddControl( InputControlType inputControlType, string handle, float lowerDeadZone, float upperDeadZone ) { var inputControl = AddControl( inputControlType, handle ); inputControl.LowerDeadZone = lowerDeadZone; inputControl.UpperDeadZone = upperDeadZone; return inputControl; } public void ClearInputState() { LeftStickX.ClearInputState(); LeftStickY.ClearInputState(); LeftStick.ClearInputState(); RightStickX.ClearInputState(); RightStickY.ClearInputState(); RightStick.ClearInputState(); DPadX.ClearInputState(); DPadY.ClearInputState(); DPad.ClearInputState(); var controlCount = Controls.Length; for (int i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null) { control.ClearInputState(); } } } internal void UpdateWithState( InputControlType inputControlType, bool state, ulong updateTick, float deltaTime ) { GetControl( inputControlType ).UpdateWithState( state, updateTick, deltaTime ); } internal void UpdateWithValue( InputControlType inputControlType, float value, ulong updateTick, float deltaTime ) { GetControl( inputControlType ).UpdateWithValue( value, updateTick, deltaTime ); } internal void UpdateLeftStickWithValue( Vector2 value, ulong updateTick, float deltaTime ) { LeftStickLeft.UpdateWithValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); LeftStickRight.UpdateWithValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { LeftStickUp.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { LeftStickUp.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void UpdateLeftStickWithRawValue( Vector2 value, ulong updateTick, float deltaTime ) { LeftStickLeft.UpdateWithRawValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); LeftStickRight.UpdateWithRawValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { LeftStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { LeftStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void CommitLeftStick() { LeftStickUp.Commit(); LeftStickDown.Commit(); LeftStickLeft.Commit(); LeftStickRight.Commit(); } internal void UpdateRightStickWithValue( Vector2 value, ulong updateTick, float deltaTime ) { RightStickLeft.UpdateWithValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); RightStickRight.UpdateWithValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { RightStickUp.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { RightStickUp.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void UpdateRightStickWithRawValue( Vector2 value, ulong updateTick, float deltaTime ) { RightStickLeft.UpdateWithRawValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); RightStickRight.UpdateWithRawValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { RightStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { RightStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void CommitRightStick() { RightStickUp.Commit(); RightStickDown.Commit(); RightStickLeft.Commit(); RightStickRight.Commit(); } public virtual void Update( ulong updateTick, float deltaTime ) { // Implemented by subclasses. } bool AnyCommandControlIsPressed() { for (int i = (int) InputControlType.Back; i <= (int) InputControlType.Power; i++) { var control = Controls[i]; if (control != null && control.IsPressed) { return true; } } return false; } internal void ProcessLeftStick( ulong updateTick, float deltaTime ) { var x = Utility.ValueFromSides( LeftStickLeft.NextRawValue, LeftStickRight.NextRawValue ); var y = Utility.ValueFromSides( LeftStickDown.NextRawValue, LeftStickUp.NextRawValue, InputManager.InvertYAxis ); Vector2 v; if (RawSticks) { v = new Vector2( x, y ); } else { var lowerDeadZone = Utility.Max( LeftStickLeft.LowerDeadZone, LeftStickRight.LowerDeadZone, LeftStickUp.LowerDeadZone, LeftStickDown.LowerDeadZone ); var upperDeadZone = Utility.Min( LeftStickLeft.UpperDeadZone, LeftStickRight.UpperDeadZone, LeftStickUp.UpperDeadZone, LeftStickDown.UpperDeadZone ); v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); } LeftStick.Raw = true; LeftStick.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); LeftStickX.Raw = true; LeftStickX.CommitWithValue( v.x, updateTick, deltaTime ); LeftStickY.Raw = true; LeftStickY.CommitWithValue( v.y, updateTick, deltaTime ); LeftStickLeft.SetValue( LeftStick.Left.Value, updateTick ); LeftStickRight.SetValue( LeftStick.Right.Value, updateTick ); LeftStickUp.SetValue( LeftStick.Up.Value, updateTick ); LeftStickDown.SetValue( LeftStick.Down.Value, updateTick ); } internal void ProcessRightStick( ulong updateTick, float deltaTime ) { var x = Utility.ValueFromSides( RightStickLeft.NextRawValue, RightStickRight.NextRawValue ); var y = Utility.ValueFromSides( RightStickDown.NextRawValue, RightStickUp.NextRawValue, InputManager.InvertYAxis ); Vector2 v; if (RawSticks) { v = new Vector2( x, y ); } else { var lowerDeadZone = Utility.Max( RightStickLeft.LowerDeadZone, RightStickRight.LowerDeadZone, RightStickUp.LowerDeadZone, RightStickDown.LowerDeadZone ); var upperDeadZone = Utility.Min( RightStickLeft.UpperDeadZone, RightStickRight.UpperDeadZone, RightStickUp.UpperDeadZone, RightStickDown.UpperDeadZone ); v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); } RightStick.Raw = true; RightStick.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); RightStickX.Raw = true; RightStickX.CommitWithValue( v.x, updateTick, deltaTime ); RightStickY.Raw = true; RightStickY.CommitWithValue( v.y, updateTick, deltaTime ); RightStickLeft.SetValue( RightStick.Left.Value, updateTick ); RightStickRight.SetValue( RightStick.Right.Value, updateTick ); RightStickUp.SetValue( RightStick.Up.Value, updateTick ); RightStickDown.SetValue( RightStick.Down.Value, updateTick ); } internal void ProcessDPad( ulong updateTick, float deltaTime ) { var lowerDeadZone = Utility.Max( DPadLeft.LowerDeadZone, DPadRight.LowerDeadZone, DPadUp.LowerDeadZone, DPadDown.LowerDeadZone ); var upperDeadZone = Utility.Min( DPadLeft.UpperDeadZone, DPadRight.UpperDeadZone, DPadUp.UpperDeadZone, DPadDown.UpperDeadZone ); var x = Utility.ValueFromSides( DPadLeft.NextRawValue, DPadRight.NextRawValue ); var y = Utility.ValueFromSides( DPadDown.NextRawValue, DPadUp.NextRawValue, InputManager.InvertYAxis ); var v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); DPad.Raw = true; DPad.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); DPadX.Raw = true; DPadX.CommitWithValue( v.x, updateTick, deltaTime ); DPadY.Raw = true; DPadY.CommitWithValue( v.y, updateTick, deltaTime ); DPadLeft.SetValue( DPad.Left.Value, updateTick ); DPadRight.SetValue( DPad.Right.Value, updateTick ); DPadUp.SetValue( DPad.Up.Value, updateTick ); DPadDown.SetValue( DPad.Down.Value, updateTick ); } public void Commit( ulong updateTick, float deltaTime ) { // We need to do some processing to ensure all the various objects // holding directional values are calculated optimally with circular // deadzones and then set properly everywhere. ProcessLeftStick( updateTick, deltaTime ); ProcessRightStick( updateTick, deltaTime ); ProcessDPad( updateTick, deltaTime ); // Next, commit all control values. int controlCount = Controls.Length; for (int i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null) { control.Commit(); if (control.HasChanged) { LastChangeTick = updateTick; } } } // Calculate the "Command" control for known controllers and commit it. if (IsKnown) { Command.CommitWithState( AnyCommandControlIsPressed(), updateTick, deltaTime ); } } public bool LastChangedAfter( InputDevice otherDevice ) { return LastChangeTick > otherDevice.LastChangeTick; } internal void RequestActivation() { LastChangeTick = InputManager.CurrentTick; } public virtual void Vibrate( float leftMotor, float rightMotor ) { } public void Vibrate( float intensity ) { Vibrate( intensity, intensity ); } public void StopVibration() { Vibrate( 0.0f ); } public virtual bool IsSupportedOnThisPlatform { get { return true; } } public virtual bool IsKnown { get { return true; } } public bool IsUnknown { get { return !IsKnown; } } public bool MenuWasPressed { get { return GetControl( InputControlType.Command ).WasPressed; } } public InputControl AnyButton { get { int controlCount = Controls.GetLength( 0 ); for (int i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null && control.IsButton && control.IsPressed) { return control; } } return InputControl.Null; } } public InputControl LeftStickUp { get { return GetControl( InputControlType.LeftStickUp ); } } public InputControl LeftStickDown { get { return GetControl( InputControlType.LeftStickDown ); } } public InputControl LeftStickLeft { get { return GetControl( InputControlType.LeftStickLeft ); } } public InputControl LeftStickRight { get { return GetControl( InputControlType.LeftStickRight ); } } public InputControl RightStickUp { get { return GetControl( InputControlType.RightStickUp ); } } public InputControl RightStickDown { get { return GetControl( InputControlType.RightStickDown ); } } public InputControl RightStickLeft { get { return GetControl( InputControlType.RightStickLeft ); } } public InputControl RightStickRight { get { return GetControl( InputControlType.RightStickRight ); } } public InputControl DPadUp { get { return GetControl( InputControlType.DPadUp ); } } public InputControl DPadDown { get { return GetControl( InputControlType.DPadDown ); } } public InputControl DPadLeft { get { return GetControl( InputControlType.DPadLeft ); } } public InputControl DPadRight { get { return GetControl( InputControlType.DPadRight ); } } public InputControl Action1 { get { return GetControl( InputControlType.Action1 ); } } public InputControl Action2 { get { return GetControl( InputControlType.Action2 ); } } public InputControl Action3 { get { return GetControl( InputControlType.Action3 ); } } public InputControl Action4 { get { return GetControl( InputControlType.Action4 ); } } public InputControl LeftTrigger { get { return GetControl( InputControlType.LeftTrigger ); } } public InputControl RightTrigger { get { return GetControl( InputControlType.RightTrigger ); } } public InputControl LeftBumper { get { return GetControl( InputControlType.LeftBumper ); } } public InputControl RightBumper { get { return GetControl( InputControlType.RightBumper ); } } public InputControl LeftStickButton { get { return GetControl( InputControlType.LeftStickButton ); } } public InputControl RightStickButton { get { return GetControl( InputControlType.RightStickButton ); } } public TwoAxisInputControl Direction { get { return DPad.UpdateTick > LeftStick.UpdateTick ? DPad : LeftStick; } } public static implicit operator bool( InputDevice device ) { return device != null; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using DBlog.TransitData; using System.Text; using System.Collections.Generic; using DBlog.Tools.Web; using System.Text.RegularExpressions; using DBlog.Tools.Drawing.Exif; using DBlog.Tools.Drawing; using System.IO; using System.Drawing; using DBlog.Data.Hibernate; public partial class ShowImage : BlogPage { private TransitPostImage mPostImage = null; private int mImageId = 0; private EXIFMetaData mEXIFMetaData = null; public int ImageId { get { return DBlog.Tools.Web.ViewState<int>.GetViewStateValue( ViewState, string.Format("{0}:ImageId", ID), mImageId); } set { DBlog.Tools.Web.ViewState<int>.SetViewStateValue( EnableViewState, ViewState, string.Format("{0}:ImageId", ID), value, ref mImageId); } } public TransitPostImage PostImage { get { return mPostImage; } set { mPostImage = value; ImageId = mPostImage.Image.Id; } } public bool PreferredOnly { get { object p = Request["PreferredOnly"]; if (p == null) return false; bool pb = false; bool.TryParse(p.ToString(), out pb); return pb; } } public bool HasAccess { get { int pid = GetId("pid"); if (pid == 0) return true; string key = string.Format("{0}:{1}:PostAccess", SessionManager.PostTicket, pid); object result = Cache[key]; if (result == null) { result = SessionManager.BlogService.HasAccessToPost( SessionManager.PostTicket, pid); Cache.Insert(key, result, null, DateTime.Now.AddHours(1), TimeSpan.Zero); } return (bool)result; } } protected void Page_Load(object sender, EventArgs e) { try { if (!HasAccess) { Response.Redirect(string.Format("./Login.aspx?r={0}&cookie={1}&access=denied", Renderer.UrlEncode(UrlPathAndQuery), SessionManager.sDBlogPostCookieName)); } comments.OnGetDataSource += new EventHandler(comments_OnGetDataSource); images.OnGetDataSource += new EventHandler(images_OnGetDataSource); if (!IsPostBack) { GetDataImages(sender, e); if (PostImage != null) { Page.Title = string.Format("{0} - {1}", SessionManager.GetSetting( "title", "Blog"), Renderer.Render(PostImage.Image.Name)); } } } catch (Exception ex) { ReportException(ex); } } public void comments_OnGetDataSource(object sender, EventArgs e) { if (PostImage == null) return; panelComments.Update(); comments.DataSource = SessionManager.GetCachedCollection<TransitImageComment>( "GetImageComments", SessionManager.PostTicket, new TransitImageCommentQueryOptions( PostImage.Image.Id, comments.AllowPaging ? comments.PageSize : 0, comments.AllowPaging ? comments.CurrentPageIndex : 0)); } public void GetDataImages(object sender, EventArgs e) { images.CurrentPageIndex = 0; int pid = GetId("pid"); int index = GetId("index"); if (RequestId > 0) { if (pid > 0) { TransitPostImageQueryOptions options = new TransitPostImageQueryOptions(pid); options.PreferredOnly = PreferredOnly; images.CurrentPageIndex = index; images.VirtualItemCount = SessionManager.GetCachedCollectionCount<TransitImage>( "GetPostImagesCountEx", SessionManager.PostTicket, options); } else { images.VirtualItemCount = 1; } } images_OnGetDataSource(sender, e); images.DataBind(); panelImages.Update(); } public void GetDataComments(object sender, EventArgs e) { if (PostImage == null) return; labelName.Text = PostImage.Image.Name; if (SessionManager.CountersEnabled) { labelCount.Text = string.Format("{0} Click{1}", PostImage.Image.Counter.Count, PostImage.Image.Counter.Count != 1 ? "s" : string.Empty); } else { labelCount.Visible = false; } panelPicture.Update(); comments.Visible = (PostImage.Image.CommentsCount > 0); comments.CurrentPageIndex = 0; comments.VirtualItemCount = SessionManager.GetCachedCollectionCount<TransitImageComment>( "GetImageCommentsCount", SessionManager.PostTicket, new TransitImageCommentQueryOptions(PostImage.Image.Id)); comments_OnGetDataSource(sender, e); comments.DataBind(); panelComments.Update(); } public EXIFMetaData ImageEXIFMetaData { get { if (mEXIFMetaData == null) { TransitImage image = SessionManager.GetCachedObject<TransitImage>( "GetImageWithBitmapById", SessionManager.PostTicket, ImageId); if (image.Data != null) { mEXIFMetaData = new EXIFMetaData(new Bitmap( new MemoryStream(image.Data)).PropertyItems); } else if (image.Data == null && ! string.IsNullOrEmpty(image.Path)) { mEXIFMetaData = new EXIFMetaData(new Bitmap(Path.Combine(Path.Combine( SessionManager.GetSetting("Images", string.Empty), image.Path), image.Name)).PropertyItems); } } return mEXIFMetaData; } } void images_OnGetDataSource(object sender, EventArgs e) { int pid = GetId("pid"); List<TransitPostImage> list = null; if (pid > 0) { TransitPostImageQueryOptions options = new TransitPostImageQueryOptions( pid, images.PageSize, images.CurrentPageIndex); options.PreferredOnly = PreferredOnly; string sortexpression = Request.Params["SortExpression"]; string sortdirection = Request.Params["SortDirection"]; if (!string.IsNullOrEmpty(sortexpression)) options.SortExpression = sortexpression; if (!string.IsNullOrEmpty(sortdirection)) options.SortDirection = (WebServiceQuerySortDirection)Enum.Parse( typeof(WebServiceQuerySortDirection), sortdirection); list = SessionManager.GetCachedCollection<TransitPostImage>( "GetPostImagesEx", SessionManager.PostTicket, options); } else { TransitImage image = SessionManager.GetCachedObject<TransitImage>( "GetImageById", SessionManager.PostTicket, RequestId); TransitPostImage postimage = new TransitPostImage(); postimage.Image = image; postimage.Post = null; postimage.Id = RequestId; list = new List<TransitPostImage>(); list.Add(postimage); } linkBack.NavigateUrl = ReturnUrl; if (list.Count > 0) { PostImage = list[0]; /* linkComment.NavigateUrl = string.Format("EditImageComment.aspx?sid={0}&r={1}", PostImage.Image.Id, Renderer.UrlEncode(UrlPathAndQuery)); */ } GetEXIFData(sender, e); GetDataComments(sender, e); images.DataSource = list; } public string GetImageLink(string name, int comments_count) { StringBuilder result = new StringBuilder(name); if (comments_count > 0) { result.AppendFormat(" | {0} Comment{1}", comments_count, comments_count != 1 ? "s" : string.Empty); } return result.ToString(); } public string ReturnUrl { get { string result = Request.QueryString["r"]; int pid = GetId("pid"); if (string.IsNullOrEmpty(result) && (pid > 0)) return string.Format("./ShowPost.aspx?id={0}&PreferredOnly={1}", pid, PreferredOnly); if (string.IsNullOrEmpty(result)) return "."; return result; } } public void GetEXIFData(object sender, EventArgs e) { if (exif.Visible) { EXIFMetaData metadata = ImageEXIFMetaData; exif.DataSource = (metadata != null) ? metadata.EXIFPropertyItems : null; exif.DataBind(); } panelEXIF.Update(); } public void linkEXIF_Click(object sender, EventArgs e) { try { exif.Visible = !exif.Visible; GetEXIFData(sender, e); } catch (Exception ex) { ReportException(ex); } } public void comments_ItemCommand(object sender, DataGridCommandEventArgs e) { try { switch (e.CommandName) { case "Delete": SessionManager.BlogService.DeleteComment(SessionManager.Ticket, int.Parse(e.CommandArgument.ToString())); SessionManager.Invalidate<TransitImageComment>(); SessionManager.Invalidate<TransitComment>(); GetDataImages(sender, e); break; } } catch (Exception ex) { ReportException(ex); } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Removed warnings * */ #region Using directives #define USE_TRACING using System; using System.IO; using System.Net; using System.Text; using System.Collections; using System.ComponentModel; #endregion ///////////////////////////////////////////////////////////////////// // <summary>contains GDataRequest, our thin wrapper class for request/response // </summary> //////////////////////////////////////////////////////////////////// namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary>constants for the authentication handler /// </summary> ////////////////////////////////////////////////////////////////////// public static class GoogleAuthentication { /// <summary>account prefix path </summary> public const string AccountPrefix = "/accounts"; /// <summary>protocol </summary> public const string DefaultProtocol = "https"; /// <summary> /// default authentication domain /// </summary> public const string DefaultDomain = "www.google.com"; /// <summary>Google client authentication handler</summary> public const string UriHandler = "https://www.google.com/accounts/ClientLogin"; /// <summary>Google client authentication email</summary> public const string Email = "Email"; /// <summary>Google client authentication password</summary> public const string Password = "Passwd"; /// <summary>Google client authentication source constant</summary> public const string Source = "source"; /// <summary>Google client authentication default service constant</summary> public const string Service = "service"; /// <summary>Google client authentication LSID</summary> public const string Lsid = "LSID"; /// <summary>Google client authentication SSID</summary> public const string Ssid = "SSID"; /// <summary>Google client authentication Token</summary> public const string AuthToken = "Auth"; /// <summary>Google authSub authentication Token</summary> public const string AuthSubToken = "Token"; /// <summary>Google client header</summary> public const string Header = "Authorization: GoogleLogin auth="; /// <summary>Google method override header</summary> public const string Override = "X-HTTP-Method-Override"; /// <summary>Google webkey identifier</summary> public const string WebKey = "X-Google-Key: key="; /// <summary>Google YouTube client identifier</summary> public const string YouTubeClientId = "X-GData-Client:"; /// <summary>Google YouTube developer identifier</summary> public const string YouTubeDevKey = "X-GData-Key: key="; /// <summary>Google webkey identifier</summary> public const string AccountType = "accountType="; /// <summary>default value for the account type</summary> public const string AccountTypeDefault = "HOSTED_OR_GOOGLE"; /// <summary>captcha url token</summary> public const string CaptchaAnswer = "logincaptcha"; /// <summary>default value for the account type</summary> public const string CaptchaToken = "logintoken"; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>base GDataRequestFactory implementation</summary> ////////////////////////////////////////////////////////////////////// public class GDataGAuthRequestFactory : GDataRequestFactory, IVersionAware { /// <summary> /// the header used to indicate version requests /// </summary> public const string GDataVersion = "GData-Version"; private string gAuthToken; // we want to remember the token here private string handler; // so the handler is useroverridable, good for testing private string gService; // the service we pass to Gaia for token creation private string applicationName; // the application name we pass to Gaia and append to the user-agent private bool fMethodOverride; // to override using post, or to use PUT/DELETE private int numberOfRetries; // holds the number of retries the request will undertake private bool fStrictRedirect; // indicates if redirects should be handled strictly private string accountType; // indicates the accountType to use private string captchaAnswer; // indicates the captcha Answer in a challenge private string captchaToken; // indicates the captchaToken in a challenge private const int RetryCount = 3; // default retry count for failed requests ////////////////////////////////////////////////////////////////////// /// <summary>default constructor</summary> ////////////////////////////////////////////////////////////////////// public GDataGAuthRequestFactory(string service, string applicationName) : this(service, applicationName, RetryCount) { } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>overloaded constructor</summary> ////////////////////////////////////////////////////////////////////// public GDataGAuthRequestFactory(string service, string applicationName, int numberOfRetries) : base(applicationName) { this.Service = service; this.ApplicationName = applicationName; this.NumberOfRetries = numberOfRetries; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>default constructor</summary> ////////////////////////////////////////////////////////////////////// public override IGDataRequest CreateRequest(GDataRequestType type, Uri uriTarget) { return new GDataGAuthRequest(type, uriTarget, this); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Get/Set accessor for gAuthToken</summary> ////////////////////////////////////////////////////////////////////// public string GAuthToken { get {return this.gAuthToken;} set { Tracing.TraceMsg("set token called with: " + value); this.gAuthToken = value; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Get's an authentication token for the current credentials</summary> ////////////////////////////////////////////////////////////////////// public string QueryAuthToken(GDataCredentials gc) { GDataGAuthRequest request = new GDataGAuthRequest(GDataRequestType.Query, null, this); return request.QueryAuthToken(gc); } ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string UserAgent, with GFE support</summary> /// <remarks>GFE will enable gzip support ONLY for browser that have the string /// "gzip" in their user agent (IE or Mozilla), since lot of browsers have a /// broken gzip support.</remarks> //////////////////////////////////////////////////////////////////////////////// public override string UserAgent { get { return (base.UserAgent + (this.UseGZip == true ? " (gzip)" : "")); } set { base.UserAgent = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>Get/Set accessor for the application name</summary> ////////////////////////////////////////////////////////////////////// public string ApplicationName { get {return this.applicationName == null ? "" : this.applicationName;} set {this.applicationName = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>returns the service string</summary> ////////////////////////////////////////////////////////////////////// public string Service { get {return this.gService;} set {this.gService = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Let's assume you are behind a corporate firewall that does not /// allow all HTTP verbs (as you know, the atom protocol uses GET, /// POST, PUT and DELETE). If you set MethodOverride to true, /// PUT and DELETE will be simulated using HTTP Post. It will /// add an X-Method-Override header to the request that /// indicates the "real" method we wanted to send. /// </summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public bool MethodOverride { get {return this.fMethodOverride;} set {this.fMethodOverride = value;} } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>indicates if a redirect should be followed on not HTTPGet</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public bool StrictRedirect { get {return this.fStrictRedirect;} set {this.fStrictRedirect = value;} } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// property accessor to adjust how often a request of this factory should retry /// </summary> public int NumberOfRetries { get { return this.numberOfRetries; } set { this.numberOfRetries = value; } } /// <summary> /// property accessor to set the account type that is used during /// authentication. Defaults, if not set, to HOSTED_OR_GOOGLE /// </summary> public string AccountType { get { return this.accountType; } set { this.accountType = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>property to hold the Answer for a challenge</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string CaptchaAnswer { get {return this.captchaAnswer;} set {this.captchaAnswer = value;} } // end of accessor public string CaptchaUrl ////////////////////////////////////////////////////////////////////// /// <summary>property to hold the token for a challenge</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string CaptchaToken { get {return this.captchaToken;} set {this.captchaToken = value;} } // end of accessor public string CaptchaToken ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Handler</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Handler { get { return this.handler!=null ? this.handler : GoogleAuthentication.UriHandler; } set {this.handler = value;} } ///////////////////////////////////////////////////////////////////////////// private VersionInformation versionInfo = new VersionInformation(); /// <summary> /// returns the major protocol version number this element /// is working against. /// </summary> /// <returns></returns> public int ProtocolMajor { get { return this.versionInfo.ProtocolMajor; } set { this.versionInfo.ProtocolMajor = value; } } /// <summary> /// returns the minor protocol version number this element /// is working against. /// </summary> /// <returns></returns> public int ProtocolMinor { get { return this.versionInfo.ProtocolMinor; } set { this.versionInfo.ProtocolMinor = value; } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>base GDataRequest implementation</summary> ////////////////////////////////////////////////////////////////////// public class GDataGAuthRequest : GDataRequest { /// <summary>holds the input in memory stream</summary> private MemoryStream requestCopy; /// <summary>holds the factory instance</summary> private GDataGAuthRequestFactory factory; private AsyncData asyncData; private VersionInformation responseVersion; ////////////////////////////////////////////////////////////////////// /// <summary>default constructor</summary> ////////////////////////////////////////////////////////////////////// internal GDataGAuthRequest(GDataRequestType type, Uri uriTarget, GDataGAuthRequestFactory factory) : base(type, uriTarget, factory as GDataRequestFactory) { // need to remember the factory, so that we can pass the new authtoken back there if need be this.factory = factory; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>returns the writable request stream</summary> /// <returns> the stream to write into</returns> ////////////////////////////////////////////////////////////////////// public override Stream GetRequestStream() { this.requestCopy = new MemoryStream(); return this.requestCopy; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Read only accessor for requestCopy</summary> ////////////////////////////////////////////////////////////////////// internal Stream RequestCopy { get {return this.requestCopy;} } ///////////////////////////////////////////////////////////////////////////// internal AsyncData AsyncData { set { this.asyncData = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>does the real disposition</summary> /// <param name="disposing">indicates if dispose called it or finalize</param> ////////////////////////////////////////////////////////////////////// protected override void Dispose(bool disposing) { base.Dispose(disposing); if (this.disposed == true) { return; } if (disposing == true) { if (this.requestCopy != null) { this.requestCopy.Close(); this.requestCopy = null; } this.disposed = true; } } ////////////////////////////////////////////////////////////////////// /// <summary>sets up the correct credentials for this call, pending /// security scheme</summary> ////////////////////////////////////////////////////////////////////// protected override void EnsureCredentials() { Tracing.Assert(this.Request!= null, "We should have a webrequest now"); if (this.Request == null) { return; } // if the token is NULL, we need to get a token. if (this.factory.GAuthToken == null) { // we will take the standard credentials for that GDataCredentials gc = this.Credentials; Tracing.TraceMsg(gc == null ? "No Network credentials set" : "Network credentials found"); if (gc != null) { // only now we have something to do... this.factory.GAuthToken = QueryAuthToken(gc); } } if (this.factory.GAuthToken != null && this.factory.GAuthToken.Length > 0) { // Tracing.Assert(this.factory.GAuthToken != null, "We should have a token now"); Tracing.TraceMsg("Using auth token: " + this.factory.GAuthToken); string strHeader = GoogleAuthentication.Header + this.factory.GAuthToken; this.Request.Headers.Add(strHeader); } } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// returns the version information that the response indicated /// can be NULL if used against a non versioned endpoint /// </summary> internal VersionInformation ResponseVersion { get { return this.responseVersion; } } ////////////////////////////////////////////////////////////////////// /// <summary>sets the redirect to false after everything else /// is done </summary> ////////////////////////////////////////////////////////////////////// protected override void EnsureWebRequest() { base.EnsureWebRequest(); HttpWebRequest http = this.Request as HttpWebRequest; if (http != null) { http.Headers.Remove(GDataGAuthRequestFactory.GDataVersion); // as we are doublebuffering due to redirect issues anyhow, // disallow the default buffering http.AllowWriteStreamBuffering = false; IVersionAware v = this.factory as IVersionAware; if (v != null) { // need to add the version header to the request http.Headers.Add(GDataGAuthRequestFactory.GDataVersion, v.ProtocolMajor.ToString() + "." + v.ProtocolMinor.ToString()); } // we do not want this to autoredirect, our security header will be // lost in that case http.AllowAutoRedirect = false; if (this.factory.MethodOverride == true && http.Method != HttpMethods.Get && http.Method != HttpMethods.Post) { // remove it, if it is already there. http.Headers.Remove(GoogleAuthentication.Override); // cache the method, because Mono will complain if we try // to open the request stream with a DELETE method. string currentMethod = http.Method; http.Headers.Add(GoogleAuthentication.Override, currentMethod); http.Method = HttpMethods.Post; // not put and delete, all is post if (currentMethod == HttpMethods.Delete) { http.ContentLength = 0; // .NET CF won't send the ContentLength parameter if no stream // was opened. So open a dummy one, and close it right after. Stream req = http.GetRequestStream(); req.Close(); } } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>goes to the Google auth service, and gets a new auth token</summary> /// <returns>the auth token, or NULL if none received</returns> ////////////////////////////////////////////////////////////////////// internal string QueryAuthToken(GDataCredentials gc) { Uri authHandler = null; // need to copy this to a new object to avoid that people mix and match // the old (factory) and the new (requestsettings) and get screwed. So // copy the settings from the gc passed in and mix with the settings from the factory GDataCredentials gdc = new GDataCredentials(gc.Username, gc.getPassword()); gdc.CaptchaToken = this.factory.CaptchaToken; gdc.CaptchaAnswer = this.factory.CaptchaAnswer; gdc.AccountType = this.factory.AccountType; try { authHandler = new Uri(this.factory.Handler); } catch { throw new GDataRequestException("Invalid authentication handler URI given"); } return Utilities.QueryClientLoginToken(gdc, this.factory.Service, this.factory.ApplicationName, this.factory.KeepAlive, authHandler); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Executes the request and prepares the response stream. Also /// does error checking</summary> ////////////////////////////////////////////////////////////////////// public override void Execute() { // call him the first time Execute(1); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Executes the request and prepares the response stream. Also /// does error checking</summary> /// <param name="retryCounter">indicates the n-th time this is run</param> ////////////////////////////////////////////////////////////////////// protected void Execute(int retryCounter) { Tracing.TraceCall("GoogleAuth: Execution called"); try { CopyRequestData(); base.Execute(); if (this.Response is HttpWebResponse) { HttpWebResponse response = this.Response as HttpWebResponse; this.responseVersion = new VersionInformation(response.Headers[GDataGAuthRequestFactory.GDataVersion]); } } catch (GDataForbiddenException) { Tracing.TraceMsg("need to reauthenticate, got a forbidden back"); // do it again, once, reset AuthToken first and streams first Reset(); this.factory.GAuthToken = null; CopyRequestData(); base.Execute(); } catch (GDataRedirectException re) { // we got a redirect. Tracing.TraceMsg("Got a redirect to: " + re.Location); // only reset the base, the auth cookie is still valid // and cookies are stored in the factory if (this.factory.StrictRedirect == true) { HttpWebRequest http = this.Request as HttpWebRequest; if (http != null) { // only redirect for GET, else throw if (http.Method != HttpMethods.Get) { throw; } } } // verify that there is a non empty location string if (re.Location.Trim().Length == 0) { throw; } Reset(); this.TargetUri = new Uri(re.Location); CopyRequestData(); base.Execute(); } catch (GDataRequestException) { if (retryCounter > this.factory.NumberOfRetries) { Tracing.TraceMsg("Number of retries exceeded"); throw; } Tracing.TraceMsg("Let's retry this"); // only reset the base, the auth cookie is still valid // and cookies are stored in the factory Reset(); this.Execute(retryCounter + 1); } catch (Exception e) { Tracing.TraceCall("*** EXCEPTION " + e.GetType().Name + " CAUGTH ***"); throw; } finally { if (this.requestCopy != null) { this.requestCopy.Close(); this.requestCopy = null; } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>takes our copy of the stream, and puts it into the request stream</summary> ////////////////////////////////////////////////////////////////////// protected void CopyRequestData() { if (this.requestCopy != null) { // Since we don't use write buffering on the WebRequest object, // we need to ensure the Content-Length field is correctly set // to the length we want to set. EnsureWebRequest(); this.Request.ContentLength = this.requestCopy.Length; // stream it into the real request stream Stream req = base.GetRequestStream(); try { const int size = 4096; byte[] bytes = new byte[size]; int numBytes; double oneLoop = 100; if (requestCopy.Length > size) { oneLoop = (100 / ((double)this.requestCopy.Length / size)); } // 3 lines of debug code // this.requestCopy.Seek(0, SeekOrigin.Begin); // StreamReader reader = new StreamReader( this.requestCopy ); // string text = reader.ReadToEnd(); this.requestCopy.Seek(0, SeekOrigin.Begin); #if WindowsCE || PocketPC #else long bytesWritten = 0; double current = 0; #endif while ((numBytes = this.requestCopy.Read(bytes, 0, size)) > 0) { req.Write(bytes, 0, numBytes); #if WindowsCE || PocketPC #else bytesWritten += numBytes; if (this.asyncData != null && this.asyncData.Delegate != null && this.asyncData.DataHandler != null) { AsyncOperationProgressEventArgs args; args = new AsyncOperationProgressEventArgs(this.requestCopy.Length, bytesWritten, (int)current, this.Request.RequestUri, this.Request.Method, this.asyncData.UserData); current += oneLoop; if (this.asyncData.DataHandler.SendProgressData(asyncData, args) == false) break; } #endif } } finally { req.Close(); } } } ///////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
// 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.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting.Indentation; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation { internal partial class CSharpIndentationService { internal class Indenter : AbstractIndenter { public Indenter( SyntacticDocument document, IEnumerable<IFormattingRule> rules, OptionSet optionSet, TextLine line, CancellationToken cancellationToken) : base(document, rules, optionSet, line, cancellationToken) { } public override IndentationResult? GetDesiredIndentation() { var indentStyle = OptionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp); if (indentStyle == FormattingOptions.IndentStyle.None) { return null; } // find previous line that is not blank var previousLine = GetPreviousNonBlankOrPreprocessorLine(); // it is beginning of the file, there is no previous line exists. // in that case, indentation 0 is our base indentation. if (previousLine == null) { return IndentFromStartOfLine(0); } // okay, now see whether previous line has anything meaningful var lastNonWhitespacePosition = previousLine.Value.GetLastNonWhitespacePosition(); if (!lastNonWhitespacePosition.HasValue) { return null; } // there is known parameter list "," parse bug. if previous token is "," from parameter list, // FindToken will not be able to find them. var token = Tree.GetRoot(CancellationToken).FindToken(lastNonWhitespacePosition.Value); if (token.IsKind(SyntaxKind.None) || indentStyle == FormattingOptions.IndentStyle.Block) { return GetIndentationOfLine(previousLine.Value); } // okay, now check whether the text we found is trivia or actual token. if (token.Span.Contains(lastNonWhitespacePosition.Value)) { // okay, it is a token case, do special work based on type of last token on previous line return GetIndentationBasedOnToken(token); } else { // there must be trivia that contains or touch this position Contract.Assert(token.FullSpan.Contains(lastNonWhitespacePosition.Value)); // okay, now check whether the trivia is at the beginning of the line var firstNonWhitespacePosition = previousLine.Value.GetFirstNonWhitespacePosition(); if (!firstNonWhitespacePosition.HasValue) { return IndentFromStartOfLine(0); } var trivia = Tree.GetRoot(CancellationToken).FindTrivia(firstNonWhitespacePosition.Value, findInsideTrivia: true); if (trivia.Kind() == SyntaxKind.None || this.LineToBeIndented.LineNumber > previousLine.Value.LineNumber + 1) { // If the token belongs to the next statement and is also the first token of the statement, then it means the user wants // to start type a new statement. So get indentation from the start of the line but not based on the token. // Case: // static void Main(string[] args) // { // // A // // B // // $$ // return; // } var containingStatement = token.GetAncestor<StatementSyntax>(); if (containingStatement != null && containingStatement.GetFirstToken() == token) { var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start); return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } // If the token previous of the base token happens to be a Comma from a separation list then we need to handle it different // Case: // var s = new List<string> // { // """", // """",/*sdfsdfsdfsdf*/ // // dfsdfsdfsdfsdf // // $$ // }; var previousToken = token.GetPreviousToken(); if (previousToken.IsKind(SyntaxKind.CommaToken)) { return GetIndentationFromCommaSeparatedList(previousToken); } else if (!previousToken.IsKind(SyntaxKind.None)) { // okay, beginning of the line is not trivia, use the last token on the line as base token return GetIndentationBasedOnToken(token); } } // this case we will keep the indentation of this trivia line // this trivia can't be preprocessor by the way. return GetIndentationOfLine(previousLine.Value); } } private IndentationResult? GetIndentationBasedOnToken(SyntaxToken token) { Contract.ThrowIfNull(Tree); Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None); // special cases // case 1: token belongs to verbatim token literal // case 2: $@"$${0}" // case 3: $@"Comment$$ inbetween{0}" // case 4: $@"{0}$$" if (token.IsVerbatimStringLiteral() || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || (token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation))) { return IndentFromStartOfLine(0); } // if previous statement belong to labeled statement, don't follow label's indentation // but its previous one. if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement()) { token = token.GetAncestor<LabeledStatementSyntax>().GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true); } var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start); // first check operation service to see whether we can determine indentation from it var indentation = Finder.FromIndentBlockOperations(Tree, token, position, CancellationToken); if (indentation.HasValue) { return IndentFromStartOfLine(indentation.Value); } var alignmentTokenIndentation = Finder.FromAlignTokensOperations(Tree, token); if (alignmentTokenIndentation.HasValue) { return IndentFromStartOfLine(alignmentTokenIndentation.Value); } // if we couldn't determine indentation from the service, use heuristic to find indentation. var sourceText = LineToBeIndented.Text; // If this is the last token of an embedded statement, walk up to the top-most parenting embedded // statement owner and use its indentation. // // cases: // if (true) // if (false) // Foo(); // // if (true) // { } if (token.IsSemicolonOfEmbeddedStatement() || token.IsCloseBraceOfEmbeddedBlock()) { Contract.Requires( token.Parent != null && (token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax)); var embeddedStatementOwner = token.Parent.Parent; while (embeddedStatementOwner.IsEmbeddedStatement()) { embeddedStatementOwner = embeddedStatementOwner.Parent; } return GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart)); } switch (token.Kind()) { case SyntaxKind.SemicolonToken: { // special cases if (token.IsSemicolonInForStatement()) { return GetDefaultIndentationFromToken(token); } return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } case SyntaxKind.CloseBraceToken: { if (token.Parent.IsKind(SyntaxKind.AccessorList) && token.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration)) { if (token.GetNextToken().IsEqualsTokenInAutoPropertyInitializers()) { return GetDefaultIndentationFromToken(token); } } return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } case SyntaxKind.OpenBraceToken: { return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } case SyntaxKind.ColonToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); if (nonTerminalNode is SwitchLabelSyntax) { return GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language)); } // default case return GetDefaultIndentationFromToken(token); } case SyntaxKind.CloseBracketToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); // if this is closing an attribute, we shouldn't indent. if (nonTerminalNode is AttributeListSyntax) { return GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart)); } // default case return GetDefaultIndentationFromToken(token); } case SyntaxKind.XmlTextLiteralToken: { return GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(token.SpanStart)); } case SyntaxKind.CommaToken: { return GetIndentationFromCommaSeparatedList(token); } default: { return GetDefaultIndentationFromToken(token); } } } private IndentationResult? GetIndentationFromCommaSeparatedList(SyntaxToken token) { var node = token.Parent; var argument = node as BaseArgumentListSyntax; if (argument != null) { return GetIndentationFromCommaSeparatedList(argument.Arguments, token); } var parameter = node as BaseParameterListSyntax; if (parameter != null) { return GetIndentationFromCommaSeparatedList(parameter.Parameters, token); } var typeArgument = node as TypeArgumentListSyntax; if (typeArgument != null) { return GetIndentationFromCommaSeparatedList(typeArgument.Arguments, token); } var typeParameter = node as TypeParameterListSyntax; if (typeParameter != null) { return GetIndentationFromCommaSeparatedList(typeParameter.Parameters, token); } var enumDeclaration = node as EnumDeclarationSyntax; if (enumDeclaration != null) { return GetIndentationFromCommaSeparatedList(enumDeclaration.Members, token); } var initializerSyntax = node as InitializerExpressionSyntax; if (initializerSyntax != null) { return GetIndentationFromCommaSeparatedList(initializerSyntax.Expressions, token); } return GetDefaultIndentationFromToken(token); } private IndentationResult? GetIndentationFromCommaSeparatedList<T>(SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode { var index = list.GetWithSeparators().IndexOf(token); if (index < 0) { return GetDefaultIndentationFromToken(token); } // find node that starts at the beginning of a line var sourceText = LineToBeIndented.Text; for (int i = (index - 1) / 2; i >= 0; i--) { var node = list[i]; var firstToken = node.GetFirstToken(includeZeroWidth: true); if (firstToken.IsFirstTokenOnLine(sourceText)) { return GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(firstToken.SpanStart)); } } // smart indenter has a special indent block rule for comma separated list, so don't // need to add default additional space for multiline expressions return GetDefaultIndentationFromTokenLine(token, additionalSpace: 0); } private IndentationResult? GetDefaultIndentationFromToken(SyntaxToken token) { if (IsPartOfQueryExpression(token)) { return GetIndentationForQueryExpression(token); } return GetDefaultIndentationFromTokenLine(token); } private IndentationResult? GetIndentationForQueryExpression(SyntaxToken token) { // find containing non terminal node var queryExpressionClause = GetQueryExpressionClause(token); if (queryExpressionClause == null) { return GetDefaultIndentationFromTokenLine(token); } // find line where first token of the node is var sourceText = LineToBeIndented.Text; var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true); var firstTokenLine = sourceText.Lines.GetLineFromPosition(firstToken.SpanStart); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); if (firstTokenLine.LineNumber != givenTokenLine.LineNumber) { // do default behavior return GetDefaultIndentationFromTokenLine(token); } // okay, we are right under the query expression. // align caret to query expression if (firstToken.IsFirstTokenOnLine(sourceText)) { return GetIndentationOfToken(firstToken); } // find query body that has a token that is a first token on the line var queryBody = queryExpressionClause.Parent as QueryBodySyntax; if (queryBody == null) { return GetIndentationOfToken(firstToken); } // find preceding clause that starts on its own. var clauses = queryBody.Clauses; for (int i = clauses.Count - 1; i >= 0; i--) { var clause = clauses[i]; if (firstToken.SpanStart <= clause.SpanStart) { continue; } var clauseToken = clause.GetFirstToken(includeZeroWidth: true); if (clauseToken.IsFirstTokenOnLine(sourceText)) { return GetIndentationOfToken(clauseToken); } } // no query clause start a line. use the first token of the query expression return GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true)); } private SyntaxNode GetQueryExpressionClause(SyntaxToken token) { var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax || n is SelectOrGroupClauseSyntax); if (clause != null) { return clause; } // If this is a query continuation, use the last clause of its parenting query. var body = token.GetAncestor<QueryBodySyntax>(); if (body != null) { if (body.SelectOrGroup.IsMissing) { return body.Clauses.LastOrDefault(); } else { return body.SelectOrGroup; } } return null; } private bool IsPartOfQueryExpression(SyntaxToken token) { var queryExpression = token.GetAncestor<QueryExpressionSyntax>(); return queryExpression != null; } private IndentationResult? GetDefaultIndentationFromTokenLine(SyntaxToken token, int? additionalSpace = null) { var spaceToAdd = additionalSpace ?? this.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language); var sourceText = LineToBeIndented.Text; // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); // find right position var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start); // find containing non expression node var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax); if (nonExpressionNode == null) { // well, I can't find any non expression node. use default behavior return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken)); } // find line where first token of the node is var firstTokenLine = sourceText.Lines.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart); // single line expression if (firstTokenLine.LineNumber == givenTokenLine.LineNumber) { return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken)); } // okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token return GetIndentationOfLine(givenTokenLine); } protected override bool HasPreprocessorCharacter(TextLine currentLine) { var text = currentLine.ToString(); Contract.Requires(!string.IsNullOrWhiteSpace(text)); var trimmedText = text.Trim(); Contract.Assert(SyntaxFacts.GetText(SyntaxKind.HashToken).Length == 1); return trimmedText[0] == SyntaxFacts.GetText(SyntaxKind.HashToken)[0]; } private int GetCurrentPositionNotBelongToEndOfFileToken(int position) { var compilationUnit = Tree.GetRoot(CancellationToken) as CompilationUnitSyntax; if (compilationUnit == null) { return position; } return Math.Min(compilationUnit.EndOfFileToken.FullSpan.Start, position); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Cache.Store { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Impl; using NUnit.Framework; /// <summary> /// /// </summary> class Key { private readonly int _idx; public Key(int idx) { _idx = idx; } public int Index() { return _idx; } public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) return false; Key key = (Key)obj; return key._idx == _idx; } public override int GetHashCode() { return _idx; } } /// <summary> /// /// </summary> class Value { private int _idx; public Value(int idx) { _idx = idx; } public int Index() { return _idx; } } /// <summary> /// Cache entry predicate. /// </summary> [Serializable] public class CacheEntryFilter : ICacheEntryFilter<int, string> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, string> entry) { return entry.Key >= 105; } } /// <summary> /// Cache entry predicate that throws an exception. /// </summary> [Serializable] public class ExceptionalEntryFilter : ICacheEntryFilter<int, string> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, string> entry) { throw new Exception("Expected exception in ExceptionalEntryFilter"); } } /// <summary> /// Filter that can't be serialized. /// </summary> public class InvalidCacheEntryFilter : CacheEntryFilter { // No-op. } /// <summary> /// /// </summary> public class CacheStoreTest { /** */ private const string BinaryStoreCacheName = "binary_store"; /** */ private const string ObjectStoreCacheName = "object_store"; /** */ private const string CustomStoreCacheName = "custom_store"; /** */ private const string TemplateStoreCacheName = "template_store*"; /** */ private volatile int _storeCount = 3; /// <summary> /// /// </summary> [TestFixtureSetUp] public virtual void BeforeTests() { TestUtils.KillProcesses(); TestUtils.JvmDebug = true; var cfg = new IgniteConfiguration { GridName = GridName, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), SpringConfigUrl = "config\\native-client-test-cache-store.xml", BinaryConfiguration = new BinaryConfiguration(typeof (Key), typeof (Value)) }; Ignition.Start(cfg); } /// <summary> /// /// </summary> [TestFixtureTearDown] public void AfterTests() { Ignition.StopAll(true); } /// <summary> /// /// </summary> [SetUp] public void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// /// </summary> [TearDown] public void AfterTest() { var cache = GetCache(); cache.Clear(); Assert.IsTrue(cache.IsEmpty(), "Cache is not empty: " + cache.GetSize()); CacheTestStore.Reset(); TestUtils.AssertHandleRegistryHasItems(300, _storeCount, Ignition.GetIgnite(GridName)); Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name); } [Test] public void TestLoadCache() { var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LoadCache(new CacheEntryFilter(), 100, 10); Assert.AreEqual(5, cache.GetSize()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache.Get(i)); // Test invalid filter Assert.Throws<BinaryObjectException>(() => cache.LoadCache(new InvalidCacheEntryFilter(), 100, 10)); // Test exception in filter Assert.Throws<CacheStoreException>(() => cache.LoadCache(new ExceptionalEntryFilter(), 100, 10)); } [Test] public void TestLocalLoadCache() { var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCache(new CacheEntryFilter(), 100, 10); Assert.AreEqual(5, cache.GetSize()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } [Test] public void TestLoadCacheMetadata() { CacheTestStore.LoadObjects = true; var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCache(null, 0, 3); Assert.AreEqual(3, cache.GetSize()); var meta = cache.WithKeepBinary<Key, IBinaryObject>().Get(new Key(0)).GetBinaryType(); Assert.NotNull(meta); Assert.AreEqual("Value", meta.TypeName); } [Test] public void TestLoadCacheAsync() { var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait(); Assert.AreEqual(5, cache.GetSizeAsync().Result); for (int i = 105; i < 110; i++) { Assert.AreEqual("val_" + i, cache.GetAsync(i).Result); } } [Test] public void TestPutLoad() { var cache = GetCache(); cache.Put(1, "val"); IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); cache.LocalEvict(new[] { 1 }); Assert.AreEqual(0, cache.GetSize()); Assert.AreEqual("val", cache.Get(1)); Assert.AreEqual(1, cache.GetSize()); } [Test] public void TestPutLoadBinarizable() { var cache = GetBinaryStoreCache<int, Value>(); cache.Put(1, new Value(1)); IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); IBinaryObject v = (IBinaryObject)map[1]; Assert.AreEqual(1, v.GetField<int>("_idx")); cache.LocalEvict(new[] { 1 }); Assert.AreEqual(0, cache.GetSize()); Assert.AreEqual(1, cache.Get(1).Index()); Assert.AreEqual(1, cache.GetSize()); } [Test] public void TestPutLoadObjects() { var cache = GetObjectStoreCache<int, Value>(); cache.Put(1, new Value(1)); IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); Value v = (Value)map[1]; Assert.AreEqual(1, v.Index()); cache.LocalEvict(new[] { 1 }); Assert.AreEqual(0, cache.GetSize()); Assert.AreEqual(1, cache.Get(1).Index()); Assert.AreEqual(1, cache.GetSize()); } [Test] public void TestPutLoadAll() { var putMap = new Dictionary<int, string>(); for (int i = 0; i < 10; i++) putMap.Add(i, "val_" + i); var cache = GetCache(); cache.PutAll(putMap); IDictionary map = StoreMap(); Assert.AreEqual(10, map.Count); for (int i = 0; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); cache.Clear(); Assert.AreEqual(0, cache.GetSize()); ICollection<int> keys = new List<int>(); for (int i = 0; i < 10; i++) keys.Add(i); IDictionary<int, string> loaded = cache.GetAll(keys); Assert.AreEqual(10, loaded.Count); for (int i = 0; i < 10; i++) Assert.AreEqual("val_" + i, loaded[i]); Assert.AreEqual(10, cache.GetSize()); } [Test] public void TestRemove() { var cache = GetCache(); for (int i = 0; i < 10; i++) cache.Put(i, "val_" + i); IDictionary map = StoreMap(); Assert.AreEqual(10, map.Count); for (int i = 0; i < 5; i++) cache.Remove(i); Assert.AreEqual(5, map.Count); for (int i = 5; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); } [Test] public void TestRemoveAll() { var cache = GetCache(); for (int i = 0; i < 10; i++) cache.Put(i, "val_" + i); IDictionary map = StoreMap(); Assert.AreEqual(10, map.Count); cache.RemoveAll(new List<int> { 0, 1, 2, 3, 4 }); Assert.AreEqual(5, map.Count); for (int i = 5; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); } [Test] public void TestTx() { var cache = GetCache(); using (var tx = cache.Ignite.GetTransactions().TxStart()) { CacheTestStore.ExpCommit = true; tx.AddMeta("meta", 100); cache.Put(1, "val"); tx.Commit(); } IDictionary map = StoreMap(); Assert.AreEqual(1, map.Count); Assert.AreEqual("val", map[1]); } [Test] public void TestLoadCacheMultithreaded() { CacheTestStore.LoadMultithreaded = true; var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCache(null, 0, null); Assert.AreEqual(1000, cache.GetSize()); for (int i = 0; i < 1000; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } [Test] public void TestCustomStoreProperties() { var cache = GetCustomStoreCache(); Assert.IsNotNull(cache); Assert.AreEqual(42, CacheTestStore.intProperty); Assert.AreEqual("String value", CacheTestStore.stringProperty); } [Test] public void TestDynamicStoreStart() { var grid = Ignition.GetIgnite(GridName); var reg = ((Ignite) grid).HandleRegistry; var handleCount = reg.Count; var cache = GetTemplateStoreCache(); Assert.IsNotNull(cache); cache.Put(1, cache.Name); Assert.AreEqual(cache.Name, CacheTestStore.Map[1]); Assert.AreEqual(handleCount + 1, reg.Count); grid.DestroyCache(cache.Name); Assert.AreEqual(handleCount, reg.Count); } [Test] public void TestLoadAll([Values(true, false)] bool isAsync) { var cache = GetCache(); var loadAll = isAsync ? (Action<IEnumerable<int>, bool>) ((x, y) => { cache.LoadAllAsync(x, y).Wait(); }) : cache.LoadAll; Assert.AreEqual(0, cache.GetSize()); loadAll(Enumerable.Range(105, 5), false); Assert.AreEqual(5, cache.GetSize()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache[i]); // Test overwrite cache[105] = "42"; cache.LocalEvict(new[] { 105 }); loadAll(new[] {105}, false); Assert.AreEqual("42", cache[105]); loadAll(new[] {105, 106}, true); Assert.AreEqual("val_105", cache[105]); Assert.AreEqual("val_106", cache[106]); } /// <summary> /// Get's grid name for this test. /// </summary> /// <value>Grid name.</value> protected virtual string GridName { get { return null; } } private IDictionary StoreMap() { return CacheTestStore.Map; } private ICache<int, string> GetCache() { return GetBinaryStoreCache<int, string>(); } private ICache<TK, TV> GetBinaryStoreCache<TK, TV>() { return Ignition.GetIgnite(GridName).GetCache<TK, TV>(BinaryStoreCacheName); } private ICache<TK, TV> GetObjectStoreCache<TK, TV>() { return Ignition.GetIgnite(GridName).GetCache<TK, TV>(ObjectStoreCacheName); } private ICache<int, string> GetCustomStoreCache() { return Ignition.GetIgnite(GridName).GetCache<int, string>(CustomStoreCacheName); } private ICache<int, string> GetTemplateStoreCache() { var cacheName = TemplateStoreCacheName.Replace("*", Guid.NewGuid().ToString()); return Ignition.GetIgnite(GridName).GetOrCreateCache<int, string>(cacheName); } } /// <summary> /// /// </summary> public class NamedNodeCacheStoreTest : CacheStoreTest { /** <inheritDoc /> */ protected override string GridName { get { return "name"; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; namespace LF2.IDE { public partial class FormTextureEditor : Form { MainForm mainForm; public static bool[,] Texture = new bool[5, 5]; public FormTextureEditor(PictureBox displayer, MainForm main) { InitializeComponent(); mainForm = main; display = displayer; pencilToolStripButton.Checked = !(reverserToolStripButton.Checked = ReversePaint = ReversePaint); trackBar_Zoom.Value = Zoom; PicDraw(); reSize(); } static bool _reversePaint = true; public static bool ReversePaint { get { return _reversePaint; } set { _reversePaint = value; } } static int _zoom = 10; public int Zoom { get { return _zoom; } set { _zoom = value; } } int lastX = -1, lastY = -1; Bitmap bitmap = null, bits = null; PictureBox display = null; string _filePath = null; bool modified = true; Stack<bool[,]> undoBuffer = new Stack<bool[,]>(0); Stack<bool[,]> redoBuffer = new Stack<bool[,]>(0); void FormBitEditKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Escape) this.Close(); } public void reSize() { Size size = new Size(Math.Min(Math.Max(menuStrip.PreferredSize.Width, toolBox.Width + pictureBox.Width), Screen.PrimaryScreen.WorkingArea.Width - 20), Math.Min(Math.Max(menuStrip.Height + pictureBox.Height + trackBar_Zoom.Height, toolBox.Height + menuStrip.PreferredSize.Height), Screen.PrimaryScreen.WorkingArea.Height - 50)); this.ClientSize = size; } public void PicDraw() { int zoom = Zoom; bool[,] texture = Texture; bits = new Bitmap(texture.GetLength(0), texture.GetLength(1)); bitmap = new Bitmap(texture.GetLength(0) * zoom, texture.GetLength(1) * zoom); Graphics g = Graphics.FromImage(bitmap); for (int i = 0; i < bits.Width; i++) { for (int j = 0; j < bits.Height; j++) { bool b = texture[i, j]; g.FillRectangle(b ? Brushes.Black : Brushes.White, i * zoom, j * zoom, zoom, zoom); bits.SetPixel(i, j, b ? Color.Black : Color.White); } } g.Dispose(); pictureBox.Image = bitmap; pictureBox.Refresh(); display.BackgroundImage = bits; display.Refresh(); } public void BitDraw(int x, int y, bool bit) { int zoom = Zoom, X = zoom * x, Y = zoom * y; Brush b = bit ? Brushes.Black : Brushes.White; Texture[x, y] = bit; bits.SetPixel(x, y, bit ? Color.Black : Color.White); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(b, X, Y, zoom, zoom); g.Dispose(); modified = true; pictureBox.Image = bitmap; pictureBox.Refresh(); display.BackgroundImage = bits; display.Refresh(); } void PictureBoxMouseMove(object sender, MouseEventArgs e) { int divx = e.X / Zoom, divy = e.Y / Zoom; if (divx == lastX && divy == lastY || e.X < 0 || e.Y < 0 || e.X >= pictureBox.Image.Width || e.Y >= pictureBox.Image.Height) return; bool b = Texture[divx, divy]; if (ReversePaint) { if (e.Button == MouseButtons.Left) { BitDraw(divx, divy, !b); lastX = divx; lastY = divy; } } else { if (e.Button == MouseButtons.Left) { BitDraw(divx, divy, true); lastX = divx; lastY = divy; } else if (e.Button == MouseButtons.Right) { BitDraw(divx, divy, false); lastX = divx; lastY = divy; } } } void PictureBoxMouseDown(object sender, MouseEventArgs e) { redoBuffer.Clear(); undoBuffer.Push((bool[,])Texture.Clone()); int divx = e.X / Zoom, divy = e.Y / Zoom; bool b = Texture[divx, divy]; if (ReversePaint) { if (e.Button == MouseButtons.Left) { BitDraw(divx, divy, !b); lastX = divx; lastY = divy; } } else { if (e.Button == MouseButtons.Left) { BitDraw(divx, divy, true); lastX = divx; lastY = divy; } else if (e.Button == MouseButtons.Right) { BitDraw(divx, divy, false); lastX = divx; lastY = divy; } } } void PictureBoxMouseUp(object sender, MouseEventArgs e) { int divx = e.X / Zoom, divy = e.Y / Zoom; if (divx == lastX && divy == lastY || e.X < 0 || e.Y < 0 || e.X >= pictureBox.Image.Width || e.Y >= pictureBox.Image.Height) return; bool b = Texture[divx, divy]; if (ReversePaint) { if (e.Button == MouseButtons.Left) { BitDraw(divx, divy, !b); lastX = divx; lastY = divy; } } else { if (e.Button == MouseButtons.Left) { BitDraw(divx, divy, true); lastX = divx; lastY = divy; } else if (e.Button == MouseButtons.Right) { BitDraw(divx, divy, false); lastX = divx; lastY = divy; } } } void FormBitEditorLoad(object sender, EventArgs e) { this.Focus(); } void TrackBarZoomValueChanged(object sender, EventArgs e) { Zoom = trackBar_Zoom.Value; PicDraw(); } void ToolPencilClick(object sender, EventArgs e) { pencilToolStripButton.Checked = !(reverserToolStripButton.Checked = ReversePaint = false); } void ToolRPencilClick(object sender, EventArgs e) { pencilToolStripButton.Checked = !(reverserToolStripButton.Checked = ReversePaint = true); } void OpenToolStripMenuItemClick(object sender, EventArgs e) { try { if (modified && MessageBox.Show(string.IsNullOrEmpty(_filePath) ? "Do you want to save changes?" : "The data in the '" + _filePath + "' has changed.\r\nDo you want to save the changes?", "Texture Editor", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Save(); if (openFileDialog.ShowDialog() == DialogResult.OK) { BinaryFormatter bf = new BinaryFormatter(); FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open); FormTextureEditor.Texture = (bool[,])bf.Deserialize(fs); fs.Close(); modified = false; Text = Path.GetFileName(openFileDialog.FileName) + " - Texture Editor"; PicDraw(); reSize(); } } catch (Exception ex) { mainForm.formEventLog.Error(ex, "Deserialization Error"); } } void SaveToolStripMenuItemClick(object sender, EventArgs e) { Save(); } public bool Save() { if (String.IsNullOrEmpty(_filePath)) return SaveAs(); return Save(_filePath); } public bool Save(string filePath) { try { BinaryFormatter bf = new BinaryFormatter(); FileStream fs = new FileStream(filePath, FileMode.Create); bf.Serialize(fs, FormTextureEditor.Texture); fs.Close(); modified = false; this.Text = Path.GetFileName(filePath) + " - Texture Editor"; } catch (Exception ex) { mainForm.formEventLog.Error(ex, "Serialization Error"); } return true; } public bool SaveAs() { if (!string.IsNullOrEmpty(_filePath)) { saveFileDialog.FileName = Path.GetFileName(_filePath); saveFileDialog.InitialDirectory = Path.GetDirectoryName(_filePath); } else { saveFileDialog.FileName = "Texture"; } if (saveFileDialog.ShowDialog() == DialogResult.OK) { _filePath = saveFileDialog.FileName; Text = Path.GetFileName(_filePath) + " - Texture Editor"; return Save(_filePath); } return false; } void SaveAsToolStripMenuItemClick(object sender, EventArgs e) { SaveAs(); } void ResizeToolStripMenuItemClick(object sender, EventArgs e) { bool[,] old = (bool[,])Texture.Clone(); FormReziseTexture frt = new FormReziseTexture(old.GetLength(0), old.GetLength(1)); if (frt.ShowDialog() == DialogResult.OK) { bool[,] texture = new bool[frt.width, frt.height]; for (int i = 0; i < frt.width; i++) { for (int j = 0; j < frt.height; j++) { texture[i, j] = old[i % old.GetLength(0), j % old.GetLength(1)]; } } redoBuffer.Clear(); undoBuffer.Push((bool[,])texture.Clone()); Texture = texture; modified = true; PicDraw(); reSize(); } } void UndoToolStripMenuItemClick(object sender, EventArgs e) { if (undoBuffer.Count == 0) return; redoBuffer.Push(Texture.Clone() as bool[,]); Texture = undoBuffer.Pop(); modified = true; PicDraw(); } void RedoToolStripMenuItemClick(object sender, EventArgs e) { if (redoBuffer.Count == 0) return; undoBuffer.Push(Texture.Clone() as bool[,]); Texture = redoBuffer.Pop(); modified = true; PicDraw(); } void PictureBoxResize(object sender, EventArgs e) { Size size = toolStripContainer.ContentPanel.Size; pictureBox.Left = size.Width / 2 - pictureBox.Width / 2; pictureBox.Top = size.Height / 2 - pictureBox.Height / 2 - trackBar_Zoom.Height / 2; } void ReverseAllToolStripMenuItemClick(object sender, EventArgs e) { for (int i = 0; i < Texture.GetLength(0); i++) { for (int j = 0; j < Texture.GetLength(1); j++) { bool b = Texture[i, j]; Texture[i, j] = !b; } } PicDraw(); } void FillAllToolStripMenuItemClick(object sender, EventArgs e) { for (int i = 0; i < Texture.GetLength(0); i++) { for (int j = 0; j < Texture.GetLength(1); j++) { Texture[i, j] = true; } } PicDraw(); } void ClearAllToolStripMenuItemClick(object sender, EventArgs e) { for (int i = 0; i < Texture.GetLength(0); i++) { for (int j = 0; j < Texture.GetLength(1); j++) { Texture[i, j] = false; } } PicDraw(); } void FitWindowToolStripMenuItemClick(object sender, EventArgs e) { reSize(); } } }
using System; using System.Diagnostics; using NAudio.Wave.SampleProviders; namespace NAudio.Wave { /// <summary> /// Represents Channel for the WaveMixerStream /// 32 bit output and 16 bit input /// It's output is always stereo /// The input stream can be panned /// </summary> public class WaveChannel32 : WaveStream, ISampleNotifier { private readonly int destBytesPerSample; private readonly long length; private readonly SampleEventArgs sampleEventArgs = new SampleEventArgs(0, 0); private readonly ISampleChunkConverter sampleProvider; private readonly int sourceBytesPerSample; private readonly WaveFormat waveFormat; private volatile float pan; private long position; private WaveStream sourceStream; private volatile float volume; /// <summary> /// Creates a new WaveChannel32 /// </summary> /// <param name="sourceStream">the source stream</param> /// <param name="volume">stream volume (1 is 0dB)</param> /// <param name="pan">pan control (-1 to 1)</param> public WaveChannel32(WaveStream sourceStream, float volume, float pan) { PadWithZeroes = true; var providers = new ISampleChunkConverter[] { new Mono8SampleChunkConverter(), new Stereo8SampleChunkConverter(), new Mono16SampleChunkConverter(), new Stereo16SampleChunkConverter(), new Mono24SampleChunkConverter(), new Stereo24SampleChunkConverter(), new MonoFloatSampleChunkConverter(), new StereoFloatSampleChunkConverter() }; foreach (ISampleChunkConverter provider in providers) { if (provider.Supports(sourceStream.WaveFormat)) { sampleProvider = provider; break; } } if (sampleProvider == null) { throw new ApplicationException("Unsupported sourceStream format"); } // always outputs stereo 32 bit waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sourceStream.WaveFormat.SampleRate, 2); destBytesPerSample = 8; // includes stereo factoring this.sourceStream = sourceStream; this.volume = volume; this.pan = pan; sourceBytesPerSample = sourceStream.WaveFormat.Channels*sourceStream.WaveFormat.BitsPerSample/8; length = SourceToDest(sourceStream.Length); position = 0; } /// <summary> /// Creates a WaveChannel32 with default settings /// </summary> /// <param name="sourceStream">The source stream</param> public WaveChannel32(WaveStream sourceStream) : this(sourceStream, 1.0f, 0.0f) { } /// <summary> /// Gets the block alignment for this WaveStream /// </summary> public override int BlockAlign { get { return (int) SourceToDest(sourceStream.BlockAlign); } } /// <summary> /// Returns the stream length /// </summary> public override long Length { get { return length; } } /// <summary> /// Gets or sets the current position in the stream /// </summary> public override long Position { get { return position; } set { lock (this) { // make sure we don't get out of sync value -= (value%BlockAlign); if (value < 0) { sourceStream.Position = 0; } else { sourceStream.Position = DestToSource(value); } // source stream may not have accepted the reposition we gave it position = SourceToDest(sourceStream.Position); } } } /// <summary> /// If true, Read always returns the number of bytes requested /// </summary> public bool PadWithZeroes { get; set; } /// <summary> /// <see cref="WaveStream.WaveFormat" /> /// </summary> public override WaveFormat WaveFormat { get { return waveFormat; } } /// <summary> /// Volume of this channel. 1.0 = full scale /// </summary> public float Volume { get { return volume; } set { volume = value; } } /// <summary> /// Pan of this channel (from -1 to 1) /// </summary> public float Pan { get { return pan; } set { pan = value; } } /// <summary> /// Sample /// </summary> public event EventHandler<SampleEventArgs> Sample; private long SourceToDest(long sourceBytes) { return (sourceBytes/sourceBytesPerSample)*destBytesPerSample; } private long DestToSource(long destBytes) { return (destBytes/destBytesPerSample)*sourceBytesPerSample; } /// <summary> /// Reads bytes from this wave stream /// </summary> /// <param name="destBuffer">The destination buffer</param> /// <param name="offset">Offset into the destination buffer</param> /// <param name="numBytes">Number of bytes read</param> /// <returns>Number of bytes read.</returns> public override int Read(byte[] destBuffer, int offset, int numBytes) { int bytesWritten = 0; var destWaveBuffer = new WaveBuffer(destBuffer); // 1. fill with silence if (position < 0) { bytesWritten = (int) Math.Min(numBytes, 0 - position); for (int n = 0; n < bytesWritten; n++) destBuffer[n + offset] = 0; } if (bytesWritten < numBytes) { sampleProvider.LoadNextChunk(sourceStream, (numBytes - bytesWritten)/8); float left, right; int outIndex = (offset/4) + bytesWritten/4; while (sampleProvider.GetNextSample(out left, out right) && bytesWritten < numBytes) { // implement better panning laws. left = (pan <= 0) ? left : (left*(1 - pan)/2.0f); right = (pan >= 0) ? right : (right*(pan + 1)/2.0f); left *= volume; right *= volume; destWaveBuffer.FloatBuffer[outIndex++] = left; destWaveBuffer.FloatBuffer[outIndex++] = right; bytesWritten += 8; if (Sample != null) RaiseSample(left, right); } } // 3. Fill out with zeroes if (PadWithZeroes && bytesWritten < numBytes) { Array.Clear(destBuffer, offset + bytesWritten, numBytes - bytesWritten); bytesWritten = numBytes; } position += bytesWritten; return bytesWritten; } /// <summary> /// Determines whether this channel has any data to play /// to allow optimisation to not read, but bump position forward /// </summary> public override bool HasData(int count) { // Check whether the source stream has data. bool sourceHasData = sourceStream.HasData(count); if (sourceHasData) { if (position + count < 0) return false; return (position < length) && (volume != 0); } return false; } /// <summary> /// Disposes this WaveStream /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (sourceStream != null) { sourceStream.Dispose(); sourceStream = null; } } else { Debug.Assert(false, "WaveChannel32 was not Disposed"); } base.Dispose(disposing); } /// <summary> /// Raise the sample event (no check for null because it has already been done) /// </summary> private void RaiseSample(float left, float right) { sampleEventArgs.Left = left; sampleEventArgs.Right = right; Sample(this, sampleEventArgs); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// Repository for updates /// First published in Unreleased. /// </summary> public partial class Repository : XenObject<Repository> { #region Constructors public Repository() { } public Repository(string uuid, string name_label, string name_description, string binary_url, string source_url, bool update, string hash, bool up_to_date) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.binary_url = binary_url; this.source_url = source_url; this.update = update; this.hash = hash; this.up_to_date = up_to_date; } /// <summary> /// Creates a new Repository from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Repository(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Repository from a Proxy_Repository. /// </summary> /// <param name="proxy"></param> public Repository(Proxy_Repository proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Repository. /// </summary> public override void UpdateFrom(Repository record) { uuid = record.uuid; name_label = record.name_label; name_description = record.name_description; binary_url = record.binary_url; source_url = record.source_url; update = record.update; hash = record.hash; up_to_date = record.up_to_date; } internal void UpdateFrom(Proxy_Repository proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; name_label = proxy.name_label == null ? null : proxy.name_label; name_description = proxy.name_description == null ? null : proxy.name_description; binary_url = proxy.binary_url == null ? null : proxy.binary_url; source_url = proxy.source_url == null ? null : proxy.source_url; update = (bool)proxy.update; hash = proxy.hash == null ? null : proxy.hash; up_to_date = (bool)proxy.up_to_date; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Repository /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("name_label")) name_label = Marshalling.ParseString(table, "name_label"); if (table.ContainsKey("name_description")) name_description = Marshalling.ParseString(table, "name_description"); if (table.ContainsKey("binary_url")) binary_url = Marshalling.ParseString(table, "binary_url"); if (table.ContainsKey("source_url")) source_url = Marshalling.ParseString(table, "source_url"); if (table.ContainsKey("update")) update = Marshalling.ParseBool(table, "update"); if (table.ContainsKey("hash")) hash = Marshalling.ParseString(table, "hash"); if (table.ContainsKey("up_to_date")) up_to_date = Marshalling.ParseBool(table, "up_to_date"); } public Proxy_Repository ToProxy() { Proxy_Repository result_ = new Proxy_Repository(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.binary_url = binary_url ?? ""; result_.source_url = source_url ?? ""; result_.update = update; result_.hash = hash ?? ""; result_.up_to_date = up_to_date; return result_; } public bool DeepEquals(Repository other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._binary_url, other._binary_url) && Helper.AreEqual2(this._source_url, other._source_url) && Helper.AreEqual2(this._update, other._update) && Helper.AreEqual2(this._hash, other._hash) && Helper.AreEqual2(this._up_to_date, other._up_to_date); } public override string SaveChanges(Session session, string opaqueRef, Repository server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_name_label, server._name_label)) { Repository.set_name_label(session, opaqueRef, _name_label); } if (!Helper.AreEqual2(_name_description, server._name_description)) { Repository.set_name_description(session, opaqueRef, _name_description); } return null; } } /// <summary> /// Get a record containing the current state of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static Repository get_record(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_record(session.opaque_ref, _repository); else return new Repository(session.XmlRpcProxy.repository_get_record(session.opaque_ref, _repository ?? "").parse()); } /// <summary> /// Get a reference to the Repository instance with the specified UUID. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Repository> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Repository>.Create(session.XmlRpcProxy.repository_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get all the Repository instances with the given label. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Repository>> get_by_name_label(Session session, string _label) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_by_name_label(session.opaque_ref, _label); else return XenRef<Repository>.Create(session.XmlRpcProxy.repository_get_by_name_label(session.opaque_ref, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static string get_uuid(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_uuid(session.opaque_ref, _repository); else return session.XmlRpcProxy.repository_get_uuid(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the name/label field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static string get_name_label(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_name_label(session.opaque_ref, _repository); else return session.XmlRpcProxy.repository_get_name_label(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the name/description field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static string get_name_description(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_name_description(session.opaque_ref, _repository); else return session.XmlRpcProxy.repository_get_name_description(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the binary_url field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static string get_binary_url(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_binary_url(session.opaque_ref, _repository); else return session.XmlRpcProxy.repository_get_binary_url(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the source_url field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static string get_source_url(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_source_url(session.opaque_ref, _repository); else return session.XmlRpcProxy.repository_get_source_url(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the update field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static bool get_update(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_update(session.opaque_ref, _repository); else return (bool)session.XmlRpcProxy.repository_get_update(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the hash field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static string get_hash(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_hash(session.opaque_ref, _repository); else return session.XmlRpcProxy.repository_get_hash(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Get the up_to_date field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static bool get_up_to_date(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_up_to_date(session.opaque_ref, _repository); else return (bool)session.XmlRpcProxy.repository_get_up_to_date(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Set the name/label field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> /// <param name="_label">New value to set</param> public static void set_name_label(Session session, string _repository, string _label) { if (session.JsonRpcClient != null) session.JsonRpcClient.repository_set_name_label(session.opaque_ref, _repository, _label); else session.XmlRpcProxy.repository_set_name_label(session.opaque_ref, _repository ?? "", _label ?? "").parse(); } /// <summary> /// Set the name/description field of the given Repository. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> /// <param name="_description">New value to set</param> public static void set_name_description(Session session, string _repository, string _description) { if (session.JsonRpcClient != null) session.JsonRpcClient.repository_set_name_description(session.opaque_ref, _repository, _description); else session.XmlRpcProxy.repository_set_name_description(session.opaque_ref, _repository ?? "", _description ?? "").parse(); } /// <summary> /// Add the configuration for a new repository /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_name_label">The name of the repository</param> /// <param name="_name_description">The description of the repository</param> /// <param name="_binary_url">Base URL of binary packages in this repository</param> /// <param name="_source_url">Base URL of source packages in this repository</param> /// <param name="_update">True if the repository is an update repository. This means that updateinfo.xml will be parsed</param> public static XenRef<Repository> introduce(Session session, string _name_label, string _name_description, string _binary_url, string _source_url, bool _update) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_introduce(session.opaque_ref, _name_label, _name_description, _binary_url, _source_url, _update); else return XenRef<Repository>.Create(session.XmlRpcProxy.repository_introduce(session.opaque_ref, _name_label ?? "", _name_description ?? "", _binary_url ?? "", _source_url ?? "", _update).parse()); } /// <summary> /// Add the configuration for a new repository /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_name_label">The name of the repository</param> /// <param name="_name_description">The description of the repository</param> /// <param name="_binary_url">Base URL of binary packages in this repository</param> /// <param name="_source_url">Base URL of source packages in this repository</param> /// <param name="_update">True if the repository is an update repository. This means that updateinfo.xml will be parsed</param> public static XenRef<Task> async_introduce(Session session, string _name_label, string _name_description, string _binary_url, string _source_url, bool _update) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_repository_introduce(session.opaque_ref, _name_label, _name_description, _binary_url, _source_url, _update); else return XenRef<Task>.Create(session.XmlRpcProxy.async_repository_introduce(session.opaque_ref, _name_label ?? "", _name_description ?? "", _binary_url ?? "", _source_url ?? "", _update).parse()); } /// <summary> /// Remove the repository record from the database /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static void forget(Session session, string _repository) { if (session.JsonRpcClient != null) session.JsonRpcClient.repository_forget(session.opaque_ref, _repository); else session.XmlRpcProxy.repository_forget(session.opaque_ref, _repository ?? "").parse(); } /// <summary> /// Remove the repository record from the database /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> /// <param name="_repository">The opaque_ref of the given repository</param> public static XenRef<Task> async_forget(Session session, string _repository) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_repository_forget(session.opaque_ref, _repository); else return XenRef<Task>.Create(session.XmlRpcProxy.async_repository_forget(session.opaque_ref, _repository ?? "").parse()); } /// <summary> /// Return a list of all the Repositorys known to the system. /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Repository>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_all(session.opaque_ref); else return XenRef<Repository>.Create(session.XmlRpcProxy.repository_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the Repository Records at once, in a single XML RPC call /// First published in Unreleased. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Repository>, Repository> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.repository_get_all_records(session.opaque_ref); else return XenRef<Repository>.Create<Proxy_Repository>(session.XmlRpcProxy.repository_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; NotifyPropertyChanged("name_label"); } } } private string _name_label = ""; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; NotifyPropertyChanged("name_description"); } } } private string _name_description = ""; /// <summary> /// Base URL of binary packages in this repository /// </summary> public virtual string binary_url { get { return _binary_url; } set { if (!Helper.AreEqual(value, _binary_url)) { _binary_url = value; NotifyPropertyChanged("binary_url"); } } } private string _binary_url = ""; /// <summary> /// Base URL of source packages in this repository /// </summary> public virtual string source_url { get { return _source_url; } set { if (!Helper.AreEqual(value, _source_url)) { _source_url = value; NotifyPropertyChanged("source_url"); } } } private string _source_url = ""; /// <summary> /// True if updateinfo.xml in this repository needs to be parsed /// </summary> public virtual bool update { get { return _update; } set { if (!Helper.AreEqual(value, _update)) { _update = value; NotifyPropertyChanged("update"); } } } private bool _update = false; /// <summary> /// SHA256 checksum of latest updateinfo.xml.gz in this repository if its 'update' is true /// </summary> public virtual string hash { get { return _hash; } set { if (!Helper.AreEqual(value, _hash)) { _hash = value; NotifyPropertyChanged("hash"); } } } private string _hash = ""; /// <summary> /// True if all hosts in pool is up to date with this repository /// </summary> public virtual bool up_to_date { get { return _up_to_date; } set { if (!Helper.AreEqual(value, _up_to_date)) { _up_to_date = value; NotifyPropertyChanged("up_to_date"); } } } private bool _up_to_date = false; } }
// ------------------------------------------------------------------------------ // 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. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type EventRequest. /// </summary> public partial class EventRequest : BaseRequest, IEventRequest { /// <summary> /// Constructs a new EventRequest. /// </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 EventRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Event using POST. /// </summary> /// <param name="eventToCreate">The Event to create.</param> /// <returns>The created Event.</returns> public System.Threading.Tasks.Task<Event> CreateAsync(Event eventToCreate) { return this.CreateAsync(eventToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Event using POST. /// </summary> /// <param name="eventToCreate">The Event to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Event.</returns> public async System.Threading.Tasks.Task<Event> CreateAsync(Event eventToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Event>(eventToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Event. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Event. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Event>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Event. /// </summary> /// <returns>The Event.</returns> public System.Threading.Tasks.Task<Event> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Event. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Event.</returns> public async System.Threading.Tasks.Task<Event> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Event>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Event using PATCH. /// </summary> /// <param name="eventToUpdate">The Event to update.</param> /// <returns>The updated Event.</returns> public System.Threading.Tasks.Task<Event> UpdateAsync(Event eventToUpdate) { return this.UpdateAsync(eventToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Event using PATCH. /// </summary> /// <param name="eventToUpdate">The Event to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Event.</returns> public async System.Threading.Tasks.Task<Event> UpdateAsync(Event eventToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Event>(eventToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <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 IEventRequest 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 IEventRequest Expand(Expression<Func<Event, 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 IEventRequest 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 IEventRequest Select(Expression<Func<Event, 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> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="eventToInitialize">The <see cref="Event"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Event eventToInitialize) { if (eventToInitialize != null && eventToInitialize.AdditionalData != null) { if (eventToInitialize.Instances != null && eventToInitialize.Instances.CurrentPage != null) { eventToInitialize.Instances.AdditionalData = eventToInitialize.AdditionalData; object nextPageLink; eventToInitialize.AdditionalData.TryGetValue("instances@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { eventToInitialize.Instances.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (eventToInitialize.Extensions != null && eventToInitialize.Extensions.CurrentPage != null) { eventToInitialize.Extensions.AdditionalData = eventToInitialize.AdditionalData; object nextPageLink; eventToInitialize.AdditionalData.TryGetValue("extensions@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { eventToInitialize.Extensions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (eventToInitialize.Attachments != null && eventToInitialize.Attachments.CurrentPage != null) { eventToInitialize.Attachments.AdditionalData = eventToInitialize.AdditionalData; object nextPageLink; eventToInitialize.AdditionalData.TryGetValue("attachments@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { eventToInitialize.Attachments.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
using Lucene.Net.Analysis; using Lucene.Net.Search; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; #endif namespace Lucene.Net.QueryParsers.Classic { /* * 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> This class is generated by JavaCC. The most important method is /// <see cref="QueryParserBase.Parse(string)" />. /// <para/> /// The syntax for query strings is as follows: /// A Query is a series of clauses. /// A clause may be prefixed by: /// <list type="bullet"> /// <item><description> a plus (<c>+</c>) or a minus (<c>-</c>) sign, indicating /// that the clause is required or prohibited respectively; or</description></item> /// <item><description> a term followed by a colon, indicating the field to be searched. /// This enables one to construct queries which search multiple fields.</description></item> /// </list> /// /// <para/> /// A clause may be either: /// <list type="bullet"> /// <item><description> a term, indicating all the documents that contain this term; or</description></item> /// <item><description> a nested query, enclosed in parentheses. Note that this may be used /// with a <c>+</c>/<c>-</c> prefix to require any of a set of /// terms.</description></item> /// </list> /// /// <para/> /// Thus, in BNF, the query grammar is: /// <code> /// Query ::= ( Clause )* /// Clause ::= ["+", "-"] [&lt;TERM&gt; ":"] ( &lt;TERM&gt; | "(" Query ")" ) /// </code> /// /// <para> /// Examples of appropriately formatted queries can be found in the <a /// href="../../../../../../queryparsersyntax.html">query syntax /// documentation</a>. /// </para> /// /// <para> /// In <see cref="TermRangeQuery" />s, QueryParser tries to detect date values, e.g. /// <tt>date:[6/1/2005 TO 6/4/2005]</tt> produces a range query that searches /// for "date" fields between 2005-06-01 and 2005-06-04. Note that the format /// of the accepted input depends on the <see cref="System.Globalization.CultureInfo" />. /// A <see cref="Documents.DateTools.Resolution" /> has to be set, /// if you want to use <see cref="Documents.DateTools"/> for date conversion.<p/> /// </para> /// <para> /// The date resolution that shall be used for RangeQueries can be set /// using <see cref="QueryParserBase.SetDateResolution(Documents.DateTools.Resolution)" /> /// or <see cref="QueryParserBase.SetDateResolution(string, Documents.DateTools.Resolution)" />. The former /// sets the default date resolution for all fields, whereas the latter can /// be used to set field specific date resolutions. Field specific date /// resolutions take, if set, precedence over the default date resolution. /// </para> /// <para> /// If you don't use <see cref="Documents.DateTools" /> in your index, you can create your own /// query parser that inherits <see cref="QueryParser"/> and overwrites /// <see cref="QueryParserBase.GetRangeQuery(string, string, string, bool, bool)" /> to /// use a different method for date conversion. /// </para> /// /// <para>Note that <see cref="QueryParser"/> is <em>not</em> thread-safe.</para> /// /// <para><b>NOTE</b>: there is a new QueryParser in contrib, which matches /// the same syntax as this class, but is more modular, /// enabling substantial customization to how a query is created. /// </para> /// /// <b>NOTE</b>: You must specify the required <see cref="LuceneVersion" /> compatibility when /// creating QueryParser: /// <list type="bullet"> /// <item><description>As of 3.1, <see cref="QueryParserBase.AutoGeneratePhraseQueries"/> is false by default.</description></item> /// </list> /// </summary> public class QueryParser : QueryParserBase { // NOTE: This was moved into the QueryParserBase class. // * The default operator for parsing queries. // * Use <see cref="QueryParser.DefaultOperator"/> to change it. // */ //public enum Operator //{ // OR, // AND //} /// <summary> /// Constructs a query parser. /// </summary> /// <param name="matchVersion">Lucene version to match.</param> /// <param name="f">the default field for query terms.</param> /// <param name="a">used to find terms in the query text.</param> public QueryParser(LuceneVersion matchVersion, string f, Analyzer a) : this(new FastCharStream(new StringReader(""))) { Init(matchVersion, f, a); } // * Query ::= ( Clause )* // * Clause ::= ["+", "-"] [<TermToken> ":"] ( <TermToken> | "(" Query ")" ) public int Conjunction() { int ret = CONJ_NONE; switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.AND: case RegexpToken.OR: switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.AND: Jj_consume_token(RegexpToken.AND); ret = CONJ_AND; break; case RegexpToken.OR: Jj_consume_token(RegexpToken.OR); ret = CONJ_OR; break; default: jj_la1[0] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } break; default: jj_la1[1] = jj_gen; break; } { if (true) return ret; } throw new InvalidOperationException("Missing return statement in function"); } public int Modifiers() { int ret = MOD_NONE; switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.NOT: case RegexpToken.PLUS: case RegexpToken.MINUS: switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.PLUS: Jj_consume_token(RegexpToken.PLUS); ret = MOD_REQ; break; case RegexpToken.MINUS: Jj_consume_token(RegexpToken.MINUS); ret = MOD_NOT; break; case RegexpToken.NOT: Jj_consume_token(RegexpToken.NOT); ret = MOD_NOT; break; default: jj_la1[2] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } break; default: jj_la1[3] = jj_gen; break; } { if (true) return ret; } throw new Exception("Missing return statement in function"); } // This makes sure that there is no garbage after the query string public override sealed Query TopLevelQuery(string field) { Query q; q = Query(field); Jj_consume_token(0); { if (true) return q; } throw new Exception("Missing return statement in function"); } public Query Query(string field) { List<BooleanClause> clauses = new List<BooleanClause>(); Query q, firstQuery = null; int conj, mods; mods = Modifiers(); q = Clause(field); AddClause(clauses, CONJ_NONE, mods, q); if (mods == MOD_NONE) firstQuery = q; while (true) { switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.AND: case RegexpToken.OR: case RegexpToken.NOT: case RegexpToken.PLUS: case RegexpToken.MINUS: case RegexpToken.BAREOPER: case RegexpToken.LPAREN: case RegexpToken.STAR: case RegexpToken.QUOTED: case RegexpToken.TERM: case RegexpToken.PREFIXTERM: case RegexpToken.WILDTERM: case RegexpToken.REGEXPTERM: case RegexpToken.RANGEIN_START: case RegexpToken.RANGEEX_START: case RegexpToken.NUMBER: break; default: jj_la1[4] = jj_gen; goto label_1; } conj = Conjunction(); mods = Modifiers(); q = Clause(field); AddClause(clauses, conj, mods, q); } label_1: if (clauses.Count == 1 && firstQuery != null) { if (true) return firstQuery; } return GetBooleanQuery(clauses); } public Query Clause(string field) { Query q; Token fieldToken = null, boost = null; if (Jj_2_1(2)) { switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.TERM: fieldToken = Jj_consume_token(RegexpToken.TERM); Jj_consume_token(RegexpToken.COLON); field = DiscardEscapeChar(fieldToken.Image); break; case RegexpToken.STAR: Jj_consume_token(RegexpToken.STAR); Jj_consume_token(RegexpToken.COLON); field = "*"; break; default: jj_la1[5] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } } else { ; } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.BAREOPER: case RegexpToken.STAR: case RegexpToken.QUOTED: case RegexpToken.TERM: case RegexpToken.PREFIXTERM: case RegexpToken.WILDTERM: case RegexpToken.REGEXPTERM: case RegexpToken.RANGEIN_START: case RegexpToken.RANGEEX_START: case RegexpToken.NUMBER: q = Term(field); break; case RegexpToken.LPAREN: Jj_consume_token(RegexpToken.LPAREN); q = Query(field); Jj_consume_token(RegexpToken.RPAREN); switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.CARAT: Jj_consume_token(RegexpToken.CARAT); boost = Jj_consume_token(RegexpToken.NUMBER); break; default: jj_la1[6] = jj_gen; break; } break; default: jj_la1[7] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } { if (true) return HandleBoost(q, boost); } throw new Exception("Missing return statement in function"); } public Query Term(string field) { Token term, boost = null, fuzzySlop = null, goop1, goop2; bool prefix = false; bool wildcard = false; bool fuzzy = false; bool regexp = false; bool startInc = false; bool endInc = false; Query q; switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.BAREOPER: case RegexpToken.STAR: case RegexpToken.TERM: case RegexpToken.PREFIXTERM: case RegexpToken.WILDTERM: case RegexpToken.REGEXPTERM: case RegexpToken.NUMBER: switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.TERM: term = Jj_consume_token(RegexpToken.TERM); break; case RegexpToken.STAR: term = Jj_consume_token(RegexpToken.STAR); wildcard = true; break; case RegexpToken.PREFIXTERM: term = Jj_consume_token(RegexpToken.PREFIXTERM); prefix = true; break; case RegexpToken.WILDTERM: term = Jj_consume_token(RegexpToken.WILDTERM); wildcard = true; break; case RegexpToken.REGEXPTERM: term = Jj_consume_token(RegexpToken.REGEXPTERM); regexp = true; break; case RegexpToken.NUMBER: term = Jj_consume_token(RegexpToken.NUMBER); break; case RegexpToken.BAREOPER: term = Jj_consume_token(RegexpToken.BAREOPER); term.Image = term.Image.Substring(0, 1); break; default: jj_la1[8] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.FUZZY_SLOP: fuzzySlop = Jj_consume_token(RegexpToken.FUZZY_SLOP); fuzzy = true; break; default: jj_la1[9] = jj_gen; break; } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.CARAT: Jj_consume_token(RegexpToken.CARAT); boost = Jj_consume_token(RegexpToken.NUMBER); switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.FUZZY_SLOP: fuzzySlop = Jj_consume_token(RegexpToken.FUZZY_SLOP); fuzzy = true; break; default: jj_la1[10] = jj_gen; break; } break; default: jj_la1[11] = jj_gen; break; } q = HandleBareTokenQuery(field, term, fuzzySlop, prefix, wildcard, fuzzy, regexp); break; case RegexpToken.RANGEIN_START: case RegexpToken.RANGEEX_START: switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.RANGEIN_START: Jj_consume_token(RegexpToken.RANGEIN_START); startInc = true; break; case RegexpToken.RANGEEX_START: Jj_consume_token(RegexpToken.RANGEEX_START); break; default: jj_la1[12] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.RANGE_GOOP: goop1 = Jj_consume_token(RegexpToken.RANGE_GOOP); break; case RegexpToken.RANGE_QUOTED: goop1 = Jj_consume_token(RegexpToken.RANGE_QUOTED); break; default: jj_la1[13] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.RANGE_TO: Jj_consume_token(RegexpToken.RANGE_TO); break; default: jj_la1[14] = jj_gen; break; } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.RANGE_GOOP: goop2 = Jj_consume_token(RegexpToken.RANGE_GOOP); break; case RegexpToken.RANGE_QUOTED: goop2 = Jj_consume_token(RegexpToken.RANGE_QUOTED); break; default: jj_la1[15] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.RANGEIN_END: Jj_consume_token(RegexpToken.RANGEIN_END); endInc = true; break; case RegexpToken.RANGEEX_END: Jj_consume_token(RegexpToken.RANGEEX_END); break; default: jj_la1[16] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.CARAT: Jj_consume_token(RegexpToken.CARAT); boost = Jj_consume_token(RegexpToken.NUMBER); break; default: jj_la1[17] = jj_gen; break; } bool startOpen = false; bool endOpen = false; if (goop1.Kind == RegexpToken.RANGE_QUOTED) { goop1.Image = goop1.Image.Substring(1, goop1.Image.Length - 2); } else if ("*".Equals(goop1.Image, StringComparison.Ordinal)) { startOpen = true; } if (goop2.Kind == RegexpToken.RANGE_QUOTED) { goop2.Image = goop2.Image.Substring(1, goop2.Image.Length - 2); } else if ("*".Equals(goop2.Image, StringComparison.Ordinal)) { endOpen = true; } q = GetRangeQuery(field, startOpen ? null : DiscardEscapeChar(goop1.Image), endOpen ? null : DiscardEscapeChar(goop2.Image), startInc, endInc); break; case RegexpToken.QUOTED: term = Jj_consume_token(RegexpToken.QUOTED); switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.FUZZY_SLOP: fuzzySlop = Jj_consume_token(RegexpToken.FUZZY_SLOP); break; default: jj_la1[18] = jj_gen; break; } switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case RegexpToken.CARAT: Jj_consume_token(RegexpToken.CARAT); boost = Jj_consume_token(RegexpToken.NUMBER); break; default: jj_la1[19] = jj_gen; break; } q = HandleQuotedTerm(field, term, fuzzySlop); break; default: jj_la1[20] = jj_gen; Jj_consume_token(-1); throw new ParseException(); } { if (true) return HandleBoost(q, boost); } throw new Exception("Missing return statement in function"); } private bool Jj_2_1(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = Token; try { return !Jj_3_1(); } catch (LookaheadSuccess) { return true; } finally { Jj_save(0, xla); } } private bool Jj_3R_2() { if (Jj_scan_token(RegexpToken.TERM)) return true; if (Jj_scan_token(RegexpToken.COLON)) return true; return false; } private bool Jj_3_1() { Token xsp; xsp = jj_scanpos; if (Jj_3R_2()) { jj_scanpos = xsp; if (Jj_3R_3()) return true; } return false; } private bool Jj_3R_3() { if (Jj_scan_token(RegexpToken.STAR)) return true; if (Jj_scan_token(RegexpToken.COLON)) return true; return false; } /// <summary>Generated Token Manager.</summary> public QueryParserTokenManager TokenSource { get; set; } /// <summary>Current token.</summary> public Token Token { get; set; } /// <summary>Next token.</summary> public Token Jj_nt { get; set; } private int jj_ntk; private Token jj_scanpos, jj_lastpos; private int jj_la; private int jj_gen; private int[] jj_la1 = new int[21]; private static uint[] jj_la1_0 = new uint[] // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { 0x300, 0x300, 0x1c00, 0x1c00, 0xfda7f00, 0x120000, 0x40000, 0xfda6000, 0x9d22000, 0x200000, 0x200000, 0x40000, 0x6000000, 0x80000000, 0x10000000, 0x80000000, 0x60000000, 0x40000, 0x200000, 0x40000, 0xfda2000, }; private static int[] jj_la1_1 = new int[] // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, }; // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) //static QueryParser() //{ // { // Jj_la1_init_0(); // Jj_la1_init_1(); // } //} //private static void Jj_la1_init_0() //{ // jj_la1_0 = new uint[] // { // 0x300, 0x300, 0x1c00, 0x1c00, 0xfda7f00, 0x120000, 0x40000, 0xfda6000, 0x9d22000, 0x200000, // 0x200000, 0x40000, 0x6000000, 0x80000000, 0x10000000, 0x80000000, 0x60000000, 0x40000, // 0x200000, 0x40000, 0xfda2000, // }; //} //private static void Jj_la1_init_1() //{ // jj_la1_1 = new int[] // { // 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, // 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, // }; //} private readonly JJCalls[] jj_2_rtns = new JJCalls[1]; private bool jj_rescan = false; private int jj_gc = 0; /// <summary>Constructor with user supplied <see cref="ICharStream"/>. </summary> protected internal QueryParser(ICharStream stream) { TokenSource = new QueryParserTokenManager(stream); Token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 21; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.Length; i++) jj_2_rtns[i] = new JJCalls(); } /// <summary>Reinitialize. </summary> public override void ReInit(ICharStream stream) { TokenSource.ReInit(stream); Token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 21; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.Length; i++) jj_2_rtns[i] = new JJCalls(); } /// <summary>Constructor with generated Token Manager. </summary> protected QueryParser(QueryParserTokenManager tm) { TokenSource = tm; Token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 21; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.Length; i++) jj_2_rtns[i] = new JJCalls(); } /// <summary>Reinitialize. </summary> public virtual void ReInit(QueryParserTokenManager tm) { TokenSource = tm; Token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 21; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.Length; i++) jj_2_rtns[i] = new JJCalls(); } private Token Jj_consume_token(int kind) { Token oldToken; if ((oldToken = Token).Next != null) Token = Token.Next; else Token = Token.Next = TokenSource.GetNextToken(); jj_ntk = -1; if (Token.Kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.Length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return Token; } Token = oldToken; jj_kind = kind; throw GenerateParseException(); } // LUCENENET: It is no longer good practice to use binary serialization. // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif private sealed class LookaheadSuccess : Exception { public LookaheadSuccess() { } #if FEATURE_SERIALIZABLE_EXCEPTIONS /// <summary> /// Initializes a new instance of this class with serialized data. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param> public LookaheadSuccess(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } private LookaheadSuccess jj_ls = new LookaheadSuccess(); private bool Jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.Next == null) { jj_lastpos = jj_scanpos = jj_scanpos.Next = TokenSource.GetNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.Next; } } else { jj_scanpos = jj_scanpos.Next; } if (jj_rescan) { int i = 0; Token tok = Token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.Next; } if (tok != null) Jj_add_error_token(kind, i); } if (jj_scanpos.Kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; } /// <summary>Get the next Token. </summary> public Token GetNextToken() { if (Token.Next != null) Token = Token.Next; else Token = Token.Next = TokenSource.GetNextToken(); jj_ntk = -1; jj_gen++; return Token; } /// <summary>Get the specific Token. </summary> public Token GetToken(int index) { Token t = Token; for (int i = 0; i < index; i++) { if (t.Next != null) t = t.Next; else t = t.Next = TokenSource.GetNextToken(); } return t; } private int Jj_ntk() { if ((Jj_nt = Token.Next) == null) return (jj_ntk = (Token.Next = TokenSource.GetNextToken()).Kind); else return (jj_ntk = Jj_nt.Kind); } private List<int[]> jj_expentries = new List<int[]>(); private int[] jj_expentry; private int jj_kind = -1; private int[] jj_lasttokens = new int[100]; private int jj_endpos; private void Jj_add_error_token(int kind, int pos) { if (pos >= 100) return; if (pos == jj_endpos + 1) { jj_lasttokens[jj_endpos++] = kind; } else if (jj_endpos != 0) { jj_expentry = new int[jj_endpos]; for (int i = 0; i < jj_endpos; i++) { jj_expentry[i] = jj_lasttokens[i]; } foreach (var oldentry in jj_expentries) { if (oldentry.Length == jj_expentry.Length) { for (int i = 0; i < jj_expentry.Length; i++) { if (oldentry[i] != jj_expentry[i]) { goto jj_entries_loop_continue; } } jj_expentries.Add(jj_expentry); goto jj_entries_loop_break; } jj_entries_loop_continue: ; } jj_entries_loop_break: if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; } } /// <summary>Generate ParseException. </summary> public virtual ParseException GenerateParseException() { jj_expentries.Clear(); bool[] la1tokens = new bool[33]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 21; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1 << j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1 << j)) != 0) { la1tokens[32 + j] = true; } } } } for (int i = 0; i < 33; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.Add(jj_expentry); } } jj_endpos = 0; Jj_rescan_token(); Jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.Count][]; for (int i = 0; i < jj_expentries.Count; i++) { exptokseq[i] = jj_expentries[i]; } return new ParseException(Token, exptokseq, QueryParserConstants.TokenImage); } /// <summary>Enable tracing. </summary> public void Enable_tracing() { } /// <summary>Disable tracing. </summary> public void Disable_tracing() { } private void Jj_rescan_token() { jj_rescan = true; for (int i = 0; i < 1; i++) { try { JJCalls p = jj_2_rtns[i]; do { if (p.gen > jj_gen) { jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; switch (i) { case 0: Jj_3_1(); break; } } p = p.next; } while (p != null); } catch (LookaheadSuccess) { } } jj_rescan = false; } private void Jj_save(int index, int xla) { JJCalls p = jj_2_rtns[index]; while (p.gen > jj_gen) { if (p.next == null) { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = Token; p.arg = xla; } internal sealed class JJCalls { internal int gen; internal Token first; internal int arg; internal JJCalls next; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using OpenMetaverse; namespace OpenSim.Framework { public class EstateSettings { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void SaveDelegate(EstateSettings rs); public event SaveDelegate OnSave; // Only the client uses these // private uint m_EstateID = 0; public uint EstateID { get { return m_EstateID; } set { m_EstateID = value; } } private string m_EstateName = "My Estate"; public string EstateName { get { return m_EstateName; } set { m_EstateName = value; } } private bool m_AllowLandmark = true; public bool AllowLandmark { get { return m_AllowLandmark; } set { m_AllowLandmark = value; } } private bool m_AllowParcelChanges = true; public bool AllowParcelChanges { get { return m_AllowParcelChanges; } set { m_AllowParcelChanges = value; } } private bool m_AllowSetHome = true; public bool AllowSetHome { get { return m_AllowSetHome; } set { m_AllowSetHome = value; } } private uint m_ParentEstateID = 1; public uint ParentEstateID { get { return m_ParentEstateID; } set { m_ParentEstateID = value; } } private float m_BillableFactor = 0.0f; public float BillableFactor { get { return m_BillableFactor; } set { m_BillableFactor = value; } } private int m_PricePerMeter = 1; public int PricePerMeter { get { return m_PricePerMeter; } set { m_PricePerMeter = value; } } private int m_RedirectGridX = 0; public int RedirectGridX { get { return m_RedirectGridX; } set { m_RedirectGridX = value; } } private int m_RedirectGridY = 0; public int RedirectGridY { get { return m_RedirectGridY; } set { m_RedirectGridY = value; } } // Used by the sim // private bool m_UseGlobalTime = true; public bool UseGlobalTime { get { return m_UseGlobalTime; } set { m_UseGlobalTime = value; } } private bool m_FixedSun = false; public bool FixedSun { get { return m_FixedSun; } set { m_FixedSun = value; } } private double m_SunPosition = 0.0; public double SunPosition { get { return m_SunPosition; } set { m_SunPosition = value; } } private bool m_AllowVoice = true; public bool AllowVoice { get { return m_AllowVoice; } set { m_AllowVoice = value; } } private bool m_AllowDirectTeleport = true; public bool AllowDirectTeleport { get { return m_AllowDirectTeleport; } set { m_AllowDirectTeleport = value; } } private bool m_DenyAnonymous = false; public bool DenyAnonymous { get { return m_DenyAnonymous; } set { m_DenyAnonymous = value; } } private bool m_DenyIdentified = false; public bool DenyIdentified { get { return m_DenyIdentified; } set { m_DenyIdentified = value; } } private bool m_DenyTransacted = false; public bool DenyTransacted { get { return m_DenyTransacted; } set { m_DenyTransacted = value; } } private bool m_AbuseEmailToEstateOwner = false; public bool AbuseEmailToEstateOwner { get { return m_AbuseEmailToEstateOwner; } set { m_AbuseEmailToEstateOwner = value; } } private bool m_BlockDwell = false; public bool BlockDwell { get { return m_BlockDwell; } set { m_BlockDwell = value; } } private bool m_EstateSkipScripts = false; public bool EstateSkipScripts { get { return m_EstateSkipScripts; } set { m_EstateSkipScripts = value; } } private bool m_ResetHomeOnTeleport = false; public bool ResetHomeOnTeleport { get { return m_ResetHomeOnTeleport; } set { m_ResetHomeOnTeleport = value; } } private bool m_TaxFree = false; public bool TaxFree { get { return m_TaxFree; } set { m_TaxFree = value; } } private bool m_PublicAccess = true; public bool PublicAccess { get { return m_PublicAccess; } set { m_PublicAccess = value; } } private string m_AbuseEmail = String.Empty; public string AbuseEmail { get { return m_AbuseEmail; } set { m_AbuseEmail= value; } } private UUID m_EstateOwner = UUID.Zero; public UUID EstateOwner { get { return m_EstateOwner; } set { m_EstateOwner = value; } } private bool m_DenyMinors = false; public bool DenyMinors { get { return m_DenyMinors; } set { m_DenyMinors = value; } } // All those lists... // private List<UUID> l_EstateManagers = new List<UUID>(); public UUID[] EstateManagers { get { return l_EstateManagers.ToArray(); } set { l_EstateManagers = new List<UUID>(value); } } private List<EstateBan> l_EstateBans = new List<EstateBan>(); public EstateBan[] EstateBans { get { return l_EstateBans.ToArray(); } set { l_EstateBans = new List<EstateBan>(value); } } private List<UUID> l_EstateAccess = new List<UUID>(); public UUID[] EstateAccess { get { return l_EstateAccess.ToArray(); } set { l_EstateAccess = new List<UUID>(value); } } private List<UUID> l_EstateGroups = new List<UUID>(); public UUID[] EstateGroups { get { return l_EstateGroups.ToArray(); } set { l_EstateGroups = new List<UUID>(value); } } public EstateSettings() { } public void Save() { if (OnSave != null) OnSave(this); } public int EstateUsersCount() { return l_EstateAccess.Count; } public void AddEstateUser(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateAccess.Contains(avatarID) && (l_EstateAccess.Count < (int)Constants.EstateAccessLimits.AllowedAccess)) l_EstateAccess.Add(avatarID); } public void RemoveEstateUser(UUID avatarID) { if (l_EstateAccess.Contains(avatarID)) l_EstateAccess.Remove(avatarID); } public int EstateGroupsCount() { return l_EstateGroups.Count; } public void AddEstateGroup(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateGroups.Contains(avatarID) && (l_EstateGroups.Count < (int)Constants.EstateAccessLimits.AllowedGroups)) l_EstateGroups.Add(avatarID); } public void RemoveEstateGroup(UUID avatarID) { if (l_EstateGroups.Contains(avatarID)) l_EstateGroups.Remove(avatarID); } public int EstateManagersCount() { return l_EstateManagers.Count; } public void AddEstateManager(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateManagers.Contains(avatarID) && (l_EstateManagers.Count < (int)Constants.EstateAccessLimits.EstateManagers)) l_EstateManagers.Add(avatarID); } public void RemoveEstateManager(UUID avatarID) { if (l_EstateManagers.Contains(avatarID)) l_EstateManagers.Remove(avatarID); } public bool IsEstateManagerOrOwner(UUID avatarID) { if (IsEstateOwner(avatarID)) return true; return l_EstateManagers.Contains(avatarID); } public bool IsEstateOwner(UUID avatarID) { if (avatarID == m_EstateOwner) return true; return false; } public bool IsBanned(UUID avatarID) { if (!IsEstateManagerOrOwner(avatarID)) { foreach (EstateBan ban in l_EstateBans) if (ban.BannedUserID == avatarID) return true; } return false; } public bool IsBanned(UUID avatarID, int userFlags) { if (!IsEstateManagerOrOwner(avatarID)) { foreach (EstateBan ban in l_EstateBans) if (ban.BannedUserID == avatarID) return true; if (!HasAccess(avatarID)) { if (DenyMinors) { if ((userFlags & 32) == 0) { return true; } } if (DenyAnonymous) { if ((userFlags & 4) == 0) { return true; } } } } return false; } public int EstateBansCount() { return l_EstateBans.Count; } public void AddBan(EstateBan ban) { if (ban == null) return; if (!IsBanned(ban.BannedUserID, 32) && (l_EstateBans.Count < (int)Constants.EstateAccessLimits.EstateBans)) //Ignore age-based bans l_EstateBans.Add(ban); } public void ClearBans() { l_EstateBans.Clear(); } public void RemoveBan(UUID avatarID) { foreach (EstateBan ban in new List<EstateBan>(l_EstateBans)) if (ban.BannedUserID == avatarID) l_EstateBans.Remove(ban); } public bool HasAccess(UUID user) { if (IsEstateManagerOrOwner(user)) return true; return l_EstateAccess.Contains(user); } public void SetFromFlags(ulong regionFlags) { ResetHomeOnTeleport = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport) == (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport); BlockDwell = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.BlockDwell) == (ulong)OpenMetaverse.RegionFlags.BlockDwell); AllowLandmark = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowLandmark) == (ulong)OpenMetaverse.RegionFlags.AllowLandmark); AllowParcelChanges = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges) == (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges); AllowSetHome = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowSetHome) == (ulong)OpenMetaverse.RegionFlags.AllowSetHome); } public bool GroupAccess(UUID groupID) { return l_EstateGroups.Contains(groupID); } public Dictionary<string, object> ToMap() { Dictionary<string, object> map = new Dictionary<string, object>(); PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in properties) { // EstateBans is a complex type, let's treat it as special if (p.Name == "EstateBans") continue; object value = p.GetValue(this, null); if (value != null) { if (p.PropertyType.IsArray) // of UUIDs { if (((Array)value).Length > 0) { string[] args = new string[((Array)value).Length]; int index = 0; foreach (object o in (Array)value) args[index++] = o.ToString(); map[p.Name] = String.Join(",", args); } } else // simple types map[p.Name] = value; } } // EstateBans are special if (EstateBans.Length > 0) { Dictionary<string, object> bans = new Dictionary<string, object>(); int i = 0; foreach (EstateBan ban in EstateBans) bans["ban" + i++] = ban.ToMap(); map["EstateBans"] = bans; } return map; } /// <summary> /// For debugging /// </summary> /// <returns></returns> public override string ToString() { Dictionary<string, object> map = ToMap(); String result = String.Empty; foreach (KeyValuePair<string, object> kvp in map) { if (kvp.Key == "EstateBans") { result += "EstateBans:" + Environment.NewLine; foreach (KeyValuePair<string, object> ban in (Dictionary<string, object>)kvp.Value) result += ban.Value.ToString(); } else result += string.Format("{0}: {1} {2}", kvp.Key, kvp.Value.ToString(), Environment.NewLine); } return result; } public EstateSettings(Dictionary<string, object> map) { foreach (KeyValuePair<string, object> kvp in map) { PropertyInfo p = this.GetType().GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance); if (p == null) continue; // EstateBans is a complex type, let's treat it as special if (p.Name == "EstateBans") continue; if (p.PropertyType.IsArray) { string[] elements = ((string)map[p.Name]).Split(new char[] { ',' }); UUID[] uuids = new UUID[elements.Length]; int i = 0; foreach (string e in elements) uuids[i++] = new UUID(e); p.SetValue(this, uuids, null); } else { object value = p.GetValue(this, null); if (value is String) p.SetValue(this, map[p.Name], null); else if (value is UInt32) p.SetValue(this, UInt32.Parse((string)map[p.Name]), null); else if (value is Boolean) p.SetValue(this, Boolean.Parse((string)map[p.Name]), null); else if (value is UUID) p.SetValue(this, UUID.Parse((string)map[p.Name]), null); } } // EstateBans are special if (map.ContainsKey("EstateBans")) { var banData = ((Dictionary<string, object>)map["EstateBans"]).Values; EstateBan[] bans = new EstateBan[banData.Count]; int b = 0; foreach (Dictionary<string, object> ban in banData) bans[b++] = new EstateBan(ban); PropertyInfo bansProperty = this.GetType().GetProperty("EstateBans", BindingFlags.Public | BindingFlags.Instance); bansProperty.SetValue(this, bans, null); } } } }
// // PlayerEngine.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using Hyena; using Banshee.Base; using Banshee.Streaming; using Banshee.Collection; using Banshee.ServiceStack; namespace Banshee.MediaEngine { public abstract class PlayerEngine { public const int VolumeDelta = 10; public const int SkipDelta = 10; public event PlayerEventHandler EventChanged; private TrackInfo current_track; private TrackInfo pending_track; private PlayerState current_state = PlayerState.NotReady; private PlayerState last_state = PlayerState.NotReady; // will be changed to PlayerState.Idle after going to PlayerState.Ready private PlayerState idle_state = PlayerState.NotReady; protected abstract void OpenUri (SafeUri uri, bool maybeVideo); internal protected virtual bool DelayedInitialize { get { return false; } } public bool IsInitialized { get; internal set; } internal protected virtual void Initialize () { } public void Reset () { current_track = null; OnStateChanged (idle_state); } public virtual void Close (bool fullShutdown) { if (fullShutdown) { Reset (); } else { OnStateChanged (idle_state); } } public virtual void Dispose () { Close (true); } public void Open (SafeUri uri) { HandleOpen (new UnknownTrackInfo (uri)); } public void Open (TrackInfo track) { HandleOpen (track); } public void SetNextTrack (SafeUri uri) { SetNextTrack (new UnknownTrackInfo (uri)); } public void SetNextTrack (TrackInfo track) { HandleNextTrack (track); } private void HandleNextTrack (TrackInfo track) { pending_track = track; if (current_state != PlayerState.Playing) { // Pre-buffering the next track only makes sense when we're currently playing // Instead, just open. if (track != null && track.Uri != null) { HandleOpen (track); Play (); } return; } try { // Setting the next track doesn't change the player state. SetNextTrackUri (track == null ? null : track.Uri, track == null || track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo); } catch (Exception e) { Log.Exception ("Failed to pre-buffer next track", e); } } private void HandleOpen (TrackInfo track) { var uri = track.Uri; if (current_state != PlayerState.Idle && current_state != PlayerState.NotReady && current_state != PlayerState.Contacting) { Close (false); } try { current_track = track; OnStateChanged (PlayerState.Loading); OpenUri (uri, track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo); } catch (Exception e) { Close (true); OnEventChanged (new PlayerEventErrorArgs (e.Message)); } } public abstract void Play (); public abstract void Pause (); public abstract void Seek (uint position, bool accurate_seek = false); public virtual void SetNextTrackUri (SafeUri uri, bool maybeVideo) { // Opening files on SetNextTrack is a sane default behaviour. // This only wants to be overridden if the PlayerEngine sends out RequestNextTrack signals before EoS OpenUri (uri, maybeVideo); } public virtual void VideoExpose (IntPtr displayContext, bool direct) { throw new NotImplementedException ("Engine must implement VideoExpose since this method only gets called when SupportsVideo is true"); } public virtual void VideoWindowRealize (IntPtr displayContext) { throw new NotImplementedException ("Engine must implement VideoWindowRealize since this method only gets called when SupportsVideo is true"); } public virtual IntPtr [] GetBaseElements () { return null; } protected virtual void OnStateChanged (PlayerState state) { if (current_state == state) { return; } if (idle_state == PlayerState.NotReady && state != PlayerState.Ready) { Hyena.Log.Warning ("Engine must transition to the ready state before other states can be entered", false); return; } else if (idle_state == PlayerState.NotReady && state == PlayerState.Ready) { idle_state = PlayerState.Idle; } last_state = current_state; current_state = state; Log.DebugFormat ("Player state change: {0} -> {1}", last_state, current_state); OnEventChanged (new PlayerEventStateChangeArgs (last_state, current_state)); // Going to the Ready state automatically transitions to the Idle state // The Ready state is advertised so one-time startup processes can easily // happen outside of the engine itself if (state == PlayerState.Ready) { OnStateChanged (PlayerState.Idle); } } protected void OnEventChanged (PlayerEvent evnt) { OnEventChanged (new PlayerEventArgs (evnt)); } protected virtual void OnEventChanged (PlayerEventArgs args) { if (args.Event == PlayerEvent.StartOfStream && pending_track != null) { Log.DebugFormat ("OnEventChanged called with StartOfStream. Replacing current_track with pending_track: \"{0}\"", pending_track.DisplayTrackTitle); current_track = pending_track; pending_track = null; } if (ThreadAssist.InMainThread) { RaiseEventChanged (args); } else { ThreadAssist.ProxyToMain (delegate { RaiseEventChanged (args); }); } } private void RaiseEventChanged (PlayerEventArgs args) { PlayerEventHandler handler = EventChanged; if (handler != null) { handler (args); } } private uint track_info_updated_timeout = 0; protected void OnTagFound (StreamTag tag) { if (tag.Equals (StreamTag.Zero) || current_track == null || (current_track.Uri != null && current_track.Uri.IsFile)) { return; } StreamTagger.TrackInfoMerge (current_track, tag); if (track_info_updated_timeout <= 0) { track_info_updated_timeout = Application.RunTimeout (250, OnTrackInfoUpdated); } } private bool OnTrackInfoUpdated () { TrackInfoUpdated (); track_info_updated_timeout = 0; return false; } public void TrackInfoUpdated () { OnEventChanged (PlayerEvent.TrackInfoUpdated); } public abstract string GetSubtitleDescription (int index); public TrackInfo CurrentTrack { get { return current_track; } } public SafeUri CurrentUri { get { return current_track == null ? null : current_track.Uri; } } public PlayerState CurrentState { get { return current_state; } } public PlayerState LastState { get { return last_state; } } public abstract ushort Volume { get; set; } public virtual bool CanSeek { get { return true; } } public abstract uint Position { get; set; } public abstract uint Length { get; } public abstract IEnumerable SourceCapabilities { get; } public abstract IEnumerable ExplicitDecoderCapabilities { get; } public abstract string Id { get; } public abstract string Name { get; } public abstract bool SupportsEqualizer { get; } public abstract VideoDisplayContextType VideoDisplayContextType { get; } public virtual IntPtr VideoDisplayContext { set { } get { return IntPtr.Zero; } } public abstract int SubtitleCount { get; } public abstract int SubtitleIndex { set; } public abstract SafeUri SubtitleUri { set; get; } public abstract bool InDvdMenu { get; } public abstract void NotifyMouseMove (double x, double y); public abstract void NotifyMouseButtonPressed (int button, double x, double y); public abstract void NotifyMouseButtonReleased (int button, double x, double y); public abstract void NavigateToLeftMenu (); public abstract void NavigateToRightMenu (); public abstract void NavigateToUpMenu (); public abstract void NavigateToDownMenu (); public abstract void NavigateToMenu (); public abstract void ActivateCurrentMenu (); public abstract void GoToNextChapter (); public abstract void GoToPreviousChapter (); } }
// Copyright (c) 2005 - 2008 Ayende Rahien (ayende@ayende.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. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace DiskQueue.Implementation { internal class PersistentQueueImpl : IPersistentQueueImpl { private readonly HashSet<Entry> checkedOutEntries = new HashSet<Entry>(); private readonly Dictionary<int, int> countOfItemsPerFile = new Dictionary<int, int>(); private readonly LinkedList<Entry> entries = new LinkedList<Entry>(); private readonly string path; private readonly object transactionLogLock = new object(); private readonly object writerLock = new object(); static readonly object _configLock = new object(); volatile bool disposed; private FileStream fileLock; const int _32Megabytes = 32*1024*1024; public bool TrimTransactionLogOnDispose { get; set; } public int SuggestedReadBuffer { get; set; } public int SuggestedWriteBuffer { get; set; } public long SuggestedMaxTransactionLogSize { get; set; } public PersistentQueueImpl(string path, int maxFileSize) { lock(_configLock) { disposed = true; TrimTransactionLogOnDispose = true; ParanoidFlushing = true; SuggestedMaxTransactionLogSize = _32Megabytes; SuggestedReadBuffer = 1024*1024; SuggestedWriteBuffer = 1024*1024; MaxFileSize = maxFileSize; try { this.path = Path.GetFullPath(path); if (!Directory.Exists(this.path)) CreateDirectory(this.path); LockQueue(); } catch (UnauthorizedAccessException) { throw new UnauthorizedAccessException("Directory \"" + path + "\" does not exist or is missing write permissions"); } catch (IOException e) { GC.SuppressFinalize(this); //avoid finalizing invalid instance throw new InvalidOperationException("Another instance of the queue is already in action, or directory does not exists", e); } try { ReadMetaState(); ReadTransactionLog(); } catch (Exception) { GC.SuppressFinalize(this); //avoid finalizing invalid instance UnlockQueue(); throw; } disposed = false; } } void UnlockQueue() { if (path == null) return; var target = Path.Combine(path, "lock"); if (fileLock != null) { fileLock.Dispose(); File.Delete(target); } fileLock = null; } void LockQueue() { var target = Path.Combine(path, "lock"); fileLock = new FileStream( target, FileMode.Create, FileAccess.ReadWrite, FileShare.None); } void CreateDirectory(string s) { Directory.CreateDirectory(s); SetPermissions.TryAllowReadWriteForAll(s); } public PersistentQueueImpl(string path) : this(path, _32Megabytes) { } public int EstimatedCountOfItemsInQueue { get { return entries.Count + checkedOutEntries.Count; } } /// <summary> /// <para>Setting this to false may cause unexpected data loss in some failure conditions.</para> /// <para>Defaults to true.</para> /// <para>If true, each transaction commit will flush the transaction log.</para> /// <para>This is slow, but ensures the log is correct per transaction in the event of a hard termination (i.e. power failure)</para> /// </summary> public bool ParanoidFlushing { get; set; } private int CurrentCountOfItemsInQueue { get { lock (entries) { return entries.Count + checkedOutEntries.Count; } } } public int MaxFileSize { get; private set; } public long CurrentFilePosition { get; private set; } private string TransactionLog { get { return Path.Combine(path, "transaction.log"); } } private string Meta { get { return Path.Combine(path, "meta.state"); } } public int CurrentFileNumber { get; private set; } ~PersistentQueueImpl() { if (disposed) return; Dispose(); } public void Dispose() { lock (_configLock) { if (disposed) return; try { disposed = true; lock (transactionLogLock) { if (TrimTransactionLogOnDispose) FlushTrimmedTransactionLog(); } GC.SuppressFinalize(this); } finally { UnlockQueue(); } } } public void AcquireWriter( Stream stream, Func<Stream, long> action, Action<Stream> onReplaceStream) { lock (writerLock) { if (stream.Position != CurrentFilePosition) { stream.Position = CurrentFilePosition; } CurrentFilePosition = action(stream); if (CurrentFilePosition < MaxFileSize) return; CurrentFileNumber += 1; var writer = CreateWriter(); // we assume same size messages, or near size messages // that gives us a good heuroistic for creating the size of // the new file, so it wouldn't be fragmented writer.SetLength(CurrentFilePosition); CurrentFilePosition = 0; onReplaceStream(writer); } } public void CommitTransaction(ICollection<Operation> operations) { if (operations.Count == 0) return; byte[] transactionBuffer = GenerateTransactionBuffer(operations); lock (transactionLogLock) { long txLogSize; using ( var stream = WaitForTransactionLog(transactionBuffer)) { stream.Write(transactionBuffer, 0, transactionBuffer.Length); txLogSize = stream.Position; stream.Flush(); } ApplyTransactionOperations(operations); TrimTransactionLogIfNeeded(txLogSize); Atomic.Write(Meta, stream => { var bytes = BitConverter.GetBytes(CurrentFileNumber); stream.Write(bytes, 0, bytes.Length); bytes = BitConverter.GetBytes(CurrentFilePosition); stream.Write(bytes, 0, bytes.Length); }); if (ParanoidFlushing) FlushTrimmedTransactionLog(); } } FileStream WaitForTransactionLog(byte[] transactionBuffer) { for (int i = 0; i < 10; i++) { try { return new FileStream(TransactionLog, FileMode.Append, FileAccess.Write, FileShare.None, transactionBuffer.Length, FileOptions.SequentialScan | FileOptions.WriteThrough); } catch (Exception) { Thread.Sleep(250); } } throw new TimeoutException("Could not aquire transaction log lock"); } public Entry Dequeue() { lock (entries) { var first = entries.First; if (first == null) return null; var entry = first.Value; if (entry.Data == null) { ReadAhead(); } entries.RemoveFirst(); // we need to create a copy so we will not hold the data // in memory as well as the position checkedOutEntries.Add(new Entry(entry.FileNumber, entry.Start, entry.Length)); return entry; } } /// <summary> /// Assumes that entries has at least one entry /// </summary> private void ReadAhead() { long currentBufferSize = 0; var firstEntry = entries.First.Value; Entry lastEntry = firstEntry; foreach (var entry in entries) { // we can't read ahead to another file or // if we have unordered queue, or sparse items if (entry != lastEntry && (entry.FileNumber != lastEntry.FileNumber || entry.Start != (lastEntry.Start + lastEntry.Length))) break; if (currentBufferSize + entry.Length > SuggestedReadBuffer) break; lastEntry = entry; currentBufferSize += entry.Length; } if (lastEntry == firstEntry) currentBufferSize = lastEntry.Length; byte[] buffer = ReadEntriesFromFile(firstEntry, currentBufferSize); var index = 0; foreach (var entry in entries) { entry.Data = new byte[entry.Length]; Buffer.BlockCopy(buffer, index, entry.Data, 0, entry.Length); index += entry.Length; if (entry == lastEntry) break; } } private byte[] ReadEntriesFromFile(Entry firstEntry, long currentBufferSize) { var buffer = new byte[currentBufferSize]; using (var reader = new FileStream(GetDataPath(firstEntry.FileNumber), FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)) { reader.Position = firstEntry.Start; var totalRead = 0; do { var bytesRead = reader.Read(buffer, totalRead, buffer.Length - totalRead); if (bytesRead == 0) throw new InvalidOperationException("End of file reached while trying to read queue item"); totalRead += bytesRead; } while (totalRead < buffer.Length); } return buffer; } public IPersistentQueueSession OpenSession() { return new PersistentQueueSession(this, CreateWriter(), SuggestedWriteBuffer); } public void Reinstate(IEnumerable<Operation> reinstatedOperations) { lock (entries) { ApplyTransactionOperations( from entry in reinstatedOperations where entry.Type == OperationType.Dequeue select new Operation( OperationType.Reinstate, entry.FileNumber, entry.Start, entry.Length ) ); } } private void ReadTransactionLog() { var requireTxLogTrimming = false; Atomic.Read(TransactionLog, stream => { using (var binaryReader = new BinaryReader(stream)) { bool readingTransaction = false; try { int txCount = 0; while (true) { txCount += 1; // this code ensures that we read the full transaction // before we start to apply it. The last truncated transaction will be // ignored automatically. AssertTransactionSeperator(binaryReader, txCount, Constants.StartTransactionSeparatorGuid, () => readingTransaction = true); var opsCount = binaryReader.ReadInt32(); var txOps = new List<Operation>(opsCount); for (var i = 0; i < opsCount; i++) { AssertOperationSeparator(binaryReader); var operation = new Operation( (OperationType)binaryReader.ReadByte(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadInt32() ); txOps.Add(operation); //if we have non enqueue entries, this means // that we have not closed properly, so we need // to trim the log if (operation.Type != OperationType.Enqueue) requireTxLogTrimming = true; } AssertTransactionSeperator(binaryReader, txCount, Constants.EndTransactionSeparatorGuid, () => { }); readingTransaction = false; ApplyTransactionOperations(txOps); } } catch (EndOfStreamException) { // we have a truncated transaction, need to clear that if (readingTransaction) requireTxLogTrimming = true; } } }); if (requireTxLogTrimming) FlushTrimmedTransactionLog(); } private void FlushTrimmedTransactionLog() { byte[] transactionBuffer; using (var ms = new MemoryStream()) { ms.Write(Constants.StartTransactionSeparator, 0, Constants.StartTransactionSeparator.Length); var count = BitConverter.GetBytes(EstimatedCountOfItemsInQueue); ms.Write(count, 0, count.Length); var checkedOut = checkedOutEntries.ToArray(); foreach (var entry in checkedOut) { WriteEntryToTransactionLog(ms, entry, OperationType.Enqueue); } var listedEntries = entries.ToArray(); foreach (var entry in listedEntries) { WriteEntryToTransactionLog(ms, entry, OperationType.Enqueue); } ms.Write(Constants.EndTransactionSeparator, 0, Constants.EndTransactionSeparator.Length); ms.Flush(); transactionBuffer = ms.ToArray(); } Atomic.Write(TransactionLog, stream => { stream.SetLength(transactionBuffer.Length); stream.Write(transactionBuffer, 0, transactionBuffer.Length); }); } private static void WriteEntryToTransactionLog(Stream ms, Entry entry, OperationType operationType) { ms.Write(Constants.OperationSeparatorBytes, 0, Constants.OperationSeparatorBytes.Length); ms.WriteByte((byte)operationType); var fileNumber = BitConverter.GetBytes(entry.FileNumber); ms.Write(fileNumber, 0, fileNumber.Length); var start = BitConverter.GetBytes(entry.Start); ms.Write(start, 0, start.Length); var length = BitConverter.GetBytes(entry.Length); ms.Write(length, 0, length.Length); } private static void AssertOperationSeparator(BinaryReader reader) { var separator = reader.ReadInt32(); if (separator != Constants.OperationSeparator) throw new InvalidOperationException( "Unexpected data in transaction log. Expected to get transaction separator but got unknonwn data"); } public int[] ApplyTransactionOperationsInMemory(IEnumerable<Operation> operations) { foreach (var operation in operations) { switch (operation.Type) { case OperationType.Enqueue: var entryToAdd = new Entry(operation); entries.AddLast(entryToAdd); var itemCountAddition = countOfItemsPerFile.GetValueOrDefault(entryToAdd.FileNumber); countOfItemsPerFile[entryToAdd.FileNumber] = itemCountAddition + 1; break; case OperationType.Dequeue: var entryToRemove = new Entry(operation); checkedOutEntries.Remove(entryToRemove); var itemCountRemoval = countOfItemsPerFile.GetValueOrDefault(entryToRemove.FileNumber); countOfItemsPerFile[entryToRemove.FileNumber] = itemCountRemoval - 1; break; case OperationType.Reinstate: var entryToReistate = new Entry(operation); entries.AddFirst(entryToReistate); checkedOutEntries.Remove(entryToReistate); break; } } var filesToRemove = new HashSet<int>( from pair in countOfItemsPerFile where pair.Value < 1 select pair.Key ); foreach (var i in filesToRemove) { countOfItemsPerFile.Remove(i); } return filesToRemove.ToArray(); } private static void AssertTransactionSeperator( BinaryReader binaryReader, int txCount, Guid expectedValue, Action hasData) { var bytes = binaryReader.ReadBytes(16); if (bytes.Length == 0) throw new EndOfStreamException(); hasData(); if (bytes.Length != 16) { // looks like we have a truncated transaction in this case, we will // say that we run into end of stream and let the log trimming to deal with this if (binaryReader.BaseStream.Length == binaryReader.BaseStream.Position) { throw new EndOfStreamException(); } throw new InvalidOperationException( "Unexpected data in transaction log. Expected to get transaction separator but got truncated data. Tx #" + txCount); } var separator = new Guid(bytes); if (separator != expectedValue) throw new InvalidOperationException( "Unexpected data in transaction log. Expected to get transaction separator but got unknown data. Tx #" + txCount); } private void ReadMetaState() { Atomic.Read(Meta, stream => { using (var binaryReader = new BinaryReader(stream)) { try { CurrentFileNumber = binaryReader.ReadInt32(); CurrentFilePosition = binaryReader.ReadInt64(); } catch (EndOfStreamException) { } } }); } private void TrimTransactionLogIfNeeded(long txLogSize) { if (txLogSize < SuggestedMaxTransactionLogSize) return; // it is not big enough to care var optimalSize = GetOptimalTransactionLogSize(); if (txLogSize < (optimalSize * 2)) return; // not enough disparity to bother trimming FlushTrimmedTransactionLog(); } private void ApplyTransactionOperations(IEnumerable<Operation> operations) { int[] filesToRemove; lock (entries) { filesToRemove = ApplyTransactionOperationsInMemory(operations); } foreach (var fileNumber in filesToRemove) { if (CurrentFileNumber == fileNumber) continue; File.Delete(GetDataPath(fileNumber)); } } private static byte[] GenerateTransactionBuffer(ICollection<Operation> operations) { byte[] transactionBuffer; using (var ms = new MemoryStream()) { ms.Write(Constants.StartTransactionSeparator, 0, Constants.StartTransactionSeparator.Length); var count = BitConverter.GetBytes(operations.Count); ms.Write(count, 0, count.Length); foreach (var operation in operations) { WriteEntryToTransactionLog(ms, new Entry(operation), operation.Type); } ms.Write(Constants.EndTransactionSeparator, 0, Constants.EndTransactionSeparator.Length); ms.Flush(); transactionBuffer = ms.ToArray(); } return transactionBuffer; } private FileStream CreateWriter() { var dataFilePath = GetDataPath(CurrentFileNumber); var stream = new FileStream( dataFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite, 0x10000, FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.WriteThrough); SetPermissions.TryAllowReadWriteForAll(dataFilePath); return stream; } public string GetDataPath(int index) { return Path.Combine(path, "data." + index); } private long GetOptimalTransactionLogSize() { long size = 0; size += 16 /*sizeof(guid)*/; // initial tx separator size += sizeof(int); // operation count size += ( // entry size == 16 sizeof(int) + // operation separator sizeof(int) + // file number sizeof(int) + // start sizeof(int) // length ) * (CurrentCountOfItemsInQueue); return size; } } }
using System; using CocosSharp; namespace tests { public class TextInputTest : TestNavigationLayer { KeyboardNotificationLayer notificationLayer; TextInputTestScene textinputTestScene = new TextInputTestScene(); public override void RestartCallback(object sender) { CCScene s = new TextInputTestScene(); s.AddChild(textinputTestScene.restartTextInputTest()); Scene.Director.ReplaceScene(s); } public override void NextCallback(object sender) { CCScene s = new TextInputTestScene(); s.AddChild(textinputTestScene.nextTextInputTest()); Scene.Director.ReplaceScene(s); } public override void BackCallback(object sender) { CCScene s = new TextInputTestScene(); s.AddChild(textinputTestScene.backTextInputTest()); Scene.Director.ReplaceScene(s); } public void addKeyboardNotificationLayer(KeyboardNotificationLayer layer) { notificationLayer = layer; AddChild(layer); } public override string Title { get { return "CCTextField Text Input Test"; } } public override string Subtitle { get { return (notificationLayer != null) ? notificationLayer.Subtitle : string.Empty; } } } public class KeyboardNotificationLayer : CCNode { CCTextField trackNode; protected CCPoint beginPosition; public KeyboardNotificationLayer() { // Register Touch Event var touchListener = new CCEventListenerTouchOneByOne(); touchListener.IsSwallowTouches = true; touchListener.OnTouchBegan = OnTouchBegan; touchListener.OnTouchEnded = OnTouchEnded; AddEventListener(touchListener); } public virtual string Subtitle { get { return string.Empty; } } public virtual void OnClickTrackNode(bool bClicked) { throw new NotFiniteNumberException(); } bool OnTouchBegan(CCTouch pTouch, CCEvent touchEvent) { beginPosition = pTouch.Location; return true; } void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent) { if (trackNode == null) { return; } var endPos = pTouch.Location; if (trackNode.BoundingBox.ContainsPoint(beginPosition) && trackNode.BoundingBox.ContainsPoint(endPos)) { OnClickTrackNode(true); } else { OnClickTrackNode(false); } } public override void OnExit() { base.OnExit(); if (trackNode != null) { trackNode.EndEdit(); DetachListeners(); } } protected CCTextField TrackNode { get { return trackNode; } set { if (value == null) { if (trackNode != null) { DetachListeners(); trackNode = value; return; } } if (trackNode != value) { DetachListeners(); } trackNode = value; AttachListeners(); } } void AttachListeners () { // Remember to remove our event listeners. var imeImplementation = trackNode.TextFieldIMEImplementation; imeImplementation.KeyboardDidHide += OnKeyboardDidHide; imeImplementation.KeyboardDidShow += OnKeyboardDidShow; imeImplementation.KeyboardWillHide += OnKeyboardWillHide; imeImplementation.KeyboardWillShow += OnKeyboardWillShow; } void DetachListeners () { if (TrackNode != null) { // Remember to remove our event listeners. var imeImplementation = TrackNode.TextFieldIMEImplementation; imeImplementation.KeyboardDidHide -= OnKeyboardDidHide; imeImplementation.KeyboardDidShow -= OnKeyboardDidShow; imeImplementation.KeyboardWillHide -= OnKeyboardWillHide; imeImplementation.KeyboardWillShow -= OnKeyboardWillShow; } } void OnKeyboardWillShow(object sender, CCIMEKeyboardNotificationInfo e) { CCLog.Log("Keyboard will show"); } void OnKeyboardWillHide(object sender, CCIMEKeyboardNotificationInfo e) { CCLog.Log("Keyboard will Hide"); } void OnKeyboardDidShow(object sender, CCIMEKeyboardNotificationInfo e) { CCLog.Log("Keyboard did show"); } void OnKeyboardDidHide(object sender, CCIMEKeyboardNotificationInfo e) { CCLog.Log("Keyboard did hide"); } } public class TextFieldDefaultTest : KeyboardNotificationLayer { CCMoveTo scrollUp; CCMoveTo scrollDown; public override void OnClickTrackNode(bool bClicked) { if (bClicked && TrackNode != null) { TrackNode.Edit(); } else { if (TrackNode != null && TrackNode != null) { TrackNode.EndEdit(); } } } public override void OnEnter() { base.OnEnter(); var s = VisibleBoundsWorldspace.Size; var textField = new CCTextField("<click here for input>", TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE, CCLabelFormat.SpriteFont); textField.BeginEditing += OnBeginEditing; textField.EndEditing += OnEndEditing; textField.Position = s.Center; textField.AutoEdit = true; AddChild(textField); TrackNode = textField; scrollUp = new CCMoveTo(0.5f, VisibleBoundsWorldspace.Top() - new CCPoint(0, s.Height / 4)); scrollDown = new CCMoveTo(0.5f, textField.Position); } private void OnEndEditing(object sender, ref string text, ref bool canceled) { ((CCNode)sender).RunAction(scrollDown); } private void OnBeginEditing(object sender, ref string text, ref bool canceled) { ((CCNode)sender).RunAction(scrollUp); } public override string Subtitle { get { return "TextField with default behavior test"; } } } ////////////////////////////////////////////////////////////////////////// // TextFieldActionTest ////////////////////////////////////////////////////////////////////////// public class TextFieldActionTest : KeyboardNotificationLayer { CCTextField textField; static CCFiniteTimeAction textFieldAction = new CCSequence( new CCFadeOut(0.25f), new CCFadeIn(0.25f)); CCActionState textFieldActionState; bool action; int charLimit; // the textfield max char limit const int RANDOM_MAX = 32767; public void callbackRemoveNodeWhenDidAction(CCNode node) { this.RemoveChild(node, true); } public override string Subtitle { get { return "CCTextField with action and char limit test"; } } public override void OnClickTrackNode(bool bClicked) { if (bClicked) { TrackNode.Edit(); } else { TrackNode.EndEdit(); } } // CCLayer public override void OnEnter() { base.OnEnter(); charLimit = 12; action = false; textField = new CCTextField("<click here for input>", TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE, CCLabelFormat.SpriteFont); var imeImplementation = textField.TextFieldIMEImplementation; imeImplementation.KeyboardDidHide += OnKeyboardDidHide; imeImplementation.KeyboardDidShow += OnKeyboardDidShow; imeImplementation.InsertText += OnInsertText; imeImplementation.ReplaceText += OnReplaceText; imeImplementation.DeleteBackward += OnDeleteBackward; textField.Position = VisibleBoundsWorldspace.Center; textField.PositionY += VisibleBoundsWorldspace.Size.Height / 4; AddChild(textField); TrackNode = textField; } public override void OnExit() { base.OnExit(); // Remember to remove our event listeners. var imeImplementation = TrackNode.TextFieldIMEImplementation; imeImplementation.KeyboardDidHide -= OnKeyboardDidHide; imeImplementation.KeyboardDidShow -= OnKeyboardDidShow; imeImplementation.InsertText -= OnInsertText; imeImplementation.ReplaceText -= OnReplaceText; imeImplementation.DeleteBackward -= OnDeleteBackward; } void OnDeleteBackward (object sender, CCIMEKeybardEventArgs e) { var focusedTextField = sender as CCTextField; if (focusedTextField == null || string.IsNullOrEmpty(focusedTextField.Text)) { e.Cancel = true; return; } // Just cancel this if we would backspace over the PlaceHolderText as it would just be // replaced anyway and the Action below should not be executed. var delText = focusedTextField.Text; if (delText == focusedTextField.PlaceHolderText) { e.Cancel = true; return; } delText = delText.Substring(delText.Length - 1); // create a delete text sprite and do some action var label = new CCLabel(delText, TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE + 3, CCLabelFormat.SpriteFont); this.AddChild(label); // move the sprite to fly out CCPoint beginPos = focusedTextField.Position; CCSize textfieldSize = focusedTextField.ContentSize; CCSize labelSize = label.ContentSize; beginPos.X += (textfieldSize.Width - labelSize.Width) / 2.0f; var nextRandom = (float)CCRandom.Next(RANDOM_MAX); CCSize winSize = VisibleBoundsWorldspace.Size; CCPoint endPos = new CCPoint(-winSize.Width / 4.0f, winSize.Height * (0.5f + nextRandom / (2.0f * RANDOM_MAX))); float duration = 1; float rotateDuration = 0.2f; int repeatTime = 5; label.Position = beginPos; var delAction = new CCSpawn(new CCMoveTo(duration, endPos), new CCRepeat( new CCRotateBy(rotateDuration, (CCRandom.Next() % 2 > 0) ? 360 : -360), (uint)repeatTime), new CCFadeOut(duration) ); label.RunActionsAsync(delAction, new CCRemoveSelf(true)); } void OnInsertText (object sender, CCIMEKeybardEventArgs e) { var focusedTextField = sender as CCTextField; if (focusedTextField == null) { e.Cancel = true; return; } var text = e.Text; var currentText = focusedTextField.Text; // if insert enter, treat as default to detach with ime if ("\n" == text) { return; } // if the textfield's char count is more than charLimit, don't insert text anymore. if (focusedTextField.CharacterCount >= charLimit) { e.Cancel = true; return; } // create a insert text sprite and do some action var label = new CCLabel(text, TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE, CCLabelFormat.SpriteFont); this.AddChild(label); var color = new CCColor3B { R = 226, G = 121, B = 7 }; label.Color = color; var inputTextSize = focusedTextField.CharacterCount == 0 ? CCSize.Zero : focusedTextField.ContentSize; // move the sprite from top to position var endPos = focusedTextField.Position; endPos.Y -= inputTextSize.Height; if (currentText.Length > 0) { endPos.X += inputTextSize.Width / 2; } var beginPos = new CCPoint(endPos.X, VisibleBoundsWorldspace.Size.Height - inputTextSize.Height * 2); var duration = 0.5f; label.Position = beginPos; label.Scale = 8; CCAction seq = new CCSequence( new CCSpawn( new CCMoveTo(duration, endPos), new CCScaleTo(duration, 1), new CCFadeOut(duration)), new CCRemoveSelf(true)); label.RunAction(seq); } void OnReplaceText (object sender, CCIMEKeybardEventArgs e) { var focusedTextField = sender as CCTextField; if (e.Length > charLimit) e.Text = e.Text.Substring (0, charLimit - 1); } void OnKeyboardDidShow(object sender, CCIMEKeyboardNotificationInfo e) { if (!action) { textFieldActionState = textField.RepeatForever(textFieldAction); action = true; } } void OnKeyboardDidHide(object sender, CCIMEKeyboardNotificationInfo e) { if (action) { textField.StopAction(textFieldActionState); textField.Opacity = 255; action = false; } } } public class TextFieldUpperCaseTest : KeyboardNotificationLayer { public override void OnClickTrackNode(bool bClicked) { if (bClicked && TrackNode != null) { TrackNode.Edit(); } else { if (TrackNode != null && TrackNode != null) { TrackNode.EndEdit(); } } } public override void OnEnter() { base.OnEnter(); var s = VisibleBoundsWorldspace.Size; var textField = new CCTextField("<CLICK HERE FOR INPUT>", TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE, CCLabelFormat.SpriteFont); var imeImplementation = textField.TextFieldIMEImplementation; imeImplementation.InsertText += OnInsertText; imeImplementation.ReplaceText += OnReplaceText; textField.Position = s.Center; textField.AutoEdit = true; AddChild(textField); TrackNode = textField; } public override void OnExit() { base.OnExit(); // Remember to remove our event listeners. var imeImplementation = TrackNode.TextFieldIMEImplementation; imeImplementation.InsertText -= OnInsertText; imeImplementation.ReplaceText -= OnReplaceText; } void OnInsertText (object sender, CCIMEKeybardEventArgs e) { var focusedTextField = sender as CCTextField; e.Text = e.Text.ToUpper(); } void OnReplaceText (object sender, CCIMEKeybardEventArgs e) { var focusedTextField = sender as CCTextField; e.Text = e.Text.ToUpper(); } public override string Subtitle { get { return "TextField Uppercase test"; } } } public class TextFieldCustomIMETest : KeyboardNotificationLayer { public override void OnClickTrackNode(bool bClicked) { if (bClicked && TrackNode != null) { TrackNode.Edit(); } else { if (TrackNode != null && TrackNode != null) { TrackNode.EndEdit(); } } } public override void OnEnter() { base.OnEnter(); var s = VisibleBoundsWorldspace.Size; var textField = new CCTextField("<CLICK HERE FOR INPUT>", TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE, CCLabelFormat.SpriteFont); // Override the default implementation textField.TextFieldIMEImplementation = UppercaseIMEKeyboardImpl.SharedInstance; textField.Position = s.Center; textField.AutoEdit = true; AddChild(textField); TrackNode = textField; } public override string Subtitle { get { return "TextField Custom Uppercase IME implementation"; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using FluentAssertions.Equivalency; namespace FluentAssertions.Common { internal static class TypeExtensions { private const BindingFlags PublicInstanceMembersFlag = BindingFlags.Public | BindingFlags.Instance; private const BindingFlags AllInstanceMembersFlag = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; private const BindingFlags AllStaticAndInstanceMembersFlag = PublicInstanceMembersFlag | BindingFlags.NonPublic | BindingFlags.Static; private static readonly ConcurrentDictionary<Type, bool> HasValueSemanticsCache = new(); private static readonly ConcurrentDictionary<Type, bool> TypeIsRecordCache = new(); private static readonly ConcurrentDictionary<(Type Type, MemberVisibility Visibility), IEnumerable<PropertyInfo>> NonPrivatePropertiesCache = new(); private static readonly ConcurrentDictionary<(Type Type, MemberVisibility Visibility), IEnumerable<FieldInfo>> NonPrivateFieldsCache = new(); public static bool IsDecoratedWith<TAttribute>(this Type type) where TAttribute : Attribute { return type.IsDefined(typeof(TAttribute), inherit: false); } public static bool IsDecoratedWith<TAttribute>(this MemberInfo type) where TAttribute : Attribute { // Do not use MemberInfo.IsDefined // There is an issue with PropertyInfo and EventInfo preventing the inherit option to work. // https://github.com/dotnet/runtime/issues/30219 return Attribute.IsDefined(type, typeof(TAttribute), inherit: false); } public static bool IsDecoratedWithOrInherit<TAttribute>(this Type type) where TAttribute : Attribute { return type.IsDefined(typeof(TAttribute), inherit: true); } public static bool IsDecoratedWithOrInherit<TAttribute>(this MemberInfo type) where TAttribute : Attribute { // Do not use MemberInfo.IsDefined // There is an issue with PropertyInfo and EventInfo preventing the inherit option to work. // https://github.com/dotnet/runtime/issues/30219 return Attribute.IsDefined(type, typeof(TAttribute), inherit: true); } public static bool IsDecoratedWith<TAttribute>(this Type type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate) where TAttribute : Attribute { return GetCustomAttributes(type, isMatchingAttributePredicate).Any(); } public static bool IsDecoratedWith<TAttribute>(this MemberInfo type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate) where TAttribute : Attribute { return GetCustomAttributes(type, isMatchingAttributePredicate).Any(); } public static bool IsDecoratedWithOrInherit<TAttribute>(this Type type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate) where TAttribute : Attribute { return GetCustomAttributes(type, isMatchingAttributePredicate, inherit: true).Any(); } public static IEnumerable<TAttribute> GetMatchingAttributes<TAttribute>(this Type type) where TAttribute : Attribute { return GetCustomAttributes<TAttribute>(type); } public static IEnumerable<TAttribute> GetMatchingAttributes<TAttribute>(this Type type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate) where TAttribute : Attribute { return GetCustomAttributes(type, isMatchingAttributePredicate); } public static IEnumerable<TAttribute> GetMatchingOrInheritedAttributes<TAttribute>(this Type type) where TAttribute : Attribute { return GetCustomAttributes<TAttribute>(type, inherit: true); } public static IEnumerable<TAttribute> GetMatchingOrInheritedAttributes<TAttribute>(this Type type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate) where TAttribute : Attribute { return GetCustomAttributes(type, isMatchingAttributePredicate, inherit: true); } public static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(this MemberInfo type, bool inherit = false) where TAttribute : Attribute { // Do not use MemberInfo.GetCustomAttributes. // There is an issue with PropertyInfo and EventInfo preventing the inherit option to work. // https://github.com/dotnet/runtime/issues/30219 return CustomAttributeExtensions.GetCustomAttributes<TAttribute>(type, inherit); } private static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(MemberInfo type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate, bool inherit = false) where TAttribute : Attribute { Func<TAttribute, bool> isMatchingAttribute = isMatchingAttributePredicate.Compile(); return GetCustomAttributes<TAttribute>(type, inherit).Where(isMatchingAttribute); } private static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(this Type type, bool inherit = false) where TAttribute : Attribute { return (IEnumerable<TAttribute>)type.GetCustomAttributes(typeof(TAttribute), inherit); } private static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(Type type, Expression<Func<TAttribute, bool>> isMatchingAttributePredicate, bool inherit = false) where TAttribute : Attribute { Func<TAttribute, bool> isMatchingAttribute = isMatchingAttributePredicate.Compile(); return GetCustomAttributes<TAttribute>(type, inherit).Where(isMatchingAttribute); } /// <summary> /// Determines whether two <see cref="IMember" /> objects refer to the same /// member. /// </summary> public static bool IsEquivalentTo(this IMember property, IMember otherProperty) { return (property.DeclaringType.IsSameOrInherits(otherProperty.DeclaringType) || otherProperty.DeclaringType.IsSameOrInherits(property.DeclaringType)) && property.Name == otherProperty.Name; } /// <summary> /// Returns the interfaces that the <paramref name="type"/> implements that are concrete /// versions of the <paramref name="openGenericType"/>. /// </summary> public static Type[] GetClosedGenericInterfaces(this Type type, Type openGenericType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == openGenericType) { return new[] { type }; } Type[] interfaces = type.GetInterfaces(); return interfaces .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == openGenericType) .ToArray(); } public static bool OverridesEquals(this Type type) { MethodInfo method = type .GetMethod("Equals", new[] { typeof(object) }); return method is not null && method.GetBaseDefinition().DeclaringType != method.DeclaringType; } /// <summary> /// Finds the property by a case-sensitive name. /// </summary> /// <returns> /// Returns <c>null</c> if no such property exists. /// </returns> public static PropertyInfo FindProperty(this Type type, string propertyName, Type preferredType) { List<PropertyInfo> properties = type.GetProperties(AllInstanceMembersFlag) .Where(pi => pi.Name == propertyName) .ToList(); return properties.Count > 1 ? properties.SingleOrDefault(p => p.PropertyType == preferredType) : properties.SingleOrDefault(); } /// <summary> /// Finds the field by a case-sensitive name. /// </summary> /// <returns> /// Returns <c>null</c> if no such property exists. /// </returns> public static FieldInfo FindField(this Type type, string fieldName, Type preferredType) { List<FieldInfo> properties = type.GetFields(AllInstanceMembersFlag) .Where(pi => pi.Name == fieldName) .ToList(); return properties.Count > 1 ? properties.SingleOrDefault(p => p.FieldType == preferredType) : properties.SingleOrDefault(); } public static IEnumerable<MemberInfo> GetNonPrivateMembers(this Type typeToReflect, MemberVisibility visibility) { return GetNonPrivateProperties(typeToReflect, visibility) .Concat<MemberInfo>(GetNonPrivateFields(typeToReflect, visibility)) .ToArray(); } public static IEnumerable<PropertyInfo> GetNonPrivateProperties(this Type typeToReflect, MemberVisibility visibility) { return NonPrivatePropertiesCache.GetOrAdd((typeToReflect, visibility), static key => { IEnumerable<PropertyInfo> query = from propertyInfo in GetPropertiesFromHierarchy(key.Type, key.Visibility) where HasNonPrivateGetter(propertyInfo) where !propertyInfo.IsIndexer() select propertyInfo; return query.ToArray(); }); } private static IEnumerable<PropertyInfo> GetPropertiesFromHierarchy(Type typeToReflect, MemberVisibility memberVisibility) { bool includeInternals = memberVisibility.HasFlag(MemberVisibility.Internal); return GetMembersFromHierarchy(typeToReflect, type => { return type .GetProperties(AllInstanceMembersFlag | BindingFlags.DeclaredOnly) .Where(property => property.GetMethod?.IsPrivate == false) .Where(property => includeInternals || (property.GetMethod?.IsAssembly == false && property.GetMethod?.IsFamilyOrAssembly == false)) .ToArray(); }); } public static IEnumerable<FieldInfo> GetNonPrivateFields(this Type typeToReflect, MemberVisibility visibility) { return NonPrivateFieldsCache.GetOrAdd((typeToReflect, visibility), static key => { IEnumerable<FieldInfo> query = from fieldInfo in GetFieldsFromHierarchy(key.Type, key.Visibility) where !fieldInfo.IsPrivate where !fieldInfo.IsFamily select fieldInfo; return query.ToArray(); }); } private static IEnumerable<FieldInfo> GetFieldsFromHierarchy(Type typeToReflect, MemberVisibility memberVisibility) { bool includeInternals = memberVisibility.HasFlag(MemberVisibility.Internal); return GetMembersFromHierarchy(typeToReflect, type => { return type .GetFields(AllInstanceMembersFlag) .Where(field => !field.IsPrivate) .Where(field => includeInternals || (!field.IsAssembly && !field.IsFamilyOrAssembly)) .ToArray(); }); } private static IEnumerable<TMemberInfo> GetMembersFromHierarchy<TMemberInfo>( Type typeToReflect, Func<Type, IEnumerable<TMemberInfo>> getMembers) where TMemberInfo : MemberInfo { if (typeToReflect.IsInterface) { return GetInterfaceMembers(typeToReflect, getMembers); } else { return GetClassMembers(typeToReflect, getMembers); } } private static List<TMemberInfo> GetInterfaceMembers<TMemberInfo>(Type typeToReflect, Func<Type, IEnumerable<TMemberInfo>> getMembers) where TMemberInfo : MemberInfo { List<TMemberInfo> members = new(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(typeToReflect); queue.Enqueue(typeToReflect); while (queue.Count > 0) { Type subType = queue.Dequeue(); foreach (Type subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) { continue; } considered.Add(subInterface); queue.Enqueue(subInterface); } IEnumerable<TMemberInfo> typeMembers = getMembers(subType); IEnumerable<TMemberInfo> newPropertyInfos = typeMembers.Where(x => !members.Contains(x)); members.InsertRange(0, newPropertyInfos); } return members; } private static List<TMemberInfo> GetClassMembers<TMemberInfo>(Type typeToReflect, Func<Type, IEnumerable<TMemberInfo>> getMembers) where TMemberInfo : MemberInfo { List<TMemberInfo> members = new(); while (typeToReflect != null) { foreach (var memberInfo in getMembers(typeToReflect)) { if (members.All(mi => mi.Name != memberInfo.Name)) { members.Add(memberInfo); } } typeToReflect = typeToReflect.BaseType; } return members; } private static bool HasNonPrivateGetter(PropertyInfo propertyInfo) { MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true); return getMethod is not null && !getMethod.IsPrivate && !getMethod.IsFamily; } /// <summary> /// Check if the type is declared as abstract. /// </summary> /// <param name="type">Type to be checked</param> public static bool IsCSharpAbstract(this Type type) { return type.IsAbstract && !type.IsSealed; } /// <summary> /// Check if the type is declared as sealed. /// </summary> /// <param name="type">Type to be checked</param> public static bool IsCSharpSealed(this Type type) { return type.IsSealed && !type.IsAbstract; } /// <summary> /// Check if the type is declared as static. /// </summary> /// <param name="type">Type to be checked</param> public static bool IsCSharpStatic(this Type type) { return type.IsSealed && type.IsAbstract; } public static MethodInfo GetMethod(this Type type, string methodName, IEnumerable<Type> parameterTypes) { return type.GetMethods(AllStaticAndInstanceMembersFlag) .SingleOrDefault(m => m.Name == methodName && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } public static bool HasMethod(this Type type, string methodName, IEnumerable<Type> parameterTypes) { return type.GetMethod(methodName, parameterTypes) is not null; } public static MethodInfo GetParameterlessMethod(this Type type, string methodName) { return type.GetMethod(methodName, Enumerable.Empty<Type>()); } public static bool HasParameterlessMethod(this Type type, string methodName) { return type.GetParameterlessMethod(methodName) is not null; } public static PropertyInfo FindPropertyByName(this Type type, string propertyName) { return type.GetProperty(propertyName, AllStaticAndInstanceMembersFlag); } public static bool HasExplicitlyImplementedProperty(this Type type, Type interfaceType, string propertyName) { bool hasGetter = type.HasParameterlessMethod($"{interfaceType.FullName}.get_{propertyName}"); bool hasSetter = type.GetMethods(AllStaticAndInstanceMembersFlag) .SingleOrDefault(m => m.Name == $"{interfaceType.FullName}.set_{propertyName}" && m.GetParameters().Length == 1) is not null; return hasGetter || hasSetter; } public static PropertyInfo GetIndexerByParameterTypes(this Type type, IEnumerable<Type> parameterTypes) { return type.GetProperties(AllStaticAndInstanceMembersFlag) .SingleOrDefault(p => p.IsIndexer() && p.GetIndexParameters().Select(i => i.ParameterType).SequenceEqual(parameterTypes)); } public static bool IsIndexer(this PropertyInfo member) { return member.GetIndexParameters().Length != 0; } public static ConstructorInfo GetConstructor(this Type type, IEnumerable<Type> parameterTypes) { return type .GetConstructors(AllInstanceMembersFlag) .SingleOrDefault(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } public static IEnumerable<MethodInfo> GetConversionOperators(this Type type, Type sourceType, Type targetType, Func<string, bool> predicate) { return type .GetMethods() .Where(m => m.IsPublic && m.IsStatic && m.IsSpecialName && m.ReturnType == targetType && predicate(m.Name) && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == sourceType); } public static bool IsAssignableToOpenGeneric(this Type type, Type definition) { // The CLR type system does not consider anything to be assignable to an open generic type. // For the purposes of test assertions, the user probably means that the subject type is // assignable to any generic type based on the given generic type definition. if (definition.IsInterface) { return type.IsImplementationOfOpenGeneric(definition); } else { return type == definition || type.IsDerivedFromOpenGeneric(definition); } } private static bool IsImplementationOfOpenGeneric(this Type type, Type definition) { // check subject against definition if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == definition) { return true; } // check subject's interfaces against definition return type.GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()) .Contains(definition); } public static bool IsDerivedFromOpenGeneric(this Type type, Type definition) { if (type == definition) { // do not consider a type to be derived from itself return false; } // check subject and its base types against definition for (Type baseType = type; baseType is not null; baseType = baseType.BaseType) { if (baseType.IsGenericType && baseType.GetGenericTypeDefinition() == definition) { return true; } } return false; } public static bool IsUnderNamespace(this Type type, string @namespace) { return IsGlobalNamespace() || IsExactNamespace() || IsParentNamespace(); bool IsGlobalNamespace() => @namespace is null; bool IsExactNamespace() => IsNamespacePrefix() && type.Namespace.Length == @namespace.Length; bool IsParentNamespace() => IsNamespacePrefix() && type.Namespace[@namespace.Length] == '.'; bool IsNamespacePrefix() => type.Namespace?.StartsWith(@namespace, StringComparison.Ordinal) == true; } public static bool IsSameOrInherits(this Type actualType, Type expectedType) { return actualType == expectedType || expectedType.IsAssignableFrom(actualType); } public static MethodInfo GetExplicitConversionOperator(this Type type, Type sourceType, Type targetType) { return type .GetConversionOperators(sourceType, targetType, name => name == "op_Explicit") .SingleOrDefault(); } public static MethodInfo GetImplicitConversionOperator(this Type type, Type sourceType, Type targetType) { return type .GetConversionOperators(sourceType, targetType, name => name == "op_Implicit") .SingleOrDefault(); } public static bool HasValueSemantics(this Type type) { return HasValueSemanticsCache.GetOrAdd(type, static t => t.OverridesEquals() && !t.IsAnonymousType() && !t.IsTuple() && !IsKeyValuePair(t)); } private static bool IsTuple(this Type type) { if (!type.IsGenericType) { return false; } Type openType = type.GetGenericTypeDefinition(); return openType == typeof(ValueTuple<>) || openType == typeof(ValueTuple<,>) || openType == typeof(ValueTuple<,,>) || openType == typeof(ValueTuple<,,,>) || openType == typeof(ValueTuple<,,,,>) || openType == typeof(ValueTuple<,,,,,>) || openType == typeof(ValueTuple<,,,,,,>) || (openType == typeof(ValueTuple<,,,,,,,>) && IsTuple(type.GetGenericArguments()[7])) || openType == typeof(Tuple<>) || openType == typeof(Tuple<,>) || openType == typeof(Tuple<,,>) || openType == typeof(Tuple<,,,>) || openType == typeof(Tuple<,,,,>) || openType == typeof(Tuple<,,,,,>) || openType == typeof(Tuple<,,,,,,>) || (openType == typeof(Tuple<,,,,,,,>) && IsTuple(type.GetGenericArguments()[7])); } private static bool IsAnonymousType(this Type type) { bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType", StringComparison.Ordinal); if (!nameContainsAnonymousType) { return false; } bool hasCompilerGeneratedAttribute = type.IsDecoratedWith<CompilerGeneratedAttribute>(); return hasCompilerGeneratedAttribute; } public static bool IsRecord(this Type type) { return TypeIsRecordCache.GetOrAdd(type, static t => t.GetMethod("<Clone>$") is not null && t.GetTypeInfo() .DeclaredProperties .FirstOrDefault(p => p.Name == "EqualityContract")? .GetMethod? .GetCustomAttribute(typeof(CompilerGeneratedAttribute)) is not null); } private static bool IsKeyValuePair(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>); } /// <summary> /// If the type provided is a nullable type, gets the underlying type. Returns the type itself otherwise. /// </summary> public static Type NullableOrActualType(this Type type) { if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments().First(); } return type; } } }
/* * The author of this software is Steven Fortune. Copyright (c) 1994 by AT&T * Bell Laboratories. * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. */ using System; using System.Collections.Generic; using UnityEngine; namespace Delaunay { public class Voronoi : IDisposable { private SiteList _sites; private Dictionary<Vector2, Site> _sitesIndexedByLocation; private List<Triangle> _triangles; private List<Edge> _edges; // TODO generalize this so it doesn't have to be a Rect; // then we can make the fractal voronois-within-voronois private Rect _plotBounds; public Rect plotBounds { get { return _plotBounds; } } public void Dispose() { int i, n; if (_sites != null) { _sites.Dispose(); _sites = null; } if (_triangles != null) { n = _triangles.Count; for (i = 0; i < n; ++i) { _triangles[i].Dispose(); } _triangles.Clear(); _triangles = null; } if (_edges != null) { n = _edges.Count; for (i = 0; i < n; ++i) { _edges[i].Dispose(); } _edges.Clear(); _edges = null; } _plotBounds = new Rect(); _sitesIndexedByLocation = null; } public Voronoi(List<Vector2> Vector2s, List<uint> colors, Rect plotBounds) { _sites = new SiteList(); _sitesIndexedByLocation = new Dictionary<Vector2, Site>(); AddSites(Vector2s, colors); _plotBounds = plotBounds; _triangles = new List<Triangle>(); _edges = new List<Edge>(); FortunesAlgorithm(); } private void AddSites(List<Vector2> Vector2s, List<uint> colors) { uint length = (uint)Vector2s.Count; for (uint i = 0; i < length; ++i) { AddSite(Vector2s[(int)i], colors != null ? colors[(int)i] : 0, (int)i); } } private void AddSite(Vector2 p, uint color, int index) { //throw new NotImplementedException("This was modified, might not work"); System.Random random = new System.Random(); float weight = (float)random.NextDouble() * 100; Site site = Site.Create(p, index, weight, color); _sites.Push(site); _sitesIndexedByLocation[p] = site; } public List<Edge> Edges() { return _edges; } public List<Vector2> Region(Vector2 p) { Site site = _sitesIndexedByLocation[p]; if (site == null) { return new List<Vector2>(); } return site.Region(_plotBounds); } // TODO: bug: if you call this before you call region(), something goes wrong :( public List<Vector2> NeighborSitesForSite(Vector2 coord) { List<Vector2> Vector2s = new List<Vector2>(); Site site = _sitesIndexedByLocation[coord]; if (site == null) { return Vector2s; } List<Site> sites = site.NeighborSites(); foreach (Site neighbor in sites) { Vector2s.Add(neighbor.Coord()); } return Vector2s; } public List<Circle> Circles() { return _sites.Circles(); } public List<LineSegment> VoronoiBoundaryForSite(Vector2 coord) { return visibleLineSegmentsClass.VisibleLineSegments(selectEdgesForSiteVector2Class.SelectEdgesForSiteVector2(coord, _edges)); } public List<LineSegment> DelaunayLinesForSite(Vector2 coord) { return DelaunayLinesForEdgesClass.DelaunayLinesForEdges(selectEdgesForSiteVector2Class.SelectEdgesForSiteVector2(coord, _edges)); } public List<LineSegment> VoronoiDiagram() { return visibleLineSegmentsClass.VisibleLineSegments(_edges); } public List<LineSegment> DelaunayTriangulation() { return DelaunayTriangulation(null); } public List<LineSegment> DelaunayTriangulation(BitmapData keepOutMask) { return DelaunayLinesForEdgesClass.DelaunayLinesForEdges(selectNonIntersectingEdgesClass.SelectNonIntersectingEdges(keepOutMask, _edges)); } public List<LineSegment> Hull() { return DelaunayLinesForEdgesClass.DelaunayLinesForEdges(HullEdges()); } private List<Edge> HullEdges() { return _edges.Filter(MyTestHullEdges); } bool MyTestHullEdges(Edge edge, int index, List<Edge> vector) { return (edge.IsPartOfConvexHull()); } public List<Vector2> HullVector2sInOrder() { List<Edge> hullEdges = HullEdges(); List<Vector2> Vector2s = new List<Vector2>(); if (hullEdges.Count == 0) { return Vector2s; } EdgeReorderer reorderer = new EdgeReorderer(hullEdges, typeof(Site)); hullEdges = reorderer.Edges; List<LR> orientations = reorderer.EdgeOrientations; reorderer.Dispose(); LR orientation; int n = hullEdges.Count; for (int i = 0; i < n; ++i) { Edge edge = hullEdges[i]; orientation = orientations[i]; Vector2s.Add(edge.GetSite(orientation).Coord()); } return Vector2s; } public List<LineSegment> SpanningTree(BitmapData keepOutMask) { return SpanningTree("minimum", keepOutMask); } public List<LineSegment> SpanningTree() { return SpanningTree("minimum", null); } public List<LineSegment> SpanningTree(string type) { return SpanningTree(type, null); } public List<LineSegment> SpanningTree(string type, BitmapData keepOutMask) { List<Edge> edges = selectNonIntersectingEdgesClass.SelectNonIntersectingEdges(keepOutMask, _edges); List<LineSegment> segments = DelaunayLinesForEdgesClass.DelaunayLinesForEdges(edges); return Kruskal.GetKruskal(segments, type); } public List<List<Vector2>> Regions() { return _sites.Regions(_plotBounds); } public List<uint> SiteColors() { return SiteColors(null); } public List<uint> SiteColors(BitmapData referenceImage) { return _sites.SiteColors(referenceImage); } /** * * @param proximityMap a BitmapData whose regions are filled with the site index values; see PlaneVector2sCanvas::fillRegions() * @param x * @param y * @return coordinates of nearest Site to (x, y) * */ public Vector2 NearestSiteVector2(BitmapData proximityMap, float x, float y) { return _sites.NearestSiteVector2(proximityMap, x, y); } public List<Vector2> SiteCoords() { return _sites.SiteCoords(); } private void FortunesAlgorithm() { Site newSite, bottomSite, topSite, tempSite; Vertex v, vertex; Vector2 newintstar = Vector2.zero; LR leftRight; Halfedge lbnd, rbnd, llbnd, rrbnd, bisector; Edge edge; Rect dataBounds = _sites.GetSitesBounds(); int sqrt_nsites = (int)(Math.Sqrt(_sites.Length + 4)); HalfedgePriorityQueue heap = new HalfedgePriorityQueue(dataBounds.y, dataBounds.height, sqrt_nsites); EdgeList edgeList = new EdgeList(dataBounds.x, dataBounds.width, sqrt_nsites); List<Halfedge> halfEdges = new List<Halfedge>(); List<Vertex> vertices = new List<Vertex>(); Site bottomMostSite = _sites.Next(); newSite = _sites.Next(); for (; ; ) { if (heap.Empty() == false) { newintstar = heap.Min(); } if (newSite != null && (heap.Empty() || CompareByYThenX(newSite, newintstar) < 0)) { /* new site is smallest */ //trace("smallest: new site " + newSite); // Step 8: lbnd = edgeList.EdgeListLeftNeighbor(newSite.Coord()); // the Halfedge just to the left of newSite //trace("lbnd: " + lbnd); rbnd = lbnd.edgeListRightNeighbor; // the Halfedge just to the right //trace("rbnd: " + rbnd); bottomSite = RightRegion(lbnd, bottomMostSite); // this is the same as leftRegion(rbnd) // this Site determines the region containing the new site //trace("new Site is in region of existing site: " + bottomSite); // Step 9: edge = Edge.CreateBisectingEdge(bottomSite, newSite); //trace("new edge: " + edge); _edges.Add(edge); bisector = Halfedge.Create(edge, LR.LEFT); halfEdges.Add(bisector); // inserting two Halfedges into edgeList static readonlyitutes Step 10: // insert bisector to the right of lbnd: edgeList.Insert(lbnd, bisector); // first half of Step 11: if ((vertex = Vertex.Intersect(lbnd, bisector)) != null) { vertices.Add(vertex); heap.Remove(lbnd); lbnd.vertex = vertex; lbnd.ystar = vertex.Y + newSite.Dist(vertex); heap.Insert(lbnd); } lbnd = bisector; bisector = Halfedge.Create(edge, LR.RIGHT); halfEdges.Add(bisector); // second Halfedge for Step 10: // insert bisector to the right of lbnd: edgeList.Insert(lbnd, bisector); // second half of Step 11: if ((vertex = Vertex.Intersect(bisector, rbnd)) != null) { vertices.Add(vertex); bisector.vertex = vertex; bisector.ystar = vertex.Y + newSite.Dist(vertex); heap.Insert(bisector); } newSite = _sites.Next(); } else if (heap.Empty() == false) { /* intersection is smallest */ lbnd = heap.ExtractMin(); llbnd = lbnd.edgeListLeftNeighbor; rbnd = lbnd.edgeListRightNeighbor; rrbnd = rbnd.edgeListRightNeighbor; bottomSite = LeftRegion(lbnd, bottomMostSite); topSite = RightRegion(rbnd, bottomMostSite); // these three sites define a Delaunay triangle // (not actually using these for anything...) //_triangles.Add(new Triangle(bottomSite, topSite, rightRegion(lbnd))); v = lbnd.vertex; v.SetIndex(); lbnd.edge.SetVertex(lbnd.leftRight, v); rbnd.edge.SetVertex(rbnd.leftRight, v); edgeList.Remove(lbnd); heap.Remove(rbnd); edgeList.Remove(rbnd); leftRight = LR.LEFT; if (bottomSite.Y > topSite.Y) { tempSite = bottomSite; bottomSite = topSite; topSite = tempSite; leftRight = LR.RIGHT; } edge = Edge.CreateBisectingEdge(bottomSite, topSite); _edges.Add(edge); bisector = Halfedge.Create(edge, leftRight); halfEdges.Add(bisector); edgeList.Insert(llbnd, bisector); edge.SetVertex(LR.Other(leftRight), v); if ((vertex = Vertex.Intersect(llbnd, bisector)) != null) { vertices.Add(vertex); heap.Remove(llbnd); llbnd.vertex = vertex; llbnd.ystar = vertex.Y + bottomSite.Dist(vertex); heap.Insert(llbnd); } if ((vertex = Vertex.Intersect(bisector, rrbnd)) != null) { vertices.Add(vertex); bisector.vertex = vertex; bisector.ystar = vertex.Y + bottomSite.Dist(vertex); heap.Insert(bisector); } } else { break; } } // heap should be empty now heap.Dispose(); edgeList.Dispose(); foreach (Halfedge halfEdge in halfEdges) { halfEdge.ReallyDispose(); } halfEdges.Clear(); // we need the vertices to clip the edges foreach (Edge edge2 in _edges) { edge2.ClipVertices(_plotBounds); } // but we don't actually ever use them again! foreach (Vertex vertex2 in vertices) { vertex2.Dispose(); } vertices.Clear(); } Site LeftRegion(Halfedge he, Site bottomMostSite) { Edge edge = he.edge; if (edge == null) { return bottomMostSite; } return edge.GetSite(he.leftRight); } Site RightRegion(Halfedge he, Site bottomMostSite) { Edge edge = he.edge; if (edge == null) { return bottomMostSite; } return edge.GetSite(LR.Other(he.leftRight)); } internal static float CompareByYThenX(Site s1, Site s2) { if (s1.Y < s2.Y) return -1; if (s1.Y > s2.Y) return 1; if (s1.X < s2.X) return -1; if (s1.X > s2.X) return 1; return 0; } internal static float CompareByYThenX(Site s1, Vector2 s2) { if (s1.Y < s2.y) return -1; if (s1.Y > s2.y) return 1; if (s1.X < s2.x) return -1; if (s1.X > s2.x) return 1; return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16805")] public partial class HttpClientHandler_SslProtocols_Test { [Fact] public void DefaultProtocols_MatchesExpected() { using (var handler = new HttpClientHandler()) { Assert.Equal(SslProtocols.None, handler.SslProtocols); } } [Theory] [InlineData(SslProtocols.None)] [InlineData(SslProtocols.Tls)] [InlineData(SslProtocols.Tls11)] [InlineData(SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11)] [InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)] public void SetGetProtocols_Roundtrips(SslProtocols protocols) { using (var handler = new HttpClientHandler()) { handler.SslProtocols = protocols; Assert.Equal(protocols, handler.SslProtocols); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsSslConfiguration))] public async Task SetProtocols_AfterRequest_ThrowsException() { using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server), client.GetAsync(url)); }); Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(~SslProtocols.None)] #pragma warning disable 0618 // obsolete warning [InlineData(SslProtocols.Ssl2)] [InlineData(SslProtocols.Ssl3)] [InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)] [InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)] #pragma warning restore 0618 public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols) { using (var handler = new HttpClientHandler()) { Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(BackendSupportsSslConfiguration))] [InlineData(SslProtocols.Tls, false)] [InlineData(SslProtocols.Tls, true)] [InlineData(SslProtocols.Tls11, false)] [InlineData(SslProtocols.Tls11, true)] [InlineData(SslProtocols.Tls12, false)] [InlineData(SslProtocols.Tls12, true)] public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol) { if (ManagedHandlerTestHelpers.IsEnabled) { // TODO #23138: The managed handler is failing. return; } using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { if (requestOnlyThisProtocol) { handler.SslProtocols = acceptedProtocol; } var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } public static readonly object [][] SupportedSSLVersionServers = { new object[] {SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer}, new object[] {SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer}, new object[] {SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer}, }; // This test is logically the same as the above test, albeit using remote servers // instead of local ones. We're keeping it for now (as outerloop) because it helps // to validate against another SSL implementation that what we mean by a particular // TLS version matches that other implementation. [OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")] [Theory] [MemberData(nameof(SupportedSSLVersionServers))] public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url) { if (ManagedHandlerTestHelpers.IsEnabled) { // TODO #23138: The managed handler is failing. return; } using (HttpClientHandler handler = new HttpClientHandler()) { if (PlatformDetection.IsCentos7) { // Default protocol selection is always TLSv1 on Centos7 libcurl 7.29.0 // Hence, set the specific protocol on HttpClient that is required by test handler.SslProtocols = sslProtocols; } using (var client = new HttpClient(handler)) { (await client.GetAsync(url)).Dispose(); } } } public static readonly object[][] NotSupportedSSLVersionServers = { new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer}, new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer}, }; // It would be easy to remove the dependency on these remote servers if we didn't // explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw // when trying to use such an SslStream, we can't stand up a localhost server that // only speaks those protocols. [OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")] [ConditionalTheory(nameof(SSLv3DisabledByDefault))] [MemberData(nameof(NotSupportedSSLVersionServers))] public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url) { if (ManagedHandlerTestHelpers.IsEnabled && !PlatformDetection.IsWindows10Version1607OrGreater) { // On Windows, https://github.com/dotnet/corefx/issues/21925#issuecomment-313408314 // On Linux, an older version of OpenSSL may permit negotiating SSLv3. return; } using (var client = new HttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsSslConfiguration), nameof(SslDefaultsToTls12))] public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12() { using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( client.GetAsync(url), LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(stream).SslProtocol); await LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer); return null; }, options)); }, options); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(BackendSupportsSslConfiguration))] [InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))] [InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))] [InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))] public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException( SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException) { using (var handler = new HttpClientHandler() { SslProtocols = allowedProtocol, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( Assert.ThrowsAsync(exceptedServerException, () => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)), Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url))); }, options); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(8538, TestPlatforms.Windows)] [Fact] public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12() { using (var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { if (BackendSupportsSslConfiguration) { LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true }; options.SslProtocols = SslProtocols.Tls; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( Assert.ThrowsAsync<IOException>(() => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)), Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url))); }, options); foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 }) { options.SslProtocols = prot; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } else { await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/")); } } } private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7; // TLS 1.2 may not be enabled on Win7 // https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12 } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Text.RegularExpressions; using Castle.Components.Validator; namespace Cuyahoga.Core.Domain { /// <summary> /// The Node class represents a node in the page hierarchy of the site. /// </summary> public class Node { private int _id; private string _title; private string _shortDescription; private int _position; private Site _site; private Node _parentNode; private IList<Node> _childNodes; private IList<Section> _sections; private Template _template; private int[] _trail; private Node[] _nodePath; private IList<NodePermission> _nodePermissions; private string _culture; private bool _showInNavigation; private string _linkUrl; private LinkTarget _linkTarget; private string _metaKeywords; private string _metaDescription; private DateTime _updateTimestamp; #region properties /// <summary> /// Property Id (int) /// </summary> public virtual int Id { get { return this._id; } set { this._id = value; } } /// <summary> /// Property Title (string) /// </summary> [ValidateNonEmpty("NodeTitleValidatorNonEmpty")] [ValidateLength(1, 255, "NodeTitleValidatorLength")] public virtual string Title { get { return this._title; } set { this._title = value; } } /// <summary> /// Property ShortDescription (string) /// </summary> [ValidateNonEmpty("NodeShortDescriptionValidatorNonEmpty")] [ValidateLength(1, 255, "NodeShortDescriptionValidatorLength")] public virtual string ShortDescription { get { return this._shortDescription; } set { this._shortDescription = value; } } /// <summary> /// Property Order (int) /// </summary> public virtual int Position { get { return this._position; } set { this._position = value; } } /// <summary> /// Property Culture (string) /// </summary> [ValidateNonEmpty("NodeCultureValidatorNonEmpty")] public virtual string Culture { get { return this._culture; } set { this._culture = value; } } /// <summary> /// Property ShowInNavigation (bool) /// </summary> public virtual bool ShowInNavigation { get { return this._showInNavigation; } set { this._showInNavigation = value; } } /// <summary> /// Link to external url. /// </summary> [ValidateLength(1, 255, "NodeLinkUrlValidatorLength")] [ValidateRegExp(@"^http(s)*://(\w[.\w]*)(:\d+)*(/\w[.\w]*)*", "NodeLinkUrlValidatorPattern")] public virtual string LinkUrl { get { return this._linkUrl; } set { this._linkUrl = value; } } /// <summary> /// Target window for an external url. /// </summary> public virtual LinkTarget LinkTarget { get { return this._linkTarget; } set { this._linkTarget = value; } } /// <summary> /// Indicates if the node represents an external link. /// </summary> public virtual bool IsExternalLink { get { return this._linkUrl != null; } } /// <summary> /// The display url of the node. /// </summary> public virtual string DisplayUrl { get { return this.IsExternalLink ? this.LinkUrl : "/" + this.ShortDescription; } } /// <summary> /// List of keywords for the page. /// </summary> [ValidateLength(1, 500, "MetaKeywordsValidatorLength")] public virtual string MetaKeywords { get { return this._metaKeywords; } set { this._metaKeywords = value; } } /// <summary> /// Description of the page. /// </summary> [ValidateLength(1, 500, "MetaDescriptionValidatorLength")] public virtual string MetaDescription { get { return this._metaDescription; } set { this._metaDescription = value; } } /// <summary> /// Property UpdateTimestamp (DateTime) /// </summary> public virtual DateTime UpdateTimestamp { get { return this._updateTimestamp; } set { this._updateTimestamp = value; } } /// <summary> /// Property Level (int) /// </summary> public virtual int Level { get { int level = 0; Node parentNode = this.ParentNode; while (parentNode != null) { parentNode = parentNode.ParentNode; level++; } return level; } } /// <summary> /// Property Site (Site) /// </summary> [ValidateNonEmpty] public virtual Site Site { get { return this._site; } set { this._site = value; } } /// <summary> /// Property ParentNode (Node). Lazy loaded. /// </summary> public virtual Node ParentNode { get { return this._parentNode; } set { this._parentNode = value; } } /// <summary> /// Property ChildNodes (IList). Lazy loaded. /// </summary> public virtual IList<Node> ChildNodes { get { return this._childNodes; } set { // TODO? // Notify that the ChildNodes are loaded. I really want to do this only when the // ChildNodes are loaded (lazy) from the database but I don't know if this happens right now. // Implement IInterceptor? //OnChildrenLoaded(); this._childNodes = value; } } /// <summary> /// Property Sections (IList). Lazy loaded. /// </summary> public virtual IList<Section> Sections { get { return this._sections; } set { this._sections = value; } } /// <summary> /// Property Template (Template) /// </summary> public virtual Template Template { get { return this._template; } set { this._template = value; } } /// <summary> /// Array with all NodeId's from the current node to the root node. /// </summary> public virtual int[] Trail { get { if (this._trail == null) { SetNodePath(); } return this._trail; } } /// <summary> /// Array with all Nodes from the current node to the root node. /// </summary> public virtual Node[] NodePath { get { if (this._nodePath == null) { SetNodePath(); } return this._nodePath; } } /// <summary> /// Property NodePermissions (IList) /// </summary> public virtual IList<NodePermission> NodePermissions { get { return this._nodePermissions; } set { this._nodePermissions = value; } } /// <summary> /// Can the node be viewed by anonymous users? /// </summary> public virtual bool AnonymousViewAllowed { get { return this._nodePermissions.Any(np => np.Role.IsAnonymousRole); } } /// <summary> /// Indicates if the node a root node (home)? /// </summary> public virtual bool IsRootNode { get { return this._id > -1 && this._parentNode == null; } } #endregion #region constructors and initialization /// <summary> /// Default constructor. /// </summary> public Node() { this._id = -1; InitNode(); } private void InitNode() { this._shortDescription = null; this._parentNode = null; this._template = null; this._childNodes = null; this._position = -1; this._trail = null; this._showInNavigation = true; this._childNodes = new List<Node>(); this._sections = new List<Section>(); this._nodePermissions = new List<NodePermission>(); } #endregion #region methods /// <summary> /// Checks if the node is in the path from the root to the given otherNode (also includes the node itself). /// </summary> /// <param name="otherNode">The node to check the path for. When null, IsInPath returns false.</param> /// <returns></returns> public virtual bool IsInPath(Node otherNode) { if (otherNode == null) { return false; } bool isInPath = this.Level < otherNode.NodePath.Length && otherNode.NodePath[this.Level].Id == this.Id; return isInPath; } /// <summary> /// Move the node to a different position in the tree. /// </summary> /// <param name="rootNodes">We need the root nodes when the node has no ParentNode</param> /// <param name="npm">Direction</param> public virtual void Move(IList<Node> rootNodes, NodePositionMovement npm) { switch (npm) { case NodePositionMovement.Up: MoveUp(rootNodes); break; case NodePositionMovement.Down: MoveDown(rootNodes); break; case NodePositionMovement.Left: MoveLeft(rootNodes); break; case NodePositionMovement.Right: MoveRight(rootNodes); break; } } /// <summary> /// Calculate the position of a new node. /// </summary> /// <param name="rootNodes">The root nodes for the case an item as added at root level.</param> public virtual void CalculateNewPosition(IList rootNodes) { if (this.ParentNode != null) { this._position = this.ParentNode.ChildNodes.Count; } else { this._position = rootNodes.Count; } } /// <summary> /// Ensure that there is no gap between the positions of nodes. /// </summary> /// <param name="nodeListWithGap"></param> /// <param name="gapPosition"></param> public virtual void ReOrderNodePositions(IList<Node> nodeListWithGap, int gapPosition) { foreach (Node node in nodeListWithGap) { if (node.Position > gapPosition) { node.Position--; } } } /// <summary> /// Set the sections to null, so they will be loaded from the database next time. /// </summary> public virtual void ResetSections() { this._sections = null; } /// <summary> /// Indicates if viewing of the node is allowed. Anonymous users get a special treatment because we /// can't check their rights because they are no full-blown Cuyahoga users (not authenticated). /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual bool ViewAllowed(IIdentity user) { User cuyahogaUser = user as User; if (this.AnonymousViewAllowed) { return true; } else if (cuyahogaUser != null) { return cuyahogaUser.CanView(this); } else { return false; } } /// <summary> /// /// </summary> /// <param name="role"></param> /// <returns></returns> public virtual bool ViewAllowed(Role role) { foreach (NodePermission np in this.NodePermissions) { if (np.Role == role && np.ViewAllowed) { return true; } } return false; } /// <summary> /// /// </summary> /// <param name="role"></param> /// <returns></returns> public virtual bool EditAllowed(Role role) { foreach (NodePermission np in this.NodePermissions) { if (np.Role == role && np.EditAllowed) { return true; } } return false; } /// <summary> /// /// </summary> public virtual void CopyRolesFromParent() { if (this._parentNode != null) { foreach (NodePermission np in this._parentNode.NodePermissions) { NodePermission npNew = new NodePermission(); npNew.Node = this; npNew.Role = np.Role; npNew.ViewAllowed = np.ViewAllowed; npNew.EditAllowed = np.EditAllowed; this.NodePermissions.Add(npNew); } } } /// <summary> /// Generate a short description based on the parent short description and the title. /// </summary> public virtual void CreateShortDescription() { string prefix = ""; if (this._parentNode != null) { prefix += this._parentNode.ShortDescription + "/"; } // Substitute spaces string tempTitle = Regex.Replace(this._title.Trim(), "\\s", "-"); // Remove illegal characters tempTitle = Regex.Replace(tempTitle, "[^A-Za-z0-9+-.]", ""); this._shortDescription = prefix + tempTitle.ToLower(); } /// <summary> /// Rebuild an already existing ShortDescription to make it unique by adding a suffix (integer). /// </summary> /// <param name="suffix"></param> public virtual void RecreateShortDescription(int suffix) { string tmpShortDescription = this._shortDescription.Substring(0, this._shortDescription.Length - 2); this._shortDescription = tmpShortDescription + "_" + suffix.ToString(); } /// <summary> /// Validate the node. /// </summary> public virtual void Validate() { // check if the the node is a root node and if so, check the uniqueness of the culture if (this.ParentNode == null) // indicates a root node { foreach (Node node in this.Site.RootNodes) { if (node.Id != this._id && node.Culture == this.Culture) { throw new Exception("Found a root node with the same culture. The culture of a root node has to be unique within a site."); } } } } /// <summary> /// Change the parent of this node to the given new parent. /// </summary> /// <param name="newParentNode"></param> public virtual void ChangeParent(Node newParentNode) { // Don't do anything when the node is a root node or when the parent hasn't changed. if (this.IsRootNode || newParentNode.Id == this.ParentNode.Id) { return; } // Remove node from parent childnodes IList<Node> oldParentChildNodes = this.ParentNode.ChildNodes; oldParentChildNodes.Remove(this); // Update sort order of old parent childnodes for (int i = 0; i < oldParentChildNodes.Count; i++) { Node childNodeToBeRepositioned = oldParentChildNodes[i]; childNodeToBeRepositioned.Position = i; } // Add to children new parent int newPosition = newParentNode.ChildNodes.Count; this.Position = newPosition; this.ParentNode = newParentNode; newParentNode.ChildNodes.Add(this); } /// <summary> /// Creates a new node that comes under the given parent node and copies the contents of this node. /// </summary> /// <param name="parentNode"></param> /// <returns>The newly created node.</returns> public virtual Node Copy(Node parentNode) { Node newNode = new Node(); newNode.Site = this.Site; newNode.Title = "Copy of " + this.Title; newNode.ParentNode = parentNode; newNode.CreateShortDescription(); newNode.Culture = parentNode.Culture; newNode.Template = this.Template; newNode.ShowInNavigation = this.ShowInNavigation; newNode.LinkUrl = this.LinkUrl; newNode.LinkTarget = this.LinkTarget; newNode.MetaDescription = this.MetaDescription; newNode.MetaKeywords = this.MetaKeywords; // Add to children parent newNode.Position = parentNode.ChildNodes.Count; newNode.ParentNode = parentNode; parentNode.ChildNodes.Add(newNode); // Apply permissions from parent node newNode.CopyRolesFromParent(); // Add sections foreach (Section section in this.Sections) { Section newSection = section.Copy(); newNode.Sections.Add(newSection); newSection.Node = newNode; newSection.CopyRolesFromNode(); } return newNode; } /// <summary> /// Add a new section to the Node. /// </summary> /// <param name="section"></param> public virtual void AddSection(Section section) { section.Node = this; // First, try to determine the position of the section. if (section.PlaceholderId != null) { section.CalculateNewPosition(); } // Add to collection. this.Sections.Add(section); // Apply security section.CopyRolesFromNode(); } /// <summary> /// Remove a section from the node and recalculate position of adjacent sections (with the same placeholder). /// </summary> /// <param name="sectionToRemove"></param> public virtual void RemoveSection(Section sectionToRemove) { this.Sections.Remove(sectionToRemove); sectionToRemove.Node = null; sectionToRemove.PlaceholderId = null; sectionToRemove.Position = -1; int position = 0; foreach (Section section in this.Sections) { if (section.PlaceholderId == sectionToRemove.PlaceholderId) { section.Position = position; position++; } } } /// <summary> /// Move the node one position upwards and move the node above this one one position downwards. /// </summary> /// <param name="rootNodes">We need these when the node has no ParentNode.</param> private void MoveUp(IList<Node> rootNodes) { if (this._position > 0) { // HACK: Assume that the node indexes are the same as the value of the positions. this._position--; IList<Node> parentChildNodes = (this.ParentNode == null ? rootNodes : this.ParentNode.ChildNodes); ((Node)parentChildNodes[this._position]).Position++; parentChildNodes.Remove(this); parentChildNodes.Insert(this._position, this); } } /// <summary> /// Move the node one position downwards and move the node above this one one position upwards. /// </summary> /// <param name="rootNodes">We need these when the node has no ParentNode.</param> private void MoveDown(IList<Node> rootNodes) { if (this._position < this.ParentNode.ChildNodes.Count - 1) { // HACK: Assume that the node indexes are the same as the value of the positions. this._position++; IList<Node> parentChildNodes = (this.ParentNode == null ? rootNodes : this.ParentNode.ChildNodes); ((Node)parentChildNodes[this._position]).Position--; parentChildNodes.Remove(this); parentChildNodes.Insert(this._position, this); } } /// <summary> /// Move node to the same level as the parentnode at the position just beneath the parent node. /// </summary> /// <param name="rootNodes">The root nodes. We need these when a node is moved to the /// root level because the nodes that come after this one ahve to be moved and can't be reached /// anymore by traversing related nodes.</param> private void MoveLeft(IList<Node> rootNodes) { int newPosition = this.ParentNode.Position + 1; if (this.ParentNode.Level == 0) { for (int i = newPosition; i < rootNodes.Count; i++) { Node nodeAlsoToBeMoved = (Node)rootNodes[i]; nodeAlsoToBeMoved.Position++; } } else { for (int i = newPosition; i < this.ParentNode.ParentNode.ChildNodes.Count; i++) { Node nodeAlsoToBeMoved = (Node)this.ParentNode.ParentNode.ChildNodes[i]; nodeAlsoToBeMoved.Position++; } } this.ParentNode.ChildNodes.Remove(this); ReOrderNodePositions(this.ParentNode.ChildNodes, this.Position); this.ParentNode = this.ParentNode.ParentNode; if (this.ParentNode != null) { this.ParentNode.ChildNodes.Add(this); } this.Position = newPosition; } /// <summary> /// Add node to the children of the previous node in the list. /// </summary> /// <param name="rootNodes"></param> private void MoveRight(IList<Node> rootNodes) { if (this._position > 0) { Node previousSibling; if (this.ParentNode != null) { previousSibling = (Node)this.ParentNode.ChildNodes[this._position - 1]; this.ParentNode.ChildNodes.Remove(this); ReOrderNodePositions(this.ParentNode.ChildNodes, this.Position); } else { previousSibling = (Node)rootNodes[this._position - 1]; ReOrderNodePositions(rootNodes, this.Position); } this.Position = previousSibling.ChildNodes.Count; previousSibling.ChildNodes.Add(this); this.ParentNode = previousSibling; } } private void SetNodePath() { if (this.Level > -1) { this._trail = new int[this.Level + 1]; this._nodePath = new Node[this.Level + 1]; this._trail[this.Level] = this._id; this._nodePath[this.Level] = this; Node tmpParentNode = this.ParentNode; while (tmpParentNode != null) { this._trail[tmpParentNode.Level] = tmpParentNode.Id; this._nodePath[tmpParentNode.Level] = tmpParentNode; tmpParentNode = tmpParentNode.ParentNode; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToZeroScalarSingle() { var test = new SimpleBinaryOpTest__RoundToZeroScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__RoundToZeroScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__RoundToZeroScalarSingle testClass) { var result = Sse41.RoundToZeroScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__RoundToZeroScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse41.RoundToZeroScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__RoundToZeroScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__RoundToZeroScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToZeroScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToZeroScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToZeroScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToZeroScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse41.RoundToZeroScalar( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse41.RoundToZeroScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.RoundToZeroScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.RoundToZeroScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__RoundToZeroScalarSingle(); var result = Sse41.RoundToZeroScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__RoundToZeroScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse41.RoundToZeroScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToZeroScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse41.RoundToZeroScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToZeroScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToZeroScalar( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((right[0] > 0) ? MathF.Floor(right[0]) : MathF.Ceiling(right[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToZeroScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using Cassandra.IntegrationTests.TestBase; using Cassandra.Tests; namespace Cassandra.IntegrationTests.TestClusterManagement { public class CloudCluster : ITestCluster { public string Name { get; set; } public string Version { get; set; } public Builder Builder { get; set; } public Cluster Cluster { get; set; } public ISession Session { get; set; } public string InitialContactPoint { get; set; } public string ClusterIpPrefix { get; set; } public string DefaultKeyspace { get; set; } public bool SniCertificateValidation { get; } public string SniHomeDirectory { get; private set; } public CloudCluster(string name, string version, bool enableCert) { SniCertificateValidation = enableCert; Name = name; InitialContactPoint = ClusterIpPrefix + "1"; Version = version; } public void ShutDown() { DockerKill(); } public void Remove() { throw new System.NotImplementedException(); } public void Remove(int nodeId) { throw new System.NotImplementedException(); } public void Create(int nodeLength, TestClusterOptions options = null) { var sniPath = Environment.GetEnvironmentVariable("SINGLE_ENDPOINT_PATH"); if (sniPath == null) { sniPath = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "proxy", "run.sh"); Trace.TraceInformation("SINGLE_ENDPOINT_PATH not set, using " + sniPath); } var fileInfo = new FileInfo(sniPath); var args = string.Empty; var envVars = new Dictionary<string, string>(); var timeout = 300000; if (SniCertificateValidation && TestCloudClusterManager.CertFile != null) { if (sniPath.EndsWith("run.ps1")) { args = " -REQUIRE_CLIENT_CERTIFICATE true"; } else { envVars["REQUIRE_CLIENT_CERTIFICATE"] = "true"; } } if (SniCertificateValidation && TestCloudClusterManager.CertFile == null) { throw new InvalidOperationException("_enableCert is true but cert file env variable is false"); } if (sniPath.EndsWith(".ps1")) { timeout = 1800000; var oldSniPath = sniPath; sniPath = @"powershell"; args = "-executionpolicy unrestricted \"& '" + oldSniPath + "'" + args + "\""; } if (envVars.ContainsKey("REQUIRE_CLIENT_CERTIFICATE")) { args = @"-c ""export REQUIRE_CLIENT_CERTIFICATE=true && " + sniPath + "\""; sniPath = "bash"; } SniHomeDirectory = fileInfo.Directory.FullName; ExecCommand(true, sniPath, args, timeout, envVars, fileInfo.Directory.FullName, true); } public void StopForce(int nodeIdToStop) { throw new System.NotImplementedException(); } public void Stop(int nodeIdToStop) { ExecCcmCommand($"node{nodeIdToStop} stop"); } public void Start(int nodeIdToStart, string additionalArgs = null, string newIp = null, string[] jvmArgs = null) { ExecCcmCommand($"node{nodeIdToStart} start --root --wait-for-binary-proto {additionalArgs} {jvmArgs}"); } public void Start(string[] jvmArgs = null) { ExecCcmCommand($"start --root --wait-for-binary-proto {jvmArgs}"); } public void UpdateDseConfig(params string[] yamlChanges) { throw new NotImplementedException(); } public void UpdateConfig(params string[] yamlChanges) { throw new System.NotImplementedException(); } public void UpdateConfig(int nodeId, params string[] yamlChanges) { throw new NotImplementedException(); } public void InitClient() { throw new System.NotImplementedException(); } public void BootstrapNode(int nodeIdToStart, bool start = true) { throw new NotImplementedException(); } public void SetNodeWorkloads(int nodeId, string[] workloads) { throw new NotImplementedException(); } public void BootstrapNode(int nodeIdToStart, string dataCenterName, bool start = true) { throw new NotImplementedException(); } public void BootstrapNode(int nodeIdToStart) { throw new NotImplementedException(); } public void BootstrapNode(int nodeIdToStart, string dataCenterName) { throw new NotImplementedException(); } public void DecommissionNode(int nodeId) { throw new System.NotImplementedException(); } public void DecommissionNodeForcefully(int nodeId) { throw new NotImplementedException(); } public void PauseNode(int nodeId) { throw new System.NotImplementedException(); } public void ResumeNode(int nodeId) { throw new System.NotImplementedException(); } public void SwitchToThisCluster() { throw new NotImplementedException(); } private static void ExecCcmCommand(string ccmCmd) { if (TestHelper.IsWin) { ccmCmd = ccmCmd.Replace("\"", "\"\"\""); ExecCommand(true, "powershell", $"-command \"docker ps -a -q --filter ancestor=single_endpoint | % {{ docker exec $_ ccm {ccmCmd} }}\""); } else { ccmCmd = ccmCmd.Replace("\"", @"\"""); ExecCommand(true, "bash", $@"-c ""docker exec $(docker ps -a -q --filter ancestor=single_endpoint) ccm {ccmCmd}"""); } } private static ProcessOutput ExecCommand(bool throwOnProcessError, string executable, string args, int timeOut = 20*60*1000, IReadOnlyDictionary<string, string> envVars = null, string workDir = null, bool killOnTimeout = false) { Trace.TraceInformation($"{executable} {args}"); var output = ExecuteProcess(executable, args, timeOut, envVariables: envVars, workDir: workDir, killOnTimeout: killOnTimeout); if (!throwOnProcessError) { return output; } if (output.ExitCode != 0) { throw new TestInfrastructureException($"Process exited in error {output}"); } return output; } public static void DockerKill() { if (TestHelper.IsWin) { ExecCommand(true, "powershell", "-command \"docker ps -a -q --filter ancestor=single_endpoint | % { docker kill $_ }\""); } else { ExecCommand(true, "bash", @"-c ""docker kill $(docker ps -a -q --filter ancestor=single_endpoint)"""); } } /// <summary> /// Spawns a new process (platform independent) /// </summary> private static ProcessOutput ExecuteProcess( string processName, string args, int timeout, IReadOnlyDictionary<string, string> envVariables = null, string workDir = null, bool killOnTimeout = false) { var output = new ProcessOutput(); using (var process = new Process()) { process.StartInfo.FileName = processName; process.StartInfo.Arguments = args; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; //Hide the python window if possible process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (envVariables != null) { foreach (var envVar in envVariables) { process.StartInfo.EnvironmentVariables[envVar.Key] = envVar.Value; } } if (workDir != null) { process.StartInfo.WorkingDirectory = workDir; } using (var outputWaitHandle = new AutoResetEvent(false)) using (var errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { try { outputWaitHandle.Set(); } catch { //probably is already disposed } } else { output.OutputText.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { try { errorWaitHandle.Set(); } catch { //probably is already disposed } } else { output.OutputText.AppendLine(e.Data); } }; try { process.Start(); } catch (Exception exception) { Trace.TraceInformation("Process start failure: " + exception.Message); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed. output.ExitCode = process.ExitCode; } else { // Timed out. output.ExitCode = -1; if (killOnTimeout) { process.Kill(); } } } } return output; } } }
using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; #if UNITY_IOS using UnityEditor.iOS.Xcode; #endif using UnityEngine.XR.iOS; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System; public class UnityARBuildPostprocessor { static List<ARReferenceImagesSet> imageSets = new List<ARReferenceImagesSet>(); // Build postprocessor. Currently only needed on: // - iOS: no dynamic libraries, so plugin source files have to be copied into Xcode project [PostProcessBuild] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { if (target == BuildTarget.iOS) OnPostprocessBuildIOS(pathToBuiltProject); } [PostProcessScene] public static void OnPostProcessScene() { if (!BuildPipeline.isBuildingPlayer) return; foreach(ARReferenceImagesSet ar in UnityEngine.Resources.FindObjectsOfTypeAll<ARReferenceImagesSet>()) { if (!imageSets.Contains (ar)) { imageSets.Add (ar); } } } private static UnityARKitPluginSettings LoadSettings() { UnityARKitPluginSettings loadedSettings = Resources.Load<UnityARKitPluginSettings> ("UnityARKitPlugin/ARKitSettings"); if (loadedSettings == null) { loadedSettings = ScriptableObject.CreateInstance<UnityARKitPluginSettings> (); } return loadedSettings; } // Replaces the first C++ macro with the given name in the source file. Only changes // single-line macro declarations, if multi-line macro declaration is detected, the // function returns without changing it. Macro name must be a valid C++ identifier. internal static bool ReplaceCppMacro(string[] lines, string name, string newValue) { bool replaced = false; Regex matchRegex = new Regex(@"^.*#\s*define\s+" + name); Regex replaceRegex = new Regex(@"^.*#\s*define\s+" + name + @"(:?|\s|\s.*[^\\])$"); for (int i = 0; i < lines.Count(); i++) { if (matchRegex.Match (lines [i]).Success) { lines [i] = replaceRegex.Replace (lines [i], "#define " + name + " " + newValue); replaced = true; } } return replaced; } internal static void AddOrReplaceCppMacro(ref string[] lines, string name, string newValue) { if (ReplaceCppMacro (lines, name, newValue) == false) { Array.Resize(ref lines, lines.Length + 1); lines[lines.Length - 1] = "#define " + name + " " + newValue; } } static void UpdateDefinesInFile(string file, Dictionary<string, bool> valuesToUpdate) { string[] src = File.ReadAllLines(file); var copy = (string[])src.Clone(); foreach (var kvp in valuesToUpdate) AddOrReplaceCppMacro(ref copy, kvp.Key, kvp.Value ? "1" : "0"); if (!copy.SequenceEqual(src)) File.WriteAllLines(file, copy); } #if UNITY_IOS static void AddReferenceImageToResourceGroup(ARReferenceImage arri, string parentFolderFullPath, string projectRelativePath, PBXProject project) { ARResourceContents resourceContents = new ARResourceContents (); resourceContents.info = new ARResourceInfo (); resourceContents.info.author = "xcode"; resourceContents.info.version = 1; resourceContents.images = new ARResourceImage[1]; resourceContents.images [0] = new ARResourceImage (); resourceContents.images [0].idiom = "universal"; resourceContents.properties = new ARResourceProperties (); resourceContents.properties.width = arri.physicalSize; //add folder for reference image string folderToCreate = arri.imageName + ".arreferenceimage"; string folderFullPath = Path.Combine (parentFolderFullPath, folderToCreate); string projectRelativeFolder = Path.Combine (projectRelativePath, folderToCreate); Directory.CreateDirectory (folderFullPath); project.AddFolderReference (folderFullPath, projectRelativeFolder); //copy file from texture asset string imagePath = AssetDatabase.GetAssetPath(arri.imageTexture); string imageFilename = Path.GetFileName (imagePath); var dstPath = Path.Combine(folderFullPath, imageFilename); File.Copy(imagePath, dstPath, true); project.AddFile (dstPath, Path.Combine (projectRelativeFolder, imageFilename)); resourceContents.images [0].filename = imageFilename; //add contents.json file string contentsJsonPath = Path.Combine(folderFullPath, "Contents.json"); File.WriteAllText (contentsJsonPath, JsonUtility.ToJson (resourceContents, true)); project.AddFile (contentsJsonPath, Path.Combine (projectRelativeFolder, "Contents.json")); } static void AddReferenceImagesSetToAssetCatalog(ARReferenceImagesSet aris, string pathToBuiltProject, PBXProject project) { List<ARReferenceImage> processedImages = new List<ARReferenceImage> (); ARResourceGroupContents groupContents = new ARResourceGroupContents(); groupContents.info = new ARResourceGroupInfo (); groupContents.info.author = "xcode"; groupContents.info.version = 1; string folderToCreate = "Unity-iPhone/Images.xcassets/" + aris.resourceGroupName + ".arresourcegroup"; string folderFullPath = Path.Combine (pathToBuiltProject, folderToCreate); Directory.CreateDirectory (folderFullPath); project.AddFolderReference (folderFullPath, folderToCreate); foreach (ARReferenceImage arri in aris.referenceImages) { if (!processedImages.Contains (arri)) { processedImages.Add (arri); //get rid of dupes AddReferenceImageToResourceGroup(arri, folderFullPath, folderToCreate, project); } } groupContents.resources = new ARResourceGroupResource[processedImages.Count]; int index = 0; foreach (ARReferenceImage arri in processedImages) { groupContents.resources [index] = new ARResourceGroupResource (); groupContents.resources [index].filename = arri.imageName + ".arreferenceimage"; index++; } string contentsJsonPath = Path.Combine(folderFullPath, "Contents.json"); File.WriteAllText (contentsJsonPath, JsonUtility.ToJson (groupContents, true)); project.AddFile (contentsJsonPath, Path.Combine (folderToCreate, "Contents.json")); } #endif private static void OnPostprocessBuildIOS(string pathToBuiltProject) { // We use UnityEditor.iOS.Xcode API which only exists in iOS editor module #if UNITY_IOS string projPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj"; UnityEditor.iOS.Xcode.PBXProject proj = new UnityEditor.iOS.Xcode.PBXProject(); proj.ReadFromString(File.ReadAllText(projPath)); proj.AddFrameworkToProject(proj.TargetGuidByName("Unity-iPhone"), "ARKit.framework", false); string target = proj.TargetGuidByName("Unity-iPhone"); Directory.CreateDirectory(Path.Combine(pathToBuiltProject, "Libraries/Unity")); // Check UnityARKitPluginSettings UnityARKitPluginSettings ps = LoadSettings(); string plistPath = Path.Combine(pathToBuiltProject, "Info.plist"); PlistDocument plist = new PlistDocument(); plist.ReadFromString(File.ReadAllText(plistPath)); PlistElementDict rootDict = plist.root; // Get or create array to manage device capabilities const string capsKey = "UIRequiredDeviceCapabilities"; PlistElementArray capsArray; PlistElement pel; if (rootDict.values.TryGetValue(capsKey, out pel)) { capsArray = pel.AsArray(); } else { capsArray = rootDict.CreateArray(capsKey); } // Remove any existing "arkit" plist entries const string arkitStr = "arkit"; capsArray.values.RemoveAll(x => arkitStr.Equals(x.AsString())); if (ps.AppRequiresARKit) { // Add "arkit" plist entry capsArray.AddString(arkitStr); } File.WriteAllText(plistPath, plist.WriteToString()); foreach(ARReferenceImagesSet ar in imageSets) { AddReferenceImagesSetToAssetCatalog(ar, pathToBuiltProject, proj); } //TODO: remove this when XCode actool is able to handles ARResources despite deployment target if (imageSets.Count > 0) { proj.SetBuildProperty(target, "IPHONEOS_DEPLOYMENT_TARGET", "11.3"); } // Add or replace define for facetracking UpdateDefinesInFile(pathToBuiltProject + "/Classes/Preprocessor.h", new Dictionary<string, bool>() { { "ARKIT_USES_FACETRACKING", ps.m_ARKitUsesFacetracking } }); string[] filesToCopy = new string[] { }; for(int i = 0 ; i < filesToCopy.Length ; ++i) { var srcPath = Path.Combine("../PluginSource/source", filesToCopy[i]); var dstLocalPath = "Libraries/" + filesToCopy[i]; var dstPath = Path.Combine(pathToBuiltProject, dstLocalPath); File.Copy(srcPath, dstPath, true); proj.AddFileToBuild(target, proj.AddFile(dstLocalPath, dstLocalPath)); } File.WriteAllText(projPath, proj.WriteToString()); #endif // #if UNITY_IOS } }
// 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.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class WorkCoordinatorRegistrationService { private partial class WorkCoordinator { private partial class IncrementalAnalyzerProcessor { private static readonly Func<int, object, bool, string> s_enqueueLogger = (t, i, s) => string.Format("[{0}] {1} : {2}", t, i.ToString(), s); private readonly int _correlationId; private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _listener; private readonly IDocumentTrackingService _documentTracker; private readonly HighPriorityProcessor _highPriorityProcessor; private readonly NormalPriorityProcessor _normalPriorityProcessor; private readonly LowPriorityProcessor _lowPriorityProcessor; private LogAggregator _logAggregator; public IncrementalAnalyzerProcessor( IAsynchronousOperationListener listener, int correlationId, Workspace workspace, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, int highBackOffTimeSpanInMs, int normalBackOffTimeSpanInMs, int lowBackOffTimeSpanInMs, CancellationToken shutdownToken) { _logAggregator = new LogAggregator(); _listener = listener; var lazyActiveFileAnalyzers = new Lazy<ImmutableArray<IIncrementalAnalyzer>>(() => GetActiveFileIncrementalAnalyzers(correlationId, workspace, analyzerProviders)); var lazyAllAnalyzers = new Lazy<ImmutableArray<IIncrementalAnalyzer>>(() => GetIncrementalAnalyzers(correlationId, workspace, analyzerProviders)); // event and worker queues _correlationId = correlationId; _workspace = workspace; _documentTracker = workspace.Services.GetService<IDocumentTrackingService>(); var globalNotificationService = workspace.Services.GetService<IGlobalOperationNotificationService>(); _highPriorityProcessor = new HighPriorityProcessor(listener, this, lazyActiveFileAnalyzers, highBackOffTimeSpanInMs, shutdownToken); _normalPriorityProcessor = new NormalPriorityProcessor(listener, this, lazyAllAnalyzers, globalNotificationService, normalBackOffTimeSpanInMs, shutdownToken); _lowPriorityProcessor = new LowPriorityProcessor(listener, this, lazyAllAnalyzers, globalNotificationService, lowBackOffTimeSpanInMs, shutdownToken); } private static ImmutableArray<IIncrementalAnalyzer> GetActiveFileIncrementalAnalyzers( int correlationId, Workspace workspace, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> providers) { var analyzers = providers.Where(p => p.Metadata.HighPriorityForActiveFile && p.Metadata.WorkspaceKinds.Contains(workspace.Kind)).Select(p => p.Value.CreateIncrementalAnalyzer(workspace)); var orderedAnalyzers = OrderAnalyzers(analyzers); SolutionCrawlerLogger.LogActiveFileAnalyzers(correlationId, workspace, orderedAnalyzers); return orderedAnalyzers; } private static ImmutableArray<IIncrementalAnalyzer> GetIncrementalAnalyzers( int correlationId, Workspace workspace, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> providers) { var analyzers = providers.Where(p => p.Metadata.WorkspaceKinds.Contains(workspace.Kind)).Select(p => p.Value.CreateIncrementalAnalyzer(workspace)); var orderedAnalyzers = OrderAnalyzers(analyzers); SolutionCrawlerLogger.LogAnalyzers(correlationId, workspace, orderedAnalyzers); return orderedAnalyzers; } private static ImmutableArray<IIncrementalAnalyzer> OrderAnalyzers(IEnumerable<IIncrementalAnalyzer> analyzers) { return SpecializedCollections.SingletonEnumerable(analyzers.FirstOrDefault(a => a.GetType() == typeof(DiagnosticAnalyzerService.DiagnosticIncrementalAnalyzer))) .Concat(analyzers.Where(a => a.GetType() != typeof(DiagnosticAnalyzerService.DiagnosticIncrementalAnalyzer))) .WhereNotNull().ToImmutableArray(); } public void Enqueue(WorkItem item) { Contract.ThrowIfNull(item.DocumentId); _highPriorityProcessor.Enqueue(item); _normalPriorityProcessor.Enqueue(item); _lowPriorityProcessor.Enqueue(item); } public void Shutdown() { _highPriorityProcessor.Shutdown(); _normalPriorityProcessor.Shutdown(); _lowPriorityProcessor.Shutdown(); } public ImmutableArray<IIncrementalAnalyzer> Analyzers { get { return _normalPriorityProcessor.Analyzers; } } public Task AsyncProcessorTask { get { return Task.WhenAll( _highPriorityProcessor.AsyncProcessorTask, _normalPriorityProcessor.AsyncProcessorTask, _lowPriorityProcessor.AsyncProcessorTask); } } private Solution CurrentSolution { get { return _workspace.CurrentSolution; } } private IEnumerable<DocumentId> GetOpenDocumentIds() { return _workspace.GetOpenDocumentIds(); } private void ResetLogAggregator() { _logAggregator = new LogAggregator(); } private static async Task ProcessDocumentAnalyzersAsync( Document document, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationToken cancellationToken) { // process all analyzers for each categories in this order - syntax, body, document if (workItem.MustRefresh || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged)) { await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeSyntaxAsync(d, c), cancellationToken).ConfigureAwait(false); } if (workItem.MustRefresh || workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); } else { // if we don't need to re-analyze whole body, see whether we need to at least re-analyze one method. await RunBodyAnalyzersAsync(analyzers, workItem, document, cancellationToken).ConfigureAwait(false); } } private static async Task RunAnalyzersAsync<T>(ImmutableArray<IIncrementalAnalyzer> analyzers, T value, Func<IIncrementalAnalyzer, T, CancellationToken, Task> runnerAsync, CancellationToken cancellationToken) { foreach (var analyzer in analyzers) { if (cancellationToken.IsCancellationRequested) { return; } var local = analyzer; await GetOrDefaultAsync(value, async (v, c) => { await runnerAsync(local, v, c).ConfigureAwait(false); return default(object); }, cancellationToken).ConfigureAwait(false); } } private static async Task RunBodyAnalyzersAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, CancellationToken cancellationToken) { try { var root = await GetOrDefaultAsync(document, (d, c) => d.GetSyntaxRootAsync(c), cancellationToken).ConfigureAwait(false); var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); if (root == null || syntaxFactsService == null) { // as a fallback mechanism, if we can't run one method body due to some missing service, run whole document analyzer. await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); return; } // check whether we know what body has changed. currently, this is an optimization toward typing case. if there are more than one body changes // it will be considered as semantic change and whole document analyzer will take care of that case. var activeMember = GetMemberNode(syntaxFactsService, root, workItem.ActiveMember); if (activeMember == null) { // no active member means, change is out side of a method body, but it didn't affect semantics (such as change in comment) // in that case, we update whole document (just this document) so that we can have updated locations. await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false); return; } // re-run just the body await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, activeMember, c), cancellationToken).ConfigureAwait(false); } catch (Exception e) when(FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task<TResult> GetOrDefaultAsync<TData, TResult>(TData value, Func<TData, CancellationToken, Task<TResult>> funcAsync, CancellationToken cancellationToken) { try { return await funcAsync(value, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { return default(TResult); } catch (AggregateException e) when(CrashUnlessCanceled(e)) { return default(TResult); } catch (Exception e) when(FatalError.Report(e)) { // TODO: manage bad workers like what code actions does now throw ExceptionUtilities.Unreachable; } } private static SyntaxNode GetMemberNode(ISyntaxFactsService service, SyntaxNode root, SyntaxPath memberPath) { if (root == null || memberPath == null) { return null; } SyntaxNode memberNode; if (!memberPath.TryResolve(root, out memberNode)) { return null; } return service.IsMethodLevelMember(memberNode) ? memberNode : null; } internal ProjectId GetActiveProject() { ProjectId activeProjectId = null; if (_documentTracker != null) { var activeDocument = _documentTracker.GetActiveDocument(); if (activeDocument != null) { activeProjectId = activeDocument.ProjectId; } } return null; } private static bool CrashUnlessCanceled(AggregateException aggregate) { var flattened = aggregate.Flatten(); if (flattened.InnerExceptions.All(e => e is OperationCanceledException)) { return true; } FatalError.Report(flattened); return false; } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { _normalPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(analyzers, items); var projectItems = items .Select(i => i.With(null, i.ProjectId, _listener.BeginAsyncOperation("WorkItem"))); _lowPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(analyzers, items); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _normalPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); _lowPriorityProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ServiceAckDecoder { public const ushort BLOCK_LENGTH = 36; public const ushort TEMPLATE_ID = 33; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ServiceAckDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ServiceAckDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ServiceAckDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LogPositionId() { return 1; } public static int LogPositionSinceVersion() { return 0; } public static int LogPositionEncodingOffset() { return 0; } public static int LogPositionEncodingLength() { return 8; } public static string LogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public long LogPosition() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int TimestampId() { return 2; } public static int TimestampSinceVersion() { return 0; } public static int TimestampEncodingOffset() { return 8; } public static int TimestampEncodingLength() { return 8; } public static string TimestampMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long TimestampNullValue() { return -9223372036854775808L; } public static long TimestampMinValue() { return -9223372036854775807L; } public static long TimestampMaxValue() { return 9223372036854775807L; } public long Timestamp() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int AckIdId() { return 3; } public static int AckIdSinceVersion() { return 0; } public static int AckIdEncodingOffset() { return 16; } public static int AckIdEncodingLength() { return 8; } public static string AckIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long AckIdNullValue() { return -9223372036854775808L; } public static long AckIdMinValue() { return -9223372036854775807L; } public static long AckIdMaxValue() { return 9223372036854775807L; } public long AckId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int RelevantIdId() { return 4; } public static int RelevantIdSinceVersion() { return 0; } public static int RelevantIdEncodingOffset() { return 24; } public static int RelevantIdEncodingLength() { return 8; } public static string RelevantIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long RelevantIdNullValue() { return -9223372036854775808L; } public static long RelevantIdMinValue() { return -9223372036854775807L; } public static long RelevantIdMaxValue() { return 9223372036854775807L; } public long RelevantId() { return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian); } public static int ServiceIdId() { return 5; } public static int ServiceIdSinceVersion() { return 0; } public static int ServiceIdEncodingOffset() { return 32; } public static int ServiceIdEncodingLength() { return 4; } public static string ServiceIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ServiceIdNullValue() { return -2147483648; } public static int ServiceIdMinValue() { return -2147483647; } public static int ServiceIdMaxValue() { return 2147483647; } public int ServiceId() { return _buffer.GetInt(_offset + 32, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[ServiceAck](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogPosition="); builder.Append(LogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='timestamp', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("Timestamp="); builder.Append(Timestamp()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='ackId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("AckId="); builder.Append(AckId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='relevantId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("RelevantId="); builder.Append(RelevantId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='serviceId', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ServiceId="); builder.Append(ServiceId()); Limit(originalLimit); return builder; } } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // QuickGraph Library HomePage: http://www.mbunit.com // Author: Jonathan de Halleux namespace QuickGraph.Representations { using System; using System.Collections; using QuickGraph.Concepts; using QuickGraph.Concepts.Providers; using QuickGraph.Concepts.Modifications; using QuickGraph.Concepts.Predicates; using QuickGraph.Concepts.Traversals; using QuickGraph.Concepts.Collections; using QuickGraph.Concepts.MutableTraversals; using QuickGraph.Collections; using QuickGraph.Exceptions; using QuickGraph.Predicates; /// <summary> /// A mutable bidirectional graph implemetation /// </summary> /// <remarks> /// <seealso cref="AdjacencyGraph"/> /// <seealso cref="IBidirectionalGraph"/> /// <seealso cref="IMutableBidirectionalGraph"/> /// </remarks> public class BidirectionalGraph : AdjacencyGraph, IFilteredBidirectionalGraph, IMutableBidirectionalGraph, IBidirectionalVertexAndEdgeListGraph, IMutableBidirectionalVertexAndEdgeListGraph { private VertexEdgesDictionary m_VertexInEdges; /// <summary> /// Builds a new empty graph with default vertex and edge providers /// </summary> public BidirectionalGraph(bool allowParallelEdges) : base(allowParallelEdges) { m_VertexInEdges = new VertexEdgesDictionary(); } /// <summary> /// Builds a new empty graph /// </summary> public BidirectionalGraph( IVertexProvider vertexProvider, IEdgeProvider edgeProvider, bool allowParallelEdges ) : base(vertexProvider,edgeProvider,allowParallelEdges) { m_VertexInEdges = new VertexEdgesDictionary(); } /// <summary> /// Vertex Out edges dictionary /// </summary> protected VertexEdgesDictionary VertexInEdges { get { return m_VertexInEdges; } } /// <summary> /// Remove all of the edges and vertices from the graph. /// </summary> public override void Clear() { base.Clear(); VertexInEdges.Clear(); } /// <summary> /// Add a new vertex to the graph and returns it. /// /// Complexity: 1 insertion. /// </summary> /// <returns>Create vertex</returns> public override IVertex AddVertex() { IVertex v = base.AddVertex(); VertexInEdges.Add(v, new EdgeCollection()); return v; } /// <summary> /// Adds a new vertex to the graph. /// </summary> /// <param name="v"></param> public override void AddVertex(IVertex v) { base.AddVertex(v); VertexInEdges.Add(v, new EdgeCollection()); } /// <summary> /// Add a new vertex from source to target /// /// Complexity: 2 search + 1 insertion /// </summary> /// <param name="source">Source vertex</param> /// <param name="target">Target vertex</param> /// <returns>Created Edge</returns> /// <exception cref="ArgumentNullException">source or target is null</exception> /// <exception cref="Exception">source or target are not part of the graph</exception> public override IEdge AddEdge( IVertex source, IVertex target ) { // look for the vertex in the list if (!VertexInEdges.ContainsKey(source)) throw new VertexNotFoundException("Could not find source vertex"); if (!VertexInEdges.ContainsKey(target)) throw new VertexNotFoundException("Could not find target vertex"); // create edge IEdge e = base.AddEdge(source,target); VertexInEdges[target].Add(e); return e; } /// <summary> /// Adds a new edge to the graph /// </summary> /// <param name="e"></param> public override void AddEdge(IEdge e) { if (e==null) throw new ArgumentNullException("edge"); if (!VertexInEdges.ContainsKey(e.Source)) throw new VertexNotFoundException("Could not find source vertex"); if (!VertexInEdges.ContainsKey(e.Target)) throw new VertexNotFoundException("Could not find target vertex"); // create edge base.AddEdge(e); VertexInEdges[e.Target].Add(e); } /// <summary> /// Gets a value indicating if the set of in-edges is empty /// </summary> /// <remarks> /// <para> /// Usually faster that calling <see cref="InDegree"/>. /// </para> /// </remarks> /// <value> /// true if the in-edge set is empty, false otherwise. /// </value> /// <exception cref="ArgumentNullException">v is a null reference</exception> public bool InEdgesEmpty(IVertex v) { if (v==null) throw new ArgumentNullException("v"); return this.VertexInEdges[v].Count==0; } /// <summary> /// Returns the number of in-degree edges of v /// </summary> /// <param name="v"></param> /// <returns></returns> public int InDegree(IVertex v) { if (v == null) throw new ArgumentNullException("v"); return VertexInEdges[v].Count; } /// <summary> /// Returns an iterable collection over the in-edge connected to v /// </summary> /// <param name="v"></param> /// <returns></returns> public EdgeCollection InEdges(IVertex v) { if (v == null) throw new ArgumentNullException("v"); return VertexInEdges[v]; } /// <summary> /// Incidence graph implementation /// </summary> IEdgeEnumerable IBidirectionalGraph.InEdges(IVertex v) { return this.InEdges(v); } /// <summary> /// Returns the first in-edge that matches the predicate /// </summary> /// <param name="v"></param> /// <param name="ep">Edge predicate</param> /// <returns>null if not found, otherwize the first Edge that /// matches the predicate.</returns> /// <exception cref="ArgumentNullException">v or ep is null</exception> public IEdge SelectSingleInEdge(IVertex v, IEdgePredicate ep) { if (ep==null) throw new ArgumentNullException("edge predicate"); foreach(IEdge e in SelectInEdges(v,ep)) return e; return null; } /// <summary> /// Returns the collection of in-edges that matches the predicate /// </summary> /// <param name="v"></param> /// <param name="ep">Edge predicate</param> /// <returns>enumerable colleciton of vertices that matches the /// criteron</returns> /// <exception cref="ArgumentNullException">v or ep is null</exception> public FilteredEdgeEnumerable SelectInEdges(IVertex v, IEdgePredicate ep) { if (v==null) throw new ArgumentNullException("vertex"); if (ep==null) throw new ArgumentNullException("edge predicate"); return new FilteredEdgeEnumerable(InEdges(v),ep); } /// <summary> /// /// </summary> /// <param name="v"></param> /// <param name="ep"></param> /// <returns></returns> IEdgeEnumerable IFilteredBidirectionalGraph.SelectInEdges(IVertex v, IEdgePredicate ep) { return this.SelectInEdges(v,ep); } /// <summary> /// Removes the vertex from the graph. /// </summary> /// <param name="v">vertex to remove</param> /// <exception cref="ArgumentNullException">v is null</exception> public override void RemoveVertex(IVertex v) { if (v == null) throw new ArgumentNullException("vertex"); base.RemoveVertex(v); // removing vertex VertexInEdges.Remove(v); } /// <summary> /// Remove all edges to and from vertex u from the graph. /// </summary> /// <param name="v"></param> public override void ClearVertex(IVertex v) { if (v == null) throw new ArgumentNullException("vertex"); base.ClearVertex(v); VertexInEdges[v].Clear(); } /// <summary> /// Removes an edge from the graph. /// /// Complexity: 2 edges removed from the vertex edge list + 1 edge /// removed from the edge list. /// </summary> /// <param name="e">edge to remove</param> /// <exception cref="ArgumentNullException">e is null</exception> public override void RemoveEdge(IEdge e) { if (e == null) throw new ArgumentNullException("edge"); base.RemoveEdge(e); EdgeCollection inEdges = VertexInEdges[e.Target]; if (inEdges==null || !inEdges.Contains(e)) throw new EdgeNotFoundException(); inEdges.Remove(e); } /// <summary> /// Remove the edge (u,v) from the graph. /// If the graph allows parallel edges this remove all occurrences of /// (u,v). /// </summary> /// <param name="u">source vertex</param> /// <param name="v">target vertex</param> public override void RemoveEdge(IVertex u, IVertex v) { if (u == null) throw new ArgumentNullException("source vertex"); if (v == null) throw new ArgumentNullException("targetvertex"); EdgeCollection outEdges = VertexOutEdges[u]; EdgeCollection inEdges = VertexInEdges[v]; // marking edges to remove EdgeCollection removedEdges = new EdgeCollection(); foreach(IEdge e in outEdges) { if (e.Target == v) removedEdges.Add(e); } foreach(IEdge e in inEdges) { if (e.Source == u) removedEdges.Add(e); } //removing edges foreach(IEdge e in removedEdges) RemoveEdge(e); } /// <summary> /// Remove all the out-edges of vertex u for which the predicate pred /// returns true. /// </summary> /// <param name="u">vertex</param> /// <param name="pred">edge predicate</param> public void RemoveInEdgeIf(IVertex u, IEdgePredicate pred) { if (u==null) throw new ArgumentNullException("vertex u"); if (pred == null) throw new ArgumentNullException("predicate"); EdgeCollection edges = VertexInEdges[u]; EdgeCollection removedEdges = new EdgeCollection(); foreach(IEdge e in edges) if (pred.Test(e)) removedEdges.Add(e); foreach(IEdge e in removedEdges) RemoveEdge(e); } /// <summary> /// Gets a value indicating if the set of edges connected to v is empty /// </summary> /// <remarks> /// <para> /// Usually faster that calling <see cref="Degree"/>. /// </para> /// </remarks> /// <value> /// true if the adjacent edge set is empty, false otherwise. /// </value> /// <exception cref="ArgumentNullException">v is a null reference</exception> public bool AdjacentEdgesEmpty(IVertex v) { return this.OutEdgesEmpty(v) && this.InEdgesEmpty(v); } /// <summary> /// Returns the number of in-edges plus out-edges. /// </summary> /// <param name="v"></param> /// <returns></returns> public int Degree(IVertex v) { if (v == null) throw new ArgumentNullException("v"); return VertexInEdges[v].Count + VertexOutEdges[v].Count; } } }
//----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- // Blaster Gun and ammo //----------------------------------------------------------------------------- datablock SFXProfile(BlasterReloadSound) { filename = "art/sound/crossbow_reload"; description = AudioClose3d; preload = true; }; datablock SFXProfile(BlasterFireSound) { filename = "art/sound/laser02"; description = AudioDefault3d; preload = true; }; datablock SFXProfile(GreenBlasterFireSound) { filename = "art/sound/laser01"; description = AudioDefault3d; preload = true; }; datablock SFXProfile(BlasterFireEmptySound) { filename = "art/sound/crossbow_firing_empty"; description = AudioClose3d; preload = true; }; datablock SFXProfile(LaserBeamExplosionSound) { filename = "art/sound/laserHit01"; description = AudioClose3d; preload = true; }; // ---------------------------------------- datablock ParticleData(RedLaserParticle) { textureName = "art/shapes/particles/spark_wet"; dragCoefficient = 0.997067; windCoefficient = 1; gravityCoefficient = 1; inheritedVelFactor = 0.199609; lifetimeMS = 481; lifetimeVarianceMS = 350; spinSpeed = 0; spinRandomMin = 0; spinRandomMax = 0; useInvAlpha = 1; colors[0] = "1 0.4 0 1"; colors[1] = "1 0.2 0 1"; colors[2] = "1 0.1 0 0"; colors[3] = "1 1 1 1"; sizes[0] = 0.15; sizes[1] = 0.1; sizes[2] = 0.1; sizes[3] = 1; times[0] = 0; times[1] = 0.5; times[2] = 1; times[3] = 1; }; datablock ParticleEmitterData(RedLaserEmitter) { ejectionPeriodMS = 3; periodVarianceMS = 0; ejectionVelocity = 5; velocityVariance = 1; ejectionOffset = 0; thetaMin = 0; thetaMax = 130; lifetimeMS = 70; lifetimeVarianceMS = 0; blendStyle = "ADDITIVE"; srcBlendFactor = "SRC_ALPHA"; dstBlendFactor = "ONE"; particles = "RedLaserParticle"; orientParticles = "1"; }; datablock ParticleEmitterNodeData(RedLaserNode) { timeMultiple = 1; }; // ---------------------------------------- datablock ParticleData(GreenLaserParticle) { textureName = "art/shapes/particles/spark_wet"; dragCoefficient = 0.997067; windCoefficient = 1; gravityCoefficient = 1; inheritedVelFactor = 0.199609; lifetimeMS = 481; lifetimeVarianceMS = 350; spinSpeed = 0; spinRandomMin = 0; spinRandomMax = 0; useInvAlpha = 1; colors[0] = "0.2 1 0 1"; colors[1] = "0.1 1 0 1"; colors[2] = "0 1 0 0"; colors[3] = "1 1 1 1"; sizes[0] = 0.12; sizes[1] = 0.08; sizes[2] = 0.08; sizes[3] = 1; times[0] = 0; times[1] = 0.5; times[2] = 1; times[3] = 1; }; datablock ParticleEmitterData(GreenLaserEmitter) { ejectionPeriodMS = 3; periodVarianceMS = 0; ejectionVelocity = 5; velocityVariance = 1; ejectionOffset = 0; thetaMin = 0; thetaMax = 130; lifetimeMS = 70; lifetimeVarianceMS = 0; blendStyle = "ADDITIVE"; srcBlendFactor = "SRC_ALPHA"; dstBlendFactor = "ONE"; particles = "GreenLaserParticle"; orientParticles = "1"; }; datablock ParticleEmitterNodeData(GreenLaserNode) { timeMultiple = 1; }; // ---------------------------------------- datablock ExplosionData(LaserBeamExplosion) { soundProfile = LaserBeamExplosionSound; lifeTimeMS = 120; // Point emission emitter[0] = RedLaserEmitter; // Dynamic light lightStartRadius = 4; lightEndRadius = 0; lightStartColor = "1 0 0"; lightEndColor = "1 0 0"; }; /* datablock ExplosionData(LaserBeamExplosion) { soundProfile = LaserBeamExplosionSound; lifeTimeMS = 120; // Point emission emitter[0] = RedLaserEmitter; // Dynamic light lightStartRadius = 3; lightEndRadius = 3; lightStartColor = "1 0.3 0.3"; lightEndColor = "0 0 0"; }; */ datablock ExplosionData(GreenLaserBeamExplosion : LaserBeamExplosion) { soundProfile = LaserBeamExplosionSound; emitter[0] = GreenLaserEmitter; // Dynamic light lightStartColor = "0 1 0"; lightEndColor = "0 0 0"; }; //----------------------------------------------------------------------------- // Projectile Object /* datablock DecalData(laserBeamHole00){ sizeX = 0.1; sizeY = 0.1; textureName = "art/shapes/lasers/laser_hit_01"; }; datablock DecalData(laserBeamHole01){ sizeX = 0.1; sizeY = 0.1; textureName = "art/shapes/lasers/laser_hit_02"; }; datablock DecalData(laserBeamHole02){ sizeX = 0.15; sizeY = 0.15; textureName = "art/shapes/lasers/laser_hit_01"; }; datablock DecalData(laserBeamHole03){ sizeX = 0.13; sizeY = 0.13; textureName = "art/shapes/lasers/laser_hit_02"; }; */ datablock ProjectileData(LaserBeamProjectile) { projectileShapeName = "art/shapes/lasers/laser_red/red_laser.dts"; directDamage = 13; areaImpulse = 2000; explosion = LaserBeamExplosion; //particleEmitter = RocketEmitter; muzzleVelocity = 70; velInheritFactor = 0.1; armingDelay = 0; lifetime = 8000; fadeDelay = 1500; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 0.10; hasLight = true; lightRadius = 6.0; lightColor = "1.0 0.3 0.3"; /* decals[0] = laserBeamHole00; decals[1] = laserBeamHole01; decals[2] = laserBeamHole02; decals[3] = laserBeamHole03; */ }; datablock ProjectileData(GreenLaserBeamProjectile : LaserBeamProjectile) { projectileShapeName = "art/shapes/lasers/laser_green/green_laser.dts"; explosion = GreenLaserBeamExplosion; directDamage = 33; muzzleVelocity = 110; velInheritFactor = 0.1; lightRadius = 5.0; lightColor = "0.0 1.0 0"; superClass = "LaserBeamProjectile"; }; function LaserBeamProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal) { echo("OnCol1", %pos, %normal); if (%col.getType() & $TypeMasks::ShapeBaseObjectType) { %col.damage(%obj,%pos,%this.directDamage, "LaserBeam"); %force = VectorScale(%normal,400); %force = VectorSub("0 0 0",%force); echo("OnCol2", %pos, %force); %col.applyImpulse(%pos,%force); } } //----------------------------------------------------------------------------- // Ammo Item datablock ItemData(BlasterAmmo) { // Mission editor category category = "Ammo"; // Add the Ammo namespace as a parent. The ammo namespace provides // common ammo related functions and hooks into the inventory system. className = "Ammo"; // Basic Item properties shapeFile = "art/shapes/weapons/SwarmGun/swarmgun.dts"; mass = 1; elasticity = 0.2; friction = 0.6; // Dynamic properties defined by the scripts pickUpName = "blaster ammo"; maxInventory = 50; }; datablock ItemData(CrossbowAmmo : BlasterAmmo) { pickUpName = "another blaster ammo"; }; datablock ItemData(BlasterGun) { category = "Weapon"; className = "Weapon"; // Basic Item properties shapeFile = "art/shapes/weapons/SwarmGun/swarmgun.dts"; mass = 1; elasticity = 0.2; friction = 0.6; emap = true; // Dynamic properties defined by the scripts pickUpName = "a blaster gun"; image = BlasterGunImage; }; //-------------------------------------------------------------------------- // Rocket Launcher image which does all the work. Images do not normally exist in // the world, they can only be mounted on ShapeBase objects. datablock ShapeBaseImageData(BlasterGunImage) { // Basic Item properties shapeFile = "art/shapes/weapons/spaceRifle/gun.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; firstPerson = false; offset = "0 0.25 0"; eyeOffset = "0.45 0.55 -0.5"; // The model may be backwards // rotation = "0.0 0.0 1.0 180.0"; // eyeRotation = "0.0 0.0 1.0 180.0"; // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = true; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; // Projectile && Ammo. item = BlasterGun; ammo = BlasterAmmo; projectile = LaserBeamProjectile; projectileType = Projectile; casing = RocketLauncherShell; shellExitDir = "1.0 0.3 1.0"; shellExitOffset = "0.15 -0.56 -0.1"; shellExitVariance = 15.0; shellVelocity = 3.0; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNoAmmo[0] = "NoAmmo"; // Activating the gun. Called when the weapon is first // mounted and there is ammo. stateName[1] = "Activate"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.5; stateSequence[1] = "Activate"; stateScript[1] = "onActivate"; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionOnNoAmmo[2] = "NoAmmo"; stateTransitionOnTriggerDown[2] = "Fire"; // Fire the weapon. Calls the fire script which does // the actual work. stateName[3] = "Fire"; stateTransitionOnTimeout[3] = "Reload"; stateTimeoutValue[3] = 0; stateFire[3] = true; stateRecoil[3] = LightRecoil; stateAllowImageChange[3] = false; stateSequence[3] = "Fire"; stateScript[3] = "onFire"; //stateEmitter[3] = RocketLauncherFireEmitter; //stateEmitterTime[3] = 0.3; stateSoundOnFire = BlasterFireSound; // Play the relead animation, and transition into stateName[4] = "Reload"; stateTransitionOnNoAmmo[4] = "NoAmmo"; stateTransitionOnTimeout[4] = "Ready"; stateTimeoutValue[4] = 0.4; stateAllowImageChange[4] = false; stateSequence[4] = "Reload"; stateEjectShell[4] = true; stateSound[4] = RocketReloadSound; // No ammo in the weapon, just idle until something // shows up. Play the dry fire sound if the trigger is // pulled. stateName[5] = "NoAmmo"; stateTransitionOnAmmo[5] = "Reload"; stateSequence[5] = "NoAmmo"; stateTransitionOnTriggerDown[5] = "DryFire"; // No ammo dry fire stateName[6] = "DryFire"; stateTimeoutValue[6] = 1.0; stateTransitionOnTimeout[6] = "NoAmmo"; stateScript[6] = "onDryFire"; }; datablock ShapeBaseImageData(GreenBlasterGunImage : BlasterGunImage) { //shapeFile = "art/shapes/weapons/SwarmGun/swarmgun.dts"; projectile = GreenLaserBeamProjectile; stateSoundOnFire = GreenBlasterFireSound; superClass = "BlasterGunImage"; }; //----------------------------------------------------------------------------- function BlasterGunImage::onFire(%this, %obj, %slot) { %projectile = %this.projectile; // Determine initial projectile velocity based on the // gun's muzzle point and the object's current velocity %muzzleVector = %obj.getMuzzleVector(%slot); %objectVelocity = %obj.getVelocity(); %muzzleVelocity = VectorAdd( VectorScale(%muzzleVector, %projectile.muzzleVelocity), VectorScale(%objectVelocity, %projectile.velInheritFactor)); // Create the projectile object %p = new (%this.projectileType)() { dataBlock = %projectile; initialVelocity = %muzzleVelocity; initialPosition = %obj.getMuzzlePoint(%slot); sourceObject = %obj; sourceSlot = %slot; client = %obj.client; }; MissionCleanup.add(%p); %pos = %obj.getPosition(); sfxPlayOnce(%this.stateSoundOnFire, getWord(%pos, 0), getWord(%pos, 1), getWord(%pos, 2)); return %p; } function GreenBlasterGunImage::onFire(%this, %obj, %slot) { return BlasterGunImage::onFire(%this, %obj, %slot); } function BlasterGunImage::onDryFire(%this, %obj, %slot) { error("No ammo!!!"); }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using IdSharp.Common.Utils; using IdSharp.Tagging.ID3v2.Frames; namespace IdSharp.Tagging.ID3v2 { /// <summary> /// ID3v2 /// </summary> public partial class ID3v2Tag : FrameContainer, IID3v2Tag { private ID3v2Header _id3v2Header; private ID3v2ExtendedHeader _id3v2ExtendedHeader; #region <<< Constructor >>> /// <summary> /// Initializes a new instance of the <see cref="ID3v2Tag"/> class. /// </summary> public ID3v2Tag() { _id3v2Header = new ID3v2Header(); _id3v2ExtendedHeader = new ID3v2ExtendedHeader(); } /// <summary> /// Initializes a new instance of the <see cref="ID3v2Tag"/> class. /// </summary> /// <param name="path">The full path of the file.</param> public ID3v2Tag(string path) : this() { Read(path); } /// <summary> /// Initializes a new instance of the <see cref="ID3v2Tag"/> class. /// </summary> /// <param name="stream">The stream to read from.</param> public ID3v2Tag(Stream stream) : this() { Read(stream); } #endregion <<< Constructor >>> #region <<< Public Methods >>> /// <summary> /// Reads the raw data from a specified file. /// </summary> /// <param name="path">The file to read from.</param> public void Read(string path) { try { // Open the file and read from the stream using (Stream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (stream.Length < 10) return; Read(stream); } } catch (Exception ex) { throw new Exception(String.Format("Error reading '{0}'", path), ex); } } /// <summary> /// Saves the tag to the specified path. /// </summary> /// <param name="path">The path to save the tag.</param> public void Save(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); int originalTagSize = GetTagSize(path); byte[] tagBytes = GetBytes(originalTagSize); if (tagBytes.Length < originalTagSize) { // Eventually this won't be a problem, but for now we won't worry about shrinking tags throw new Exception("GetBytes() returned a size less than the minimum size"); } else if (tagBytes.Length > originalTagSize) { ByteUtils.ReplaceBytes(path, originalTagSize, tagBytes); } else { // Write tag of equal length using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None)) { fileStream.Write(tagBytes, 0, tagBytes.Length); } } } /// <summary> /// Gets all frames in the ID3v2 tag as a collection of IFrames. /// </summary> /// <returns>All frames in the ID3v2 tag as a collection of IFrames.</returns> public List<IFrame> GetFrames() { return GetAllFrames(_id3v2Header.TagVersion); } /// <summary> /// Gets all frames in the ID3v2 tag with the specified <paramref name="frameID"/> as a collection of IFrames. /// </summary> /// <returns>All frames in the ID3v2 tag with the specified <paramref name="frameID"/> as a collection of IFrames.</returns> public List<IFrame> GetFrames(string frameID) { if (string.IsNullOrEmpty(frameID)) throw new ArgumentNullException("frameID"); return GetAllFrames(_id3v2Header.TagVersion, frameID); } /// <summary> /// Gets all frames in the ID3v2 tag with the specified <paramref name="frameIDs"/> as a collection of IFrames. /// </summary> /// <returns>All frames in the ID3v2 tag with the specified <paramref name="frameIDs"/> as a collection of IFrames.</returns> public List<IFrame> GetFrames(IEnumerable<string> frameIDs) { if (frameIDs == null) throw new ArgumentNullException("frameIDs"); return GetAllFrames(_id3v2Header.TagVersion, frameIDs); } /// <summary> /// Gets all frames in the ID3v2 tag which implement the specified interface <typeparamref name="T"/>. /// </summary> /// <returns>All frames in the ID3v2 tag which implement the specified interface <typeparamref name="T"/>.</returns> public List<T> GetFrames<T>() { return GetAllFrames(_id3v2Header.TagVersion).OfType<T>().ToList(); } /// <summary> /// Gets the bytes of the current ID3v2 tag. /// </summary> /// <param name="minimumSize">The minimum size of the new tag, including the header and footer.</param> /// <returns>The bytes of the current ID3v2 tag.</returns> public byte[] GetBytes(int minimumSize) { ID3v2TagVersion tagVersion = _id3v2Header.TagVersion; using (MemoryStream tag = new MemoryStream()) { byte[] framesByteArray = GetBytes(tagVersion); int tagSize = framesByteArray.Length; _id3v2Header.UsesUnsynchronization = false; // hack _id3v2Header.IsExperimental = true; // hack //_id3v2ExtendedHeader.IsCRCDataPresent = true; // hack: for testing //_id3v2Header.HasExtendedHeader = true; // hack: for testing if (_id3v2Header.HasExtendedHeader) { // Add total size of extended header tagSize += _id3v2ExtendedHeader.SizeExcludingSizeBytes + 4; } int paddingSize = minimumSize - (tagSize + 10); if (paddingSize < 0) { paddingSize = 2000; } tagSize += paddingSize; // Set tag size in ID3v2 header _id3v2Header.TagSize = tagSize; byte[] id3v2Header = _id3v2Header.GetBytes(); tag.Write(id3v2Header, 0, id3v2Header.Length); if (_id3v2Header.HasExtendedHeader) { if (_id3v2ExtendedHeader.IsCRCDataPresent) { // TODO: Calculate total frame CRC (before or after unsync? compression? encr?) _id3v2ExtendedHeader.CRC32 = CRC32.CalculateInt32(framesByteArray); } // Set padding size _id3v2ExtendedHeader.PaddingSize = paddingSize; // todo: check byte[] id3v2ExtendedHeader = _id3v2ExtendedHeader.GetBytes(tagVersion); tag.Write(id3v2ExtendedHeader, 0, id3v2ExtendedHeader.Length); } tag.Write(framesByteArray, 0, framesByteArray.Length); byte[] padding = new byte[paddingSize]; tag.Write(padding, 0, paddingSize); // Make sure WE can read it without throwing errors // TODO: Take this out eventually, this is just a precaution. tag.Position = 0; ID3v2Tag newID3v2 = new ID3v2Tag(); newID3v2.Read(tag); return tag.ToArray(); } } #endregion <<< Public Methods >>> #region <<< Public Properties >>> /// <summary> /// Gets the ID3v2 header. /// </summary> /// <value>The ID3v2 header.</value> public IID3v2Header Header { get { return _id3v2Header; } } /// <summary> /// Gets the ID3v2 extended header. /// </summary> /// <value>The ID3v2 extended header.</value> public IID3v2ExtendedHeader ExtendedHeader { get { return _id3v2ExtendedHeader; } } #endregion <<< Public Properties >>> /// <summary> /// Reads the raw data from a specified stream. /// </summary> /// <param name="stream">The stream to read from.</param> public void Read(Stream stream) { // Check for 'ID3' marker byte[] identifier = stream.Read(3); if (!(identifier[0] == 0x49 && identifier[1] == 0x44 && identifier[2] == 0x33)) { return; } // Read the header _id3v2Header = new ID3v2Header(stream, false); TagReadingInfo tagReadingInfo = new TagReadingInfo(_id3v2Header.TagVersion); if (_id3v2Header.UsesUnsynchronization) tagReadingInfo.TagVersionOptions = TagVersionOptions.Unsynchronized; else tagReadingInfo.TagVersionOptions = TagVersionOptions.None; if (_id3v2Header.HasExtendedHeader) { _id3v2ExtendedHeader = new ID3v2ExtendedHeader(tagReadingInfo, stream); } int frameIDSize = (tagReadingInfo.TagVersion == ID3v2TagVersion.ID3v22 ? 3 : 4); int bytesRead; int readUntil; #region <<< ID3v2.4 - Guess if syncsafe frame size was used or not >>> if (_id3v2Header.TagVersion == ID3v2TagVersion.ID3v24) { bool isID3v24SyncSafe = true; bytesRead = 0; readUntil = _id3v2Header.TagSize - _id3v2ExtendedHeader.SizeIncludingSizeBytes - frameIDSize; long initialPosition = stream.Position; while (bytesRead < readUntil) { byte[] frameIDBytes = stream.Read(frameIDSize); // TODO: Noticed some tags contain 0x00 'E' 'N' as a FrameID. Frame is well structured // and other frames follow. I believe the below (keep reading+looking) will cover this issue. // If character is not a letter or number, padding reached, audio began, // or otherwise the frame is not readable if (frameIDBytes[0] < 0x30 || frameIDBytes[0] > 0x5A || frameIDBytes[1] < 0x30 || frameIDBytes[1] > 0x5A || frameIDBytes[2] < 0x30 || frameIDBytes[2] > 0x5A || frameIDBytes[3] < 0x30 || frameIDBytes[3] > 0x5A) { // TODO: Try to keep reading and look for a valid frame if (frameIDBytes[0] != 0 && frameIDBytes[0] != 0xFF) { /*String msg = String.Format("Out of range FrameID - 0x{0:X}|0x{1:X}|0x{2:X}|0x{3:X}", tmpFrameIDBytes[0], tmpFrameIDBytes[1], tmpFrameIDBytes[2], tmpFrameIDBytes[3]); Trace.WriteLine(msg);*/ } break; } int frameSize = stream.ReadInt32(); if (frameSize > 0xFF) { if ((frameSize & 0x80) == 0x80) { isID3v24SyncSafe = false; break; } if ((frameSize & 0x8000) == 0x8000) { isID3v24SyncSafe = false; break; } if ((frameSize & 0x800000) == 0x800000) { isID3v24SyncSafe = false; break; } if (bytesRead + frameSize + 10 == _id3v2Header.TagSize) { // Could give a false positive, but relatively unlikely (famous last words, huh?) isID3v24SyncSafe = false; break; } else { stream.Seek(-4, SeekOrigin.Current); // go back to read sync-safe version int syncSafeFrameSize = ID3v2Utils.ReadInt32SyncSafe(stream); long currentPosition = stream.Position; bool isValidAtSyncSafe = true; bool isValidAtNonSyncSafe = true; // TODO - if it's the last frame and there is padding, both would indicate false // Use the one that returns some padding bytes opposed to bytes with non-zero values (could be frame data) // If non sync-safe reads past the end of the tag, then it's sync safe // Testing non-sync safe since it will always be bigger than the sync safe integer if (currentPosition + frameSize + 2 >= readUntil) { isID3v24SyncSafe = true; break; } // Test non-sync safe stream.Seek(currentPosition + frameSize + 2, SeekOrigin.Begin); frameIDBytes = stream.Read(frameIDSize); if (frameIDBytes[0] < 0x30 || frameIDBytes[0] > 0x5A || frameIDBytes[1] < 0x30 || frameIDBytes[1] > 0x5A || frameIDBytes[2] < 0x30 || frameIDBytes[2] > 0x5A || frameIDBytes[3] < 0x30 || frameIDBytes[3] > 0x5A) { isValidAtNonSyncSafe = false; } // Test sync-safe stream.Seek(currentPosition + syncSafeFrameSize + 2, SeekOrigin.Begin); frameIDBytes = stream.Read(frameIDSize); if (frameIDBytes[0] < 0x30 || frameIDBytes[0] > 0x5A || frameIDBytes[1] < 0x30 || frameIDBytes[1] > 0x5A || frameIDBytes[2] < 0x30 || frameIDBytes[2] > 0x5A || frameIDBytes[3] < 0x30 || frameIDBytes[3] > 0x5A) { isValidAtSyncSafe = false; } // if they're equal, we'll just have to go with syncsafe, since that's the spec if (isValidAtNonSyncSafe != isValidAtSyncSafe) { isID3v24SyncSafe = isValidAtSyncSafe; } break; } } stream.Seek(frameSize + 2, SeekOrigin.Current); bytesRead += frameSize + 10; } stream.Position = initialPosition; if (isID3v24SyncSafe == false) { tagReadingInfo.TagVersionOptions |= TagVersionOptions.UseNonSyncSafeFrameSizeID3v24; } } else if (_id3v2Header.TagVersion == ID3v2TagVersion.ID3v22) { bool isID3v22CorrectSize = true; bytesRead = 0; readUntil = _id3v2Header.TagSize - _id3v2ExtendedHeader.SizeIncludingSizeBytes - frameIDSize; long initialPosition = stream.Position; stream.Read(frameIDSize); UnknownFrame unknownFrame = new UnknownFrame(null, tagReadingInfo, stream); bytesRead += unknownFrame.FrameHeader.FrameSizeTotal; if (bytesRead < readUntil) { byte[] frameIDBytes = stream.Read(frameIDSize); // TODO: Noticed some tags contain 0x00 'E' 'N' as a FrameID. Frame is well structured // and other frames follow. I believe the below (keep reading+looking) will cover this issue. // If character is not a letter or number, padding reached, audio began, // or otherwise the frame is not readable if (frameIDBytes[0] < 0x30 || frameIDBytes[0] > 0x5A) { if (frameIDBytes[1] >= 0x30 && frameIDBytes[1] <= 0x5A && frameIDBytes[2] >= 0x30 && frameIDBytes[2] <= 0x5A) { Trace.WriteLine("ID3v2.2 frame size off by 1 byte"); isID3v22CorrectSize = false; } } } stream.Position = initialPosition; if (isID3v22CorrectSize == false) { tagReadingInfo.TagVersionOptions |= TagVersionOptions.AddOneByteToSize; } } #endregion <<< ID3v2.4 - Guess if syncsafe frame size was used or not >>> readUntil = _id3v2Header.TagSize - _id3v2ExtendedHeader.SizeIncludingSizeBytes - frameIDSize; Read(stream, _id3v2Header.TagVersion, tagReadingInfo, readUntil, frameIDSize); } } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Play Developer API Version v1.1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/android-publisher'>Google Play Developer API</a> * <tr><th>API Version<td>v1.1 * <tr><th>API Rev<td>20160221 (416) * <tr><th>API Docs * <td><a href='https://developers.google.com/android-publisher'> * https://developers.google.com/android-publisher</a> * <tr><th>Discovery Name<td>androidpublisher * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Play Developer API can be found at * <a href='https://developers.google.com/android-publisher'>https://developers.google.com/android-publisher</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.AndroidPublisher.v1_1 { /// <summary>The AndroidPublisher Service.</summary> public class AndroidPublisherService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1.1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public AndroidPublisherService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public AndroidPublisherService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { inapppurchases = new InapppurchasesResource(this); purchases = new PurchasesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "androidpublisher"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/androidpublisher/v1.1/applications/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "androidpublisher/v1.1/applications/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Google Play Developer API.</summary> public class Scope { /// <summary>View and manage your Google Play Developer account</summary> public static string Androidpublisher = "https://www.googleapis.com/auth/androidpublisher"; } private readonly InapppurchasesResource inapppurchases; /// <summary>Gets the Inapppurchases resource.</summary> public virtual InapppurchasesResource Inapppurchases { get { return inapppurchases; } } private readonly PurchasesResource purchases; /// <summary>Gets the Purchases resource.</summary> public virtual PurchasesResource Purchases { get { return purchases; } } } ///<summary>A base abstract class for AndroidPublisher requests.</summary> public abstract class AndroidPublisherBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new AndroidPublisherBaseServiceRequest instance.</summary> protected AndroidPublisherBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes AndroidPublisher parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "inapppurchases" collection of methods.</summary> public class InapppurchasesResource { private const string Resource = "inapppurchases"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public InapppurchasesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Checks the purchase and consumption status of an inapp item.</summary> /// <param name="packageName">The package name of the application the inapp product was sold in (for example, /// 'com.some.thing').</param> /// <param name="productId">The inapp product SKU (for example, /// 'com.some.thing.inapp1').</param> /// <param name="token">The token provided to the user's device when the inapp /// product was purchased.</param> public virtual GetRequest Get(string packageName, string productId, string token) { return new GetRequest(service, packageName, productId, token); } /// <summary>Checks the purchase and consumption status of an inapp item.</summary> public class GetRequest : AndroidPublisherBaseServiceRequest<Google.Apis.AndroidPublisher.v1_1.Data.InappPurchase> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string packageName, string productId, string token) : base(service) { PackageName = packageName; ProductId = productId; Token = token; InitParameters(); } /// <summary>The package name of the application the inapp product was sold in (for example, /// 'com.some.thing').</summary> [Google.Apis.Util.RequestParameterAttribute("packageName", Google.Apis.Util.RequestParameterType.Path)] public virtual string PackageName { get; private set; } /// <summary>The inapp product SKU (for example, 'com.some.thing.inapp1').</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>The token provided to the user's device when the inapp product was purchased.</summary> [Google.Apis.Util.RequestParameterAttribute("token", Google.Apis.Util.RequestParameterType.Path)] public virtual string Token { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{packageName}/inapp/{productId}/purchases/{token}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "packageName", new Google.Apis.Discovery.Parameter { Name = "packageName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "token", new Google.Apis.Discovery.Parameter { Name = "token", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "purchases" collection of methods.</summary> public class PurchasesResource { private const string Resource = "purchases"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PurchasesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Cancels a user's subscription purchase. The subscription remains valid until its expiration /// time.</summary> /// <param name="packageName">The package name of the application for which this subscription was purchased (for /// example, 'com.some.thing').</param> /// <param name="subscriptionId">The purchased subscription ID (for example, /// 'monthly001').</param> /// <param name="token">The token provided to the user's device when the subscription was /// purchased.</param> public virtual CancelRequest Cancel(string packageName, string subscriptionId, string token) { return new CancelRequest(service, packageName, subscriptionId, token); } /// <summary>Cancels a user's subscription purchase. The subscription remains valid until its expiration /// time.</summary> public class CancelRequest : AndroidPublisherBaseServiceRequest<string> { /// <summary>Constructs a new Cancel request.</summary> public CancelRequest(Google.Apis.Services.IClientService service, string packageName, string subscriptionId, string token) : base(service) { PackageName = packageName; SubscriptionId = subscriptionId; Token = token; InitParameters(); } /// <summary>The package name of the application for which this subscription was purchased (for example, /// 'com.some.thing').</summary> [Google.Apis.Util.RequestParameterAttribute("packageName", Google.Apis.Util.RequestParameterType.Path)] public virtual string PackageName { get; private set; } /// <summary>The purchased subscription ID (for example, 'monthly001').</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } /// <summary>The token provided to the user's device when the subscription was purchased.</summary> [Google.Apis.Util.RequestParameterAttribute("token", Google.Apis.Util.RequestParameterType.Path)] public virtual string Token { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "cancel"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel"; } } /// <summary>Initializes Cancel parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "packageName", new Google.Apis.Discovery.Parameter { Name = "packageName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "token", new Google.Apis.Discovery.Parameter { Name = "token", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Checks whether a user's subscription purchase is valid and returns its expiry time.</summary> /// <param name="packageName">The package name of the application for which this subscription was purchased (for /// example, 'com.some.thing').</param> /// <param name="subscriptionId">The purchased subscription ID (for example, /// 'monthly001').</param> /// <param name="token">The token provided to the user's device when the subscription was /// purchased.</param> public virtual GetRequest Get(string packageName, string subscriptionId, string token) { return new GetRequest(service, packageName, subscriptionId, token); } /// <summary>Checks whether a user's subscription purchase is valid and returns its expiry time.</summary> public class GetRequest : AndroidPublisherBaseServiceRequest<Google.Apis.AndroidPublisher.v1_1.Data.SubscriptionPurchase> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string packageName, string subscriptionId, string token) : base(service) { PackageName = packageName; SubscriptionId = subscriptionId; Token = token; InitParameters(); } /// <summary>The package name of the application for which this subscription was purchased (for example, /// 'com.some.thing').</summary> [Google.Apis.Util.RequestParameterAttribute("packageName", Google.Apis.Util.RequestParameterType.Path)] public virtual string PackageName { get; private set; } /// <summary>The purchased subscription ID (for example, 'monthly001').</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } /// <summary>The token provided to the user's device when the subscription was purchased.</summary> [Google.Apis.Util.RequestParameterAttribute("token", Google.Apis.Util.RequestParameterType.Path)] public virtual string Token { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{packageName}/subscriptions/{subscriptionId}/purchases/{token}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "packageName", new Google.Apis.Discovery.Parameter { Name = "packageName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "token", new Google.Apis.Discovery.Parameter { Name = "token", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.AndroidPublisher.v1_1.Data { /// <summary>An InappPurchase resource indicates the status of a user's inapp product purchase.</summary> public class InappPurchase : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The consumption state of the inapp product. Possible values are: - Yet to be consumed - /// Consumed</summary> [Newtonsoft.Json.JsonPropertyAttribute("consumptionState")] public virtual System.Nullable<int> ConsumptionState { get; set; } /// <summary>A developer-specified string that contains supplemental information about an order.</summary> [Newtonsoft.Json.JsonPropertyAttribute("developerPayload")] public virtual string DeveloperPayload { get; set; } /// <summary>This kind represents an inappPurchase object in the androidpublisher service.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The purchase state of the order. Possible values are: - Purchased - Cancelled</summary> [Newtonsoft.Json.JsonPropertyAttribute("purchaseState")] public virtual System.Nullable<int> PurchaseState { get; set; } /// <summary>The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).</summary> [Newtonsoft.Json.JsonPropertyAttribute("purchaseTime")] public virtual System.Nullable<long> PurchaseTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A SubscriptionPurchase resource indicates the status of a user's subscription purchase.</summary> public class SubscriptionPurchase : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Whether the subscription will automatically be renewed when it reaches its current expiry /// time.</summary> [Newtonsoft.Json.JsonPropertyAttribute("autoRenewing")] public virtual System.Nullable<bool> AutoRenewing { get; set; } /// <summary>Time at which the subscription was granted, in milliseconds since Epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("initiationTimestampMsec")] public virtual System.Nullable<long> InitiationTimestampMsec { get; set; } /// <summary>This kind represents a subscriptionPurchase object in the androidpublisher service.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Time at which the subscription will expire, in milliseconds since Epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("validUntilTimestampMsec")] public virtual System.Nullable<long> ValidUntilTimestampMsec { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
namespace Community.CsharpSqlite { using System; public partial class Sqlite3 { /* ** 2010 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements routines used to report what compile-time options ** SQLite was built with. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7 ** ************************************************************************* */ #if !SQLITE_OMIT_COMPILEOPTION_DIAGS //#include "sqliteInt.h" /* ** An array of names of all compile-time options. This array should ** be sorted A-Z. ** ** This array looks large, but in a typical installation actually uses ** only a handful of compile-time options, so most times this array is usually ** rather short and uses little memory space. */ private static string[] azCompileOpt = { /* These macros are provided to "stringify" the value of the define ** for those options in which the value is meaningful. */ //#define CTIMEOPT_VAL_(opt) #opt //#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) #if SQLITE_32BIT_ROWID "32BIT_ROWID", #endif #if SQLITE_4_BYTE_ALIGNED_MALLOC "4_BYTE_ALIGNED_MALLOC", #endif #if SQLITE_CASE_SENSITIVE_LIKE "CASE_SENSITIVE_LIKE", #endif #if SQLITE_CHECK_PAGES "CHECK_PAGES", #endif #if SQLITE_COVERAGE_TEST "COVERAGE_TEST", #endif #if SQLITE_DEBUG "DEBUG", #endif #if SQLITE_DEFAULT_LOCKING_MODE "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), #endif #if SQLITE_DISABLE_DIRSYNC "DISABLE_DIRSYNC", #endif #if SQLITE_DISABLE_LFS "DISABLE_LFS", #endif #if SQLITE_ENABLE_ATOMIC_WRITE "ENABLE_ATOMIC_WRITE", #endif #if SQLITE_ENABLE_CEROD "ENABLE_CEROD", #endif #if SQLITE_ENABLE_COLUMN_METADATA "ENABLE_COLUMN_METADATA", #endif #if SQLITE_ENABLE_EXPENSIVE_ASSERT "ENABLE_EXPENSIVE_ASSERT", #endif #if SQLITE_ENABLE_FTS1 "ENABLE_FTS1", #endif #if SQLITE_ENABLE_FTS2 "ENABLE_FTS2", #endif #if SQLITE_ENABLE_FTS3 "ENABLE_FTS3", #endif #if SQLITE_ENABLE_FTS3_PARENTHESIS "ENABLE_FTS3_PARENTHESIS", #endif #if SQLITE_ENABLE_FTS4 "ENABLE_FTS4", #endif #if SQLITE_ENABLE_ICU "ENABLE_ICU", #endif #if SQLITE_ENABLE_IOTRACE "ENABLE_IOTRACE", #endif #if SQLITE_ENABLE_LOAD_EXTENSION "ENABLE_LOAD_EXTENSION", #endif #if SQLITE_ENABLE_LOCKING_STYLE "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT "ENABLE_MEMORY_MANAGEMENT", #endif #if SQLITE_ENABLE_MEMSYS3 "ENABLE_MEMSYS3", #endif #if SQLITE_ENABLE_MEMSYS5 "ENABLE_MEMSYS5", #endif #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK "ENABLE_OVERSIZE_CELL_CHECK", #endif #if SQLITE_ENABLE_RTREE "ENABLE_RTREE", #endif #if SQLITE_ENABLE_STAT2 "ENABLE_STAT2", #endif #if SQLITE_ENABLE_UNLOCK_NOTIFY "ENABLE_UNLOCK_NOTIFY", #endif #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT "ENABLE_UPDATE_DELETE_LIMIT", #endif #if SQLITE_HAS_CODEC "HAS_CODEC", #endif #if SQLITE_HAVE_ISNAN "HAVE_ISNAN", #endif #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX "HOMEGROWN_RECURSIVE_MUTEX", #endif #if SQLITE_IGNORE_AFP_LOCK_ERRORS "IGNORE_AFP_LOCK_ERRORS", #endif #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS "IGNORE_FLOCK_LOCK_ERRORS", #endif #if SQLITE_INT64_TYPE "INT64_TYPE", #endif #if SQLITE_LOCK_TRACE "LOCK_TRACE", #endif #if SQLITE_MEMDEBUG "MEMDEBUG", #endif #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT "MIXED_ENDIAN_64BIT_FLOAT", #endif #if SQLITE_NO_SYNC "NO_SYNC", #endif #if SQLITE_OMIT_ALTERTABLE "OMIT_ALTERTABLE", #endif #if SQLITE_OMIT_ANALYZE "OMIT_ANALYZE", #endif #if SQLITE_OMIT_ATTACH "OMIT_ATTACH", #endif #if SQLITE_OMIT_AUTHORIZATION "OMIT_AUTHORIZATION", #endif #if SQLITE_OMIT_AUTOINCREMENT "OMIT_AUTOINCREMENT", #endif #if SQLITE_OMIT_AUTOINIT "OMIT_AUTOINIT", #endif #if SQLITE_OMIT_AUTOMATIC_INDEX "OMIT_AUTOMATIC_INDEX", #endif #if SQLITE_OMIT_AUTORESET "OMIT_AUTORESET", #endif #if SQLITE_OMIT_AUTOVACUUM "OMIT_AUTOVACUUM", #endif #if SQLITE_OMIT_BETWEEN_OPTIMIZATION "OMIT_BETWEEN_OPTIMIZATION", #endif #if SQLITE_OMIT_BLOB_LITERAL "OMIT_BLOB_LITERAL", #endif #if SQLITE_OMIT_BTREECOUNT "OMIT_BTREECOUNT", #endif #if SQLITE_OMIT_BUILTIN_TEST "OMIT_BUILTIN_TEST", #endif #if SQLITE_OMIT_CAST "OMIT_CAST", #endif #if SQLITE_OMIT_CHECK "OMIT_CHECK", #endif /* // redundant ** #if SQLITE_OMIT_COMPILEOPTION_DIAGS ** "OMIT_COMPILEOPTION_DIAGS", ** #endif */ #if SQLITE_OMIT_COMPLETE "OMIT_COMPLETE", #endif #if SQLITE_OMIT_COMPOUND_SELECT "OMIT_COMPOUND_SELECT", #endif #if SQLITE_OMIT_DATETIME_FUNCS "OMIT_DATETIME_FUNCS", #endif #if SQLITE_OMIT_DECLTYPE "OMIT_DECLTYPE", #endif #if SQLITE_OMIT_DEPRECATED "OMIT_DEPRECATED", #endif #if SQLITE_OMIT_DISKIO "OMIT_DISKIO", #endif #if SQLITE_OMIT_EXPLAIN "OMIT_EXPLAIN", #endif #if SQLITE_OMIT_FLAG_PRAGMAS "OMIT_FLAG_PRAGMAS", #endif #if SQLITE_OMIT_FLOATING_POINT "OMIT_FLOATING_POINT", #endif #if SQLITE_OMIT_FOREIGN_KEY "OMIT_FOREIGN_KEY", #endif #if SQLITE_OMIT_GET_TABLE "OMIT_GET_TABLE", #endif #if SQLITE_OMIT_INCRBLOB "OMIT_INCRBLOB", #endif #if SQLITE_OMIT_INTEGRITY_CHECK "OMIT_INTEGRITY_CHECK", #endif #if SQLITE_OMIT_LIKE_OPTIMIZATION "OMIT_LIKE_OPTIMIZATION", #endif #if SQLITE_OMIT_LOAD_EXTENSION "OMIT_LOAD_EXTENSION", #endif #if SQLITE_OMIT_LOCALTIME "OMIT_LOCALTIME", #endif #if SQLITE_OMIT_LOOKASIDE "OMIT_LOOKASIDE", #endif #if SQLITE_OMIT_MEMORYDB "OMIT_MEMORYDB", #endif #if SQLITE_OMIT_OR_OPTIMIZATION "OMIT_OR_OPTIMIZATION", #endif #if SQLITE_OMIT_PAGER_PRAGMAS "OMIT_PAGER_PRAGMAS", #endif #if SQLITE_OMIT_PRAGMA "OMIT_PRAGMA", #endif #if SQLITE_OMIT_PROGRESS_CALLBACK "OMIT_PROGRESS_CALLBACK", #endif #if SQLITE_OMIT_QUICKBALANCE "OMIT_QUICKBALANCE", #endif #if SQLITE_OMIT_REINDEX "OMIT_REINDEX", #endif #if SQLITE_OMIT_SCHEMA_PRAGMAS "OMIT_SCHEMA_PRAGMAS", #endif #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS "OMIT_SCHEMA_VERSION_PRAGMAS", #endif #if SQLITE_OMIT_SHARED_CACHE "OMIT_SHARED_CACHE", #endif #if SQLITE_OMIT_SUBQUERY "OMIT_SUBQUERY", #endif #if SQLITE_OMIT_TCL_VARIABLE "OMIT_TCL_VARIABLE", #endif #if SQLITE_OMIT_TEMPDB "OMIT_TEMPDB", #endif #if SQLITE_OMIT_TRACE "OMIT_TRACE", #endif #if SQLITE_OMIT_TRIGGER "OMIT_TRIGGER", #endif #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION "OMIT_TRUNCATE_OPTIMIZATION", #endif #if SQLITE_OMIT_UTF16 "OMIT_UTF16", #endif #if SQLITE_OMIT_VACUUM "OMIT_VACUUM", #endif #if SQLITE_OMIT_VIEW "OMIT_VIEW", #endif #if SQLITE_OMIT_VIRTUALTABLE "OMIT_VIRTUALTABLE", #endif #if SQLITE_OMIT_WAL "OMIT_WAL", #endif #if SQLITE_OMIT_WSD "OMIT_WSD", #endif #if SQLITE_OMIT_XFER_OPT "OMIT_XFER_OPT", #endif #if SQLITE_PERFORMANCE_TRACE "PERFORMANCE_TRACE", #endif #if SQLITE_PROXY_DEBUG "PROXY_DEBUG", #endif #if SQLITE_SECURE_DELETE "SECURE_DELETE", #endif #if SQLITE_SMALL_STACK "SMALL_STACK", #endif #if SQLITE_SOUNDEX "SOUNDEX", #endif #if SQLITE_TCL "TCL", #endif //#if SQLITE_TEMP_STORE "TEMP_STORE=1",//CTIMEOPT_VAL(SQLITE_TEMP_STORE), //#endif #if SQLITE_TEST "TEST", #endif #if SQLITE_THREADSAFE "THREADSAFE=2", // For C#, hardcode to = 2 CTIMEOPT_VAL(SQLITE_THREADSAFE), #else "THREADSAFE=0", // For C#, hardcode to = 0 #endif #if SQLITE_USE_ALLOCA "USE_ALLOCA", #endif #if SQLITE_ZERO_MALLOC "ZERO_MALLOC" #endif }; /* ** Given the name of a compile-time option, return true if that option ** was used and false if not. ** ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix ** is not required for a match. */ private static int sqlite3_compileoption_used(string zOptName) { if (zOptName.EndsWith("=")) return 0; int i, n = 0; if (zOptName.StartsWith("SQLITE_", System.StringComparison.OrdinalIgnoreCase)) n = 7; //n = sqlite3Strlen30(zOptName); /* Since ArraySize(azCompileOpt) is normally in single digits, a ** linear search is adequate. No need for a binary search. */ if (!String.IsNullOrEmpty(zOptName)) for (i = 0; i < ArraySize(azCompileOpt); i++) { int n1 = (zOptName.Length - n < azCompileOpt[i].Length) ? zOptName.Length - n : azCompileOpt[i].Length; if (String.Compare(zOptName, n, azCompileOpt[i], 0, n1, StringComparison.OrdinalIgnoreCase) == 0) return 1; } return 0; } /* ** Return the N-th compile-time option string. If N is out of range, ** return a NULL pointer. */ private static string sqlite3_compileoption_get(int N) { if (N >= 0 && N < ArraySize(azCompileOpt)) { return azCompileOpt[N]; } return null; } #endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Management.Automation; using System.Net; using System.Net.Cache; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.Common.Models; using Microsoft.WindowsAzure.Commands.ServiceManagement.Extensions; using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests { [TestClass] public class ScenarioTest : ServiceManagementTest { private const string ReadyState = "ReadyRole"; private string serviceName; //string perfFile; [TestInitialize] public void Initialize() { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); pass = false; testStartTime = DateTime.Now; } /// <summary> /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestCategory(Category.BVT), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureQuickVM,Get-AzureVMImage,Get-AzureVM,Get-AzureLocation,Import-AzurePublishSettingsFile,Get-AzureSubscription,Set-AzureSubscription)")] public void NewWindowsAzureQuickVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName1 = Utilities.GetUniqueShortName(vmNamePrefix); string newAzureQuickVMName2 = Utilities.GetUniqueShortName(vmNamePrefix); try { if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName1, serviceName, imageName, username, password, locationName); // Verify Assert.AreEqual(newAzureQuickVMName1, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName1, serviceName).Name, true); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName2, serviceName, imageName, username, password); // Verify Assert.AreEqual(newAzureQuickVMName2, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName2, serviceName).Name, true); try { vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName1 + "wrongVMName", serviceName); Assert.Fail("Should Fail!!"); } catch (Exception e) { Console.WriteLine("Fail as expected: {0}", e.ToString()); } // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName1, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName1, serviceName)); Assert.AreEqual(newAzureQuickVMName2, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName2, serviceName).Name, true); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName2, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName2, serviceName)); //Remove the service after removing the VM above vmPowershellCmdlets.RemoveAzureService(serviceName); //DisableWinRMHttps Test Case try { vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName2, serviceName, imageName, username, password, locationName, null, ""); pass = true; } catch (Exception e) { pass = false; if (e is AssertFailedException) { throw; } } finally { if (pass == true) pass = true; vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName2, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName2, serviceName)); } //End DisableWinRMHttps Test Case // Negative Test Case--It should Fail try { vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName1, serviceName, imageName, username, password, locationName); Assert.Fail("Should have failed, but succeeded!!"); pass = true; } catch (Exception e) { if (e is AssertFailedException) { throw; } Console.WriteLine("This exception is expected."); pass = true; } // End of Negative Test Case -- It should Fail] } catch (Exception e) { Console.WriteLine(e); throw; } } /// <summary> /// Get-AzureWinRMUri /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestCategory(Category.BVT), TestProperty("Feature", "IaaS"), Priority(1), Owner("v-rakonj"), Description("Test the cmdlets (Get-AzureWinRMUri)")] public void GetAzureWinRMUri() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); try { string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); Utilities.RetryActionUntilSuccess(() => { if (vmPowershellCmdlets.TestAzureServiceName(serviceName)) { var op = vmPowershellCmdlets.RemoveAzureService(serviceName); } vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); }, "Windows Azure is currently performing an operation on this hosted service that requires exclusive access.", 10, 30); // Verify the VM var vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true, "VM names are not matched!"); // Get the WinRM Uri var resultUri = vmPowershellCmdlets.GetAzureWinRMUri(serviceName, vmRoleCtxt.Name); // starting the test. InputEndpointContext winRMEndpoint = null; foreach (InputEndpointContext inputEndpointCtxt in vmPowershellCmdlets.GetAzureEndPoint(vmRoleCtxt)) { if (inputEndpointCtxt.Name.Equals(WinRmEndpointName)) { winRMEndpoint = inputEndpointCtxt; } } Assert.IsNotNull(winRMEndpoint, "There is no WinRM endpoint!"); Assert.IsNotNull(resultUri, "No WinRM Uri!"); Console.WriteLine("InputEndpointContext Name: {0}", winRMEndpoint.Name); Console.WriteLine("InputEndpointContext port: {0}", winRMEndpoint.Port); Console.WriteLine("InputEndpointContext protocol: {0}", winRMEndpoint.Protocol); Console.WriteLine("WinRM Uri: {0}", resultUri.AbsoluteUri); Console.WriteLine("WinRM Port: {0}", resultUri.Port); Console.WriteLine("WinRM Scheme: {0}", resultUri.Scheme); Assert.AreEqual(winRMEndpoint.Port, resultUri.Port, "Port numbers are not matched!"); pass = true; } catch (Exception e) { Console.WriteLine(e); throw; } } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestCategory(Category.BVT), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureLocation,Test-AzureName ,Get-AzureVMImage,New-AzureQuickVM,Get-AzureVM ,Restart-AzureVM,Stop-AzureVM , Start-AzureVM)")] public void ProvisionLinuxVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureLinuxVMName = Utilities.GetUniqueShortName("PSLinuxVM"); string linuxImageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux" }, false); try { vmPowershellCmdlets.NewAzureQuickVM(OS.Linux, newAzureLinuxVMName, serviceName, linuxImageName, "user", password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureLinuxVMName, serviceName); Assert.AreEqual(newAzureLinuxVMName, vmRoleCtxt.Name, true); try { vmPowershellCmdlets.RemoveAzureVM(newAzureLinuxVMName + "wrongVMName", serviceName); Assert.Fail("Should Fail!!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } Console.WriteLine("Fail as expected: {0}", e); } // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureLinuxVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureLinuxVMName, serviceName)); pass = true; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } } /// <summary> /// Verify Advanced Provisioning for the Dev/Test Scenario /// Make an Service /// Make a VM /// Add 4 additonal endpoints /// Makes a storage account /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("msampson"), Description("Test the cmdlets (Get-AzureDeployment, New-AzureVMConfig, Add-AzureProvisioningConfig, Add-AzureEndpoint, New-AzureVM, New-AzureStorageAccount)")] public void DevTestProvisioning() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureVM1Name = Utilities.GetUniqueShortName(vmNamePrefix); //Find a Windows VM Image imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); //Specify a small Windows image, with username and pw AzureVMConfigInfo azureVMConfigInfo1 = new AzureVMConfigInfo(newAzureVM1Name, InstanceSize.ExtraSmall.ToString(), imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.NoLB, ProtocolInfo.tcp, 80, 80, "Http"); PersistentVMConfigInfo persistentVMConfigInfo1 = new PersistentVMConfigInfo(azureVMConfigInfo1, azureProvisioningConfig, null, azureEndPointConfigInfo); PersistentVM persistentVM1 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo1); //Add all the endpoints that are added by the Dev Test feature in Azure Tools azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.NoLB, ProtocolInfo.tcp, 443, 443, "Https"); azureEndPointConfigInfo.Vm = persistentVM1; persistentVM1 = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo); azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.NoLB, ProtocolInfo.tcp, 1433, 1433, "MSSQL"); azureEndPointConfigInfo.Vm = persistentVM1; persistentVM1 = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo); azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.NoLB, ProtocolInfo.tcp, 8172, 8172, "WebDeploy"); azureEndPointConfigInfo.Vm = persistentVM1; persistentVM1 = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo); // Make a storage account named "devtestNNNNN" string storageAcctName = "devtest" + new Random().Next(10000, 99999); vmPowershellCmdlets.NewAzureStorageAccount(storageAcctName, locationName); // When making a new azure VM, you can't specify a location if you want to use the existing service PersistentVM[] VMs = { persistentVM1 }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs, locationName); var svcDeployment = vmPowershellCmdlets.GetAzureDeployment(serviceName); Assert.AreEqual(svcDeployment.ServiceName, serviceName); var vmDeployment = vmPowershellCmdlets.GetAzureVM(newAzureVM1Name, serviceName); Assert.AreEqual(vmDeployment.InstanceName, newAzureVM1Name); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureVM1Name, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM1Name, serviceName)); Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureStorageAccount(storageAcctName), "in use", 10, 30); pass = true; } /// <summary> /// Verify Advanced Provisioning /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureService,New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void AdvancedProvisioning() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureVM1Name = Utilities.GetUniqueShortName(vmNamePrefix); string newAzureVM2Name = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) { imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); } vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); var azureVMConfigInfo1 = new AzureVMConfigInfo(newAzureVM1Name, InstanceSize.ExtraSmall.ToString(), imageName); var azureVMConfigInfo2 = new AzureVMConfigInfo(newAzureVM2Name, InstanceSize.ExtraSmall.ToString(), imageName); var azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); var azureDataDiskConfigInfo = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); var azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, 80, 80, "web", "lbweb", 80, ProtocolInfo.http, @"/", null, null); var persistentVMConfigInfo1 = new PersistentVMConfigInfo(azureVMConfigInfo1, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); var persistentVMConfigInfo2 = new PersistentVMConfigInfo(azureVMConfigInfo2, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVM persistentVM1 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo1); PersistentVM persistentVM2 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo2); PersistentVM[] VMs = { persistentVM1, persistentVM2 }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureVM1Name, serviceName); vmPowershellCmdlets.RemoveAzureVM(newAzureVM2Name, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM1Name, serviceName)); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM2Name, serviceName)); pass = true; } /// <summary> /// Modifying Existing Virtual Machines /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void ModifyingVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.NoLB, ProtocolInfo.tcp, 1433, 2000, "sql"); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisksAndEndPoint(newAzureQuickVMName, serviceName, dataDiskConfig, azureEndPointConfigInfo); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, serviceName, diskConfig); vmPowershellCmdlets.GetAzureDataDisk(newAzureQuickVMName, serviceName); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Changes that Require a Reboot /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureVM,Set-AzureDataDisk ,Update-AzureVM,Set-AzureVMSize)")] public void UpdateAndReboot() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); var azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); var azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisks(newAzureQuickVMName, serviceName, dataDiskConfig); var setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); var setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, serviceName, diskConfig); var vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium.ToString()); vmPowershellCmdlets.SetVMSize(newAzureQuickVMName, serviceName, vmSizeConfig); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureDisk,Remove-AzureVM,Remove-AzureDisk,Get-AzureVMImage)")] public void ManagingDiskImages() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a unique VM name and Service Name string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) { imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); } vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. Collection<DiskContext> vmDisks = vmPowershellCmdlets.GetAzureDiskAttachedToRoleName(new[] { newAzureQuickVMName }); // Get-AzureDisk | Where {$_.AttachedTo.RoleName -eq $vmname } foreach (var disk in vmDisks) Console.WriteLine("The disk, {0}, is created", disk.DiskName); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); Console.WriteLine("The VM, {0}, is successfully removed.", newAzureQuickVMName); foreach (var disk in vmDisks) { for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.RemoveAzureDisk(disk.DiskName, false); // Remove-AzureDisk break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The vhd, {0}, is still in the state of being used by the deleted VM", disk.DiskName); Thread.Sleep(120000); continue; } else { Assert.Fail("error during Remove-AzureDisk: {0}", e.ToString()); } } } try { vmPowershellCmdlets.GetAzureDisk(disk.DiskName); // Get-AzureDisk -DiskName (try to get the removed disk.) Console.WriteLine("Disk is not removed: {0}", disk.DiskName); pass = false; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The disk, {0}, is successfully removed.", disk.DiskName); continue; } else { Assert.Fail("Exception: {0}", e.ToString()); } } } pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig,New-AzureVM,Save-AzureVMImage)")] public void CaptureImagingExportingImportingVMConfig() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a unique VM name string newAzureVMName = Utilities.GetUniqueShortName("PSTestVM"); Console.WriteLine("VM Name: {0}", newAzureVMName); // Create a unique Service Name vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("Service Name: {0}", serviceName); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); // starting the test. var azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small.ToString(), imageName); // parameters for New-AzureVMConfig (-Name -InstanceSize -ImageName) var azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); // parameters for Add-AzureProvisioningConfig (-Windows -Password) var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM persistentVM = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); // New-AzureVMConfig & Add-AzureProvisioningConfig PersistentVM[] VMs = { persistentVM }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // New-AzureVM Console.WriteLine("The VM is successfully created: {0}", persistentVM.RoleName); PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName); Assert.AreEqual(vmRoleCtxt.Name, persistentVM.RoleName, true); vmPowershellCmdlets.StopAzureVM(newAzureVMName, serviceName, true); // Stop-AzureVM for (int i = 0; i < 3; i++) { vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName); if (vmRoleCtxt.InstanceStatus == "StoppedVM") { break; } Console.WriteLine("The status of the VM {0} : {1}", persistentVM.RoleName, vmRoleCtxt.InstanceStatus); Thread.Sleep(120000); } Assert.AreEqual(vmRoleCtxt.InstanceStatus, "StoppedVM", true); // Save-AzureVMImage vmPowershellCmdlets.SaveAzureVMImage(serviceName, newAzureVMName, newAzureVMName); // Verify VM image. var image = vmPowershellCmdlets.GetAzureVMImage(newAzureVMName)[0]; Assert.AreEqual("Windows", image.OS, "OS is not matching!"); Assert.AreEqual(newAzureVMName, image.ImageName, "Names are not matching!"); // Verify that the VM is removed Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName)); // Cleanup the registered image vmPowershellCmdlets.RemoveAzureVMImage(newAzureVMName, true); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Export-AzureVM,Remove-AzureVM,Import-AzureVM,New-AzureVM)")] public void ExportingImportingVMConfigAsTemplateforRepeatableUsage() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a new Azure quick VM string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. string path = ".\\mytestvmconfig1.xml"; PersistentVMRoleContext vmRole = vmPowershellCmdlets.ExportAzureVM(newAzureQuickVMName, serviceName, path); // Export-AzureVM Console.WriteLine("Exporting VM is successfully done: path - {0} Name - {1}", path, vmRole.Name); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); Console.WriteLine("The VM is successfully removed: {0}", newAzureQuickVMName); List<PersistentVM> VMs = new List<PersistentVM>(); foreach (var pervm in vmPowershellCmdlets.ImportAzureVM(path)) // Import-AzureVM { VMs.Add(pervm); Console.WriteLine("The VM, {0}, is imported.", pervm.RoleName); } for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.NewAzureVM(serviceName, VMs.ToArray()); // New-AzureVM Console.WriteLine("All VMs are successfully created."); foreach (var vm in VMs) { Console.WriteLine("created VM: {0}", vm.RoleName); } break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The removed VM is still using the vhd"); Thread.Sleep(120000); continue; } else { Assert.Fail("error during New-AzureVM: {0}", e.ToString()); } } } // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureVM,Get-AzureEndpoint,Get-AzureRemoteDesktopFile)")] public void ManagingRDPSSHConnectivity() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a new Azure quick VM string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); // Get-AzureVM InputEndpointContext inputEndpointCtxt = vmPowershellCmdlets.GetAzureEndPoint(vmRoleCtxt)[0]; // Get-AzureEndpoint Console.WriteLine("InputEndpointContext Name: {0}", inputEndpointCtxt.Name); Console.WriteLine("InputEndpointContext port: {0}", inputEndpointCtxt.Port); Console.WriteLine("InputEndpointContext protocol: {0}", inputEndpointCtxt.Protocol); Assert.AreEqual(WinRmEndpointName, inputEndpointCtxt.Name, true); string path = ".\\myvmconnection.rdp"; vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, serviceName, path, false); // Get-AzureRemoteDesktopFile Console.WriteLine("RDP file is successfully created at: {0}", path); // ToDo: Automate RDP. //vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, newAzureQuickVMSvcName, path, true); // Get-AzureRemoteDesktopFile -Launch Console.WriteLine("Test passed"); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\packageScenario.csv", "packageScenario#csv", DataAccessMethod.Sequential)] public void DeploymentUpgrade() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string path = Convert.ToString(TestContext.DataRow["path"]); string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); var packagePath1 = new FileInfo(@path + packageName); // package with two roles var configPath1 = new FileInfo(@path + configName); // config with 2 roles, 4 instances each Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; try { vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); // New deployment to Production DateTime start = DateTime.Now; vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); TimeSpan duration = DateTime.Now - start; Console.WriteLine("Time for all instances to become in ready state: {0}", DateTime.Now - start); // Auto-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Auto, packagePath1.FullName, configPath1.FullName); duration = DateTime.Now - start; Console.WriteLine("Auto upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 4); Console.WriteLine("successfully updated the deployment"); // Manual-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Manual, packagePath1.FullName, configPath1.FullName); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 0); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 1); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 2); duration = DateTime.Now - start; Console.WriteLine("Manual upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 4); Console.WriteLine("successfully updated the deployment"); // Simulatenous-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Simultaneous, packagePath1.FullName, configPath1.FullName); duration = DateTime.Now - start; Console.WriteLine("Simulatenous upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 4); Console.WriteLine("successfully updated the deployment"); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } /// <summary> /// AzureVNetGatewayTest() /// </summary> /// Note: Create a VNet, a LocalNet from the portal without creating a gateway. [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Set,Remove)-AzureVNetConfig, Get-AzureVNetSite, (New,Get,Set,Remove)-AzureVNetGateway, Get-AzureVNetConnection)")] public void VNetTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); // Read the vnetconfig file and get the names of local networks, virtual networks and affinity groups. XDocument vnetconfigxml = XDocument.Load(vnetConfigFilePath); List<string> localNets = new List<string>(); List<string> virtualNets = new List<string>(); HashSet<string> affinityGroups = new HashSet<string>(); Dictionary<string, string> dns = new Dictionary<string, string>(); List<LocalNetworkSite> localNetworkSites = new List<LocalNetworkSite>(); AddressPrefixList prefixlist = null; foreach (XElement el in vnetconfigxml.Descendants()) { switch (el.Name.LocalName) { case "LocalNetworkSite": { localNets.Add(el.FirstAttribute.Value); List<XElement> elements = el.Elements().ToList<XElement>(); prefixlist = new AddressPrefixList(); prefixlist.Add(elements[0].Elements().First().Value); localNetworkSites.Add(new LocalNetworkSite() { VpnGatewayAddress = elements[1].Value, AddressSpace = new AddressSpace() { AddressPrefixes = prefixlist } } ); } break; case "VirtualNetworkSite": virtualNets.Add(el.Attribute("name").Value); affinityGroups.Add(el.Attribute("AffinityGroup").Value); break; case "DnsServer": { dns.Add(el.Attribute("name").Value, el.Attribute("IPAddress").Value); break; } default: break; } } foreach (string aff in affinityGroups) { if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, aff)) { vmPowershellCmdlets.NewAzureAffinityGroup(aff, locationName, null, null); } } string vnet1 = virtualNets[0]; string lnet1 = localNets[0]; try { vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath); foreach (VirtualNetworkSiteContext site in vmPowershellCmdlets.GetAzureVNetSite(null)) { Console.WriteLine("Name: {0}, AffinityGroup: {1}", site.Name, site.AffinityGroup); Console.WriteLine("Name: {0}, Location: {1}", site.Name, site.Location); } foreach (string vnet in virtualNets) { VirtualNetworkSiteContext vnetsite = vmPowershellCmdlets.GetAzureVNetSite(vnet)[0]; Assert.AreEqual(vnet, vnetsite.Name); //Verify DNS and IPAddress Assert.AreEqual(1, vnetsite.DnsServers.Count()); Assert.IsTrue(dns.ContainsKey(vnetsite.DnsServers.First().Name)); Assert.AreEqual(dns[vnetsite.DnsServers.First().Name], vnetsite.DnsServers.First().Address); //Verify the Gateway sites Assert.AreEqual(1, vnetsite.GatewaySites.Count); Assert.AreEqual(localNetworkSites[0].VpnGatewayAddress, vnetsite.GatewaySites[0].VpnGatewayAddress); Assert.IsTrue(localNetworkSites[0].AddressSpace.AddressPrefixes.All(c => vnetsite.GatewaySites[0].AddressSpace.AddressPrefixes.Contains(c))); Assert.AreEqual(Microsoft.Azure.Commands.Network.ProvisioningState.NotProvisioned, vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State); } vmPowershellCmdlets.NewAzureVNetGateway(vnet1); Assert.IsTrue(GetVNetState(vnet1, Microsoft.Azure.Commands.Network.ProvisioningState.Provisioned, 12, 60)); // Set-AzureVNetGateway -Connect Test vmPowershellCmdlets.SetAzureVNetGateway("connect", vnet1, lnet1); foreach (Microsoft.Azure.Commands.Network.Gateway.Model.GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1)) { Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName); Assert.IsFalse(connection.ConnectivityState.ToLowerInvariant().Contains("notconnected")); } // Get-AzureVNetGatewayKey Microsoft.Azure.Commands.Network.Gateway.Model.SharedKeyContext result = vmPowershellCmdlets.GetAzureVNetGatewayKey(vnet1, vmPowershellCmdlets.GetAzureVNetConnection(vnet1).First().LocalNetworkSiteName); Console.WriteLine("Gateway Key: {0}", result.Value); // Set-AzureVNetGateway -Disconnect vmPowershellCmdlets.SetAzureVNetGateway("disconnect", vnet1, lnet1); foreach (Microsoft.Azure.Commands.Network.Gateway.Model.GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1)) { Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName); } // Remove-AzureVnetGateway vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); foreach (string vnet in virtualNets) { Microsoft.Azure.Commands.Network.VirtualNetworkGatewayContext gateway = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0]; Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress); if (vnet.Equals(vnet1)) { if (gateway.State != Microsoft.Azure.Commands.Network.ProvisioningState.Deprovisioning && gateway.State != Microsoft.Azure.Commands.Network.ProvisioningState.NotProvisioned) { Assert.Fail("The state of the gateway is neither Deprovisioning nor NotProvisioned!"); } } else { Assert.AreEqual(Microsoft.Azure.Commands.Network.ProvisioningState.NotProvisioned, gateway.State); } } Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureVNetConfig(), "in use", 10, 30); pass = true; } catch (Exception e) { pass = false; if (cleanupIfFailed) { try { vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); } catch { } Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureVNetConfig(), "in use", 10, 30); } Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { foreach (string aff in affinityGroups) { try { vmPowershellCmdlets.RemoveAzureAffinityGroup(aff); } catch { // Some service uses the affinity group, so it cannot be deleted. Just leave it. } } } } #region AzureServiceDiagnosticsExtension Tests [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\nodiagpackage.csv", "nodiagpackage#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureServiceDiagnosticsExtensionConfigScenarioTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; string storage = defaultAzureSubscription.CurrentStorageAccountName; string daConfig = @".\da.xml"; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); ExtensionConfigurationInput config = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, daConfig); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false, config); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); DiagnosticExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName)[0]; VerifyDiagExtContext(resultContext, "AllRoles", "Default-Diagnostics-Production-Ext-0", storage, daConfig); vmPowershellCmdlets.RemoveAzureServiceDiagnosticsExtension(serviceName); Assert.AreEqual(vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName).Count, 0); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureServiceRemoteDesktopExtension)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\nodiagpackage.csv", "nodiagpackage#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureServiceDiagnosticsExtensionTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; string storage = defaultAzureSubscription.CurrentStorageAccountName; string daConfig = @".\da.xml"; string defaultExtensionId = string.Format("Default-{0}-Production-Ext-0", Utilities.PaaSDiagnosticsExtensionName); try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); vmPowershellCmdlets.SetAzureServiceDiagnosticsExtension(serviceName, storage, daConfig, null, null); DiagnosticExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName)[0]; Assert.IsTrue(VerifyDiagExtContext(resultContext, "AllRoles", defaultExtensionId, storage, daConfig)); vmPowershellCmdlets.RemoveAzureServiceDiagnosticsExtension(serviceName, true); Assert.AreEqual(vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName).Count, 0); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } #endregion #region AzureServiceRemoteDesktopExtension Tests [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void AzureServiceRemoteDesktopExtensionConfigScenarioTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string configName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password)); string rdpPath = @".\WebRole1.rdp"; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); ExtensionConfigurationInput config = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false, config); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(serviceName)[0]; VerifyRDPExtContext(resultContext, "AllRoles", "Default-RDP-Production-Ext-0", username, DateTime.Now.AddYears(1)); VerifyRDP(serviceName, rdpPath); vmPowershellCmdlets.RemoveAzureServiceRemoteDesktopExtension(serviceName); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } else { Console.WriteLine("Failed to get RDP file as expected"); } } vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void AzureServiceRemoteDesktopExtensionConfigWithVersionScenarioTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string configName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password)); string rdpPath = @".\WebRole1.rdp"; string version10 = "1.0"; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); ExtensionConfigurationInput config = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, null, null, version10); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false, config); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(serviceName)[0]; VerifyRDPExtContext(resultContext, "AllRoles", "Default-RDP-Production-Ext-0", username, DateTime.Now.AddYears(1), version10); VerifyRDP(serviceName, rdpPath); vmPowershellCmdlets.RemoveAzureServiceRemoteDesktopExtension(serviceName); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } else { Console.WriteLine("Failed to get RDP file as expected"); } } vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureServiceRemoteDesktopExtension)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void AzureServiceRemoteDesktopExtensionTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string configName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password)); string rdpPath = @".\WebRole1.rdp"; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); vmPowershellCmdlets.SetAzureServiceRemoteDesktopExtension(serviceName, cred); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(serviceName)[0]; VerifyRDPExtContext(resultContext, "AllRoles", "Default-RDP-Production-Ext-0", username, DateTime.Now.AddYears(1)); VerifyRDP(serviceName, rdpPath); vmPowershellCmdlets.RemoveAzureServiceRemoteDesktopExtension(serviceName, true); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } else { Console.WriteLine("Failed to get RDP file as expected"); } } vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureServiceRemoteDesktopExtension)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void AzureServiceRemoteDesktopExtensionWithVersionTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string configName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password)); string rdpPath = @".\WebRole1.rdp"; string version10 = "1.0"; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); vmPowershellCmdlets.SetAzureServiceRemoteDesktopExtension(serviceName, cred, null, null, null, version10); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(serviceName)[0]; VerifyRDPExtContext(resultContext, "AllRoles", "Default-RDP-Production-Ext-0", username, DateTime.Now.AddYears(1), version10); VerifyRDP(serviceName, rdpPath); vmPowershellCmdlets.RemoveAzureServiceRemoteDesktopExtension(serviceName, true); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } else { Console.WriteLine("Failed to get RDP file as expected"); } } vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } #endregion [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Reset-AzureRoleInstanceTest with Reboot and Reimage paramaeters)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void ReSetAzureRoleInstanceTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow[2]); string configName = Convert.ToString(TestContext.DataRow[3]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "file not exist={0}", configPath1); string deploymentName = Utilities.GetUniqueShortName("ResetRoleInst", 20); string deploymentLabel = Utilities.GetUniqueShortName("ResetRoleInstDepLabel", 20); DeploymentInfoContext result; try { vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 2); Console.WriteLine("successfully deployed the package"); //Reboot the role instance vmPowershellCmdlets.ResetAzureRoleInstance(serviceName, "WebRole1_IN_0", DeploymentSlotType.Staging, reboot: true); var deploymentContextInfo = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging); //verify that other instances are in ready state string roleStatus = string.Empty; foreach (var instance in deploymentContextInfo.RoleInstanceList) { if (instance.InstanceName.Equals("WebRole1_IN_1")) { roleStatus = instance.InstanceStatus; break; } } pass = roleStatus == ReadyState; //Reimage the role instance vmPowershellCmdlets.ResetAzureRoleInstance(serviceName, "WebRole1_IN_1", DeploymentSlotType.Staging, reimage: true); //verify that other instances are in ready state deploymentContextInfo = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging); roleStatus = string.Empty; foreach (var instance in deploymentContextInfo.RoleInstanceList) { if (instance.InstanceName.Equals("WebRole1_IN_0")) { roleStatus = instance.InstanceStatus; break; } } pass = roleStatus == ReadyState; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { //Ceanup service vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Staging, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Staging); } } /// <summary> /// Deploy an IaaS VM with Domain Join /// </summary> [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig,New-AzureVM)")] public void NewAzureVMDomainJoinTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); var newAzureVMName = Utilities.GetUniqueShortName(vmNamePrefix); const string joinDomainStr = "www.microsoft.com"; const string domainStr = "microsoft.com"; const string domainUser = "pstestdomainuser"; const string domainPassword = "p@ssw0rd"; try { if (string.IsNullOrEmpty(imageName)) { imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); } vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); var azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small.ToString(), imageName); var azureProvisioningConfig = new AzureProvisioningConfigInfo("WindowsDomain", username, password, joinDomainStr, domainStr, domainUser, domainPassword); var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM persistentVM = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); PersistentVM[] VMs = { persistentVM }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // Todo: Check the domain of the VM pass = true; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } } [TestMethod(), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig,New-AzureVM)")] public void SetProvisionGuestAgentTest() { try { string vmName = Utilities.GetUniqueShortName(vmNamePrefix); Console.WriteLine("VM Name:{0}", vmName); PersistentVM vm = Utilities.CreateIaaSVMObject(vmName, InstanceSize.Small, imageName, true, username, password, true); vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, locationName, false); var vmRoleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Utilities.PrintContext(vmRoleContext); Assert.IsNotNull(vmRoleContext.VM.ProvisionGuestAgent, "ProvisionGuestAgent value cannot be null"); Assert.IsFalse(vmRoleContext.VM.ProvisionGuestAgent.Value); Console.WriteLine("Guest Agent Status: {0}", vmRoleContext.VM.ProvisionGuestAgent.Value); vmRoleContext.VM.ProvisionGuestAgent = true; vmPowershellCmdlets.UpdateAzureVM(vmName, serviceName, vmRoleContext.VM); vmRoleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Utilities.PrintContext(vmRoleContext); Assert.IsNotNull(vmRoleContext.VM.ProvisionGuestAgent, "ProvisionGuestAgent value cannot be null"); Assert.IsTrue(vmRoleContext.VM.ProvisionGuestAgent.Value); Console.WriteLine("Guest Agent Status: {0}", vmRoleContext.VM.ProvisionGuestAgent.Value); pass = true; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } } [TestCleanup] public virtual void CleanUp() { Console.WriteLine("Test {0}", pass ? "passed" : "failed"); // Remove the service if ((cleanupIfPassed && pass) || (cleanupIfFailed && !pass)) { CleanupService(serviceName); } } private string GetSiteContent(Uri uri, int maxRetryTimes, bool holdConnection) { Console.WriteLine("GetSiteContent. uri={0} maxRetryTimes={1}", uri.AbsoluteUri, maxRetryTimes); HttpWebRequest request; HttpWebResponse response = null; var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); HttpWebRequest.DefaultCachePolicy = noCachePolicy; int i; for (i = 1; i <= maxRetryTimes; i++) { try { request = (HttpWebRequest)WebRequest.Create(uri); request.Timeout = 10 * 60 * 1000; //set to 10 minutes, default 100 sec. default IE7/8 is 60 minutes response = (HttpWebResponse)request.GetResponse(); break; } catch (WebException e) { Console.WriteLine("Exception Message: " + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code: {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description: {0}", ((HttpWebResponse)e.Response).StatusDescription); } } Thread.Sleep(30 * 1000); } if (i > maxRetryTimes) { throw new Exception("Web Site has error and reached maxRetryTimes"); } Stream responseStream = response.GetResponseStream(); StringBuilder sb = new StringBuilder(); byte[] buf = new byte[100]; int length; while ((length = responseStream.Read(buf, 0, 100)) != 0) { if (holdConnection) { Thread.Sleep(TimeSpan.FromSeconds(10)); } sb.Append(Encoding.UTF8.GetString(buf, 0, length)); } string responseString = sb.ToString(); Console.WriteLine("Site content: (IsFromCache={0})", response.IsFromCache); Console.WriteLine(responseString); return responseString; } private bool GetVNetState(string vnet, Microsoft.Azure.Commands.Network.ProvisioningState expectedState, int maxTime, int intervalTime) { Microsoft.Azure.Commands.Network.ProvisioningState vnetState; int i = 0; do { vnetState = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State; Thread.Sleep(intervalTime * 1000); i++; } while (!vnetState.Equals(expectedState) || i < maxTime); return vnetState.Equals(expectedState); } private bool VerifyDiagExtContext(DiagnosticExtensionContext resultContext, string role, string extID, string storage, string config) { Utilities.PrintContext(resultContext); try { Assert.AreEqual(role, resultContext.Role.RoleType.ToString(), "role is not same"); Assert.AreEqual(Utilities.PaaSDiagnosticsExtensionName, resultContext.Extension, "extension is not Diagnostics"); Assert.AreEqual(extID, resultContext.Id, "extension id is not same"); //Assert.AreEqual(storage, resultContext.StorageAccountName, "storage account name is not same"); XmlDocument doc = new XmlDocument(); doc.Load("@./da.xml"); string inner = Utilities.GetInnerXml(resultContext.WadCfg, "WadCfg"); Assert.IsTrue(Utilities.CompareWadCfg(inner, doc), "xml is not same"); return true; } catch (Exception e) { Console.WriteLine("Error happens: {0}", e.ToString()); return false; } } private void VerifyRDPExtContext(RemoteDesktopExtensionContext resultContext, string role, string extID, string userName, DateTime exp, string version = null) { Utilities.PrintContextAndItsBase(resultContext); try { Assert.AreEqual(role, resultContext.Role.RoleType.ToString(), "role is not same"); Assert.AreEqual("RDP", resultContext.Extension, "extension is not RDP"); Assert.AreEqual(extID, resultContext.Id, "extension id is not same"); Assert.AreEqual(userName, resultContext.UserName, "storage account name is not same"); Assert.IsTrue(Utilities.CompareDateTime(exp, resultContext.Expiration), "expiration is not same"); if (!string.IsNullOrEmpty(version)) { Assert.AreEqual(version, resultContext.Version, "version numbers are not same"); } } catch (Exception e) { Console.WriteLine("Error happens: {0}", e.ToString()); throw; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public partial class ApiManagementClient : ServiceClient<ApiManagementClient>, IApiManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IApiOperationPolicyOperations _apiOperationPolicy; /// <summary> /// Operations for managing API Operation Policy. /// </summary> public virtual IApiOperationPolicyOperations ApiOperationPolicy { get { return this._apiOperationPolicy; } } private IApiOperationsOperations _apiOperations; /// <summary> /// Operations for managing API Operations. /// </summary> public virtual IApiOperationsOperations ApiOperations { get { return this._apiOperations; } } private IApiPolicyOperations _apiPolicy; /// <summary> /// Operations for managing API Policy. /// </summary> public virtual IApiPolicyOperations ApiPolicy { get { return this._apiPolicy; } } private IApiProductsOperations _apiProducts; /// <summary> /// Operations for listing API associated Products. /// </summary> public virtual IApiProductsOperations ApiProducts { get { return this._apiProducts; } } private IApisOperations _apis; /// <summary> /// Operations for managing APIs. /// </summary> public virtual IApisOperations Apis { get { return this._apis; } } private IAuthorizationServersOperations _authorizationServers; /// <summary> /// Operations for managing Authorization Servers. /// </summary> public virtual IAuthorizationServersOperations AuthorizationServers { get { return this._authorizationServers; } } private ICertificatesOperations _certificates; /// <summary> /// Operations for managing Certificates. /// </summary> public virtual ICertificatesOperations Certificates { get { return this._certificates; } } private IGroupsOperations _groups; /// <summary> /// Operations for managing Groups. /// </summary> public virtual IGroupsOperations Groups { get { return this._groups; } } private IGroupUsersOperations _groupUsers; /// <summary> /// Operations for managing Group Users (list, add, remove users within /// a group). /// </summary> public virtual IGroupUsersOperations GroupUsers { get { return this._groupUsers; } } private IPolicySnippetsOperations _policySnippents; /// <summary> /// Operations for managing Policy Snippets. /// </summary> public virtual IPolicySnippetsOperations PolicySnippents { get { return this._policySnippents; } } private IProductApisOperations _productApis; /// <summary> /// Operations for managing Product APIs. /// </summary> public virtual IProductApisOperations ProductApis { get { return this._productApis; } } private IProductGroupsOperations _productGroups; /// <summary> /// Operations for managing Product Groups. /// </summary> public virtual IProductGroupsOperations ProductGroups { get { return this._productGroups; } } private IProductPolicyOperations _productPolicy; /// <summary> /// Operations for managing Product Policy. /// </summary> public virtual IProductPolicyOperations ProductPolicy { get { return this._productPolicy; } } private IProductsOperations _products; /// <summary> /// Operations for managing Products. /// </summary> public virtual IProductsOperations Products { get { return this._products; } } private IProductSubscriptionsOperations _productSubscriptions; /// <summary> /// Operations for managing Product Subscriptions. /// </summary> public virtual IProductSubscriptionsOperations ProductSubscriptions { get { return this._productSubscriptions; } } private IRegionsOperations _regions; /// <summary> /// Operations for managing Regions. /// </summary> public virtual IRegionsOperations Regions { get { return this._regions; } } private IReportsOperations _reports; /// <summary> /// Operations for managing Reports. /// </summary> public virtual IReportsOperations Reports { get { return this._reports; } } private IResourceProviderOperations _resourceProvider; /// <summary> /// Operations for managing Api Management service provisioning /// (create/remove, backup/restore, scale, etc.). /// </summary> public virtual IResourceProviderOperations ResourceProvider { get { return this._resourceProvider; } } private ISubscriptionsOperations _subscriptions; /// <summary> /// Operations for managing Subscriptions. /// </summary> public virtual ISubscriptionsOperations Subscriptions { get { return this._subscriptions; } } private ITenantAccessInformationOperations _tenantAccess; /// <summary> /// Operations for managing Tenant Access Information. /// </summary> public virtual ITenantAccessInformationOperations TenantAccess { get { return this._tenantAccess; } } private ITenantPolicyOperations _tenantPolicy; /// <summary> /// Operations for managing Tenant Policy. /// </summary> public virtual ITenantPolicyOperations TenantPolicy { get { return this._tenantPolicy; } } private IUserApplicationsOperations _userApplications; /// <summary> /// Operations for managing User Applications. /// </summary> public virtual IUserApplicationsOperations UserApplications { get { return this._userApplications; } } private IUserGroupsOperations _userGroups; /// <summary> /// Operations for managing User Groups. /// </summary> public virtual IUserGroupsOperations UserGroups { get { return this._userGroups; } } private IUserIdentitiesOperations _userIdentities; /// <summary> /// Operations for managing User Identities. /// </summary> public virtual IUserIdentitiesOperations UserIdentities { get { return this._userIdentities; } } private IUsersOperations _users; /// <summary> /// Operations for managing Users. /// </summary> public virtual IUsersOperations Users { get { return this._users; } } private IUserSubscriptionsOperations _userSubscriptions; /// <summary> /// Operations for managing User Subscriptions. /// </summary> public virtual IUserSubscriptionsOperations UserSubscriptions { get { return this._userSubscriptions; } } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> public ApiManagementClient() : base() { this._apiOperationPolicy = new ApiOperationPolicyOperations(this); this._apiOperations = new ApiOperationsOperations(this); this._apiPolicy = new ApiPolicyOperations(this); this._apiProducts = new ApiProductsOperations(this); this._apis = new ApisOperations(this); this._authorizationServers = new AuthorizationServersOperations(this); this._certificates = new CertificatesOperations(this); this._groups = new GroupsOperations(this); this._groupUsers = new GroupUsersOperations(this); this._policySnippents = new PolicySnippetsOperations(this); this._productApis = new ProductApisOperations(this); this._productGroups = new ProductGroupsOperations(this); this._productPolicy = new ProductPolicyOperations(this); this._products = new ProductsOperations(this); this._productSubscriptions = new ProductSubscriptionsOperations(this); this._regions = new RegionsOperations(this); this._reports = new ReportsOperations(this); this._resourceProvider = new ResourceProviderOperations(this); this._subscriptions = new SubscriptionsOperations(this); this._tenantAccess = new TenantAccessInformationOperations(this); this._tenantPolicy = new TenantPolicyOperations(this); this._userApplications = new UserApplicationsOperations(this); this._userGroups = new UserGroupsOperations(this); this._userIdentities = new UserIdentitiesOperations(this); this._users = new UsersOperations(this); this._userSubscriptions = new UserSubscriptionsOperations(this); this._apiVersion = "2014-02-14"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(HttpClient httpClient) : base(httpClient) { this._apiOperationPolicy = new ApiOperationPolicyOperations(this); this._apiOperations = new ApiOperationsOperations(this); this._apiPolicy = new ApiPolicyOperations(this); this._apiProducts = new ApiProductsOperations(this); this._apis = new ApisOperations(this); this._authorizationServers = new AuthorizationServersOperations(this); this._certificates = new CertificatesOperations(this); this._groups = new GroupsOperations(this); this._groupUsers = new GroupUsersOperations(this); this._policySnippents = new PolicySnippetsOperations(this); this._productApis = new ProductApisOperations(this); this._productGroups = new ProductGroupsOperations(this); this._productPolicy = new ProductPolicyOperations(this); this._products = new ProductsOperations(this); this._productSubscriptions = new ProductSubscriptionsOperations(this); this._regions = new RegionsOperations(this); this._reports = new ReportsOperations(this); this._resourceProvider = new ResourceProviderOperations(this); this._subscriptions = new SubscriptionsOperations(this); this._tenantAccess = new TenantAccessInformationOperations(this); this._tenantPolicy = new TenantPolicyOperations(this); this._userApplications = new UserApplicationsOperations(this); this._userGroups = new UserGroupsOperations(this); this._userIdentities = new UserIdentitiesOperations(this); this._users = new UsersOperations(this); this._userSubscriptions = new UserSubscriptionsOperations(this); this._apiVersion = "2014-02-14"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ApiManagementClient instance /// </summary> /// <param name='client'> /// Instance of ApiManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ApiManagementClient> client) { base.Clone(client); if (client is ApiManagementClient) { ApiManagementClient clonedClient = ((ApiManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type BearerTokenSendingMethodsContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static BearerTokenSendingMethodsContract ParseBearerTokenSendingMethodsContract(string value) { if ("authorizationHeader".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BearerTokenSendingMethodsContract.AuthorizationHeader; } if ("query".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BearerTokenSendingMethodsContract.Query; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type BearerTokenSendingMethodsContract to a /// string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string BearerTokenSendingMethodsContractToString(BearerTokenSendingMethodsContract value) { if (value == BearerTokenSendingMethodsContract.AuthorizationHeader) { return "authorizationHeader"; } if (value == BearerTokenSendingMethodsContract.Query) { return "query"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type GrantTypesContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static GrantTypesContract ParseGrantTypesContract(string value) { if ("authorizationCode".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.AuthorizationCode; } if ("implicit".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.Implicit; } if ("resourceOwnerPassword".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.ResourceOwnerPassword; } if ("clientCredentials".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.ClientCredentials; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type GrantTypesContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string GrantTypesContractToString(GrantTypesContract value) { if (value == GrantTypesContract.AuthorizationCode) { return "authorizationCode"; } if (value == GrantTypesContract.Implicit) { return "implicit"; } if (value == GrantTypesContract.ResourceOwnerPassword) { return "resourceOwnerPassword"; } if (value == GrantTypesContract.ClientCredentials) { return "clientCredentials"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type MethodContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static MethodContract ParseMethodContract(string value) { if ("HEAD".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Head; } if ("OPTIONS".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Options; } if ("TRACE".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Trace; } if ("GET".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Get; } if ("POST".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Post; } if ("PUT".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Put; } if ("PATCH".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Patch; } if ("DELETE".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Delete; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type MethodContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string MethodContractToString(MethodContract value) { if (value == MethodContract.Head) { return "HEAD"; } if (value == MethodContract.Options) { return "OPTIONS"; } if (value == MethodContract.Trace) { return "TRACE"; } if (value == MethodContract.Get) { return "GET"; } if (value == MethodContract.Post) { return "POST"; } if (value == MethodContract.Put) { return "PUT"; } if (value == MethodContract.Patch) { return "PATCH"; } if (value == MethodContract.Delete) { return "DELETE"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type ReportsAggregation. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static ReportsAggregation ParseReportsAggregation(string value) { if ("byApi".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByApi; } if ("byGeo".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByGeo; } if ("byOperation".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByOperation; } if ("byProduct".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByProduct; } if ("bySubscription".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.BySubscription; } if ("byTime".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByTime; } if ("byUser".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByUser; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type ReportsAggregation to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string ReportsAggregationToString(ReportsAggregation value) { if (value == ReportsAggregation.ByApi) { return "byApi"; } if (value == ReportsAggregation.ByGeo) { return "byGeo"; } if (value == ReportsAggregation.ByOperation) { return "byOperation"; } if (value == ReportsAggregation.ByProduct) { return "byProduct"; } if (value == ReportsAggregation.BySubscription) { return "bySubscription"; } if (value == ReportsAggregation.ByTime) { return "byTime"; } if (value == ReportsAggregation.ByUser) { return "byUser"; } throw new ArgumentOutOfRangeException("value"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml; using ThreadingTask = System.Threading.Tasks.Task; namespace Microsoft.DotNet.Build.CloudTestTasks { public class UploadToAzure : AzureConnectionStringBuildTask, ICancelableTask { private static readonly CancellationTokenSource TokenSource = new CancellationTokenSource(); private static readonly CancellationToken CancellationToken = TokenSource.Token; /// <summary> /// The name of the container to access. The specified name must be in the correct format, see the /// following page for more info. https://msdn.microsoft.com/en-us/library/azure/dd135715.aspx /// </summary> [Required] public string ContainerName { get; set; } /// <summary> /// An item group of files to upload. Each item must have metadata RelativeBlobPath /// that specifies the path relative to ContainerName where the item will be uploaded. /// </summary> [Required] public ITaskItem[] Items { get; set; } /// <summary> /// Indicates if the destination blob should be overwritten if it already exists. The default if false. /// </summary> public bool Overwrite { get; set; } = false; /// <summary> /// Enables idempotency when Overwrite is false. /// /// false: (default) Attempting to upload an item that already exists fails. /// /// true: When an item already exists, download the existing blob to check if it's /// byte-for-byte identical to the one being uploaded. If so, pass. If not, fail. /// </summary> public bool PassIfExistingItemIdentical { get; set; } /// <summary> /// Specifies the maximum number of clients to concurrently upload blobs to azure /// </summary> public int MaxClients { get; set; } = 8; public int UploadTimeoutInMinutes { get; set; } = 5; public void Cancel() { TokenSource.Cancel(); } public override bool Execute() { return ExecuteAsync(CancellationToken).GetAwaiter().GetResult(); } public async Task<bool> ExecuteAsync(CancellationToken ct) { ParseConnectionString(); // If the connection string AND AccountKey & AccountName are provided, error out. if (Log.HasLoggedErrors) { return false; } Log.LogMessage( MessageImportance.Normal, "Begin uploading blobs to Azure account {0} in container {1}.", AccountName, ContainerName); if (Items.Length == 0) { Log.LogError("No items were provided for upload."); return false; } // first check what blobs are present string checkListUrl = $"{AzureHelper.GetContainerRestUrl(AccountName, ContainerName)}?restype=container&comp=list"; HashSet<string> blobsPresent = new HashSet<string>(StringComparer.OrdinalIgnoreCase); try { using (HttpClient client = new HttpClient()) { var createRequest = AzureHelper.RequestMessage("GET", checkListUrl, AccountName, AccountKey); Log.LogMessage(MessageImportance.Low, "Sending request to check whether Container blobs exist"); using (HttpResponseMessage response = await AzureHelper.RequestWithRetry(Log, client, createRequest)) { var doc = new XmlDocument(); doc.LoadXml(await response.Content.ReadAsStringAsync()); XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("Blob"); foreach (XmlNode node in nodes) { blobsPresent.Add(node["Name"].InnerText); } Log.LogMessage(MessageImportance.Low, "Received response to check whether Container blobs exist"); } } using (var clientThrottle = new SemaphoreSlim(this.MaxClients, this.MaxClients)) { await ThreadingTask.WhenAll(Items.Select(item => UploadAsync(ct, item, blobsPresent, clientThrottle))); } Log.LogMessage(MessageImportance.Normal, "Upload to Azure is complete, a total of {0} items were uploaded.", Items.Length); } catch (Exception e) { Log.LogErrorFromException(e, true); } return !Log.HasLoggedErrors; } private async ThreadingTask UploadAsync(CancellationToken ct, ITaskItem item, HashSet<string> blobsPresent, SemaphoreSlim clientThrottle) { if (ct.IsCancellationRequested) { Log.LogError("Task UploadToAzure cancelled"); ct.ThrowIfCancellationRequested(); } string relativeBlobPath = item.GetMetadata("RelativeBlobPath"); if (string.IsNullOrEmpty(relativeBlobPath)) throw new Exception(string.Format("Metadata 'RelativeBlobPath' is missing for item '{0}'.", item.ItemSpec)); if (!File.Exists(item.ItemSpec)) throw new Exception(string.Format("The file '{0}' does not exist.", item.ItemSpec)); UploadClient uploadClient = new UploadClient(Log); if (!Overwrite && blobsPresent.Contains(relativeBlobPath)) { if (PassIfExistingItemIdentical && await ItemEqualsExistingBlobAsync(item, relativeBlobPath, uploadClient, clientThrottle)) { return; } throw new Exception(string.Format("The blob '{0}' already exists.", relativeBlobPath)); } string contentType = item.GetMetadata("ContentType"); await clientThrottle.WaitAsync(); try { Log.LogMessage("Uploading {0} to {1}.", item.ItemSpec, ContainerName); await uploadClient.UploadBlockBlobAsync( ct, AccountName, AccountKey, ContainerName, item.ItemSpec, relativeBlobPath, contentType, UploadTimeoutInMinutes); } finally { clientThrottle.Release(); } } private async Task<bool> ItemEqualsExistingBlobAsync( ITaskItem item, string relativeBlobPath, UploadClient client, SemaphoreSlim clientThrottle) { await clientThrottle.WaitAsync(); try { return await client.FileEqualsExistingBlobAsync( AccountName, AccountKey, ContainerName, item.ItemSpec, relativeBlobPath, UploadTimeoutInMinutes); } finally { clientThrottle.Release(); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading; using NUnit.Framework; using osu.Framework.Threading; using osu.Framework.Timing; namespace osu.Framework.Tests.Threading { [TestFixture] public class SchedulerTest { private Scheduler scheduler; [SetUp] public void Setup() { scheduler = new Scheduler(new Thread(() => { })); } [Test] public void TestScheduleOnce([Values(false, true)] bool fromMainThread, [Values(false, true)] bool forceScheduled) { if (fromMainThread) scheduler.SetCurrentThread(); int invocations = 0; scheduler.Add(() => invocations++, forceScheduled); if (fromMainThread && !forceScheduled) Assert.AreEqual(1, invocations); else Assert.AreEqual(0, invocations); scheduler.Update(); Assert.AreEqual(1, invocations); // Ensures that the delegate runs only once in the scheduled/not on main thread branch scheduler.Update(); Assert.AreEqual(1, invocations); } [Test] public void TestCancelScheduledDelegate() { int invocations = 0; ScheduledDelegate del; scheduler.Add(del = new ScheduledDelegate(() => invocations++)); del.Cancel(); scheduler.Update(); Assert.AreEqual(0, invocations); } [Test] public void TestAddCancelledDelegate() { int invocations = 0; ScheduledDelegate del = new ScheduledDelegate(() => invocations++); del.Cancel(); scheduler.Add(del); scheduler.Update(); Assert.AreEqual(0, invocations); } [Test] public void TestCustomScheduledDelegateRunsOnce() { int invocations = 0; scheduler.Add(new ScheduledDelegate(() => invocations++)); scheduler.Update(); Assert.AreEqual(1, invocations); scheduler.Update(); Assert.AreEqual(1, invocations); } [Test] public void TestDelayedDelegatesAreScheduledWithCorrectTime() { var clock = new StopwatchClock(); scheduler.UpdateClock(clock); ScheduledDelegate del = scheduler.AddDelayed(() => { }, 1000); Assert.AreEqual(1000, del.ExecutionTime); clock.Seek(500); del = scheduler.AddDelayed(() => { }, 1000); Assert.AreEqual(1500, del.ExecutionTime); } [Test] public void TestDelayedDelegateDoesNotRunUntilExpectedTime() { var clock = new StopwatchClock(); scheduler.UpdateClock(clock); int invocations = 0; scheduler.AddDelayed(() => invocations++, 1000); clock.Seek(1000); scheduler.AddDelayed(() => invocations++, 1000); for (double d = 0; d <= 2500; d += 100) { clock.Seek(d); scheduler.Update(); int expectedInvocations = 0; if (d >= 1000) expectedInvocations++; if (d >= 2000) expectedInvocations++; Assert.AreEqual(expectedInvocations, invocations); } } [Test] public void TestCancelDelayedDelegate() { var clock = new StopwatchClock(); scheduler.UpdateClock(clock); int invocations = 0; ScheduledDelegate del; scheduler.Add(del = new ScheduledDelegate(() => invocations++, 1000)); del.Cancel(); clock.Seek(1500); scheduler.Update(); Assert.AreEqual(0, invocations); } [Test] public void TestRepeatingDelayedDelegate() { var clock = new StopwatchClock(); scheduler.UpdateClock(clock); int invocations = 0; scheduler.Add(new ScheduledDelegate(() => invocations++, 500, 500)); scheduler.Add(new ScheduledDelegate(() => invocations++, 1000, 500)); for (double d = 0; d <= 2500; d += 100) { clock.Seek(d); scheduler.Update(); int expectedInvocations = 0; if (d >= 500) expectedInvocations += 1 + (int)((d - 500) / 500); if (d >= 1000) expectedInvocations += 1 + (int)((d - 1000) / 500); Assert.AreEqual(expectedInvocations, invocations); } } [Test] public void TestCancelAfterRepeatReschedule() { var clock = new StopwatchClock(); scheduler.UpdateClock(clock); int invocations = 0; ScheduledDelegate del; scheduler.Add(del = new ScheduledDelegate(() => invocations++, 500, 500)); clock.Seek(750); scheduler.Update(); Assert.AreEqual(1, invocations); del.Cancel(); clock.Seek(1250); scheduler.Update(); Assert.AreEqual(1, invocations); } [Test] public void TestAddOnce() { int invocations = 0; Action action = () => { invocations++; }; scheduler.AddOnce(action); scheduler.AddOnce(action); scheduler.Update(); Assert.AreEqual(1, invocations); } [Test] public void TestScheduleFromInsideDelegate([Values(false, true)] bool forceScheduled) { const int max_reschedules = 3; if (!forceScheduled) scheduler.SetCurrentThread(); int reschedules = 0; scheduleTask(); if (forceScheduled) { for (int i = 0; i <= max_reschedules; i++) { scheduler.Update(); Assert.AreEqual(Math.Min(max_reschedules, i + 1), reschedules); } } else Assert.AreEqual(max_reschedules, reschedules); void scheduleTask() => scheduler.Add(() => { if (reschedules == max_reschedules) return; reschedules++; scheduleTask(); }, forceScheduled); } } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "GalleryImageVersion", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSGalleryImageVersion))] public partial class NewAzureRmGalleryImageVersion : ComputeAutomationBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (ShouldProcess(this.Name, VerbsCommon.New)) { string resourceGroupName = this.ResourceGroupName; string galleryName = this.GalleryName; string galleryImageName = this.GalleryImageDefinitionName; string galleryImageVersionName = this.Name; GalleryImageVersion galleryImageVersion = new GalleryImageVersion(); galleryImageVersion.Location = this.Location; galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); galleryImageVersion.PublishingProfile.Source = new GalleryArtifactSource(); galleryImageVersion.PublishingProfile.Source.ManagedImage = new ManagedArtifact(); galleryImageVersion.PublishingProfile.Source.ManagedImage.Id = this.SourceImageId; if (this.MyInvocation.BoundParameters.ContainsKey("Tag")) { galleryImageVersion.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value); } if (this.MyInvocation.BoundParameters.ContainsKey("ReplicaCount")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.ReplicaCount = this.ReplicaCount; } if (this.MyInvocation.BoundParameters.ContainsKey("PublishingProfileExcludeFromLatest")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.ExcludeFromLatest = this.PublishingProfileExcludeFromLatest.IsPresent; } if (this.MyInvocation.BoundParameters.ContainsKey("PublishingProfileEndOfLifeDate")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.EndOfLifeDate = this.PublishingProfileEndOfLifeDate; } if (this.MyInvocation.BoundParameters.ContainsKey("TargetRegion")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.TargetRegions = new List<TargetRegion>(); foreach (var t in this.TargetRegion) { galleryImageVersion.PublishingProfile.TargetRegions.Add(new TargetRegion((string)t["Name"], (int?)t["ReplicaCount"])); } } var result = GalleryImageVersionsClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion); var psObject = new PSGalleryImageVersion(); ComputeAutomationAutoMapperProfile.Mapper.Map<GalleryImageVersion, PSGalleryImageVersion>(result, psObject); WriteObject(psObject); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ResourceGroupCompleter] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string GalleryName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string GalleryImageDefinitionName { get; set; } [Alias("GalleryImageVersionName")] [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string Name { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true)] [LocationCompleter("Microsoft.Compute/Galleries")] public string Location { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true)] public string SourceImageId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int ReplicaCount { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public SwitchParameter PublishingProfileExcludeFromLatest { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime PublishingProfileEndOfLifeDate { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable[] TargetRegion { get; set; } } [Cmdlet(VerbsData.Update, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "GalleryImageVersion", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSGalleryImageVersion))] public partial class UpdateAzureRmGalleryImageVersion : ComputeAutomationBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (ShouldProcess(this.Name, VerbsData.Update)) { string resourceGroupName; string galleryName; string galleryImageName; string galleryImageVersionName; switch (this.ParameterSetName) { case "ResourceIdParameter": resourceGroupName = GetResourceGroupName(this.ResourceId); galleryName = GetResourceName(this.ResourceId, "Microsoft.Compute/Galleries", "Images", "Versions"); galleryImageName = GetInstanceId(this.ResourceId, "Microsoft.Compute/Galleries", "Images", "Versions"); galleryImageVersionName = GetVersion(this.ResourceId, "Microsoft.Compute/Galleries", "Images", "Versions"); break; case "ObjectParameter": resourceGroupName = GetResourceGroupName(this.InputObject.Id); galleryName = GetResourceName(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images", "Versions"); galleryImageName = GetInstanceId(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images", "Versions"); galleryImageVersionName = GetVersion(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images", "Versions"); break; default: resourceGroupName = this.ResourceGroupName; galleryName = this.GalleryName; galleryImageName = this.GalleryImageDefinitionName; galleryImageVersionName = this.Name; break; } var galleryImageVersion = new GalleryImageVersion(); if (this.ParameterSetName == "ObjectParameter") { ComputeAutomationAutoMapperProfile.Mapper.Map<PSGalleryImageVersion, GalleryImageVersion>(this.InputObject, galleryImageVersion); } else { galleryImageVersion = GalleryImageVersionsClient.Get(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName); } if (this.MyInvocation.BoundParameters.ContainsKey("Tag")) { galleryImageVersion.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value); } if (this.MyInvocation.BoundParameters.ContainsKey("ReplicaCount")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.ReplicaCount = this.ReplicaCount; } if (this.MyInvocation.BoundParameters.ContainsKey("PublishingProfileExcludeFromLatest")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.ExcludeFromLatest = this.PublishingProfileExcludeFromLatest.IsPresent; } if (this.MyInvocation.BoundParameters.ContainsKey("PublishingProfileEndOfLifeDate")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.EndOfLifeDate = this.PublishingProfileEndOfLifeDate; } if (this.MyInvocation.BoundParameters.ContainsKey("TargetRegion")) { if (galleryImageVersion.PublishingProfile == null) { galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile(); } galleryImageVersion.PublishingProfile.TargetRegions = new List<TargetRegion>(); foreach (var t in this.TargetRegion) { galleryImageVersion.PublishingProfile.TargetRegions.Add(new TargetRegion((string)t["Name"], (int?)t["ReplicaCount"])); } } var result = GalleryImageVersionsClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion); var psObject = new PSGalleryImageVersion(); ComputeAutomationAutoMapperProfile.Mapper.Map<GalleryImageVersion, PSGalleryImageVersion>(result, psObject); WriteObject(psObject); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ResourceGroupCompleter] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string GalleryName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string GalleryImageDefinitionName { get; set; } [Alias("GalleryImageVersionName")] [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string Name { get; set; } [Parameter( ParameterSetName = "ResourceIdParameter", Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string ResourceId { get; set; } [Alias("GalleryImageVersion")] [Parameter( ParameterSetName = "ObjectParameter", Position = 0, Mandatory = true, ValueFromPipeline = true)] public PSGalleryImageVersion InputObject { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int ReplicaCount { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public SwitchParameter PublishingProfileExcludeFromLatest { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime PublishingProfileEndOfLifeDate { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable[] TargetRegion { get; set; } } }
// ---------------------------------------------------------------------------- // XmlValidityConstraintTestFixture.cs // // Contains the definition of the XmlValidityConstraintTestFixture class. // Copyright 2009 Steve Guidi. // // File created: 7/7/2009 16:04:49 // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; using Jolt.Reflection; using NUnit.Framework; using NUnit.Framework.Constraints; using Rhino.Mocks; namespace Jolt.Testing.Assertions.NUnit.Test { [TestFixture] public sealed class XmlValidityConstraintTestFixture { #region public methods -------------------------------------------------------------------- /// <summary> /// Verifies the construction of the class, when given an XmlSchemaSet. /// </summary> [Test] public void Construction_Schemas() { ConstraintConstructionTests.XmlValidityConstraint_Schemas(schemas => new XmlValidityConstraint(schemas)); } /// <summary> /// Verifies the construction of the class, when given an XmlSchemaSet /// and an XmlSchemaValidationFlags instance. /// </summary> [Test] public void Construction_Schemas_Flags() { ConstraintConstructionTests.XmlValidityConstraint_Schemas_Flags((schemas, flags) => new XmlValidityConstraint(schemas, flags)); } /// <summary> /// Verifies the internal construction of the class. /// </summary> [Test] public void Construction_Internal() { XmlValidityAssertion expectedAssertion = new XmlValidityAssertion(new XmlSchemaSet()); XmlValidityConstraint constraint = new XmlValidityConstraint(expectedAssertion); Assert.That(constraint.Assertion, Is.SameAs(expectedAssertion)); } /// <summary> /// Verifies the behavior of the Matches() method, when /// given an object of an invalid type. /// </summary> [Test] public void Matches_InvalidType() { XmlValidityConstraint constraint = new XmlValidityConstraint(new XmlSchemaSet()); Assert.That(!constraint.Matches(String.Empty)); } /// <summary> /// Verifies the behavior of the Matches() method, /// when the validation succeeds. /// </summary> [Test] public void Matches() { XmlValidityAssertion assertion = MockRepository.GenerateMock<XmlValidityAssertion>(new XmlSchemaSet()); using (XmlReader expectedReader = XmlReader.Create(Stream.Null)) { assertion.Expect(a => a.Validate(expectedReader)).Return(new ValidationEventArgs[0]); XmlValidityConstraint constraint = new XmlValidityConstraint(assertion); Assert.That(constraint.Matches(expectedReader)); } assertion.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the Matches() method, /// when the validation fails. /// </summary> [Test] public void Matches_DoesNotMatch() { XmlValidityAssertion assertion = MockRepository.GenerateMock<XmlValidityAssertion>(new XmlSchemaSet()); using (XmlReader expectedReader = XmlReader.Create(Stream.Null)) { assertion.Expect(a => a.Validate(expectedReader)).Return(CreateFailedComparisonResult()); XmlValidityConstraint constraint = new XmlValidityConstraint(assertion); Assert.That(!constraint.Matches(expectedReader)); } assertion.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the Matches() method, /// when an unexpected exception is raised. /// </summary> [Test] public void Matches_UnexpectedException() { XmlValidityAssertion assertion = MockRepository.GenerateMock<XmlValidityAssertion>(new XmlSchemaSet()); using (XmlReader expectedReader = XmlReader.Create(Stream.Null)) { Exception expectedException = new InvalidProgramException(); assertion.Expect(a => a.Validate(expectedReader)).Throw(expectedException); XmlValidityConstraint constraint = new XmlValidityConstraint(assertion); Assert.That( () => constraint.Matches(expectedReader), Throws.Exception.SameAs(expectedException)); } assertion.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the WriteDescriptionTo() method. /// </summary> [Test, ExpectedException(typeof(NotImplementedException))] public void WriteDescriptionTo() { MessageWriter writer = MockRepository.GenerateStub<MessageWriter>(); XmlValidityConstraint constraint = new XmlValidityConstraint(new XmlSchemaSet()); constraint.WriteDescriptionTo(writer); } /// <summary> /// Verifies the behavior of the WriteMessageTo() method. /// </summary> [Test] public void WriteMessageTo() { XmlValidityAssertion assertion = MockRepository.GenerateMock<XmlValidityAssertion>(new XmlSchemaSet()); MessageWriter writer = MockRepository.GenerateMock<MessageWriter>(); using (XmlReader expectedReader = XmlReader.Create(Stream.Null)) { IList<ValidationEventArgs> assertionResult = CreateFailedComparisonResult(); assertion.Expect(a => a.Validate(expectedReader)).Return(assertionResult); writer.Expect(w => w.WriteLine("message")); XmlValidityConstraint constraint = new XmlValidityConstraint(assertion); constraint.Matches(expectedReader); constraint.WriteMessageTo(writer); } assertion.VerifyAllExpectations(); writer.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the WriteActualValueTo() method. /// </summary> [Test] public void WriteActualValueTo() { XmlValidityAssertion assertion = MockRepository.GenerateMock<XmlValidityAssertion>(new XmlSchemaSet()); MessageWriter writer = MockRepository.GenerateMock<MessageWriter>(); using (XmlReader expectedReader = XmlReader.Create(Stream.Null)) { writer.Expect(w => w.WriteActualValue(expectedReader)); assertion.Expect(a => a.Validate(expectedReader)).Return(new ValidationEventArgs[0]); XmlValidityConstraint constraint = new XmlValidityConstraint(assertion); constraint.Matches(expectedReader); constraint.WriteActualValueTo(writer); } assertion.VerifyAllExpectations(); writer.VerifyAllExpectations(); } #endregion #region private methods ------------------------------------------------------------------- /// <summary> /// Creates a single-element collection of <see cref="ValidationEventArgs"/> representing a failed comparison. /// </summary> private static IList<ValidationEventArgs> CreateFailedComparisonResult() { return new ValidationEventArgs[] { Activator.CreateInstance( typeof(ValidationEventArgs), CompoundBindingFlags.NonPublicInstance, null, new object[] { new XmlSchemaException("message") }, null) as ValidationEventArgs }; } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime.Collections { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; // System.Collections.Specialized.OrderedDictionary is NOT generic. // This class is essentially a generic wrapper for OrderedDictionary. class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary { OrderedDictionary privateDictionary; public OrderedDictionary() { this.privateDictionary = new OrderedDictionary(); } public OrderedDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary != null) { this.privateDictionary = new OrderedDictionary(); foreach (KeyValuePair<TKey, TValue> pair in dictionary) { this.privateDictionary.Add(pair.Key, pair.Value); } } } public int Count { get { return this.privateDictionary.Count; } } public bool IsReadOnly { get { return false; } } public TValue this[TKey key] { get { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } if (this.privateDictionary.Contains(key)) { return (TValue)this.privateDictionary[(object)key]; } else { throw Fx.Exception.AsError(new KeyNotFoundException(InternalSR.KeyNotFoundInDictionary)); } } set { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } this.privateDictionary[(object)key] = value; } } public ICollection<TKey> Keys { get { List<TKey> keys = new List<TKey>(this.privateDictionary.Count); foreach (TKey key in this.privateDictionary.Keys) { keys.Add(key); } // Keys should be put in a ReadOnlyCollection, // but since this is an internal class, for performance reasons, // we choose to avoid creating yet another collection. return keys; } } public ICollection<TValue> Values { get { List<TValue> values = new List<TValue>(this.privateDictionary.Count); foreach (TValue value in this.privateDictionary.Values) { values.Add(value); } // Values should be put in a ReadOnlyCollection, // but since this is an internal class, for performance reasons, // we choose to avoid creating yet another collection. return values; } } public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public void Add(TKey key, TValue value) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } this.privateDictionary.Add(key, value); } public void Clear() { this.privateDictionary.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { if (item.Key == null || !this.privateDictionary.Contains(item.Key)) { return false; } else { return this.privateDictionary[(object)item.Key].Equals(item.Value); } } public bool ContainsKey(TKey key) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } return this.privateDictionary.Contains(key); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) { throw Fx.Exception.ArgumentNull("array"); } if (arrayIndex < 0) { throw Fx.Exception.AsError(new ArgumentOutOfRangeException("arrayIndex")); } if (array.Rank > 1 || arrayIndex >= array.Length || array.Length - arrayIndex < this.privateDictionary.Count) { throw Fx.Exception.Argument("array", InternalSR.BadCopyToArray); } int index = arrayIndex; foreach (DictionaryEntry entry in this.privateDictionary) { array[index] = new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value); index++; } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { foreach (DictionaryEntry entry in this.privateDictionary) { yield return new KeyValuePair<TKey, TValue>((TKey)entry.Key, (TValue)entry.Value); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Remove(KeyValuePair<TKey, TValue> item) { if (Contains(item)) { this.privateDictionary.Remove(item.Key); return true; } else { return false; } } public bool Remove(TKey key) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } if (this.privateDictionary.Contains(key)) { this.privateDictionary.Remove(key); return true; } else { return false; } } public bool TryGetValue(TKey key, out TValue value) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } bool keyExists = this.privateDictionary.Contains(key); value = keyExists ? (TValue)this.privateDictionary[(object)key] : default(TValue); return keyExists; } void IDictionary.Add(object key, object value) { this.privateDictionary.Add(key, value); } void IDictionary.Clear() { this.privateDictionary.Clear(); } bool IDictionary.Contains(object key) { return this.privateDictionary.Contains(key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return this.privateDictionary.GetEnumerator(); } bool IDictionary.IsFixedSize { get { return ((IDictionary)this.privateDictionary).IsFixedSize; } } bool IDictionary.IsReadOnly { get { return this.privateDictionary.IsReadOnly; } } ICollection IDictionary.Keys { get { return this.privateDictionary.Keys; } } void IDictionary.Remove(object key) { this.privateDictionary.Remove(key); } ICollection IDictionary.Values { get { return this.privateDictionary.Values; } } object IDictionary.this[object key] { get { return this.privateDictionary[key]; } set { this.privateDictionary[key] = value; } } void ICollection.CopyTo(Array array, int index) { this.privateDictionary.CopyTo(array, index); } int ICollection.Count { get { return this.privateDictionary.Count; } } bool ICollection.IsSynchronized { get { return ((ICollection)this.privateDictionary).IsSynchronized; } } object ICollection.SyncRoot { get { return ((ICollection)this.privateDictionary).SyncRoot; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.ExternalPackageGenerators.Msdn { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.DocAsCode.Build.Engine; using Microsoft.DocAsCode.Glob; using Microsoft.DocAsCode.Plugins; internal sealed class Program { #region Fields private static readonly Regex GenericMethodPostFix = new Regex(@"``\d+$", RegexOptions.Compiled); private static string MsdnUrlTemplate = "https://msdn.microsoft.com/en-us/library/{0}(v={1}).aspx"; private static string MtpsApiUrlTemplate = "http://services.mtps.microsoft.com/ServiceAPI/content/{0}/en-us;{1}/common/mtps.links"; private static int HttpMaxConcurrency = 64; private static int[] RetryDelay = new[] { 1000, 3000, 10000 }; private static int StatisticsFreshPerSecond = 5; private static readonly Stopwatch Stopwatch = Stopwatch.StartNew(); private readonly Regex NormalUid = new Regex(@"^[a-zA-Z0-9_\.]+$", RegexOptions.Compiled); private readonly HttpClient _client = new HttpClient(); private readonly Cache<string> _shortIdCache; private readonly Cache<Dictionary<string, string>> _commentIdToShortIdMapCache; private readonly Cache<StrongBox<bool?>> _checkUrlCache; private readonly string _packageFile; private readonly string _baseDirectory; private readonly string _globPattern; private readonly string _msdnVersion; private readonly int _maxHttp; private readonly int _maxEntry; private readonly SemaphoreSlim _semaphoreForHttp; private readonly SemaphoreSlim _semaphoreForEntry; private int _entryCount; private int _apiCount; private string[] _currentPackages = new string[2]; #endregion #region Entry Point private static int Main(string[] args) { if (args.Length != 4) { PrintUsage(); return 2; } try { ReadConfig(); ServicePointManager.DefaultConnectionLimit = HttpMaxConcurrency; ThreadPool.SetMinThreads(HttpMaxConcurrency, HttpMaxConcurrency); var p = new Program(args[0], args[1], args[2], args[3]); p.PackReference(); return 0; } catch (Exception ex) { Console.Error.WriteLine(ex); return 1; } } private static void ReadConfig() { MsdnUrlTemplate = ConfigurationManager.AppSettings["MsdnUrlTemplate"] ?? MsdnUrlTemplate; MtpsApiUrlTemplate = ConfigurationManager.AppSettings["MtpsApiUrlTemplate"] ?? MtpsApiUrlTemplate; if (ConfigurationManager.AppSettings["HttpMaxConcurrency"] != null) { int value; if (int.TryParse(ConfigurationManager.AppSettings["HttpMaxConcurrency"], out value) && value > 0) { HttpMaxConcurrency = value; } else { Console.WriteLine("Bad config: HttpMaxConcurrency, using default value:{0}", HttpMaxConcurrency); } } if (ConfigurationManager.AppSettings["RetryDelayInMillisecond"] != null) { string[] texts; texts = ConfigurationManager.AppSettings["RetryDelayInMillisecond"].Split(','); var values = new int[texts.Length]; for (int i = 0; i < texts.Length; i++) { if (!int.TryParse(texts[i].Trim(), out values[i])) { break; } } if (values.All(v => v > 0)) { RetryDelay = values; } else { Console.WriteLine("Bad config: RetryDelayInMillisecond, using default value:{0}", string.Join(", ", RetryDelay)); } } if (ConfigurationManager.AppSettings["StatisticsFreshPerSecond"] != null) { int value; if (int.TryParse(ConfigurationManager.AppSettings["StatisticsFreshPerSecond"], out value) && value > 0) { StatisticsFreshPerSecond = value; } else { Console.WriteLine("Bad config: StatisticsFreshPerSecond, using default value:{0}", HttpMaxConcurrency); } } } #endregion #region Constructor public Program(string packageDirectory, string baseDirectory, string globPattern, string msdnVersion) { _packageFile = packageDirectory; _baseDirectory = baseDirectory; _globPattern = globPattern; _msdnVersion = msdnVersion; _shortIdCache = new Cache<string>(nameof(_shortIdCache), LoadShortIdAsync); _commentIdToShortIdMapCache = new Cache<Dictionary<string, string>>(nameof(_commentIdToShortIdMapCache), LoadCommentIdToShortIdMapAsync); _checkUrlCache = new Cache<StrongBox<bool?>>(nameof(_checkUrlCache), IsUrlOkAsync); _maxHttp = HttpMaxConcurrency; _maxEntry = (int)(HttpMaxConcurrency * 1.1) + 1; _semaphoreForHttp = new SemaphoreSlim(_maxHttp); _semaphoreForEntry = new SemaphoreSlim(_maxEntry); } #endregion #region Methods private static void PrintUsage() { Console.WriteLine("Usage:"); Console.WriteLine("{0} <outputFile> <baseDirectory> <globPattern> <msdnVersion>", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(" outputFile The output xref archive file."); Console.WriteLine(" e.g. \"msdn\""); Console.WriteLine(" baseDirectory The base directory contains develop comment xml file."); Console.WriteLine(" e.g. \"c:\\\""); Console.WriteLine(" globPattern The glob pattern for develop comment xml file."); Console.WriteLine(" '\' is considered as ESCAPE character, make sure to transform '\' in file path to '/'"); Console.WriteLine(" e.g. \"**/*.xml\""); Console.WriteLine(" msdnVersion The version in msdn."); Console.WriteLine(" e.g. \"vs.110\""); } private void PackReference() { var task = PackReferenceAsync(); PrintStatistics(task).Wait(); } private async Task PackReferenceAsync() { var files = GetAllFiles(); if (files.Count == 0) { return; } var dir = Path.GetDirectoryName(_packageFile); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } bool updateMode = File.Exists(_packageFile); using (var writer = XRefArchive.Open(_packageFile, updateMode ? XRefArchiveMode.Update : XRefArchiveMode.Create)) { if (!updateMode) { writer.CreateMajor(new XRefMap { HrefUpdated = true, Redirections = new List<XRefMapRedirection>() }); } if (files.Count == 1) { await PackOneReferenceAsync(files[0], writer); return; } // left is smaller files, right is bigger files. var left = 0; var right = files.Count - 1; var leftTask = PackOneReferenceAsync(files[left], writer); var rightTask = PackOneReferenceAsync(files[right], writer); while (left <= right) { var completed = await Task.WhenAny(new[] { leftTask, rightTask }.Where(t => t != null)); await completed; // throw if any error. if (completed == leftTask) { left++; if (left < right) { leftTask = PackOneReferenceAsync(files[left], writer); } else { leftTask = null; } } else { right--; if (left < right) { rightTask = PackOneReferenceAsync(files[right], writer); } else { rightTask = null; } } } } } private async Task PackOneReferenceAsync(string file, XRefArchive writer) { var currentPackage = Path.GetFileName(file); lock (_currentPackages) { _currentPackages[Array.IndexOf(_currentPackages, null)] = currentPackage; } var entries = new List<XRefMapRedirection>(); await GetItems(file).ForEachAsync(pair => { lock (writer) { entries.Add( new XRefMapRedirection { UidPrefix = pair.EntryName, Href = writer.CreateMinor( new XRefMap { Sorted = true, HrefUpdated = true, References = pair.ViewModel, }, new[] { pair.EntryName }) }); _entryCount++; _apiCount += pair.ViewModel.Count; } }); lock (writer) { var map = writer.GetMajor(); map.Redirections = (from r in map.Redirections.Concat(entries) orderby r.UidPrefix.Length descending select r).ToList(); writer.UpdateMajor(map); } lock (_currentPackages) { _currentPackages[Array.IndexOf(_currentPackages, currentPackage)] = null; } } private async Task PrintStatistics(Task mainTask) { bool isFirst = true; var queue = new Queue<Tuple<int, int>>(10 * StatisticsFreshPerSecond); while (!mainTask.IsCompleted) { await Task.Delay(1000 / StatisticsFreshPerSecond); if (queue.Count >= 10 * StatisticsFreshPerSecond) { queue.Dequeue(); } var last = Tuple.Create(_entryCount, _apiCount); queue.Enqueue(last); if (isFirst) { isFirst = false; } else { Console.SetCursorPosition(0, Console.CursorTop - 3 - _currentPackages.Length); } lock (_currentPackages) { for (int i = 0; i < _currentPackages.Length; i++) { Console.WriteLine("Packing: " + (_currentPackages[i] ?? string.Empty).PadRight(Console.WindowWidth - "Packing: ".Length - 1)); } } Console.WriteLine( "Elapsed time: {0}, generated type: {1}, generated api: {2}", Stopwatch.Elapsed.ToString(@"hh\:mm\:ss"), _entryCount.ToString(), _apiCount.ToString()); Console.WriteLine( "Status: http:{0,4}, type entry:{1,4}", (_maxHttp - _semaphoreForHttp.CurrentCount).ToString(), (_maxEntry - _semaphoreForEntry.CurrentCount).ToString()); Console.WriteLine( "Generating per second: type:{0,7}, api:{1,7}", ((double)(last.Item1 - queue.Peek().Item1) * StatisticsFreshPerSecond / queue.Count).ToString("F1"), ((double)(last.Item2 - queue.Peek().Item2) * StatisticsFreshPerSecond / queue.Count).ToString("F1")); } try { await mainTask; } catch (Exception ex) { Console.WriteLine(ex); } } private IObservable<EntryNameAndViewModel> GetItems(string file) { return from entry in (from entry in GetAllCommentId(file) select entry).AcquireSemaphore(_semaphoreForEntry).ToObservable(Scheduler.Default) from vm in Observable.FromAsync(() => GetXRefSpecAsync(entry)).Do(_ => _semaphoreForEntry.Release()) where vm.Count > 0 select new EntryNameAndViewModel(entry.EntryName, vm); } private async Task<List<XRefSpec>> GetXRefSpecAsync(ClassEntry entry) { var result = new List<XRefSpec>(entry.Items.Count); var type = entry.Items.Find(item => item.Uid == entry.EntryName); XRefSpec typeSpec = null; if (type != null) { typeSpec = await GetXRefSpecAsync(type); if (typeSpec != null) { result.Add(typeSpec); } } int size = 0; foreach (var specsTask in from block in (from item in entry.Items where item != type select item).BlockBuffer(() => size = size * 2 + 1) select Task.WhenAll(from item in block select GetXRefSpecAsync(item))) { result.AddRange(from s in await specsTask where s != null select s); } result.AddRange(await GetOverloadXRefSpecAsync(result)); if (typeSpec != null && typeSpec.Href != null) { // handle enum field, or other one-page-member foreach (var item in result) { if (item.Href == null) { item.Href = typeSpec.Href; } } } else { result.RemoveAll(item => item.Href == null); } result.Sort(XRefSpecUidComparer.Instance); return result; } private async Task<XRefSpec> GetXRefSpecAsync(CommentIdAndUid pair) { var alias = GetAliasWithMember(pair.CommentId); if (alias != null) { var url = string.Format(MsdnUrlTemplate, alias, _msdnVersion); // verify alias exists var vr = (await _checkUrlCache.GetAsync(pair.CommentId + "||||" + url)).Value; if (vr == true) { return new XRefSpec { Uid = pair.Uid, CommentId = pair.CommentId, Href = url, }; } } var shortId = await _shortIdCache.GetAsync(pair.CommentId); if (string.IsNullOrEmpty(shortId)) { if (pair.CommentId.StartsWith("F:")) { // work around for enum field. shortId = await _shortIdCache.GetAsync( "T:" + pair.CommentId.Remove(pair.CommentId.LastIndexOf('.')).Substring(2)); if (string.IsNullOrEmpty(shortId)) { return null; } } else { return null; } } return new XRefSpec { Uid = pair.Uid, CommentId = pair.CommentId, Href = string.Format(MsdnUrlTemplate, shortId, _msdnVersion), }; } private async Task<XRefSpec[]> GetOverloadXRefSpecAsync(List<XRefSpec> specs) { var pairs = (from spec in specs let overload = GetOverloadIdBody(spec) where overload != null group Tuple.Create(spec, overload) by overload.Uid into g select g.First()); return await Task.WhenAll(from pair in pairs select GetOverloadXRefSpecCoreAsync(pair)); } private async Task<XRefSpec> GetOverloadXRefSpecCoreAsync(Tuple<XRefSpec, CommentIdAndUid> pair) { var dict = await _commentIdToShortIdMapCache.GetAsync(pair.Item1.CommentId); string shortId; if (dict.TryGetValue(pair.Item2.CommentId, out shortId)) { return new XRefSpec { Uid = pair.Item2.Uid, CommentId = pair.Item2.CommentId, Href = string.Format(MsdnUrlTemplate, shortId, _msdnVersion), }; } else { return new XRefSpec(pair.Item1) { Uid = pair.Item2.Uid }; } } private static CommentIdAndUid GetOverloadIdBody(XRefSpec pair) { switch (pair.CommentId[0]) { case 'M': case 'P': var body = pair.Uid; var index = body.IndexOf('('); if (index != -1) { body = body.Remove(index); } body = GenericMethodPostFix.Replace(body, string.Empty); return new CommentIdAndUid("Overload:" + body, body + "*"); default: return null; } } private string GetContainingCommentId(string commentId) { var result = commentId; var index = result.IndexOf('('); if (index != -1) { result = result.Remove(index); } index = result.LastIndexOf('.'); if (index != -1) { result = result.Remove(index); switch (result[0]) { case 'E': case 'F': case 'M': case 'P': return "T" + result.Substring(1); case 'O': return "T" + result.Substring("Overload".Length); default: return "N" + result.Substring(1); } } return null; } private string GetAlias(string commentId) { if (!commentId.StartsWith("T:") && !commentId.StartsWith("N:")) { return null; } var uid = commentId.Substring(2); if (NormalUid.IsMatch(uid)) { return uid.ToLower(); } return null; } private string GetAliasWithMember(string commentId) { var uid = commentId.Substring(2); var parameterIndex = uid.IndexOf('('); if (parameterIndex != -1) { uid = uid.Remove(parameterIndex); } uid = GenericMethodPostFix.Replace(uid, string.Empty); if (NormalUid.IsMatch(uid)) { return uid.ToLower(); } return null; } private async Task<string> LoadShortIdAsync(string commentId) { string alias = GetAlias(commentId); string currentCommentId = commentId; if (alias != null) { using (var response = await _client.GetWithRetryAsync(string.Format(MsdnUrlTemplate, alias, _msdnVersion), _semaphoreForHttp, RetryDelay)) { if (response.StatusCode == HttpStatusCode.OK) { using (var stream = await response.Content.ReadAsStreamAsync()) using (var xr = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { while (xr.ReadToFollowing("meta")) { if (xr.GetAttribute("name") == "Search.ShortId" || xr.GetAttribute("name") == "ms.shortidmsdn") { return xr.GetAttribute("content"); } } } } } } do { var containingCommentId = GetContainingCommentId(currentCommentId); if (containingCommentId == null) { return string.Empty; } var dict = await _commentIdToShortIdMapCache.GetAsync(containingCommentId); string shortId; if (dict.TryGetValue(commentId, out shortId)) { return shortId; } else { // maybe case not match. shortId = dict.FirstOrDefault(p => string.Equals(p.Key, commentId, StringComparison.OrdinalIgnoreCase)).Value; if (shortId != null) { return shortId; } } currentCommentId = containingCommentId; } while (commentId[0] == 'T'); // handle nested type return string.Empty; } private async Task<Dictionary<string, string>> LoadCommentIdToShortIdMapAsync(string containingCommentId) { var result = new Dictionary<string, string>(); var shortId = await _shortIdCache.GetAsync(containingCommentId); if (!string.IsNullOrEmpty(shortId)) { using (var response = await _client.GetWithRetryAsync(string.Format(MtpsApiUrlTemplate, shortId, _msdnVersion), _semaphoreForHttp, RetryDelay)) { if (response.StatusCode == HttpStatusCode.OK) { using (var stream = await response.Content.ReadAsStreamAsync()) using (var xr = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { foreach (var item in ReadApiContent(xr)) { result[item.Item1] = item.Item2; } } } } } return result; } private IEnumerable<Tuple<string, string>> ReadApiContent(XmlReader xr) { while (xr.ReadToFollowing("div")) { if (xr.GetAttribute("class") == "link-data") { using (var subtree = xr.ReadSubtree()) { string assetId = null; string shortId = null; while (subtree.ReadToFollowing("span")) { var className = subtree.GetAttribute("class"); if (className == "link-short-id") { shortId = subtree.ReadElementContentAsString(); } if (className == "link-asset-id") { assetId = subtree.ReadElementContentAsString(); } } if (shortId != null && assetId != null && assetId.StartsWith("AssetId:")) { yield return Tuple.Create(assetId.Substring("AssetId:".Length), shortId); } } } } } private IEnumerable<ClassEntry> GetAllCommentId(string file) { return from commentId in GetAllCommentIdCore(file) where commentId.StartsWith("N:") || commentId.StartsWith("T:") || commentId.StartsWith("E:") || commentId.StartsWith("F:") || commentId.StartsWith("M:") || commentId.StartsWith("P:") let uid = commentId.Substring(2) let lastDot = uid.Split('(')[0].LastIndexOf('.') group new CommentIdAndUid(commentId, uid) by commentId.StartsWith("N:") || commentId.StartsWith("T:") || lastDot == -1 ? uid : uid.Remove(lastDot) into g select new ClassEntry(g.Key, g.ToList()); } private List<string> GetAllFiles() { // just guess: the bigger files contains more apis/types. var files = (from file in FileGlob.GetFiles(_baseDirectory, new string[] { _globPattern }, null) let fi = new FileInfo(file) orderby fi.Length select file).ToList(); if (files.Count > 0) { Console.WriteLine("Loading comment id from:"); foreach (var file in files) { Console.WriteLine(file); } } else { Console.WriteLine("File not found."); } return files; } private IEnumerable<string> GetAllCommentIdCore(string file) { if (".xml".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)) { return GetAllCommentIdFromXml(file); } if (".txt".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)) { return GetAllCommentIdFromText(file); } throw new NotSupportedException($"Unable to read comment id from file: {file}."); } private IEnumerable<string> GetAllCommentIdFromXml(string file) { return from reader in new Func<XmlReader>(() => XmlReader.Create(file)) .EmptyIfThrow() .ProtectResource() where reader.ReadToFollowing("members") from apiReader in reader.Elements("member") let commentId = apiReader.GetAttribute("name") where commentId != null select commentId; } private IEnumerable<string> GetAllCommentIdFromText(string file) { return File.ReadLines(file); } private async Task<StrongBox<bool?>> IsUrlOkAsync(string pair) { var index = pair.IndexOf("||||"); var commentId = pair.Remove(index); var url = pair.Substring(index + "||||".Length); using (var response = await _client.GetWithRetryAsync(url, _semaphoreForHttp, RetryDelay)) { if (response.StatusCode != HttpStatusCode.OK) { return new StrongBox<bool?>(null); } using (var stream = await response.Content.ReadAsStreamAsync()) using (var xr = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { while (xr.ReadToFollowing("meta")) { if (xr.GetAttribute("name") == "ms.assetid") { return new StrongBox<bool?>(commentId.Equals(xr.GetAttribute("content"), StringComparison.OrdinalIgnoreCase)); } } } return new StrongBox<bool?>(false); } } #endregion } }
#region File Description //----------------------------------------------------------------------------- // PlatformerGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input.Touch; namespace Platformer { /// <summary> /// This is the main type for your game /// </summary> public class PlatformerGame : Microsoft.Xna.Framework.Game { // Resources for drawing. private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; // Global content. private SpriteFont hudFont; private Texture2D winOverlay; private Texture2D loseOverlay; private Texture2D diedOverlay; // Meta-level game state. private int levelIndex = -1; private Level level; private bool wasContinuePressed; // When the time remaining is less than the warning time, it blinks on the hud private static readonly TimeSpan WarningTime = TimeSpan.FromSeconds(30); // We store our input states so that we only poll once per frame, // then we use the same input state wherever needed private GamePadState gamePadState; private KeyboardState keyboardState; private TouchCollection touchState; private AccelerometerState accelerometerState; // The number of levels in the Levels directory of our content. We assume that // levels in our content are 0-based and that all numbers under this constant // have a level file present. This allows us to not need to check for the file // or handle exceptions, both of which can add unnecessary time to level loading. private const int numberOfLevels = 3; public PlatformerGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; #if WINDOWS_PHONE graphics.IsFullScreen = true; TargetElapsedTime = TimeSpan.FromTicks(333333); #endif Accelerometer.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Load fonts hudFont = Content.Load<SpriteFont>("Fonts/Hud"); // Load overlay textures winOverlay = Content.Load<Texture2D>("Overlays/you_win"); loseOverlay = Content.Load<Texture2D>("Overlays/you_lose"); diedOverlay = Content.Load<Texture2D>("Overlays/you_died"); //Known issue that you get exceptions if you use Media PLayer while connected to your PC //See http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/c8a243d2-d360-46b1-96bd-62b1ef268c66 //Which means its impossible to test this from VS. //So we have to catch the exception and throw it away try { MediaPlayer.IsRepeating = true; MediaPlayer.Play(Content.Load<Song>("Sounds/Music")); } catch { } LoadNextLevel(); } /// <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) { // Handle polling for our input and handling high-level input HandleInput(); // update our level, passing down the GameTime along with all of our input states level.Update(gameTime, keyboardState, gamePadState, touchState, accelerometerState, Window.CurrentOrientation); base.Update(gameTime); } private void HandleInput() { // get all of our input states keyboardState = Keyboard.GetState(); gamePadState = GamePad.GetState(PlayerIndex.One); touchState = TouchPanel.GetState(); accelerometerState = Accelerometer.GetState(); // Exit the game when back is pressed. if (gamePadState.Buttons.Back == ButtonState.Pressed) Exit(); bool continuePressed = keyboardState.IsKeyDown(Keys.Space) || gamePadState.IsButtonDown(Buttons.A) || touchState.AnyTouch(); // Perform the appropriate action to advance the game and // to get the player back to playing. if (!wasContinuePressed && continuePressed) { if (!level.Player.IsAlive) { level.StartNewLife(); } else if (level.TimeRemaining == TimeSpan.Zero) { if (level.ReachedExit) LoadNextLevel(); else ReloadCurrentLevel(); } } wasContinuePressed = continuePressed; } private void LoadNextLevel() { // move to the next level levelIndex = (levelIndex + 1) % numberOfLevels; // Unloads the content for the current level before loading the next one. if (level != null) level.Dispose(); // Load the level. string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex); using (Stream fileStream = TitleContainer.OpenStream(levelPath)) level = new Level(Services, fileStream, levelIndex); } private void ReloadCurrentLevel() { --levelIndex; LoadNextLevel(); } /// <summary> /// Draws the game from background to foreground. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); level.Draw(gameTime, spriteBatch); DrawHud(); spriteBatch.End(); base.Draw(gameTime); } private void DrawHud() { Rectangle titleSafeArea = GraphicsDevice.Viewport.TitleSafeArea; Vector2 hudLocation = new Vector2(titleSafeArea.X, titleSafeArea.Y); Vector2 center = new Vector2(titleSafeArea.X + titleSafeArea.Width / 2.0f, titleSafeArea.Y + titleSafeArea.Height / 2.0f); // Draw time remaining. Uses modulo division to cause blinking when the // player is running out of time. string timeString = "TIME: " + level.TimeRemaining.Minutes.ToString("00") + ":" + level.TimeRemaining.Seconds.ToString("00"); Color timeColor; if (level.TimeRemaining > WarningTime || level.ReachedExit || (int)level.TimeRemaining.TotalSeconds % 2 == 0) { timeColor = Color.Yellow; } else { timeColor = Color.Red; } DrawShadowedString(hudFont, timeString, hudLocation, timeColor); // Draw score float timeHeight = hudFont.MeasureString(timeString).Y; DrawShadowedString(hudFont, "SCORE: " + level.Score.ToString(), hudLocation + new Vector2(0.0f, timeHeight * 1.2f), Color.Yellow); // Determine the status overlay message to show. Texture2D status = null; if (level.TimeRemaining == TimeSpan.Zero) { if (level.ReachedExit) { status = winOverlay; } else { status = loseOverlay; } } else if (!level.Player.IsAlive) { status = diedOverlay; } if (status != null) { // Draw status message. Vector2 statusSize = new Vector2(status.Width, status.Height); spriteBatch.Draw(status, center - statusSize / 2, Color.White); } } private void DrawShadowedString(SpriteFont font, string value, Vector2 position, Color color) { spriteBatch.DrawString(font, value, position + new Vector2(1.0f, 1.0f), Color.Black); spriteBatch.DrawString(font, value, position, color); } } }
// <copyright file="GPGSStrings.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // Keep the strings even if NO_GPGS #if (UNITY_ANDROID || UNITY_IPHONE) namespace GooglePlayGames.Editor { public class GPGSStrings { public const string Error = "Error"; public const string Ok = "OK"; public const string Cancel = "Cancel"; public const string Yes = "Yes"; public const string No = "No"; public const string Success = "Success"; public const string Warning = "Warning"; public class PostInstall { public const string Title = "Google Play Games Plugin for Unity"; public const string Text = "The Google Play Games Plugin for Unity version $VERSION " + "is now ready to use. If this is a new installation or of you have " + "just upgraded from a previous version, please click the 'Google Play Games' " + "menu and select 'Android Setup' and/or 'iOS Setup' to set up your " + "project to build for the corresponding platforms."; } public class Setup { public const string AppIdTitle = "Google Play Games Application ID"; public const string AppId = "Application ID"; public const string AppIdBlurb = "Enter your application ID below. This is the numeric\n" + "identifier provided by the Developer Console (for example, 123456789012)."; public const string AppIdError = "The App Id does not appear to be valid. " + "It must consist solely of digits, usually 10 or more."; public const string RequiresGPlusTitle = "Enable Google Plus API Access"; public const string RequiresGPlusBlurb = "(Not recommended) Enable access to the Google + API. " + "This is only needed if you are calling Google+ APIs directly."; public const string WebClientIdTitle = "Web App Client ID (Optional)"; public const string ClientId = "Client ID"; public const string ClientIdError = "The Client ID does not appear to be valid. " + "It should end in .apps.googleusercontent.com."; public const string AppIdMismatch = "Web app client ID not associated with this game!"; public const string NearbyServiceId = "Nearby Connection Service ID"; public const string NearbyServiceBlurb = "Enter the service id that identifies the " + "nearby connections service scope"; public const string ServiceIdError = "Invalid service ID. The service id should follow " + "namespace naming rules."; public const string SetupButton = "Setup"; } public class IOSSetup { public const string Title = "Google Play Games - iOS Setup"; public const string Blurb = "To configure Google Play Games for iOS in this project,\n" + "please enter the information below and click on the Setup button."; public const string ClientIdTitle = "iOS App Client ID"; public const string ClientId = "Client ID"; public const string ClientIdBlurb = "Enter your oauth2 client ID below. To obtain this\n" + "ID, generate an iOS linked app in Developer Console. Example:\n" + "123456789012-jafwiawoijjfe.apps.googleusercontent.com"; public const string BundleIdTitle = "Bundle Identifier"; public const string BundleId = "Bundle ID"; public const string BundleIdBlurb = "Enter your application's bundle identifier below.\n" + "(for example, com.example.lorem.ipsum)."; public const string BundleIdError = "The bundle ID does not appear to be valid."; public const string SetupComplete = "Setup complete. Ready for iOS build."; } public class NearbyConnections { public const string Title = "Google Play Games - Nearby Connections Setup"; public const string Blurb = "To configure Nearby Connections in this project,\n" + "please enter the information below and click on the Setup button."; public const string SetupComplete = "Nearby connections configured successfully."; } public class AndroidSetup { public const string Title = "Google Play Games - Android Configuration"; public const string Blurb = "To configure Google Play Games in this project,\n" + "go to the Play Game console, then enter the information below and click on the Setup button."; public const string WebClientIdBlurb = "The web app client ID is needed to access the user's ID token and " + "call other APIs onbehalf of the user." + " It is not required for Game Services. Enter your oauth2 client ID below.\nTo obtain this " + "ID, generate a web linked app in Developer Console. Example:\n" + "123456789012-abcdefghijklm.apps.googleusercontent.com"; public const string PkgName = "Package name"; public const string PkgNameBlurb = "Enter your application's package name below.\n" + "(for example, com.example.lorem.ipsum)."; public const string PackageNameError = "The package name does not appear to be valid. " + "Enter a valid Android package name (for example, com.example.lorem.ipsum)."; public const string SdkNotFound = "Android SDK Not found"; public const string SdkNotFoundBlurb = "The Android SDK path was not found. " + "Please configure it in the Unity preferences window (under External Tools)."; public const string LibProjNotFound = "Google Play Services Library Project Not Found"; public const string LibProjNotFoundBlurb = "Google Play Services library project " + "could not be found your SDK installation. Make sure it is installed (open " + "the SDK manager and go to Extras, and select Google Play Services)."; public const string SupportJarNotFound = "Android Support Library v4 Not Found"; public const string SupportJarNotFoundBlurb = "Android Support Library v4 " + "could not be found your SDK installation. Make sure it is installed (open " + "the SDK manager and go to Extras, and select 'Android Support Library')."; public const string LibProjVerNotFound = "The version of your copy of the Google Play " + "Services Library Project could not be determined. Please make sure it is " + "at least version {0}. Continue?"; public const string LibProjVerTooOld = "Your copy of the Google Play " + "Services Library Project is out of date. Please launch the Android SDK manager " + "and upgrade your Google Play Services bundle to the latest version (your version: " + "{0}; required version: {1}). Proceeding may cause problems. Proceed anyway?"; public const string SetupComplete = "Google Play Games configured successfully."; } public class ExternalLinks { public const string GettingStartedGuideURL = "https://github.com/playgameservices/play-games-plugin-for-unity"; public const string PlayGamesServicesApiURL = "https://developers.google.com/games/services"; public const string GooglePlusSdkTitle = "Google+ SDK Download"; public const string GooglePlusSdkBlurb = "You will be taken to the download site for " + "the Google+ for iOS SDK. This is only necessary for iOS builds. Once you are " + "on that page, download the item named 'Google+ iOS SDK'."; public const string GooglePlusSdkUrl = "https://developers.google.com/+/downloads/"; public const string GooglePlayGamesSdkTitle = "Google Play Games C++ SDK Download"; public const string GooglePlayGamesSdkBlurb = "You will be taken to the download site for " + "the Google Play Games C++ SDK. This is only necessary for iOS builds. " + "Once you are on that page, download the item named 'Play Games C++ SDK Version X.Y.Z'."; public const string GooglePlayGamesUrl = "https://developers.google.com/games/services/downloads/"; public const string GooglePlayGamesAndroidSdkTitle = "Google Play Games Android SDK Download"; public const string GooglePlayGamesAndroidSdkBlurb = "The Google Play Games SDK for " + "Android must be downloaded via the Android SDK Manager. Do you wish to " + "start the SDK manager now?"; public const string GooglePlayGamesAndroidSdkInstructions = "The Android SDK manager " + "will be launched. Install or upgrade the 'Google Play Services' package, " + "which can be found under the 'Extras' " + "category."; public const string GooglePlayGamesAndroidSdkManagerFailed = "Failed to find the " + "Android SDK manager executable. Make sure the Android SDK is properly installed " + "and that its path is correctly configured in the Unity preferences window " + "(under External Tools)."; } public const string AboutTitle = "Google Play Games Plugin for Unity"; public const string AboutText = "Copyright (C) 2014 Google Inc.\n\nThis is an open-source " + "plugin that allows cross-platform integration with Google Play games services. " + "For more information, visit the official site on Github:\n\n" + "https://github.com/playgameservices/play-games-plugin-for-unity\n\nPlugin version: "; public const string LicenseTitle = "Google Play Games Plugin for Unity"; public const string LicenseText = "Copyright (C) 2014 Google Inc. All Rights Reserved.\n\n" + "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\n\n" + " http://www.apache.org/licenses/LICENSE-2.0\n\n" + "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."; } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // OrderablePartitioner.cs // // // // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; namespace System.Collections.Concurrent { /// <summary> /// Represents a particular manner of splitting an orderable data source into multiple partitions. /// </summary> /// <typeparam name="TSource">Type of the elements in the collection.</typeparam> /// <remarks> /// <para> /// Each element in each partition has an integer index associated with it, which determines the relative /// order of that element against elements in other partitions. /// </para> /// <para> /// Inheritors of <see cref="OrderablePartitioner{TSource}"/> must adhere to the following rules: /// <ol> /// <li>All indices must be unique, such that there may not be duplicate indices. If all indices are not /// unique, the output ordering may be scrambled.</li> /// <li>All indices must be non-negative. If any indices are negative, consumers of the implementation /// may throw exceptions.</li> /// <li><see cref="GetPartitions"/> and <see cref="GetOrderablePartitions"/> should throw a /// <see cref="T:System.ArgumentOutOfRangeException"/> if the requested partition count is less than or /// equal to zero.</li> /// <li><see cref="GetPartitions"/> and <see cref="GetOrderablePartitions"/> should always return a number /// of enumerables equal to the requested partition count. If the partitioner runs out of data and cannot /// create as many partitions as requested, an empty enumerator should be returned for each of the /// remaining partitions. If this rule is not followed, consumers of the implementation may throw a <see /// cref="T:System.InvalidOperationException"/>.</li> /// <li><see cref="GetPartitions"/>, <see cref="GetOrderablePartitions"/>, /// <see cref="GetDynamicPartitions"/>, and <see cref="GetOrderableDynamicPartitions"/> /// should never return null. If null is returned, a consumer of the implementation may throw a /// <see cref="T:System.InvalidOperationException"/>.</li> /// <li><see cref="GetPartitions"/>, <see cref="GetOrderablePartitions"/>, /// <see cref="GetDynamicPartitions"/>, and <see cref="GetOrderableDynamicPartitions"/> /// should always return partitions that can fully and uniquely enumerate the input data source. All of /// the data and only the data contained in the input source should be enumerated, with no duplication /// that was not already in the input, unless specifically required by the particular partitioner's /// design. If this is not followed, the output ordering may be scrambled.</li> /// <li>If <see cref="KeysOrderedInEachPartition"/> returns true, each partition must return elements /// with increasing key indices.</li> /// <li>If <see cref="KeysOrderedAcrossPartitions"/> returns true, all the keys in partition numbered N /// must be larger than all the keys in partition numbered N-1.</li> /// <li>If <see cref="KeysNormalized"/> returns true, all indices must be monotonically increasing from /// 0, though not necessarily within a single partition.</li> /// </ol> /// </para> /// </remarks> public abstract class OrderablePartitioner<TSource> : Partitioner<TSource> { /// <summary> /// Initializes a new instance of the <see cref="OrderablePartitioner{TSource}"/> class with the /// specified constraints on the index keys. /// </summary> /// <param name="keysOrderedInEachPartition"> /// Indicates whether the elements in each partition are yielded in the order of /// increasing keys. /// </param> /// <param name="keysOrderedAcrossPartitions"> /// Indicates whether elements in an earlier partition always come before /// elements in a later partition. If true, each element in partition 0 has a smaller order key than /// any element in partition 1, each element in partition 1 has a smaller order key than any element /// in partition 2, and so on. /// </param> /// <param name="keysNormalized"> /// Indicates whether keys are normalized. If true, all order keys are distinct /// integers in the range [0 .. numberOfElements-1]. If false, order keys must still be dictinct, but /// only their relative order is considered, not their absolute values. /// </param> protected OrderablePartitioner(bool keysOrderedInEachPartition, bool keysOrderedAcrossPartitions, bool keysNormalized) { KeysOrderedInEachPartition = keysOrderedInEachPartition; KeysOrderedAcrossPartitions = keysOrderedAcrossPartitions; KeysNormalized = keysNormalized; } /// <summary> /// Partitions the underlying collection into the specified number of orderable partitions. /// </summary> /// <remarks> /// Each partition is represented as an enumerator over key-value pairs. /// The value of the pair is the element itself, and the key is an integer which determines /// the relative ordering of this element against other elements in the data source. /// </remarks> /// <param name="partitionCount">The number of partitions to create.</param> /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns> public abstract IList<IEnumerator<KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount); /// <summary> /// Creates an object that can partition the underlying collection into a variable number of /// partitions. /// </summary> /// <remarks> /// <para> /// The returned object implements the <see /// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see /// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the /// object creates another partition over the sequence. /// </para> /// <para> /// Each partition is represented as an enumerator over key-value pairs. The value in the pair is the element /// itself, and the key is an integer which determines the relative ordering of this element against /// other elements. /// </para> /// <para> /// The <see cref="GetOrderableDynamicPartitions"/> method is only supported if the <see /// cref="System.Collections.Concurrent.Partitioner{TSource}.SupportsDynamicPartitions">SupportsDynamicPartitions</see> /// property returns true. /// </para> /// </remarks> /// <returns>An object that can create partitions over the underlying data source.</returns> /// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this /// partitioner.</exception> public virtual IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicPartitions() { throw new NotSupportedException(SR.Partitioner_DynamicPartitionsNotSupported); } /// <summary> /// Gets whether elements in each partition are yielded in the order of increasing keys. /// </summary> public bool KeysOrderedInEachPartition { get; private set; } /// <summary> /// Gets whether elements in an earlier partition always come before elements in a later partition. /// </summary> /// <remarks> /// If <see cref="KeysOrderedAcrossPartitions"/> returns true, each element in partition 0 has a /// smaller order key than any element in partition 1, each element in partition 1 has a smaller /// order key than any element in partition 2, and so on. /// </remarks> public bool KeysOrderedAcrossPartitions { get; private set; } /// <summary> /// Gets whether order keys are normalized. /// </summary> /// <remarks> /// If <see cref="KeysNormalized"/> returns true, all order keys are distinct integers in the range /// [0 .. numberOfElements-1]. If the property returns false, order keys must still be dictinct, but /// only their relative order is considered, not their absolute values. /// </remarks> public bool KeysNormalized { get; private set; } /// <summary> /// Partitions the underlying collection into the given number of ordered partitions. /// </summary> /// <remarks> /// The default implementation provides the same behavior as <see cref="GetOrderablePartitions"/> except /// that the returned set of partitions does not provide the keys for the elements. /// </remarks> /// <param name="partitionCount">The number of partitions to create.</param> /// <returns>A list containing <paramref name="partitionCount"/> enumerators.</returns> public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount) { IList<IEnumerator<KeyValuePair<long, TSource>>> orderablePartitions = GetOrderablePartitions(partitionCount); if (orderablePartitions.Count != partitionCount) { throw new InvalidOperationException("OrderablePartitioner_GetPartitions_WrongNumberOfPartitions"); } IEnumerator<TSource>[] partitions = new IEnumerator<TSource>[partitionCount]; for (int i = 0; i < partitionCount; i++) { partitions[i] = new EnumeratorDropIndices(orderablePartitions[i]); } return partitions; } /// <summary> /// Creates an object that can partition the underlying collection into a variable number of /// partitions. /// </summary> /// <remarks> /// <para> /// The returned object implements the <see /// cref="T:System.Collections.Generic.IEnumerable{TSource}"/> interface. Calling <see /// cref="System.Collections.Generic.IEnumerable{TSource}.GetEnumerator">GetEnumerator</see> on the /// object creates another partition over the sequence. /// </para> /// <para> /// The default implementation provides the same behavior as <see cref="GetOrderableDynamicPartitions"/> except /// that the returned set of partitions does not provide the keys for the elements. /// </para> /// <para> /// The <see cref="GetDynamicPartitions"/> method is only supported if the <see /// cref="System.Collections.Concurrent.Partitioner{TSource}.SupportsDynamicPartitions"/> /// property returns true. /// </para> /// </remarks> /// <returns>An object that can create partitions over the underlying data source.</returns> /// <exception cref="NotSupportedException">Dynamic partitioning is not supported by this /// partitioner.</exception> public override IEnumerable<TSource> GetDynamicPartitions() { IEnumerable<KeyValuePair<long, TSource>> orderablePartitions = GetOrderableDynamicPartitions(); return new EnumerableDropIndices(orderablePartitions); } /// <summary> /// Converts an enumerable over key-value pairs to an enumerable over values. /// </summary> private class EnumerableDropIndices : IEnumerable<TSource>, IDisposable { private readonly IEnumerable<KeyValuePair<long, TSource>> _source; public EnumerableDropIndices(IEnumerable<KeyValuePair<long, TSource>> source) { _source = source; } public IEnumerator<TSource> GetEnumerator() { return new EnumeratorDropIndices(_source.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return ((EnumerableDropIndices)this).GetEnumerator(); } public void Dispose() { IDisposable d = _source as IDisposable; if (d != null) { d.Dispose(); } } } private class EnumeratorDropIndices : IEnumerator<TSource> { private readonly IEnumerator<KeyValuePair<long, TSource>> _source; public EnumeratorDropIndices(IEnumerator<KeyValuePair<long, TSource>> source) { _source = source; } public bool MoveNext() { return _source.MoveNext(); } public TSource Current { get { return _source.Current.Value; } } Object IEnumerator.Current { get { return ((EnumeratorDropIndices)this).Current; } } public void Dispose() { _source.Dispose(); } public void Reset() { _source.Reset(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.IO; using Microsoft.SqlServer.Server; namespace System.Data.SqlClient.ManualTesting.Tests { public static class SqlVariantParam { // Katmai connection string (Katmai or later is required). private static string s_connStr; /// <summary> /// Tests all SqlTypes inside sql_variant to server using sql_variant parameter, SqlBulkCopy, and TVP parameter with sql_variant inside. /// </summary> public static void SendAllSqlTypesInsideVariant(string connStr) { s_connStr = connStr; Console.WriteLine(""); Console.WriteLine("Starting test 'SqlVariantParam'"); SendVariant(new SqlSingle((float)123.45), "System.Data.SqlTypes.SqlSingle", "real"); SendVariant(new SqlSingle((double)123.45), "System.Data.SqlTypes.SqlSingle", "real"); SendVariant(new SqlString("hello"), "System.Data.SqlTypes.SqlString", "nvarchar"); SendVariant(new SqlDouble((double)123.45), "System.Data.SqlTypes.SqlDouble", "float"); SendVariant(new SqlBinary(new byte[] { 0x00, 0x11, 0x22 }), "System.Data.SqlTypes.SqlBinary", "varbinary"); SendVariant(new SqlGuid(Guid.NewGuid()), "System.Data.SqlTypes.SqlGuid", "uniqueidentifier"); SendVariant(new SqlBoolean(true), "System.Data.SqlTypes.SqlBoolean", "bit"); SendVariant(new SqlBoolean(1), "System.Data.SqlTypes.SqlBoolean", "bit"); SendVariant(new SqlByte(1), "System.Data.SqlTypes.SqlByte", "tinyint"); SendVariant(new SqlInt16(1), "System.Data.SqlTypes.SqlInt16", "smallint"); SendVariant(new SqlInt32(1), "System.Data.SqlTypes.SqlInt32", "int"); SendVariant(new SqlInt64(1), "System.Data.SqlTypes.SqlInt64", "bigint"); SendVariant(new SqlDecimal(1234.123M), "System.Data.SqlTypes.SqlDecimal", "numeric"); SendVariant(new SqlDateTime(DateTime.Now), "System.Data.SqlTypes.SqlDateTime", "datetime"); SendVariant(new SqlMoney(123.123M), "System.Data.SqlTypes.SqlMoney", "money"); Console.WriteLine("End test 'SqlVariantParam'"); } /// <summary> /// Returns a SqlDataReader with embedded sql_variant column with paramValue inside. /// </summary> /// <param name="paramValue">object value to embed as sql_variant field value</param> /// <param name="includeBaseType">Set to true to return optional BaseType column which extracts base type of sql_variant column.</param> /// <returns></returns> private static SqlDataReader GetReaderForVariant(object paramValue, bool includeBaseType) { SqlConnection conn = new SqlConnection(s_connStr); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select @p1 as f1"; if (includeBaseType) cmd.CommandText += ", sql_variant_property(@p1,'BaseType') as BaseType"; cmd.Parameters.Add("@p1", SqlDbType.Variant); cmd.Parameters["@p1"].Value = paramValue; SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); return dr; } /// <summary> /// Verifies if SqlDataReader returns expected SqlType and base type. /// </summary> /// <param name="tag">Test tag to identify caller</param> /// <param name="dr">SqlDataReader to verify</param> /// <param name="expectedTypeName">Expected type name (SqlType)</param> /// <param name="expectedBaseTypeName">Expected base type name (Sql Server type name)</param> private static void VerifyReader(string tag, SqlDataReader dr, string expectedTypeName, string expectedBaseTypeName) { // select sql_variant_property(cast(cast(123.45 as money) as sql_variant),'BaseType' ) as f1 dr.Read(); string actualTypeName = dr.GetSqlValue(0).GetType().ToString(); string actualBaseTypeName = dr.GetString(1); Console.WriteLine("{0,-40} -> {1}:{2}", tag, actualTypeName, actualBaseTypeName); if (!actualTypeName.Equals(expectedTypeName)) { Console.WriteLine(" --> ERROR: Expected type {0} does not match actual type {1}", expectedTypeName, actualTypeName); } if (!actualBaseTypeName.Equals(expectedBaseTypeName)) { Console.WriteLine(" --> ERROR: Expected base type {0} does not match actual base type {1}", expectedBaseTypeName, actualBaseTypeName); } } /// <summary> /// Round trips a sql_variant to server and verifies result. /// </summary> /// <param name="paramValue">Value to send as sql_variant</param> /// <param name="expectedTypeName">Expected SqlType name to round trip</param> /// <param name="expectedBaseTypeName">Expected base type name (SQL Server base type inside sql_variant)</param> private static void SendVariant(object paramValue, string expectedTypeName, string expectedBaseTypeName) { // Round trip using Bulk Copy, normal param, and TVP param. SendVariantBulkCopy(paramValue, expectedTypeName, expectedBaseTypeName); SendVariantParam(paramValue, expectedTypeName, expectedBaseTypeName); SendVariantTvp(paramValue, expectedTypeName, expectedBaseTypeName); } /// <summary> /// Round trip sql_variant value as normal parameter. /// </summary> private static void SendVariantParam(object paramValue, string expectedTypeName, string expectedBaseTypeName) { using (SqlDataReader dr = GetReaderForVariant(paramValue, true)) { VerifyReader("SendVariantParam", dr, expectedTypeName, expectedBaseTypeName); } } /// <summary> /// Round trip sql_variant value using SqlBulkCopy. /// </summary> private static void SendVariantBulkCopy(object paramValue, string expectedTypeName, string expectedBaseTypeName) { string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDest"); // Fetch reader using type. using (SqlDataReader dr = GetReaderForVariant(paramValue, false)) { using (SqlConnection connBulk = new SqlConnection(s_connStr)) { connBulk.Open(); // Drop and re-create target bulk copy table. xsql(connBulk, "if exists(select 1 from sys.tables where name='{0}') begin drop table {0} end", bulkCopyTableName); xsql(connBulk, "create table {0} (f1 sql_variant)", bulkCopyTableName); // Perform bulk copy to target. using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connBulk)) { bulkCopy.BulkCopyTimeout = 60; bulkCopy.BatchSize = 1; bulkCopy.DestinationTableName = bulkCopyTableName; bulkCopy.WriteToServer(dr); } // Verify target. using (SqlCommand cmd = connBulk.CreateCommand()) { cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName); using (SqlDataReader drVerify = cmd.ExecuteReader()) { VerifyReader("SendVariantBulkCopy[SqlDataReader]", drVerify, expectedTypeName, expectedBaseTypeName); } } // Truncate target table for next pass. xsql(connBulk, "truncate table {0}", bulkCopyTableName); // Send using DataTable as source. DataTable t = new DataTable(); t.Columns.Add("f1", typeof(object)); t.Rows.Add(new object[] { paramValue }); // Perform bulk copy to target. using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connBulk)) { bulkCopy.BulkCopyTimeout = 60; bulkCopy.BatchSize = 1; bulkCopy.DestinationTableName = bulkCopyTableName; bulkCopy.WriteToServer(t, DataRowState.Added); } // Verify target. using (SqlCommand cmd = connBulk.CreateCommand()) { cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName); using (SqlDataReader drVerify = cmd.ExecuteReader()) { VerifyReader("SendVariantBulkCopy[DataTable]", drVerify, expectedTypeName, expectedBaseTypeName); } } // Truncate target table for next pass. xsql(connBulk, "truncate table {0}", bulkCopyTableName); // Send using DataRow as source. DataRow[] rowToSend = t.Select(); // Perform bulk copy to target. using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connBulk)) { bulkCopy.BulkCopyTimeout = 60; bulkCopy.BatchSize = 1; bulkCopy.DestinationTableName = bulkCopyTableName; bulkCopy.WriteToServer(rowToSend); } // Verify target. using (SqlCommand cmd = connBulk.CreateCommand()) { cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName); using (SqlDataReader drVerify = cmd.ExecuteReader()) { VerifyReader("SendVariantBulkCopy[DataRow]", drVerify, expectedTypeName, expectedBaseTypeName); } } // Cleanup target table. xsql(connBulk, "if exists(select 1 from sys.tables where name='{0}') begin drop table {0} end", bulkCopyTableName); } } } /// <summary> /// Round trip sql_variant value using TVP. /// </summary> private static void SendVariantTvp(object paramValue, string expectedTypeName, string expectedBaseTypeName) { string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpVariant"); using (SqlConnection connTvp = new SqlConnection(s_connStr)) { connTvp.Open(); // Drop and re-create tvp type. xsql(connTvp, "if exists(select 1 from sys.types where name='{0}') begin drop type {0} end", tvpTypeName); xsql(connTvp, "create type {0} as table (f1 sql_variant)", tvpTypeName); // Send TVP using SqlMetaData. SqlMetaData[] metadata = new SqlMetaData[1]; metadata[0] = new SqlMetaData("f1", SqlDbType.Variant); SqlDataRecord[] record = new SqlDataRecord[1]; record[0] = new SqlDataRecord(metadata); record[0].SetValue(0, paramValue); using (SqlCommand cmd = connTvp.CreateCommand()) { cmd.CommandText = "select f1, sql_variant_property(f1,'BaseType') as BaseType from @tvpParam"; SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", record); p.SqlDbType = SqlDbType.Structured; p.TypeName = string.Format("dbo.{0}", tvpTypeName); using (SqlDataReader dr = cmd.ExecuteReader()) { VerifyReader("SendVariantTvp[SqlMetaData]", dr, expectedTypeName, expectedBaseTypeName); } } // Send TVP using DataSet. // DEVNOTE: TVPs do not support sql_variant inside DataTable, by design according to tvp spec: // 4.3 DbDataReader // The only difference or special case for DataTable is that we will not support: // 1) UDT?s // 2) Variant /* DataTable t = new DataTable(); t.Columns.Add("f1", typeof(object)); t.Rows.Add(new object[] { paramValue }); t.AcceptChanges(); using (SqlCommand cmd = connTvp.CreateCommand()) { cmd.CommandText = "select f1, sql_variant_property(@p1,'BaseType') as BaseType from @tvpParam"; SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", t); p.SqlDbType = SqlDbType.Structured; p.TypeName = @"dbo.tvpVariant"; using (SqlDataReader dr = cmd.ExecuteReader()) { VerifyReader("SendVariantTvp[DataTable]", dr, expectedTypeName, expectedBaseTypeName); } } */ // Send TVP using SqlDataReader. using (SqlDataReader dr = GetReaderForVariant(paramValue, false)) { using (SqlCommand cmd = connTvp.CreateCommand()) { cmd.CommandText = "select f1, sql_variant_property(f1,'BaseType') as BaseType from @tvpParam"; SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", dr); p.SqlDbType = SqlDbType.Structured; p.TypeName = string.Format("dbo.{0}", tvpTypeName); using (SqlDataReader dr2 = cmd.ExecuteReader()) { VerifyReader("SendVariantTvp[SqlDataReader]", dr2, expectedTypeName, expectedBaseTypeName); } } } // Cleanup tvp type. xsql(connTvp, "if exists(select 1 from sys.types where name='{0}') begin drop type {0} end", tvpTypeName); } } /// <summary> /// Helper to execute t-sql with variable object name. /// </summary> /// <param name="conn"></param> /// <param name="formatSql">Format string using {0} to designate where to place objectName</param> /// <param name="objectName">Variable object name for t-sql</param> private static void xsql(SqlConnection conn, string formatSql, string objectName) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = string.Format(formatSql, objectName); cmd.ExecuteNonQuery(); } } /// <summary> /// Simple helper to execute t-sql. /// </summary> private static void xsql(SqlConnection conn, string sql) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } } }
namespace Epi.Windows.Analysis.Dialogs { partial class ComplexSampleMeansDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ComplexSampleMeansDialog)); this.btnHelp = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.gbxPageSettings = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.txtNumCol = new System.Windows.Forms.TextBox(); this.cbxNoLineWrap = new System.Windows.Forms.CheckBox(); this.lbxStratifyBy = new System.Windows.Forms.ListBox(); this.picHeight = new System.Windows.Forms.PictureBox(); this.cmbStratifyBy = new System.Windows.Forms.ComboBox(); this.lblStratifyBy = new System.Windows.Forms.Label(); this.cmbCrossTab = new System.Windows.Forms.ComboBox(); this.lblCrossTabulate = new System.Windows.Forms.Label(); this.lblWeight = new System.Windows.Forms.Label(); this.cmbMeansOf = new System.Windows.Forms.ComboBox(); this.lblMeansOf = new System.Windows.Forms.Label(); this.lblOutput = new System.Windows.Forms.Label(); this.txtOutput = new System.Windows.Forms.TextBox(); this.cmbWeight = new System.Windows.Forms.ComboBox(); this.btnSettings = new System.Windows.Forms.Button(); this.cmbPSU = new System.Windows.Forms.ComboBox(); this.lblPSU = new System.Windows.Forms.Label(); this.gbxPageSettings.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picHeight)).BeginInit(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // gbxPageSettings // this.gbxPageSettings.Controls.Add(this.label1); this.gbxPageSettings.Controls.Add(this.txtNumCol); this.gbxPageSettings.Controls.Add(this.cbxNoLineWrap); this.gbxPageSettings.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.gbxPageSettings, "gbxPageSettings"); this.gbxPageSettings.Name = "gbxPageSettings"; this.gbxPageSettings.TabStop = false; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // txtNumCol // resources.ApplyResources(this.txtNumCol, "txtNumCol"); this.txtNumCol.Name = "txtNumCol"; this.txtNumCol.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtNumCol_KeyPress); this.txtNumCol.Leave += new System.EventHandler(this.txtNumCol_Leave); // // cbxNoLineWrap // resources.ApplyResources(this.cbxNoLineWrap, "cbxNoLineWrap"); this.cbxNoLineWrap.Name = "cbxNoLineWrap"; // // lbxStratifyBy // resources.ApplyResources(this.lbxStratifyBy, "lbxStratifyBy"); this.lbxStratifyBy.Name = "lbxStratifyBy"; this.lbxStratifyBy.TabStop = false; this.lbxStratifyBy.SelectedIndexChanged += new System.EventHandler(this.lbxStratifyBy_SelectedIndexChanged); // // picHeight // resources.ApplyResources(this.picHeight, "picHeight"); this.picHeight.Name = "picHeight"; this.picHeight.TabStop = false; // // cmbStratifyBy // this.cmbStratifyBy.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbStratifyBy.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbStratifyBy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbStratifyBy, "cmbStratifyBy"); this.cmbStratifyBy.Name = "cmbStratifyBy"; this.cmbStratifyBy.Sorted = true; this.cmbStratifyBy.SelectedIndexChanged += new System.EventHandler(this.cmbStratifyBy_SelectedIndexChanged); // // lblStratifyBy // this.lblStratifyBy.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblStratifyBy, "lblStratifyBy"); this.lblStratifyBy.Name = "lblStratifyBy"; // // cmbCrossTab // this.cmbCrossTab.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbCrossTab.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbCrossTab.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbCrossTab, "cmbCrossTab"); this.cmbCrossTab.Name = "cmbCrossTab"; this.cmbCrossTab.Sorted = true; this.cmbCrossTab.SelectedIndexChanged += new System.EventHandler(this.cmbCrossTab_SelectedIndexChanged); this.cmbCrossTab.Click += new System.EventHandler(this.cmbCrossTab_Click); this.cmbCrossTab.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbCrossTab_KeyDown); // // lblCrossTabulate // this.lblCrossTabulate.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblCrossTabulate, "lblCrossTabulate"); this.lblCrossTabulate.Name = "lblCrossTabulate"; // // lblWeight // this.lblWeight.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblWeight, "lblWeight"); this.lblWeight.Name = "lblWeight"; // // cmbMeansOf // this.cmbMeansOf.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbMeansOf.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbMeansOf.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbMeansOf, "cmbMeansOf"); this.cmbMeansOf.Name = "cmbMeansOf"; this.cmbMeansOf.Sorted = true; this.cmbMeansOf.SelectedIndexChanged += new System.EventHandler(this.cmbMeansOf_SelectedIndexChanged); this.cmbMeansOf.Click += new System.EventHandler(this.cmbMeansOf_Click); // // lblMeansOf // this.lblMeansOf.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblMeansOf, "lblMeansOf"); this.lblMeansOf.Name = "lblMeansOf"; // // lblOutput // this.lblOutput.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblOutput, "lblOutput"); this.lblOutput.Name = "lblOutput"; // // txtOutput // resources.ApplyResources(this.txtOutput, "txtOutput"); this.txtOutput.Name = "txtOutput"; // // cmbWeight // this.cmbWeight.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbWeight.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbWeight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbWeight, "cmbWeight"); this.cmbWeight.Name = "cmbWeight"; this.cmbWeight.Sorted = true; this.cmbWeight.SelectedIndexChanged += new System.EventHandler(this.cmbWeight_SelectedIndexChanged); this.cmbWeight.Click += new System.EventHandler(this.cmbWeight_Click); this.cmbWeight.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbWeight_KeyDown); // // btnSettings // resources.ApplyResources(this.btnSettings, "btnSettings"); this.btnSettings.Name = "btnSettings"; this.btnSettings.UseVisualStyleBackColor = true; this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click); // // cmbPSU // this.cmbPSU.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbPSU.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbPSU.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbPSU, "cmbPSU"); this.cmbPSU.Name = "cmbPSU"; this.cmbPSU.Sorted = true; this.cmbPSU.SelectedIndexChanged += new System.EventHandler(this.cmbPSU_SelectedIndexChanged); this.cmbPSU.Click += new System.EventHandler(this.cmbPSU_Click); // // lblPSU // this.lblPSU.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblPSU, "lblPSU"); this.lblPSU.Name = "lblPSU"; // // ComplexSampleMeansDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.cmbPSU); this.Controls.Add(this.lblPSU); this.Controls.Add(this.btnSettings); this.Controls.Add(this.cmbWeight); this.Controls.Add(this.lblOutput); this.Controls.Add(this.txtOutput); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.gbxPageSettings); this.Controls.Add(this.lbxStratifyBy); this.Controls.Add(this.picHeight); this.Controls.Add(this.cmbStratifyBy); this.Controls.Add(this.lblStratifyBy); this.Controls.Add(this.cmbCrossTab); this.Controls.Add(this.lblCrossTabulate); this.Controls.Add(this.lblWeight); this.Controls.Add(this.cmbMeansOf); this.Controls.Add(this.lblMeansOf); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ComplexSampleMeansDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.ComplexSampleMeansDialog_Load); this.gbxPageSettings.ResumeLayout(false); this.gbxPageSettings.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picHeight)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox picHeight; private System.Windows.Forms.ComboBox cmbStratifyBy; private System.Windows.Forms.Label lblStratifyBy; private System.Windows.Forms.ComboBox cmbCrossTab; private System.Windows.Forms.Label lblCrossTabulate; private System.Windows.Forms.Label lblWeight; private System.Windows.Forms.ComboBox cmbMeansOf; private System.Windows.Forms.Label lblMeansOf; private System.Windows.Forms.Label lblOutput; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.ComboBox cmbWeight; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.GroupBox gbxPageSettings; private System.Windows.Forms.TextBox txtNumCol; private System.Windows.Forms.CheckBox cbxNoLineWrap; private System.Windows.Forms.ListBox lbxStratifyBy; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnSettings; private System.Windows.Forms.ComboBox cmbPSU; private System.Windows.Forms.Label lblPSU; } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System.Collections.Generic; using System.Linq; using Glass.Mapper.Maps; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Configuration.Fluent; using Glass.Mapper.Sc.Maps; using NUnit.Framework; namespace Glass.Mapper.Sc.FakeDb.Configuation { [TestFixture] public class SitecoreMapConfigurationFixture { [Test] public void ConfigMapProperties_MapsSinglePropertyToConfiguration() { //Assign StubBaseMap stubMap = new StubBaseMap(); SitecoreFluentConfigurationLoader loader = new SitecoreFluentConfigurationLoader(); ConfigurationMap configMap = new ConfigurationMap(new IGlassMap[] { stubMap }); configMap.Load(loader); //Act stubMap.PerformMap(loader); //Assert Assert.AreEqual(1, stubMap.GlassType.Config.Properties.Count()); Assert.IsNull(stubMap.GlassType.Config.ItemConfig); } [Test] public void ConfigMapProperties_MapsAllPropertiesToConfiguration() { //Assign FinalStubMap finalStubMap = new FinalStubMap(); PartialStub1Map partialStub1Map = new PartialStub1Map(); StubBaseMap stubBaseMap = new StubBaseMap(); PartialStub2Map partialStub2Map = new PartialStub2Map(); SitecoreFluentConfigurationLoader loader = new SitecoreFluentConfigurationLoader(); ConfigurationMap configMap = new ConfigurationMap(new IGlassMap[] { partialStub1Map, stubBaseMap, partialStub2Map, finalStubMap }); configMap.Load(loader); //Act finalStubMap.PerformMap(loader); partialStub1Map.PerformMap(loader); stubBaseMap.PerformMap(loader); partialStub2Map.PerformMap(loader); //Assert Assert.AreEqual(5, finalStubMap.GlassType.Config.Properties.Count()); SitecoreFieldConfiguration fieldNameProperty = finalStubMap.GlassType.Config.Properties.FirstOrDefault(x => x.PropertyInfo.Name == "FieldName") as SitecoreFieldConfiguration; Assert.AreEqual("Field Name", fieldNameProperty.FieldName); SitecoreInfoConfiguration qwertyProperty = finalStubMap.GlassType.Config.Properties.FirstOrDefault(x => x.PropertyInfo.Name == "Qwerty") as SitecoreInfoConfiguration; Assert.AreEqual(SitecoreInfoType.Name, qwertyProperty.Type); Assert.IsNotNull(finalStubMap.GlassType.Config.IdConfig); } [Test] public void ConfigMapProperties_ImportMap_CanOverrideExistingPropertyConfig() { //Assign FinalStubMap finalStubMap = new FinalStubMap(); FinalStubSubClassMap finalStubSubClassMap = new FinalStubSubClassMap(); PartialStub1Map partialStub1Map = new PartialStub1Map(); PartialStub2Map partialStub2Map = new PartialStub2Map(); StubBaseMap stubBaseMap = new StubBaseMap(); SitecoreFluentConfigurationLoader loader = new SitecoreFluentConfigurationLoader(); ConfigurationMap configMap = new ConfigurationMap(new IGlassMap[] { partialStub1Map, stubBaseMap, partialStub2Map, finalStubMap, finalStubSubClassMap }); configMap.Load(loader); //Act finalStubMap.PerformMap(loader); finalStubSubClassMap.PerformMap(loader); //Assert Assert.AreEqual(5, finalStubSubClassMap.GlassType.Config.Properties.Count()); SitecoreFieldConfiguration fieldNameProperty = finalStubSubClassMap.GlassType.Config.Properties.FirstOrDefault(x => x.PropertyInfo.Name == "FieldName") as SitecoreFieldConfiguration; Assert.AreEqual("Field Other Name", fieldNameProperty.FieldName); SitecoreInfoConfiguration qwertyProperty = finalStubSubClassMap.GlassType.Config.Properties.FirstOrDefault(x => x.PropertyInfo.Name == "Qwerty") as SitecoreInfoConfiguration; Assert.AreEqual(SitecoreInfoType.Name, qwertyProperty.Type); Assert.IsNotNull(finalStubSubClassMap.GlassType.Config.IdConfig); } [Test] public void Issue254_Test() { MapStubWithChildren mapStubWithChildren = new MapStubWithChildren(); MapStubInherit1 mapStubInherit1 = new MapStubInherit1(); MapStubInherit2 mapStubInherit2 = new MapStubInherit2(); SitecoreFluentConfigurationLoader loader = new SitecoreFluentConfigurationLoader(); ConfigurationMap configMap = new ConfigurationMap(new IGlassMap[] { mapStubWithChildren, mapStubInherit1, mapStubInherit2 }); configMap.Load(loader); //Assert //Assert Assert.IsTrue(mapStubWithChildren.GlassType.Config.Properties.Any(x => x is SitecoreChildrenConfiguration)); Assert.IsTrue(mapStubInherit1.GlassType.Config.Properties.Any(x => x is SitecoreChildrenConfiguration)); Assert.IsTrue(mapStubInherit2.GlassType.Config.Properties.Any(x => x is SitecoreChildrenConfiguration)); } #region Stubs public class StubBaseMap : SitecoreGlassMap<IStubBase> { public override void Configure() { Map(x => x.Id(y => y.Id)); } } public class PartialStub1Map : SitecoreGlassMap<IPartialStub1> { public override void Configure() { Map(x => { ImportType<IStubBase>(); x.Info(y => y.Qwerty).InfoType(SitecoreInfoType.Name); }); } } public class PartialStub2Map : SitecoreGlassMap<IPartialStub2> { public override void Configure() { Map(x => { ImportType<IStubBase>(); x.Parent(y => y.Parent); }); } } public class FinalStubMap : SitecoreGlassMap<IFinalStub> { public override void Configure() { Map( x => { ImportType<IPartialStub1>(); ImportType<IPartialStub2>(); x.Children(y => y.Children); x.Field(y => y.FieldName).FieldName("Field Name"); x.Id(y => y.Id); }); } } public class FinalStubSubClassMap : SitecoreGlassMap<IFinalSubClassStub> { public override void Configure() { Map( x => { ImportMap<IFinalStub>(); x.Field(y => y.FieldName).FieldName("Field Other Name"); }); } } public class MapStubWithChildren : SitecoreGlassMap<StubWithChildren> { public override void Configure() { Map( x => { x.Children(y => y.BaseChildren); }); } } public class MapStubInherit1 : SitecoreGlassMap<StubInherit1> { public override void Configure() { Map( x => { ImportMap<StubWithChildren>(); x.AutoMap(); }); } } public class MapStubInherit2 : SitecoreGlassMap<StubInherit2> { public override void Configure() { Map( x => { ImportMap<StubInherit1>(); x.AutoMap(); }); } } public interface IStubBase { string Id { get; set; } } public interface IFinalStub : IPartialStub1, IPartialStub2 { string Children { get; set; } string FieldName { get; set; } } public interface IFinalSubClassStub : IPartialStub1, IPartialStub2 { string Children { get; set; } string FieldName { get; set; } } public interface IPartialStub1 : IStubBase { string Qwerty { get; set; } } public interface IPartialStub2 : IStubBase { string Parent { get; set; } } public class StubWithChildren { public virtual IEnumerable<IStubBase> BaseChildren { get; set; } } public class StubInherit1 : StubWithChildren { } public class StubInherit2 : StubInherit1 { } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="AsyncCopyController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Azure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Storage.Blob; using Microsoft.Azure.Storage.Blob.Protocol; using Microsoft.Azure.Storage.DataMovement.Extensions; using Microsoft.Azure.Storage.File; internal abstract class AsyncCopyController : TransferControllerBase { /// <summary> /// Timer to signal refresh status. /// </summary> private Timer statusRefreshTimer; /// <summary> /// Lock to protect statusRefreshTimer. /// </summary> private object statusRefreshTimerLock = new object(); /// <summary> /// Wait time between two status refresh requests. /// </summary> private long statusRefreshWaitTime = Constants.CopyStatusRefreshMinWaitTimeInMilliseconds; /// <summary> /// Indicates whether the copy job is apporaching finish. /// </summary> private bool approachingFinish = false; /// <summary> /// Request count sent with current statusRefreshWaitTime /// </summary> private long statusRefreshRequestCount = 0; /// <summary> /// Keeps track of the internal state-machine state. /// </summary> private volatile State state; /// <summary> /// Indicates whether the controller has work available /// or not for the calling code. /// </summary> private bool hasWork; /// <summary> /// Indicates the BytesCopied value of last CopyState /// </summary> private long lastBytesCopied; /// <summary> /// Initializes a new instance of the <see cref="AsyncCopyController"/> class. /// </summary> /// <param name="scheduler">Scheduler object which creates this object.</param> /// <param name="transferJob">Instance of job to start async copy.</param> /// <param name="userCancellationToken">Token user input to notify about cancellation.</param> internal AsyncCopyController( TransferScheduler scheduler, TransferJob transferJob, CancellationToken userCancellationToken) : base(scheduler, transferJob, userCancellationToken) { if (null == transferJob.Destination) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ParameterCannotBeNullException, "Dest"), "transferJob"); } switch(this.TransferJob.Source.Type) { case TransferLocationType.AzureBlob: this.SourceBlob = (this.TransferJob.Source as AzureBlobLocation).Blob; break; case TransferLocationType.AzureFile: this.SourceFile = (this.TransferJob.Source as AzureFileLocation).AzureFile; break; case TransferLocationType.SourceUri: this.SourceUri = (this.TransferJob.Source as UriLocation).Uri; break; default: throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ProvideExactlyOneOfThreeParameters, "Source.SourceUri", "Source.Blob", "Source.AzureFile"), "transferJob"); } // initialize the status refresh timer this.statusRefreshTimer = new Timer( new TimerCallback( delegate(object timerState) { this.hasWork = true; #if DOTNET5_4 }), null, -1, Timeout.Infinite); #else })); #endif this.SetInitialStatus(); } /// <summary> /// Internal state values. /// </summary> private enum State { FetchSourceAttributes, GetDestination, StartCopy, GetCopyState, Finished, Error, } public override bool HasWork { get { return this.hasWork; } } protected CloudBlob SourceBlob { get; private set; } protected CloudFile SourceFile { get; private set; } protected Uri SourceUri { get; private set; } protected abstract Uri DestUri { get; } /// <summary> /// Do work in the controller. /// A controller controls the whole transfer from source to destination, /// which could be split into several work items. This method is to let controller to do one of those work items. /// There could be several work items to do at the same time in the controller. /// </summary> /// <returns>Whether the controller has completed. This is to tell <c>TransferScheduler</c> /// whether the controller can be disposed.</returns> protected override async Task<bool> DoWorkInternalAsync() { if (!this.TransferJob.Transfer.ShouldTransferChecked) { this.hasWork = false; if (await this.CheckShouldTransfer()) { return true; } else { this.hasWork = true; return false; } } switch (this.state) { case State.FetchSourceAttributes: await this.FetchSourceAttributesAsync(); break; case State.GetDestination: await this.GetDestinationAsync(); break; case State.StartCopy: await this.StartCopyAsync(); break; case State.GetCopyState: await this.GetCopyStateAsync(); break; case State.Finished: case State.Error: default: break; } return (State.Error == this.state || State.Finished == this.state); } /// <summary> /// Sets the state of the controller to Error, while recording /// the last occurred exception and setting the HasWork and /// IsFinished fields. /// </summary> /// <param name="ex">Exception to record.</param> protected override void SetErrorState(Exception ex) { Debug.Assert( this.state != State.Finished, "SetErrorState called, while controller already in Finished state"); this.state = State.Error; this.hasWork = false; } /// <summary> /// Taken from <c>Microsoft.Azure.Storage.Core.Util.HttpUtility</c>: Parse the http query string. /// </summary> /// <param name="query">Http query string.</param> /// <returns>A dictionary of query pairs.</returns> protected static Dictionary<string, string> ParseQueryString(string query) { Dictionary<string, string> retVal = new Dictionary<string, string>(); if (query == null || query.Length == 0) { return retVal; } // remove ? if present if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } string[] valuePairs = query.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries); foreach (string vp in valuePairs) { int equalDex = vp.IndexOf("=", StringComparison.OrdinalIgnoreCase); if (equalDex < 0) { retVal.Add(Uri.UnescapeDataString(vp), null); continue; } string key = vp.Substring(0, equalDex); string value = vp.Substring(equalDex + 1); retVal.Add(Uri.UnescapeDataString(key), Uri.UnescapeDataString(value)); } return retVal; } private void SetInitialStatus() { switch (this.TransferJob.Status) { case TransferJobStatus.NotStarted: this.TransferJob.Status = TransferJobStatus.Transfer; break; case TransferJobStatus.Transfer: break; case TransferJobStatus.Monitor: this.lastBytesCopied = this.TransferJob.Transfer.ProgressTracker.BytesTransferred; break; case TransferJobStatus.Finished: default: throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, Resources.InvalidInitialEntryStatusForControllerException, this.TransferJob.Status, this.GetType().Name)); } this.SetHasWorkAfterStatusChanged(); } private void SetHasWorkAfterStatusChanged() { if (TransferJobStatus.Transfer == this.TransferJob.Status) { if (null != this.SourceUri) { this.state = State.GetDestination; } else { this.state = State.FetchSourceAttributes; } } else if(TransferJobStatus.Monitor == this.TransferJob.Status) { this.state = State.GetCopyState; } else { Debug.Fail("We should never be here"); } this.hasWork = true; } private async Task FetchSourceAttributesAsync() { Debug.Assert( this.state == State.FetchSourceAttributes, "FetchSourceAttributesAsync called, but state isn't FetchSourceAttributes"); this.hasWork = false; this.StartCallbackHandler(); try { await this.DoFetchSourceAttributesAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception ex) when (ex is StorageException || (ex is AggregateException && ex.InnerException is StorageException)) { var e = ex as StorageException ?? ex.InnerException as StorageException; #else catch (StorageException e) { #endif HandleFetchSourceAttributesException(e); throw; } if (this.TransferJob.Source.Type == TransferLocationType.AzureBlob) { (this.TransferJob.Source as AzureBlobLocation).CheckedAccessCondition = true; } else { (this.TransferJob.Source as AzureFileLocation).CheckedAccessCondition = true; } this.state = State.GetDestination; this.hasWork = true; } private static void HandleFetchSourceAttributesException(StorageException e) { // Getting a storage exception is expected if the source doesn't // exist. For those cases that indicate the source doesn't exist // we will set a specific error state. if (e?.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.NotFound) { throw new InvalidOperationException(Resources.SourceDoesNotExistException, e); } } private async Task GetDestinationAsync() { Debug.Assert( this.state == State.GetDestination, "GetDestinationAsync called, but state isn't GetDestination"); this.hasWork = false; this.StartCallbackHandler(); if (!this.IsForceOverwrite) { try { await this.DoFetchDestAttributesAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception e) when (e is StorageException || (e is AggregateException && e.InnerException is StorageException)) { var se = e as StorageException ?? e.InnerException as StorageException; #else catch (StorageException se) { #endif if (!await this.HandleGetDestinationResultAsync(se)) { throw se; } return; } } await this.HandleGetDestinationResultAsync(null); } private async Task<bool> HandleGetDestinationResultAsync(Exception e) { bool destExist = !this.IsForceOverwrite; if (null != e) { StorageException se = e as StorageException; // Getting a storage exception is expected if the destination doesn't // exist. In this case we won't error out, but set the // destExist flag to false to indicate we will copy to // a new blob/file instead of overwriting an existing one. if (null != se && null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { destExist = false; } else { this.DoHandleGetDestinationException(se); return false; } } if (this.TransferJob.Destination.Type == TransferLocationType.AzureBlob) { (this.TransferJob.Destination as AzureBlobLocation).CheckedAccessCondition = true; } else if(this.TransferJob.Destination.Type == TransferLocationType.AzureFile) { (this.TransferJob.Destination as AzureFileLocation).CheckedAccessCondition = true; } if ((TransferJobStatus.Monitor == this.TransferJob.Status) && string.IsNullOrEmpty(this.TransferJob.CopyId)) { throw new InvalidOperationException(Resources.RestartableInfoCorruptedException); } if (!this.IsForceOverwrite) { Uri sourceUri = this.GetSourceUri(); // If destination file exists, query user whether to overwrite it. await this.CheckOverwriteAsync( destExist, sourceUri.ToString(), this.DestUri.ToString()); } this.UpdateProgressAddBytesTransferred(0); this.state = State.StartCopy; this.hasWork = true; return true; } private async Task StartCopyAsync() { Debug.Assert( this.state == State.StartCopy, "StartCopyAsync called, but state isn't StartCopy"); this.hasWork = false; StorageCopyState copyState = null; try { copyState = await this.DoStartCopyAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception e) when (e is StorageException || (e is AggregateException && e.InnerException is StorageException)) { var se = e as StorageException ?? e.InnerException as StorageException; #else catch (StorageException se) { #endif if (!this.HandleStartCopyResult(se)) { throw; } return; } this.TransferJob.CopyId = copyState.CopyId; if ((copyState.Status == StorageCopyStatus.Success) && copyState.TotalBytes.HasValue) { await this.HandleFetchCopyStateResultAsync(copyState, false); } else { this.HandleStartCopyResult(null); } } private bool HandleStartCopyResult(StorageException se) { if (null != se) { if (null != se.RequestInformation && BlobErrorCodeStrings.PendingCopyOperation == se.RequestInformation.ErrorCode) { StorageCopyState copyState = this.FetchCopyStateAsync().Result; if (null == copyState) { return false; } string baseUriString = copyState.Source.GetComponents( UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); Uri sourceUri = this.GetSourceUri(); string ourBaseUriString = sourceUri.GetComponents(UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); DateTimeOffset? baseSnapshot = null; DateTimeOffset? ourSnapshot = null == this.SourceBlob ? null : this.SourceBlob.SnapshotTime; string snapshotString; if (ParseQueryString(copyState.Source.Query).TryGetValue("snapshot", out snapshotString)) { if (!string.IsNullOrEmpty(snapshotString)) { DateTimeOffset snapshotTime; if (DateTimeOffset.TryParse( snapshotString, CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out snapshotTime)) { baseSnapshot = snapshotTime; } } } if (!baseUriString.Equals(ourBaseUriString) || !baseSnapshot.Equals(ourSnapshot)) { return false; } if (string.IsNullOrEmpty(this.TransferJob.CopyId)) { this.TransferJob.CopyId = copyState.CopyId; } } else { return false; } } this.TransferJob.Status = TransferJobStatus.Monitor; this.state = State.GetCopyState; this.TransferJob.Transfer.UpdateJournal(); this.hasWork = true; return true; } private async Task GetCopyStateAsync() { Debug.Assert( this.state == State.GetCopyState, "GetCopyStateAsync called, but state isn't GetCopyState"); this.hasWork = false; this.StartCallbackHandler(); StorageCopyState copyState = null; try { copyState = await this.FetchCopyStateAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception e) when (e is StorageException || (e is AggregateException && e.InnerException is StorageException)) { var se = e as StorageException ?? e.InnerException as StorageException; #else catch (StorageException se) { #endif if (null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { // The reason of 404 (Not Found) may be that the destination blob has not been created yet. this.RestartTimer(); } else { throw; } } await this.HandleFetchCopyStateResultAsync(copyState); } // In this method, it may need to set customized properties to destination. // If this method is invoked just after StartCopyAsync, // properties on destination instance may not be totally the same with the one on server. // If this is the case, it should try to fetch attributes from server first. private async Task HandleFetchCopyStateResultAsync( StorageCopyState copyState, bool gotDestinationAttributes = true) { if (null == copyState) { // Reach here, the destination should already exist. string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToRetrieveCopyStateForObjectException, this.DestUri.ToString()); throw new TransferException( TransferErrorCode.FailToRetrieveCopyStateForObject, exceptionMessage); } else { // Verify we are monitoring the right blob copying process. if (!this.TransferJob.CopyId.Equals(copyState.CopyId)) { throw new TransferException( TransferErrorCode.MismatchCopyId, Resources.MismatchFoundBetweenLocalAndServerCopyIdsException); } if (StorageCopyStatus.Success == copyState.Status) { this.UpdateTransferProgress(copyState); this.DisposeStatusRefreshTimer(); if (null != this.TransferContext && null != this.TransferContext.SetAttributesCallbackAsync) { if (!gotDestinationAttributes) { await this.DoFetchDestAttributesAsync(); } // If got here, we've done FetchAttributes on destination after copying completed on server, // no need to one more round of FetchAttributes anymore. await this.SetAttributesAsync(this.TransferContext.SetAttributesCallbackAsync); } this.SetFinished(); } else if (StorageCopyStatus.Pending == copyState.Status) { this.UpdateTransferProgress(copyState); // Wait a period to restart refresh the status. this.RestartTimer(); } else { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToAsyncCopyObjectException, this.GetSourceUri().ToString(), this.DestUri.ToString(), copyState.Status.ToString(), copyState.StatusDescription); // CopyStatus.Invalid | Failed | Aborted throw new TransferException( TransferErrorCode.AsyncCopyFailed, exceptionMessage); } } } private void UpdateTransferProgress(StorageCopyState copyState) { if (null != copyState && copyState.TotalBytes.HasValue) { Debug.Assert( copyState.BytesCopied.HasValue, "BytesCopied cannot be null as TotalBytes is not null."); if (this.approachingFinish == false && copyState.TotalBytes - copyState.BytesCopied <= Constants.CopyApproachingFinishThresholdInBytes) { this.approachingFinish = true; } if (this.TransferContext != null) { long bytesTransferred = copyState.BytesCopied.Value; this.UpdateProgress(() => { this.UpdateProgressAddBytesTransferred(bytesTransferred - this.lastBytesCopied); }); this.lastBytesCopied = bytesTransferred; } } } private void SetFinished() { this.state = State.Finished; this.hasWork = false; this.FinishCallbackHandler(null); } private void RestartTimer() { if (this.approachingFinish) { this.statusRefreshWaitTime = Constants.CopyStatusRefreshMinWaitTimeInMilliseconds; } else if (this.statusRefreshRequestCount >= Constants.CopyStatusRefreshWaitTimeMaxRequestCount && this.statusRefreshWaitTime < Constants.CopyStatusRefreshMaxWaitTimeInMilliseconds) { this.statusRefreshRequestCount = 0; this.statusRefreshWaitTime *= 10; this.statusRefreshWaitTime = Math.Min(this.statusRefreshWaitTime, Constants.CopyStatusRefreshMaxWaitTimeInMilliseconds); } else if (this.statusRefreshWaitTime < Constants.CopyStatusRefreshMaxWaitTimeInMilliseconds) { this.statusRefreshRequestCount++; } // Wait a period to restart refresh the status. this.statusRefreshTimer.Change( TimeSpan.FromMilliseconds(this.statusRefreshWaitTime), new TimeSpan(-1)); } private void DisposeStatusRefreshTimer() { if (null != this.statusRefreshTimer) { lock (this.statusRefreshTimerLock) { if (null != this.statusRefreshTimer) { this.statusRefreshTimer.Dispose(); this.statusRefreshTimer = null; } } } } private Uri GetSourceUri() { if (null != this.SourceUri) { return this.SourceUri; } if (null != this.SourceBlob) { return this.SourceBlob.SnapshotQualifiedUri; } return this.SourceFile.SnapshotQualifiedUri; } protected async Task DoFetchSourceAttributesAsync() { if (this.TransferJob.Source.Type == TransferLocationType.AzureBlob) { AzureBlobLocation sourceLocation = this.TransferJob.Source as AzureBlobLocation; AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( sourceLocation.AccessCondition, sourceLocation.CheckedAccessCondition); OperationContext operationContext = Utils.GenerateOperationContext(this.TransferContext); await sourceLocation.Blob.FetchAttributesAsync( accessCondition, Utils.GenerateBlobRequestOptions(sourceLocation.BlobRequestOptions), operationContext, this.CancellationToken); } else if(this.TransferJob.Source.Type == TransferLocationType.AzureFile) { AzureFileLocation sourceLocation = this.TransferJob.Source as AzureFileLocation; AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( sourceLocation.AccessCondition, sourceLocation.CheckedAccessCondition); OperationContext operationContext = Utils.GenerateOperationContext(this.TransferContext); await sourceLocation.AzureFile.FetchAttributesAsync( accessCondition, Utils.GenerateFileRequestOptions(sourceLocation.FileRequestOptions), operationContext, this.CancellationToken); } } protected abstract Task DoFetchDestAttributesAsync(); protected abstract Task<StorageCopyState> DoStartCopyAsync(); protected abstract void DoHandleGetDestinationException(StorageException se); protected abstract Task<StorageCopyState> FetchCopyStateAsync(); protected abstract Task SetAttributesAsync(SetAttributesCallbackAsync setAttributes); } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion namespace Nancy.Helpers { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; internal static class ReflectionUtils { public static bool IsInstantiatableType(Type t) { if (t == null) throw new ArgumentNullException("t"); if (t.IsAbstract || t.IsInterface || t.IsArray) return false; if (!HasDefaultConstructor(t)) return false; return true; } public static bool HasDefaultConstructor(Type t) { if (t == null) throw new ArgumentNullException("t"); return (t.GetConstructor(BindingFlags.Instance, null, Type.EmptyTypes, null) != null); } public static bool IsAssignable(Type to, Type from) { if (to == null) throw new ArgumentNullException("to"); if (to.IsAssignableFrom(from)) return true; if (to.IsGenericType && from.IsGenericTypeDefinition) return to.IsAssignableFrom(from.MakeGenericType(to.GetGenericArguments())); return false; } public static bool IsSubClass(Type type, Type check) { if (type == null || check == null) return false; if (type == check) return true; if (check.IsInterface) { foreach (Type t in type.GetInterfaces()) { if (IsSubClass(t, check)) return true; } } if (type.IsGenericType && !type.IsGenericTypeDefinition) { if (IsSubClass(type.GetGenericTypeDefinition(), check)) return true; } return IsSubClass(type.BaseType, check); } /// <summary> /// Gets the type of the typed list's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed list's items.</returns> public static Type GetTypedListItemType(Type type) { if (type == null) throw new ArgumentNullException("type"); if (type.IsArray) return type.GetElementType (); else if (type.IsGenericType && typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition())) return type.GetGenericArguments()[0]; else throw new Exception("Bad type"); } public static Type GetTypedDictionaryValueType(Type type) { if (type == null) throw new ArgumentNullException("type"); Type genDictType = GetGenericDictionary(type); if (genDictType != null) return genDictType.GetGenericArguments () [1]; else if (typeof(IDictionary).IsAssignableFrom(type)) return null; else throw new Exception("Bad type"); } static readonly Type GenericDictionaryType = typeof(IDictionary<,>); public static Type GetGenericDictionary(Type type) { if (type.IsGenericType && GenericDictionaryType.IsAssignableFrom (type.GetGenericTypeDefinition())) return type; Type[] ifaces = type.GetInterfaces(); if (ifaces != null) for (int i = 0; i < ifaces.Length; i++) { Type current = GetGenericDictionary (ifaces[i]); if (current != null) return current; } return null; } public static Type GetMemberUnderlyingType(MemberInfo member) { switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { if (member == null) throw new ArgumentNullException("member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo)member).GetValue(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo has index parameters", "member", e); } default: throw new ArgumentException("MemberInfo is not of type FieldInfo or PropertyInfo", "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { switch (member.MemberType) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo must be if type FieldInfo or PropertyInfo", "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member) { switch (member.MemberType) { case MemberTypes.Field: return true; case MemberTypes.Property: return ((PropertyInfo) member).CanRead; default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member) { switch (member.MemberType) { case MemberTypes.Field: return true; case MemberTypes.Property: return ((PropertyInfo)member).CanWrite; default: return false; } } public static IEnumerable<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { MemberInfo[] members = type.GetFields(bindingAttr); for (int i = 0; i < members.Length; i++) yield return members[i]; members = type.GetProperties(bindingAttr); for (int i = 0; i < members.Length; i++) yield return members[i]; } } }