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 System.IO; using TokenStream = Lucene.Net.Analysis.TokenStream; using StringHelper = Lucene.Net.Util.StringHelper; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; namespace Lucene.Net.Documents { /// <summary> /// /// /// </summary> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public abstract class AbstractField : IFieldable { protected internal System.String internalName = "body"; protected internal bool storeTermVector = false; protected internal bool storeOffsetWithTermVector = false; protected internal bool storePositionWithTermVector = false; protected internal bool internalOmitNorms = false; protected internal bool internalIsStored = false; protected internal bool internalIsIndexed = true; protected internal bool internalIsTokenized = true; protected internal bool internalIsBinary = false; protected internal bool lazy = false; protected internal bool internalOmitTermFreqAndPositions = false; protected internal float internalBoost = 1.0f; // the data object for all different kind of field values protected internal System.Object fieldsData = null; // pre-analyzed tokenStream for indexed fields protected internal TokenStream tokenStream; // length/offset for all primitive types protected internal int internalBinaryLength; protected internal int internalbinaryOffset; protected internal AbstractField() { } protected internal AbstractField(System.String name, Field.Store store, Field.Index index, Field.TermVector termVector) { if (name == null) throw new System.NullReferenceException("name cannot be null"); this.internalName = StringHelper.Intern(name); // field names are interned this.internalIsStored = store.IsStored(); this.internalIsIndexed = index.IsIndexed(); this.internalIsTokenized = index.IsAnalyzed(); this.internalOmitNorms = index.OmitNorms(); this.internalIsBinary = false; SetStoreTermVector(termVector); } /// <summary>Gets or sets the boost factor for hits for this field. /// /// <p/>The default value is 1.0. /// /// <p/>Note: this value is not stored directly with the document in the index. /// Documents returned from <see cref="Lucene.Net.Index.IndexReader.Document(int)" /> and /// <see cref="Lucene.Net.Search.Searcher.Doc(int)" /> may thus not have the same value present as when /// this field was indexed. /// </summary> public virtual float Boost { get { return internalBoost; } set { this.internalBoost = value; } } /// <summary>Returns the name of the field as an interned string. /// For example "date", "title", "body", ... /// </summary> public virtual string Name { get { return internalName; } } protected internal virtual void SetStoreTermVector(Field.TermVector termVector) { this.storeTermVector = termVector.IsStored(); this.storePositionWithTermVector = termVector.WithPositions(); this.storeOffsetWithTermVector = termVector.WithOffsets(); } /// <summary>True iff the value of the field is to be stored in the index for return /// with search hits. It is an error for this to be true if a field is /// Reader-valued. /// </summary> public bool IsStored { get { return internalIsStored; } } /// <summary>True iff the value of the field is to be indexed, so that it may be /// searched on. /// </summary> public bool IsIndexed { get { return internalIsIndexed; } } /// <summary>True iff the value of the field should be tokenized as text prior to /// indexing. Un-tokenized fields are indexed as a single word and may not be /// Reader-valued. /// </summary> public bool IsTokenized { get { return internalIsTokenized; } } /// <summary>True iff the term or terms used to index this field are stored as a term /// vector, available from <see cref="Lucene.Net.Index.IndexReader.GetTermFreqVector(int,String)" />. /// These methods do not provide access to the original content of the field, /// only to terms used to index it. If the original content must be /// preserved, use the <c>stored</c> attribute instead. /// /// </summary> /// <seealso cref="Lucene.Net.Index.IndexReader.GetTermFreqVector(int, String)"> /// </seealso> public bool IsTermVectorStored { get { return storeTermVector; } } /// <summary> True iff terms are stored as term vector together with their offsets /// (start and end position in source text). /// </summary> public virtual bool IsStoreOffsetWithTermVector { get { return storeOffsetWithTermVector; } } /// <summary> True iff terms are stored as term vector together with their token positions.</summary> public virtual bool IsStorePositionWithTermVector { get { return storePositionWithTermVector; } } /// <summary>True iff the value of the filed is stored as binary </summary> public bool IsBinary { get { return internalIsBinary; } } /// <summary> Return the raw byte[] for the binary field. Note that /// you must also call <see cref="BinaryLength" /> and <see cref="BinaryOffset" /> /// to know which range of bytes in this /// returned array belong to the field. /// </summary> /// <returns> reference to the Field value as byte[]. </returns> public virtual byte[] GetBinaryValue() { return GetBinaryValue(null); } public virtual byte[] GetBinaryValue(byte[] result) { if (internalIsBinary || fieldsData is byte[]) return (byte[]) fieldsData; else return null; } /// <summary> Returns length of byte[] segment that is used as value, if Field is not binary /// returned value is undefined /// </summary> /// <value> length of byte[] segment that represents this Field value </value> public virtual int BinaryLength { get { if (internalIsBinary) { return internalBinaryLength; } return fieldsData is byte[] ? ((byte[]) fieldsData).Length : 0; } } /// <summary> Returns offset into byte[] segment that is used as value, if Field is not binary /// returned value is undefined /// </summary> /// <value> index of the first character in byte[] segment that represents this Field value </value> public virtual int BinaryOffset { get { return internalbinaryOffset; } } /// <summary>True if norms are omitted for this indexed field </summary> public virtual bool OmitNorms { get { return internalOmitNorms; } set { this.internalOmitNorms = value; } } /// <summary>Expert: /// /// If set, omit term freq, positions and payloads from /// postings for this field. /// /// <p/><b>NOTE</b>: While this option reduces storage space /// required in the index, it also means any query /// requiring positional information, such as <see cref="PhraseQuery" /> /// or <see cref="SpanQuery" /> subclasses will /// silently fail to find results. /// </summary> public virtual bool OmitTermFreqAndPositions { set { this.internalOmitTermFreqAndPositions = value; } get { return internalOmitTermFreqAndPositions; } } public virtual bool IsLazy { get { return lazy; } } /// <summary>Prints a Field for human consumption. </summary> public override System.String ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder(); if (internalIsStored) { result.Append("stored"); } if (internalIsIndexed) { if (result.Length > 0) result.Append(","); result.Append("indexed"); } if (internalIsTokenized) { if (result.Length > 0) result.Append(","); result.Append("tokenized"); } if (storeTermVector) { if (result.Length > 0) result.Append(","); result.Append("termVector"); } if (storeOffsetWithTermVector) { if (result.Length > 0) result.Append(","); result.Append("termVectorOffsets"); } if (storePositionWithTermVector) { if (result.Length > 0) result.Append(","); result.Append("termVectorPosition"); } if (internalIsBinary) { if (result.Length > 0) result.Append(","); result.Append("binary"); } if (internalOmitNorms) { result.Append(",omitNorms"); } if (internalOmitTermFreqAndPositions) { result.Append(",omitTermFreqAndPositions"); } if (lazy) { result.Append(",lazy"); } result.Append('<'); result.Append(internalName); result.Append(':'); if (fieldsData != null && lazy == false) { result.Append(fieldsData); } result.Append('>'); return result.ToString(); } public abstract TokenStream TokenStreamValue { get; } public abstract TextReader ReaderValue { get; } public abstract string StringValue { get; } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; namespace Grpc.Core { /// <summary> /// Server is implemented only to be able to do /// in-process testing. /// </summary> public class Server { // TODO: make sure the delegate doesn't get garbage collected while // native callbacks are in the completion queue. readonly ServerShutdownCallbackDelegate serverShutdownHandler; readonly CompletionCallbackDelegate newServerRpcHandler; readonly BlockingCollection<NewRpcInfo> newRpcQueue = new BlockingCollection<NewRpcInfo>(); readonly ServerSafeHandle handle; readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); public Server() { this.handle = ServerSafeHandle.NewServer(GetCompletionQueue(), IntPtr.Zero); this.newServerRpcHandler = HandleNewServerRpc; this.serverShutdownHandler = HandleServerShutdown; } // only call this before Start() public void AddServiceDefinition(ServerServiceDefinition serviceDefinition) { foreach(var entry in serviceDefinition.CallHandlers) { callHandlers.Add(entry.Key, entry.Value); } } // only call before Start() public int AddPort(string addr) { return handle.AddPort(addr); } // only call before Start() public int AddPort(string addr, ServerCredentials credentials) { using (var nativeCredentials = credentials.ToNativeCredentials()) { return handle.AddPort(addr, nativeCredentials); } } public void Start() { handle.Start(); // TODO: this basically means the server is single threaded.... StartHandlingRpcs(); } /// <summary> /// Requests and handles single RPC call. /// </summary> internal void RunRpc() { AllowOneRpc(); try { var rpcInfo = newRpcQueue.Take(); //Console.WriteLine("Server received RPC " + rpcInfo.Method); IServerCallHandler callHandler; if (!callHandlers.TryGetValue(rpcInfo.Method, out callHandler)) { callHandler = new NoSuchMethodCallHandler(); } callHandler.StartCall(rpcInfo.Method, rpcInfo.Call, GetCompletionQueue()); } catch(Exception e) { Console.WriteLine("Exception while handling RPC: " + e); } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. /// </summary> /// <returns>The async.</returns> public async Task ShutdownAsync() { handle.ShutdownAndNotify(serverShutdownHandler); await shutdownTcs.Task; handle.Dispose(); } /// <summary> /// To allow awaiting termination of the server. /// </summary> public Task ShutdownTask { get { return shutdownTcs.Task; } } public void Kill() { handle.Dispose(); } private async Task StartHandlingRpcs() { while (true) { await Task.Factory.StartNew(RunRpc); } } private void AllowOneRpc() { AssertCallOk(handle.RequestCall(GetCompletionQueue(), newServerRpcHandler)); } private void HandleNewServerRpc(GRPCOpError error, IntPtr batchContextPtr) { try { var ctx = new BatchContextSafeHandleNotOwned(batchContextPtr); if (error != GRPCOpError.GRPC_OP_OK) { // TODO: handle error } var rpcInfo = new NewRpcInfo(ctx.GetServerRpcNewCall(), ctx.GetServerRpcNewMethod()); // after server shutdown, the callback returns with null call if (!rpcInfo.Call.IsInvalid) { newRpcQueue.Add(rpcInfo); } } catch(Exception e) { Console.WriteLine("Caught exception in a native handler: " + e); } } private void HandleServerShutdown(IntPtr eventPtr) { try { shutdownTcs.SetResult(null); } catch (Exception e) { Console.WriteLine("Caught exception in a native handler: " + e); } } private static void AssertCallOk(GRPCCallError callError) { Trace.Assert(callError == GRPCCallError.GRPC_CALL_OK, "Status not GRPC_CALL_OK"); } private static CompletionQueueSafeHandle GetCompletionQueue() { return GrpcEnvironment.ThreadPool.CompletionQueue; } private struct NewRpcInfo { private CallSafeHandle call; private string method; public NewRpcInfo(CallSafeHandle call, string method) { this.call = call; this.method = method; } public CallSafeHandle Call { get { return this.call; } } public string Method { get { return this.method; } } } } }
// // 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.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.Azure.Commands.Compute.Automation { public abstract class ComputeAutomationBaseCmdlet : Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); } protected static PSArgument[] ConvertFromObjectsToArguments(string[] names, object[] objects) { var arguments = new PSArgument[objects.Length]; for (int index = 0; index < objects.Length; index++) { arguments[index] = new PSArgument { Name = names[index], Type = objects[index].GetType(), Value = objects[index] }; } return arguments; } protected static object[] ConvertFromArgumentsToObjects(object[] arguments) { if (arguments == null) { return null; } var objects = new object[arguments.Length]; for (int index = 0; index < arguments.Length; index++) { if (arguments[index] is PSArgument) { objects[index] = ((PSArgument)arguments[index]).Value; } else { objects[index] = arguments[index]; } } return objects; } public IContainerServicesOperations ContainerServicesClient { get { return ComputeClient.ComputeManagementClient.ContainerServices; } } public IDisksOperations DisksClient { get { return ComputeClient.ComputeManagementClient.Disks; } } public IGalleriesOperations GalleriesClient { get { return ComputeClient.ComputeManagementClient.Galleries; } } public IGalleryImagesOperations GalleryImagesClient { get { return ComputeClient.ComputeManagementClient.GalleryImages; } } public IGalleryImageVersionsOperations GalleryImageVersionsClient { get { return ComputeClient.ComputeManagementClient.GalleryImageVersions; } } public IImagesOperations ImagesClient { get { return ComputeClient.ComputeManagementClient.Images; } } public ILogAnalyticsOperations LogAnalyticsClient { get { return ComputeClient.ComputeManagementClient.LogAnalytics; } } public IResourceSkusOperations ResourceSkusClient { get { return ComputeClient.ComputeManagementClient.ResourceSkus; } } public ISnapshotsOperations SnapshotsClient { get { return ComputeClient.ComputeManagementClient.Snapshots; } } public IVirtualMachineRunCommandsOperations VirtualMachineRunCommandsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineRunCommands; } } public IVirtualMachineScaleSetRollingUpgradesOperations VirtualMachineScaleSetRollingUpgradesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetRollingUpgrades; } } public IVirtualMachineScaleSetsOperations VirtualMachineScaleSetsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSets; } } public IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetVMs; } } public IVirtualMachinesOperations VirtualMachinesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachines; } } public static string FormatObject(Object obj) { var objType = obj.GetType(); System.Reflection.PropertyInfo[] pros = objType.GetProperties(); string result = "\n"; var resultTuples = new List<Tuple<string, string, int>>(); var totalTab = GetTabLength(obj, 0, 0, resultTuples) + 1; foreach (var t in resultTuples) { string preTab = new string(' ', t.Item3 * 2); string postTab = new string(' ', totalTab - t.Item3 * 2 - t.Item1.Length); result += preTab + t.Item1 + postTab + ": " + t.Item2 + "\n"; } return result; } private static int GetTabLength(Object obj, int max, int depth, List<Tuple<string, string, int>> tupleList) { var objType = obj.GetType(); var propertySet = new List<PropertyInfo>(); if (objType.BaseType != null) { foreach (var property in objType.BaseType.GetProperties()) { propertySet.Add(property); } } foreach (var property in objType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) { propertySet.Add(property); } foreach (var property in propertySet) { Object childObject = property.GetValue(obj, null); var isJObject = childObject as Newtonsoft.Json.Linq.JObject; if (isJObject != null) { var objStringValue = Newtonsoft.Json.JsonConvert.SerializeObject(childObject); int i = objStringValue.IndexOf("xmlCfg"); if (i >= 0) { var xmlCfgString = objStringValue.Substring(i + 7); int start = xmlCfgString.IndexOf('"'); int end = xmlCfgString.IndexOf('"', start + 1); xmlCfgString = xmlCfgString.Substring(start + 1, end - start - 1); objStringValue = objStringValue.Replace(xmlCfgString, "..."); } tupleList.Add(MakeTuple(property.Name, objStringValue, depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else { var elem = childObject as IList; if (elem != null) { if (elem.Count != 0) { max = Math.Max(max, depth * 2 + property.Name.Length + 4); for (int i = 0; i < elem.Count; i++) { Type propType = elem[i].GetType(); if (propType.IsSerializable || propType.Equals(typeof(Newtonsoft.Json.Linq.JObject))) { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", elem[i].ToString(), depth)); } else { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", "", depth)); max = Math.Max(max, GetTabLength((Object)elem[i], max, depth + 1, tupleList)); } } } } else { if (property.PropertyType.IsSerializable) { if (childObject != null) { tupleList.Add(MakeTuple(property.Name, childObject.ToString(), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } } else { var isDictionary = childObject as IDictionary; if (isDictionary != null) { tupleList.Add(MakeTuple(property.Name, Newtonsoft.Json.JsonConvert.SerializeObject(childObject), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else if (childObject != null) { tupleList.Add(MakeTuple(property.Name, "", depth)); max = Math.Max(max, GetTabLength(childObject, max, depth + 1, tupleList)); } } } } } return max; } private static Tuple<string, string, int> MakeTuple(string key, string value, int depth) { return new Tuple<string, string, int>(key, value, depth); } public static string GetResourceGroupName(string resourceId) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = new Regex(@"(.*?)/resourcegroups/(?<rgname>\S+)/providers/(.*?)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["rgname"].Value : null; } public static string GetResourceName(string resourceId, string resourceName, string instanceName = null, string version = null) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = (instanceName == null && version == null) ? new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)", RegexOptions.IgnoreCase) : new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)/" + instanceName + @"/(?<instanceId>\S+)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["rgname"].Value : null; } public static string GetInstanceId(string resourceId, string resourceName, string instanceName, string version = null) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = (version == null) ? new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)/" + instanceName + @"/(?<instanceId>\S+)", RegexOptions.IgnoreCase) : new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)/" + instanceName + @"/(?<instanceId>\S+)/" + version + @"/(?<version>\S+)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["instanceId"].Value : null; } public static string GetVersion(string resourceId, string resourceName, string instanceName, string version) { if (string.IsNullOrEmpty(resourceId)) { return null; } Regex r = new Regex(@"(.*?)/" + resourceName + @"/(?<rgname>\S+)/" + instanceName + @"/(?<instanceId>\S+)/" + version + @"/(?<version>\S+)", RegexOptions.IgnoreCase); Match m = r.Match(resourceId); return m.Success ? m.Groups["version"].Value : null; } } public static class LocationStringExtensions { public static string Canonicalize(this string location) { if (!string.IsNullOrEmpty(location)) { StringBuilder sb = new StringBuilder(); foreach (char ch in location) { if (!char.IsWhiteSpace(ch)) { sb.Append(ch); } } location = sb.ToString().ToLower(); } return location; } } }
#region License // Copyright (c) 2010 Ross McDermott // 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 Microsoft.SPOT; using System.Collections; namespace NetMf.CommonExtensions { /// <summary> /// Provides additional standard string operations /// </summary> public abstract class StringUtility { /// <summary> /// Check if the provided string is either null or empty /// </summary> /// <param name="str">String to validate</param> /// <returns>True if the string is null or empty</returns> public static bool IsNullOrEmpty(string str) { if (str == null || str == string.Empty) return true; return false; } /// <summary> /// Replaces one or more format items in a specified string with the string representation of a specified object. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg">The object to format.</param> /// <returns>A copy of format in which any format items are replaced by the string representation of arg0.</returns> /// <exception cref="NetMf.CommonExtensions.FormatException">format is invalid, or the index of a format item is less than zero, or greater than or equal to the length of the args array.</exception> /// <exception cref="System.ArgumentNullException">format or args is null</exception> public static string Format(string format, object arg) { return Format(format, new object[] { arg }); } /// <summary> /// Format the given string using the provided collection of objects. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns> /// <exception cref="NetMf.CommonExtensions.FormatException">format is invalid, or the index of a format item is less than zero, or greater than or equal to the length of the args array.</exception> /// <exception cref="System.ArgumentNullException">format or args is null</exception> /// <example> /// x = StringUtility.Format("Quick brown {0}","fox"); /// </example> public static string Format(string format, params object[] args) { if (format == null) throw new ArgumentNullException("format"); if (args == null) throw new ArgumentNullException("args"); // Validate the structure of the format string. ValidateFormatString(format); StringBuilder bld = new StringBuilder(); int endOfLastMatch = 0; int starting = 0; while (starting >= 0) { starting = format.IndexOf('{', starting); if (starting >= 0) { if (starting != format.Length - 1) { if (format[starting + 1] == '{') { // escaped starting bracket. starting = starting + 2; continue; } else { bool found = false; int endsearch = format.IndexOf('}', starting); while(endsearch > starting) { if (endsearch != (format.Length - 1) && format[endsearch + 1] == '}') { // escaped ending bracket endsearch = endsearch + 2; } else { if(starting != endOfLastMatch) { string t = format.Substring(endOfLastMatch, starting - endOfLastMatch); t = t.Replace("{{", "{"); // get rid of the escaped brace t = t.Replace("}}", "}"); // get rid of the escaped brace bld.Append(t); } // we have a winner string fmt = format.Substring(starting, endsearch-starting + 1); if (fmt.Length >= 3) { fmt = fmt.Substring(1, fmt.Length - 2); string[] indexFormat = fmt.Split(new char[] { ':' }); string formatString = string.Empty; if (indexFormat.Length == 2) { formatString = indexFormat[1]; } int index = 0; // no format, just number if (Parse.TryParseInt(indexFormat[0], out index)) { bld.Append(FormatParameter(args[index], formatString)); } else { throw new FormatException(FormatException.ERROR_MESSAGE); } } endOfLastMatch = endsearch + 1; found = true; starting = endsearch + 1; break; } endsearch = format.IndexOf('}', endsearch); } // need to find the ending point if(!found) { throw new FormatException(FormatException.ERROR_MESSAGE); } } } else { // invalid throw new FormatException(FormatException.ERROR_MESSAGE); } } } // copy any additional remaining part of the format string. if (endOfLastMatch != format.Length) { bld.Append(format.Substring(endOfLastMatch, format.Length - endOfLastMatch)); } return bld.ToString(); } private static void ValidateFormatString(string format) { char expected = '{'; int i = 0; while ((i = format.IndexOfAny(new char[] { '{', '}' }, i)) >= 0) { if (i < (format.Length - 1) && format[i] == format[i + 1]) { // escaped brace. continue looking. i = i + 2; continue; } else if (format[i] != expected) { // badly formed string. throw new FormatException(FormatException.ERROR_MESSAGE); } else { // move it along. i++; // expected it. if (expected == '{') expected = '}'; else expected = '{'; } } if (expected == '}') { // orpaned opening brace. Bad format. throw new FormatException(FormatException.ERROR_MESSAGE); } } /// <summary> /// Format the provided object using the provided format string. /// </summary> /// <param name="p">Object to be formatted</param> /// <param name="formatString">Format string to be applied to the object</param> /// <returns>Formatted string for the object</returns> private static string FormatParameter(object p, string formatString) { if (formatString == string.Empty) return p.ToString(); if (p as IFormattable != null) { return ((IFormattable)p).ToString(formatString,null); } else if (p is DateTime) { return ((DateTime)p).ToString(formatString); } else if (p is Double) { return ((Double)p).ToString(formatString); } else if (p is Int16) { return ((Int16)p).ToString(formatString); } else if (p is Int32) { return ((Int32)p).ToString(formatString); } else if (p is Int64) { return ((Int64)p).ToString(formatString); } else if (p is SByte) { return ((SByte)p).ToString(formatString); } else if (p is Single) { return ((Single)p).ToString(formatString); } else if (p is UInt16) { return ((UInt16)p).ToString(formatString); } else if (p is UInt32) { return ((UInt32)p).ToString(formatString); } else if (p is UInt64) { return ((UInt64)p).ToString(formatString); } else { return p.ToString(); } } } }
#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; using System.Linq; using System.Abstract; using System.Collections.Generic; namespace Contoso.Abstract { /// <remark> /// An static dictionary specific service cache interface /// </remark> public interface IStaticServiceCache : IServiceCache { /// <summary> /// Gets the cache. /// </summary> Dictionary<string, object> Cache { get; } } //: might need to make thread safe /// <summary> /// /// </summary> /// <remark> /// Provides a static dictionary adapter for the service cache sub-system. /// </remark> /// <example> /// ServiceCacheManager.SetProvider(() =&gt; new StaticServiceCache()) /// </example> public class StaticServiceCache : IStaticServiceCache, ServiceCacheManager.ISetupRegistration { private static readonly Dictionary<string, object> _cache = new Dictionary<string, object>(); static StaticServiceCache() { ServiceCacheManager.EnsureRegistration(); } /// <summary> /// Initializes a new instance of the <see cref="StaticServiceCache"/> class. /// </summary> public StaticServiceCache() { Settings = new ServiceCacheSettings(new DefaultFileTouchableCacheItem(this, new DefaultTouchableCacheItem(this, null))); } Action<IServiceLocator, string> ServiceCacheManager.ISetupRegistration.DefaultServiceRegistrar { get { return (locator, name) => ServiceCacheManager.RegisterInstance<IStaticServiceCache>(this, locator, name); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An object that specifies the type of service object to get.</param> /// <returns> /// A service object of type <paramref name="serviceType"/>. /// -or- /// null if there is no service object of type <paramref name="serviceType"/>. /// </returns> public object GetService(Type serviceType) { throw new NotImplementedException(); } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified name. /// </summary> public object this[string name] { get { return Get(null, name); } set { Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); } } /// <summary> /// Adds an object into cache based on the parameters provided. /// </summary> /// <param name="tag">Not used</param> /// <param name="name">The key used to identify the item in cache.</param> /// <param name="itemPolicy">Not used</param> /// <param name="value">The value to store in cache.</param> /// <param name="dispatch">Not used</param> /// <returns>Last value that what in cache.</returns> public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch) { // TODO: Throw on dependency or other stuff not supported by this simple system object lastValue; if (!_cache.TryGetValue(name, out lastValue)) { _cache[name] = value; var registration = dispatch.Registration; if (registration != null && registration.UseHeaders) { var header = dispatch.Header; header.Item = name; _cache[name + "#"] = header; } return null; } return lastValue; } /// <summary> /// Gets the item from cache associated with the key provided. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The key.</param> /// <returns> /// The cached item. /// </returns> public object Get(object tag, string name) { object value; return (_cache.TryGetValue(name, out value) ? value : null); } /// <summary> /// Gets the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="registration">The registration.</param> /// <param name="header">The header.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header) { if (registration == null) throw new ArgumentNullException("registration"); object value; header = (registration.UseHeaders && _cache.TryGetValue(name + "#", out value) ? (CacheItemHeader)value : null); return (_cache.TryGetValue(name, out value) ? value : null); } /// <summary> /// Gets the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> /// <returns></returns> public object Get(object tag, IEnumerable<string> names) { if (names == null) throw new ArgumentNullException("names"); return names.Select(name => new { name, value = Get(null, name) }).ToDictionary(x => x.name, x => x.value); } /// <summary> /// Gets the specified registration. /// </summary> /// <param name="tag">The tag.</param> /// <param name="registration">The registration.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration) { if (registration == null) throw new ArgumentNullException("registration"); var registrationName = registration.AbsoluteName + "#"; CacheItemHeader value; var e = _cache.GetEnumerator(); while (e.MoveNext()) { var current = e.Current; var key = current.Key; if (key == null || !key.EndsWith(registrationName) || (value = (current.Value as CacheItemHeader)) == null) continue; yield return value; } } /// <summary> /// Tries the get. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool TryGet(object tag, string name, out object value) { return _cache.TryGetValue(name, out value); } /// <summary> /// Adds an object into cache based on the parameters provided. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name used to identify the item in cache.</param> /// <param name="itemPolicy">The itemPolicy defining caching policies.</param> /// <param name="value">The value to store in cache.</param> /// <param name="dispatch"></param> /// <returns></returns> public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch) { _cache[name] = value; var registration = dispatch.Registration; if (registration != null && registration.UseHeaders) { var header = dispatch.Header; header.Item = name; _cache[name + "#"] = header; } return value; } /// <summary> /// Removes from cache the item associated with the key provided. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The key.</param> /// <param name="registration">The registration.</param> /// <returns> /// The item removed from the Cache. If the value in the key parameter is not found, returns null. /// </returns> public object Remove(object tag, string name, IServiceCacheRegistration registration) { object value; if (_cache.TryGetValue(name, out value)) { if (registration != null && registration.UseHeaders) _cache.Remove(name + "#"); _cache.Remove(name); return value; } return null; } /// <summary> /// Settings /// </summary> public ServiceCacheSettings Settings { get; private set; } #region TouchableCacheItem /// <summary> /// DefaultTouchableCacheItem /// </summary> public class DefaultTouchableCacheItem : ITouchableCacheItem { private StaticServiceCache _parent; private ITouchableCacheItem _base; /// <summary> /// Initializes a new instance of the <see cref="DefaultTouchableCacheItem"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="base">The @base.</param> public DefaultTouchableCacheItem(StaticServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; } /// <summary> /// Touches the specified tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> public void Touch(object tag, string[] names) { if (names == null || names.Length == 0) return; _cache.Clear(); if (_base != null) _base.Touch(tag, names); } /// <summary> /// Makes the dependency. /// </summary> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> /// <returns></returns> public object MakeDependency(object tag, string[] names) { if (names == null || names.Length == 0) return null; throw new NotSupportedException(); } } /// <summary> /// DefaultFileTouchableCacheItem /// </summary> public class DefaultFileTouchableCacheItem : ServiceCache.FileTouchableCacheItemBase { /// <summary> /// Initializes a new instance of the <see cref="DefaultFileTouchableCacheItem"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="base">The @base.</param> public DefaultFileTouchableCacheItem(StaticServiceCache parent, ITouchableCacheItem @base) : base(parent, @base) { } /// <summary> /// Makes the dependency internal. /// </summary> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> /// <returns></returns> protected override object MakeDependencyInternal(object tag, string[] names) { return null; } } #endregion #region Domain-specific /// <summary> /// Gets the cache. /// </summary> public Dictionary<string, object> Cache { get { return _cache; } } #endregion } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.DepthFrameReader // public sealed partial class DepthFrameReader : RootSystem.IDisposable, Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal DepthFrameReader(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_DepthFrameReader_AddRefObject(ref _pNative); } ~DepthFrameReader() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_DepthFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_DepthFrameReader_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } Helper.NativeObjectCache.RemoveObject<DepthFrameReader>(_pNative); if (disposing) { Windows_Kinect_DepthFrameReader_Dispose(_pNative); } Windows_Kinect_DepthFrameReader_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_DepthFrameReader_get_DepthFrameSource(RootSystem.IntPtr pNative); public Windows.Kinect.DepthFrameSource DepthFrameSource { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("DepthFrameReader"); } RootSystem.IntPtr objectPointer = Windows_Kinect_DepthFrameReader_get_DepthFrameSource(_pNative); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.DepthFrameSource>(objectPointer, n => new Windows.Kinect.DepthFrameSource(n)); } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern bool Windows_Kinect_DepthFrameReader_get_IsPaused(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_DepthFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused); public bool IsPaused { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("DepthFrameReader"); } return Windows_Kinect_DepthFrameReader_get_IsPaused(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("DepthFrameReader"); } Windows_Kinect_DepthFrameReader_put_IsPaused(_pNative, value); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Kinect_DepthFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.DepthFrameArrivedEventArgs>>> Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.DepthFrameArrivedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_DepthFrameArrivedEventArgs_Delegate))] private static void Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Kinect.DepthFrameArrivedEventArgs>> callbackList = null; Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<DepthFrameReader>(pNative); var args = new Windows.Kinect.DepthFrameArrivedEventArgs(result); foreach(var func in callbackList) { #if UNITY_METRO || UNITY_XBOXONE UnityEngine.WSA.Application.InvokeOnAppThread(() => { try { func(objThis, args); } catch { } }, true); #else Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); #endif } } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_DepthFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_DepthFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Kinect.DepthFrameArrivedEventArgs> FrameArrived { add { #if !UNITY_METRO && !UNITY_XBOXONE Helper.EventPump.EnsureInitialized(); #endif Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Kinect_DepthFrameArrivedEventArgs_Delegate(Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_Handler); _Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_DepthFrameReader_add_FrameArrived(_pNative, del, false); } } } remove { Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_DepthFrameReader_add_FrameArrived(_pNative, Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_Handler, true); _Windows_Kinect_DepthFrameArrivedEventArgs_Delegate_Handle.Free(); } } } } private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<DepthFrameReader>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { #if UNITY_METRO || UNITY_XBOXONE UnityEngine.WSA.Application.InvokeOnAppThread(() => { try { func(objThis, args); } catch { } }, true); #else Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); #endif } } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_DepthFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { #if !UNITY_METRO && !UNITY_XBOXONE Helper.EventPump.EnsureInitialized(); #endif Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_DepthFrameReader_add_PropertyChanged(_pNative, del, false); } } } remove { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_DepthFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_DepthFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative); public Windows.Kinect.DepthFrame AcquireLatestFrame() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("DepthFrameReader"); } RootSystem.IntPtr objectPointer = Windows_Kinect_DepthFrameReader_AcquireLatestFrame(_pNative); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.DepthFrame>(objectPointer, n => new Windows.Kinect.DepthFrame(n)); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_DepthFrameReader_Dispose(RootSystem.IntPtr pNative); public void Dispose() { if (_pNative == RootSystem.IntPtr.Zero) { return; } Dispose(true); RootSystem.GC.SuppressFinalize(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public class ParameterBlockTests : SharedBlockTests { private static IEnumerable<ParameterExpression> SingleParameter { get { return Enumerable.Repeat(Expression.Variable(typeof(int)), 1); } } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void SingleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( SingleParameter, constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void DoubleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( SingleParameter, Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void NullExpicitType() { Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Expression.Constant(0))); Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Enumerable.Repeat(Expression.Constant(0), 1))); } [Fact] public void NullExpressionList() { Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(Expression[]))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(IEnumerable<Expression>))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(Expression[]))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(IEnumerable<Expression>))); } [Theory] [MemberData(nameof(BlockSizes))] public void NullExpressionInExpressionList(int size) { List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList(); for (int i = 0; i < expressionList.Count; ++i) { Expression[] expressions = expressionList.ToArray(); expressions[i] = null; Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions)); Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0))); Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions)); Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0))); } } [Theory] [MemberData(nameof(BlockSizes))] public void UnreadableExpressionInExpressionList(int size) { List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList(); for (int i = 0; i != expressionList.Count; ++i) { Expression[] expressions = expressionList.ToArray(); expressions[i] = UnreadableExpression; Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions)); Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0))); Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions)); Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0))); } } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))] public void BlockExplicitType(object value, int blockSize, bool useInterpreter) { ConstantExpression constant = Expression.Constant(value, value.GetType()); BlockExpression block = Expression.Block(typeof(object), SingleParameter, PadBlock(blockSize - 1, constant)); Assert.Equal(typeof(object), block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(BlockSizes))] public void BlockInvalidExplicitType(int blockSize) { ConstantExpression constant = Expression.Constant(0); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions)); Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions.ToArray())); } [Theory] [PerCompilationType(nameof(ConstantValuesAndSizes))] public void BlockFromEmptyParametersSameAsFromParams(object value, int blockSize, bool useInterpreter) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression fromParamsBlock = Expression.Block(SingleParameter, expressions.ToArray()); BlockExpression fromEnumBlock = Expression.Block(SingleParameter, expressions); Assert.Equal(fromParamsBlock.GetType(), fromEnumBlock.GetType()); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromParamsBlock)).Compile(useInterpreter)()); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromEnumBlock)).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void InvalidExpressionIndex(object value, int blockSize) { BlockExpression block = Expression.Block(SingleParameter, PadBlock(blockSize - 1, Expression.Constant(value, value.GetType()))); Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]); } [Fact] public void EmptyBlockWithParametersAndNonVoidTypeNotAllowed() { Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter)); Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter, Enumerable.Empty<Expression>())); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ResultPropertyFromParams(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions.ToArray()); Assert.Same(constant, block.Result); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ResultPropertyFromEnumerable(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Same(constant, block.Result); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void VariableCountCorrect(object value, int blockSize) { IEnumerable<ParameterExpression> vars = Enumerable.Range(0, blockSize).Select(i => Expression.Variable(value.GetType())); BlockExpression block = Expression.Block(vars, Expression.Constant(value, value.GetType())); Assert.Equal(blockSize, block.Variables.Count); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void RewriteToSameWithSameValues(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray(); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Same(block, block.Update(block.Variables.ToArray(), expressions)); Assert.Same(block, block.Update(block.Variables.ToArray(), expressions)); Assert.Same(block, NoOpVisitor.Instance.Visit(block)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void CanFindItems(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(SingleParameter, values); IList<Expression> expressions = block.Expressions; for (int i = 0; i != values.Length; ++i) Assert.Equal(i, expressions.IndexOf(values[i])); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long)))); Assert.False(block.Expressions.Contains(null)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ExpressionsEnumerable(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(SingleParameter, values); Assert.True(values.SequenceEqual(block.Expressions)); int index = 0; foreach (Expression exp in ((IEnumerable)block.Expressions)) Assert.Same(exp, values[index++]); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void UpdateWithExpressionsReturnsSame(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.Same(block, block.Update(block.Variables, block.Expressions)); Assert.Same(block, NoOpVisitor.Instance.Visit(block)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void Visit(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(SingleParameter, expressions); Assert.NotSame(block, new TestVistor().Visit(block)); } [Theory] [MemberData(nameof(ObjectAssignableConstantValuesAndSizes))] public void VisitTyped(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(typeof(object), SingleParameter, expressions); Assert.NotSame(block, new TestVistor().Visit(block)); } [Theory] [MemberData(nameof(BlockSizes))] public void NullVariables(int blockSize) { IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); IEnumerable<ParameterExpression> vars = Enumerable.Repeat(default(ParameterExpression), 1); Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions)); Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions.ToArray())); Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions)); Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray())); } [Theory] [MemberData(nameof(BlockSizes))] public void ByRefVariables(int blockSize) { IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); IEnumerable<ParameterExpression> vars = Enumerable.Repeat(Expression.Parameter(typeof(int).MakeByRefType()), 1); Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions)); Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions.ToArray())); Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions)); Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray())); } [Theory] [MemberData(nameof(BlockSizes))] public void RepeatedVariables(int blockSize) { IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); ParameterExpression variable = Expression.Variable(typeof(int)); IEnumerable<ParameterExpression> vars = Enumerable.Repeat(variable, 2); Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions)); Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions.ToArray())); Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions)); Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions.ToArray())); } [Theory, MemberData(nameof(BlockSizes))] public void UpdateDoesntRepeatEnumeration(int blockSize) { ConstantExpression constant = Expression.Constant(0); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray(); ParameterExpression[] vars = {Expression.Variable(typeof(int)), Expression.Variable(typeof(string))}; BlockExpression block = Expression.Block(vars, expressions); Assert.Same(block, block.Update(new RunOnceEnumerable<ParameterExpression>(vars), block.Expressions)); vars = new[] {Expression.Variable(typeof(int)), Expression.Variable(typeof(string))}; Assert.NotSame(block, block.Update(new RunOnceEnumerable<ParameterExpression>(vars), block.Expressions)); } [Theory, MemberData(nameof(BlockSizes))] public void UpdateDifferentSizeReturnsDifferent(int blockSize) { ConstantExpression constant = Expression.Constant(0); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray(); ParameterExpression[] vars = { Expression.Variable(typeof(int)), Expression.Variable(typeof(string)) }; BlockExpression block = Expression.Block(vars, expressions); Assert.NotSame(block, block.Update(vars, block.Expressions.Prepend(Expression.Empty()))); } } }
/* * 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 Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Index { /// <summary> /// A {@link MergeScheduler} that runs each merge using a /// separate thread, up until a maximum number of threads /// ({@link #setMaxThreadCount}) at which when a merge is /// needed, the thread(s) that are updating the index will /// pause until one or more merges completes. This is a /// simple way to use concurrency in the indexing process /// without having to create and manage application level /// threads. /// </summary> public class ConcurrentMergeScheduler : MergeScheduler { private int mergeThreadPriority = -1; protected System.Collections.Generic.List<MergeThread> mergeThreads = new System.Collections.Generic.List<MergeThread>(); // max number of threads allowed to be merging at once private int maxThreadCount = 3; private System.Collections.Generic.List<System.Exception> exceptions = new System.Collections.Generic.List<System.Exception>(); protected Directory dir; private bool closed; protected IndexWriter writer; protected int mergeThreadCount; public ConcurrentMergeScheduler() { if (allInstances != null) { // Only for testing AddMyself(); } } /// <summary>Sets the max # simultaneous threads that may be /// running. If a merge is necessary yet we already have /// this many threads running, the incoming thread (that /// is calling add/updateDocument) will block until /// a merge thread has completed. /// </summary> public virtual void SetMaxThreadCount(int count) { if (count < 1) throw new System.ArgumentException("count should be at least 1"); maxThreadCount = count; } /// <summary>Get the max # simultaneous threads that may be</summary> /// <seealso cref="setMaxThreadCount."> /// </seealso> public virtual int GetMaxThreadCount() { return maxThreadCount; } /// <summary>Return the priority that merge threads run at. By /// default the priority is 1 plus the priority of (ie, /// slightly higher priority than) the first thread that /// calls merge. /// </summary> public virtual int GetMergeThreadPriority() { lock (this) { InitMergeThreadPriority(); return mergeThreadPriority; } } /// <summary>Return the priority that merge threads run at. </summary> public virtual void SetMergeThreadPriority(int pri) { lock (this) { if (pri > (int)System.Threading.ThreadPriority.Highest || pri < (int)System.Threading.ThreadPriority.Lowest) throw new System.ArgumentException("priority must be in range " + (int)System.Threading.ThreadPriority.Lowest + " .. " + (int)System.Threading.ThreadPriority.Highest + " inclusive"); mergeThreadPriority = pri; int numThreads = MergeThreadCount(); for (int i = 0; i < numThreads; i++) { MergeThread merge = mergeThreads[i]; merge.SetThreadPriority(pri); } } } private void Message(System.String message) { if (writer != null) writer.Message("CMS: " + message); } private void InitMergeThreadPriority() { lock (this) { if (mergeThreadPriority == -1) { // Default to slightly higher priority than our calling thread mergeThreadPriority = 1 + (int)System.Threading.Thread.CurrentThread.Priority; if (mergeThreadPriority > (int)System.Threading.ThreadPriority.Highest) mergeThreadPriority = (int)System.Threading.ThreadPriority.Highest; } } } public override void Close() { closed = true; } public virtual void Sync() { lock (this) { while (MergeThreadCount() > 0) { Message("now wait for threads; currently " + mergeThreads.Count + " still running"); int count = mergeThreads.Count; for (int i = 0; i < count; i++) Message(" " + i + ": " + mergeThreads[i]); try { System.Threading.Monitor.Wait(this); } catch (System.Threading.ThreadInterruptedException) { } } } } private int MergeThreadCount() { lock (this) { int count = 0; int numThreads = mergeThreads.Count; for (int i = 0; i < numThreads; i++) if (mergeThreads[i].IsAlive) count++; return count; } } public override void Merge(IndexWriter writer) { this.writer = writer; InitMergeThreadPriority(); dir = writer.GetDirectory(); // First, quickly run through the newly proposed merges // and add any orthogonal merges (ie a merge not // involving segments already pending to be merged) to // the queue. If we are way behind on merging, many of // these newly proposed merges will likely already be // registered. Message("now merge"); Message(" index: " + writer.SegString()); // Iterate, pulling from the IndexWriter's queue of // pending merges, until its empty: while (true) { // TODO: we could be careful about which merges to do in // the BG (eg maybe the "biggest" ones) vs FG, which // merges to do first (the easiest ones?), etc. MergePolicy.OneMerge merge = writer.GetNextMerge(); if (merge == null) { Message(" no more merges pending; now return"); return; } // We do this w/ the primary thread to keep // deterministic assignment of segment names writer.MergeInit(merge); lock (this) { while (MergeThreadCount() >= maxThreadCount) { Message(" too may merge threads running; stalling..."); try { System.Threading.Monitor.Wait(this); } catch (System.Threading.ThreadInterruptedException) { SupportClass.ThreadClass.Current().Interrupt(); } } Message(" consider merge " + merge.SegString(dir)); System.Diagnostics.Debug.Assert(MergeThreadCount() < maxThreadCount); // OK to spawn a new merge thread to handle this // merge: MergeThread merger = GetMergeThread(writer, merge); mergeThreads.Add(merger); Message(" launch new thread [" + merger.Name + "]"); merger.Start(); } } } /// <summary> /// Does the acural merge, by calling IndexWriter.Merge(). /// </summary> /// <param name="merge"></param> virtual protected void DoMerge(MergePolicy.OneMerge merge) { writer.Merge(merge); } /// <summary> /// Create and return a new MergeThread. /// </summary> /// <param name="writer"></param> /// <param name="merge"></param> /// <returns></returns> virtual protected MergeThread GetMergeThread(IndexWriter writer, MergePolicy.OneMerge merge) { MergeThread thread = new MergeThread(this, writer, merge); thread.SetThreadPriority(mergeThreadPriority); thread.IsBackground = true; thread.Name = "Lucene Merge Thread #" + mergeThreadCount++; return thread; } protected class MergeThread : SupportClass.ThreadClass { private void InitBlock(ConcurrentMergeScheduler enclosingInstance) { this.enclosingInstance = enclosingInstance; } private ConcurrentMergeScheduler enclosingInstance; public ConcurrentMergeScheduler Enclosing_Instance { get { return enclosingInstance; } } internal IndexWriter writer; internal MergePolicy.OneMerge startMerge; internal MergePolicy.OneMerge runningMerge; public MergeThread(ConcurrentMergeScheduler enclosingInstance, IndexWriter writer, MergePolicy.OneMerge startMerge) { InitBlock(enclosingInstance); this.writer = writer; this.startMerge = startMerge; } public virtual void SetRunningMerge(MergePolicy.OneMerge merge) { lock (this) { runningMerge = merge; } } public virtual MergePolicy.OneMerge GetRunningMerge() { lock (this) { return runningMerge; } } public virtual void SetThreadPriority(int pri) { try { Priority = (System.Threading.ThreadPriority)pri; } catch (System.NullReferenceException) { // Strangely, Sun's JDK 1.5 on Linux sometimes // throws NPE out of here... } catch (System.Security.SecurityException) { // Ignore this because we will still run fine with // normal thread priority } } override public void Run() { // First time through the while loop we do the merge // that we were started with: MergePolicy.OneMerge merge = this.startMerge; try { Enclosing_Instance.Message(" merge thread: start"); while (true) { SetRunningMerge(merge); Enclosing_Instance.DoMerge(merge); // Subsequent times through the loop we do any new // merge that writer says is necessary: merge = writer.GetNextMerge(); if (merge != null) { writer.MergeInit(merge); Enclosing_Instance.Message(" merge thread: do another merge " + merge.SegString(Enclosing_Instance.dir)); } else break; } Enclosing_Instance.Message(" merge thread: done"); } catch (System.Exception exc) { // Ignore the exception if it was due to abort: if (!(exc is MergePolicy.MergeAbortedException)) { lock (Enclosing_Instance) { Enclosing_Instance.exceptions.Add(exc); } if (!Enclosing_Instance.suppressExceptions) { // suppressExceptions is normally only set during // testing. Lucene.Net.Index.ConcurrentMergeScheduler.anyExceptions = true; Enclosing_Instance.HandleMergeException(exc); } } } finally { lock (Enclosing_Instance) { System.Threading.Monitor.PulseAll(Enclosing_Instance); bool removed = Enclosing_Instance.mergeThreads.Remove(this); System.Diagnostics.Debug.Assert(removed); } } } public override System.String ToString() { MergePolicy.OneMerge merge = GetRunningMerge(); if (merge == null) merge = startMerge; return "merge thread: " + merge.SegString(Enclosing_Instance.dir); } } virtual protected void HandleMergeException(System.Exception exc) { throw new MergePolicy.MergeException(exc, dir); } internal static bool anyExceptions = false; /// <summary>Used for testing </summary> public static bool AnyUnhandledExceptions() { lock (allInstances.SyncRoot) { int count = allInstances.Count; // Make sure all outstanding threads are done so we see // any exceptions they may produce: for (int i = 0; i < count; i++) ((ConcurrentMergeScheduler)allInstances[i]).Sync(); bool v = anyExceptions; anyExceptions = false; return v; } } public static void ClearUnhandledExceptions() { lock (allInstances) { anyExceptions = false; } } /// <summary>Used for testing </summary> private void AddMyself() { lock (allInstances.SyncRoot) { int size = 0; int upto = 0; for (int i = 0; i < size; i++) { ConcurrentMergeScheduler other = (ConcurrentMergeScheduler)allInstances[i]; if (!(other.closed && 0 == other.MergeThreadCount())) // Keep this one for now: it still has threads or // may spawn new threads allInstances[upto++] = other; } ((System.Collections.IList)((System.Collections.ArrayList)allInstances).GetRange(upto, allInstances.Count - upto)).Clear(); allInstances.Add(this); } } private bool suppressExceptions; /// <summary>Used for testing </summary> internal virtual void SetSuppressExceptions() { suppressExceptions = true; } /// <summary>Used for testing </summary> internal virtual void ClearSuppressExceptions() { suppressExceptions = false; } /// <summary>Used for testing </summary> private static System.Collections.IList allInstances; public static void SetTestMode() { allInstances = new System.Collections.ArrayList(); } public void SetSuppressExceptions_ForNUnitTest() { SetSuppressExceptions(); } public void ClearSuppressExceptions_ForNUnitTest() { ClearSuppressExceptions(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading; using System.Threading.Tasks; using Manatee.Trello.Internal; using Manatee.Trello.Internal.DataAccess; using Manatee.Trello.Internal.Synchronization; using Manatee.Trello.Internal.Validation; using Manatee.Trello.Json; namespace Manatee.Trello { /// <summary> /// Represents a checklist item. /// </summary> public class CheckItem : ICheckItem, IMergeJson<IJsonCheckItem>, IBatchRefresh, IHandleSynchronization { /// <summary> /// Enumerates the data which can be pulled for check items. /// </summary> [Flags] public enum Fields { /// <summary> /// Indicates the State property should be populated. /// </summary> [Display(Description="state")] State = 1, /// <summary> /// Indicates the Name property should be populated. /// </summary> [Display(Description="name")] Name = 1 << 1, /// <summary> /// Indicates the Position property should be populated. /// </summary> [Display(Description="pos")] Position = 1 << 2 } private readonly Field<CheckList> _checkList; private readonly Field<string> _name; private readonly Field<Position> _position; private readonly Field<CheckItemState?> _state; private readonly CheckItemContext _context; private DateTime? _creation; private static Fields _downloadedFields; /// <summary> /// Specifies which fields should be downloaded. /// </summary> public static Fields DownloadedFields { get { return _downloadedFields; } set { _downloadedFields = value; CheckItemContext.UpdateParameters(); } } /// <summary> /// Gets or sets the checklist to which the item belongs. /// </summary> /// <remarks> /// Trello only supports moving a check item between lists on the same card. /// </remarks> public ICheckList CheckList { get { return _checkList.Value; } set { _checkList.Value = (CheckList) value; } } /// <summary> /// Gets the creation date of the checklist item. /// </summary> public DateTime CreationDate { get { if (_creation == null) _creation = Id.ExtractCreationDate(); return _creation.Value; } } /// <summary> /// Gets or sets the checklist item's ID. /// </summary> public string Id { get; private set; } /// <summary> /// Gets or sets the checklist item's name. /// </summary> public string Name { get { return _name.Value; } set { _name.Value = value; } } /// <summary> /// Gets or sets the checklist item's position. /// </summary> public Position Position { get { return _position.Value; } set { _position.Value = value; } } /// <summary> /// Gets or sets the checklist item's state. /// </summary> public CheckItemState? State { get { return _state.Value; } set { _state.Value = value; } } internal IJsonCheckItem Json { get { return _context.Data; } set { _context.Merge(value); } } TrelloAuthorization IBatchRefresh.Auth => _context.Auth; /// <summary> /// Raised when data on the checklist item is updated. /// </summary> public event Action<ICheckItem, IEnumerable<string>> Updated; static CheckItem() { DownloadedFields = (Fields)Enum.GetValues(typeof(Fields)).Cast<int>().Sum(); } internal CheckItem(IJsonCheckItem json, string checkListId, TrelloAuthorization auth = null) { Id = json.Id; _context = new CheckItemContext(Id, checkListId, auth); _checkList = new Field<CheckList>(_context, nameof(CheckList)); _checkList.AddRule(NotNullRule<CheckList>.Instance); _name = new Field<string>(_context, nameof(Name)); _name.AddRule(NotNullOrWhiteSpaceRule.Instance); _position = new Field<Position>(_context, nameof(Position)); _position.AddRule(NotNullRule<Position>.Instance); _position.AddRule(PositionRule.Instance); _state = new Field<CheckItemState?>(_context, nameof(State)); _state.AddRule(NullableHasValueRule<CheckItemState>.Instance); _state.AddRule(EnumerationRule<CheckItemState?>.Instance); if (auth != TrelloAuthorization.Null) TrelloConfiguration.Cache.Add(this); _context.Merge(json); _context.Synchronized.Add(this); } /// <summary> /// Deletes the checklist item. /// </summary> /// <param name="ct">(Optional) A cancellation token for async processing.</param> /// <remarks> /// This permanently deletes the checklist item from Trello's server, however, this object will remain in memory and all properties will remain accessible. /// </remarks> public async Task Delete(CancellationToken ct = default) { await _context.Delete(ct); if (TrelloConfiguration.RemoveDeletedItemsFromCache) TrelloConfiguration.Cache.Remove(this); } /// <summary> /// Refreshes the checklist item data. /// </summary> /// <param name="force">Indicates that the refresh should ignore the value in <see cref="TrelloConfiguration.RefreshThrottle"/> and make the call to the API.</param> /// <param name="ct">(Optional) A cancellation token for async processing.</param> public Task Refresh(bool force = false, CancellationToken ct = default) { return _context.Synchronize(force, ct); } void IMergeJson<IJsonCheckItem>.Merge(IJsonCheckItem json, bool overwrite) { _context.Merge(json, overwrite); } /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> /// <filterpriority>2</filterpriority> public override string ToString() { return Name; } Endpoint IBatchRefresh.GetRefreshEndpoint() { return _context.GetRefreshEndpoint(); } void IBatchRefresh.Apply(string content) { var json = TrelloConfiguration.Deserializer.Deserialize<IJsonCheckItem>(content); _context.Merge(json); } void IHandleSynchronization.HandleSynchronized(IEnumerable<string> properties) { Id = _context.Data.Id; var handler = Updated; handler?.Invoke(this, properties); } } }
using System; using CslaSrd; using CslaSrd.Properties; namespace CslaSrd { /// <summary> /// Provides an integer data type that understands the concept /// of an empty value. /// </summary> /// <remarks> /// See Chapter 5 for a full discussion of the need for a similar /// data type and the design choices behind it. Basically, we are /// using the same approach to handle integers instead of dates. /// </remarks> [Serializable()] public struct SmartInt16 : IComparable, ISmartField { private Int16 _int; private bool _initialized; private bool _emptyIsMax; private string _format; #region Constructors /// <summary> /// Creates a new SmartInt16 object. /// </summary> /// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param> public SmartInt16(bool emptyIsMin) { _emptyIsMax = !emptyIsMin; _format = null; _initialized = false; // provide a dummy value to allow real initialization _int = Int16.MinValue; if (!_emptyIsMax) Int = Int16.MinValue; else Int = Int16.MaxValue; } /// <summary> /// Creates a new SmartInt16 object. /// </summary> /// <remarks> /// The SmartInt16 created will use the min possible /// int to represent an empty int. /// </remarks> /// <param name="value">The initial value of the object.</param> public SmartInt16(Int16 value) { _emptyIsMax = false; _format = null; _initialized = false; _int = Int16.MinValue; Int = value; } /// <summary> /// Creates a new SmartInt16 object. /// </summary> /// <param name="value">The initial value of the object.</param> /// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param> public SmartInt16(Int16 value, bool emptyIsMin) { _emptyIsMax = !emptyIsMin; _format = null; _initialized = false; _int = Int16.MinValue; Int = value; } /// <summary> /// Creates a new SmartInt16 object. /// </summary> /// <remarks> /// The SmartInt16 created will use the min possible /// int to represent an empty int. /// </remarks> /// <param name="value">The initial value of the object (as text).</param> public SmartInt16(string value) { _emptyIsMax = false; _format = null; _initialized = true; _int = Int16.MinValue; this.Text = value; } /// <summary> /// Creates a new SmartInt16 object. /// </summary> /// <param name="value">The initial value of the object (as text).</param> /// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param> public SmartInt16(string value, bool emptyIsMin) { _emptyIsMax = !emptyIsMin; _format = null; _initialized = true; _int = Int16.MinValue; this.Text = value; } #endregion #region Text Support /// <summary> /// Gets or sets the format string used to format a int /// value when it is returned as text. /// </summary> /// <remarks> /// The format string should follow the requirements for the /// .NET <see cref="System.String.Format"/> statement. /// </remarks> /// <value>A format string.</value> public string FormatString { get { if (_format == null) _format = "d"; return _format; } set { _format = value; } } /// <summary> /// Gets or sets the int value. /// </summary> /// <remarks> /// <para> /// This property can be used to set the int value by passing a /// text representation of the int. Any text int representation /// that can be parsed by the .NET runtime is valid. /// </para><para> /// When the int value is retrieved via this property, the text /// is formatted by using the format specified by the /// <see cref="FormatString" /> property. The default is the /// short int format (d). /// </para> /// </remarks> public string Text { get { return IntToString(this.Int, FormatString, !_emptyIsMax); } set { this.Int = StringToInt(value, !_emptyIsMax); } } #endregion #region Int Support /// <summary> /// Gets or sets the int value. /// </summary> public Int16 Int { get { if (!_initialized) { _int = Int16.MinValue; _initialized = true; } return _int; } set { _int = value; _initialized = true; } } #endregion #region System.Object overrides /// <summary> /// Returns a text representation of the int value. /// </summary> public override string ToString() { return this.Text; } /// <summary> /// Compares this object to another <see cref="SmartInt16"/> /// for equality. /// </summary> public override bool Equals(object obj) { if (obj is SmartInt16) { SmartInt16 tmp = (SmartInt16)obj; if (this.IsEmpty && tmp.IsEmpty) return true; else return this.Int.Equals(tmp.Int); } else if (obj is Int16) return this.Int.Equals((Int16)obj); else if (obj is string) return (this.CompareTo(obj.ToString()) == 0); else return false; } /// <summary> /// Returns a hash code for this object. /// </summary> public override int GetHashCode() { return this.Int.GetHashCode(); } #endregion #region DBValue /// <summary> /// Gets a database-friendly version of the int value. /// </summary> /// <remarks> /// <para> /// If the SmartInt16 contains an empty int, this returns <see cref="DBNull"/>. /// Otherwise the actual int value is returned as type Int. /// </para><para> /// This property is very useful when setting parameter values for /// a Command object, since it automatically stores null values into /// the database for empty int values. /// </para><para> /// When you also use the SafeDataReader and its GetSmartInt16 method, /// you can easily read a null value from the database back into a /// SmartInt16 object so it remains considered as an empty int value. /// </para> /// </remarks> public object DBValue { get { if (this.IsEmpty) return DBNull.Value; else return this.Int; } } #endregion #region Empty Ints /// <summary> /// Gets a value indicating whether this object contains an empy value. /// </summary> /// <returns>True if the value is empty.</returns> public bool HasNullValue() { return !_initialized; } /// <summary> /// Gets a value indicating whether this object contains an empty int. /// </summary> public bool IsEmpty { get { if (!_emptyIsMax) return this.Int.Equals(Int16.MinValue); else return this.Int.Equals(Int16.MaxValue); } } /// <summary> /// Gets a value indicating whether an empty int is the /// min or max possible int value. /// </summary> /// <remarks> /// Whether an empty int is considered to be the smallest or largest possible /// int is only important for comparison operations. This allows you to /// compare an empty int with a real int and get a meaningful result. /// </remarks> public bool EmptyIsMin { get { return !_emptyIsMax; } } #endregion #region Conversion Functions /// <summary> /// Converts a string value into a SmartInt16. /// </summary> /// <param name="value">String containing the int value.</param> /// <returns>A new SmartInt16 containing the int value.</returns> /// <remarks> /// EmptyIsMin will default to <see langword="true"/>. /// </remarks> public static SmartInt16 Parse(string value) { return new SmartInt16(value); } /// <summary> /// Converts a string value into a SmartInt16. /// </summary> /// <param name="value">String containing the int value.</param> /// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param> /// <returns>A new SmartInt16 containing the int value.</returns> public static SmartInt16 Parse(string value, bool emptyIsMin) { return new SmartInt16(value, emptyIsMin); } /// <summary> /// Converts a text int representation into a Int value. /// </summary> /// <remarks> /// An empty string is assumed to represent an empty int. An empty int /// is returned as the MinValue of the Int datatype. /// </remarks> /// <param name="value">The text representation of the int.</param> /// <returns>A Int value.</returns> public static Int16 StringToInt(string value) { return StringToInt(value, true); } /// <summary> /// Converts a text int representation into a Int value. /// </summary> /// <remarks> /// An empty string is assumed to represent an empty int. An empty int /// is returned as the MinValue or MaxValue of the Int datatype depending /// on the EmptyIsMin parameter. /// </remarks> /// <param name="value">The text representation of the int.</param> /// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param> /// <returns>A Int value.</returns> public static Int16 StringToInt(string value, bool emptyIsMin) { Int16 tmp; if (String.IsNullOrEmpty(value)) { if (emptyIsMin) return Int16.MinValue; else return Int16.MaxValue; } else if (Int16.TryParse(value, out tmp)) return tmp; else { string lint = value.Trim().ToLower(); throw new ArgumentException(Resources.StringToInt16Exception); } } /// <summary> /// Converts a int value into a text representation. /// </summary> /// <remarks> /// The int is considered empty if it matches the min value for /// the Int datatype. If the int is empty, this /// method returns an empty string. Otherwise it returns the int /// value formatted based on the FormatString parameter. /// </remarks> /// <param name="value">The int value to convert.</param> /// <param name="formatString">The format string used to format the int into text.</param> /// <returns>Text representation of the int value.</returns> public static string IntToString(Int16 value, string formatString) { return IntToString(value, formatString, true); } /// <summary> /// Converts a int value into a text representation. /// </summary> /// <remarks> /// Whether the int value is considered empty is determined by /// the EmptyIsMin parameter value. If the int is empty, this /// method returns an empty string. Otherwise it returns the int /// value formatted based on the FormatString parameter. /// </remarks> /// <param name="value">The int value to convert.</param> /// <param name="formatString">The format string used to format the int into text.</param> /// <param name="emptyIsMin">Indicates whether an empty int is the min or max int value.</param> /// <returns>Text representation of the int value.</returns> public static string IntToString( Int16 value, string formatString, bool emptyIsMin) { if (emptyIsMin && value == Int16.MinValue) return string.Empty; else if (!emptyIsMin && value == Int16.MaxValue) return string.Empty; else return string.Format("{0:" + formatString + "}", value); } #endregion #region Manipulation Functions /// <summary> /// Compares one SmartInt16 to another. /// </summary> /// <remarks> /// This method works the same as the <see cref="int.CompareTo"/> method /// on the Int inttype, with the exception that it /// understands the concept of empty int values. /// </remarks> /// <param name="value">The int to which we are being compared.</param> /// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns> public int CompareTo(SmartInt16 value) { if (this.IsEmpty && value.IsEmpty) return 0; else return _int.CompareTo(value.Int); } /// <summary> /// Compares one SmartInt16 to another. /// </summary> /// <remarks> /// This method works the same as the <see cref="int.CompareTo"/> method /// on the Int inttype, with the exception that it /// understands the concept of empty int values. /// </remarks> /// <param name="value">The int to which we are being compared.</param> /// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns> int IComparable.CompareTo(object value) { if (value is SmartInt16) return CompareTo((SmartInt16)value); else throw new ArgumentException(Resources.ValueNotSmartInt16Exception); } /// <summary> /// Compares a SmartInt16 to a text int value. /// </summary> /// <param name="value">The int to which we are being compared.</param> /// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns> public int CompareTo(string value) { return this.Int.CompareTo(StringToInt(value, !_emptyIsMax)); } /// <summary> /// Compares a SmartInt16 to a int value. /// </summary> /// <param name="value">The int to which we are being compared.</param> /// <returns>A value indicating if the comparison int is less than, equal to or greater than this int.</returns> public int CompareTo(Int16 value) { return this.Int.CompareTo(value); } /// <summary> /// Adds an integer value onto the object. /// </summary> public Int16 Add(Int16 value) { if (IsEmpty) return this.Int; else return (Int16)(this.Int + value); } /// <summary> /// Subtracts an integer value from the object. /// </summary> public Int16 Subtract(Int16 value) { if (IsEmpty) return this.Int; else return (Int16)(this.Int - value); } #endregion #region Operators /// <summary> /// Compares two of this type of object for equality. /// </summary> /// <param name="obj1">The first object to compare</param> /// <param name="obj2">The second object to compare</param> /// <returns>Whether the object values are equal</returns> public static bool operator ==(SmartInt16 obj1, SmartInt16 obj2) { return obj1.Equals(obj2); } /// <summary> /// Checks two of this type of object for non-equality. /// </summary> /// <param name="obj1">The first object to compare</param> /// <param name="obj2">The second object to compare</param> /// <returns>Whether the two values are not equal</returns> public static bool operator !=(SmartInt16 obj1, SmartInt16 obj2) { return !obj1.Equals(obj2); } /// <summary> /// Compares an object of this type with an Int16 for equality. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the two values are equal</returns> public static bool operator ==(SmartInt16 obj1, Int16 obj2) { return obj1.Equals(obj2); } /// <summary> /// Compares an object of this type with an Int16 for non-equality. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the two values are not equal</returns> public static bool operator !=(SmartInt16 obj1, Int16 obj2) { return !obj1.Equals(obj2); } /// <summary> /// Compares an object of this type with an Int16 for equality. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the two values are equal</returns> public static bool operator ==(SmartInt16 obj1, string obj2) { return obj1.Equals(obj2); } /// <summary> /// Compares an object of this type with an string for non-equality. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The string to compare</param> /// <returns>Whether the two values are not equal</returns> public static bool operator !=(SmartInt16 obj1, string obj2) { return !obj1.Equals(obj2); } /// <summary> /// Adds an object of this type to an Int16. /// </summary> /// <param name="start">The object of this type to add</param> /// <param name="span">The Int16 to add</param> /// <returns>A SmartInt16 with the sum</returns> public static SmartInt16 operator +(SmartInt16 start, Int16 span) { return new SmartInt16(start.Add(span), start.EmptyIsMin); } /// <summary> /// Subtracts an Int16 from an object of this type. /// </summary> /// <param name="start">The object of this type to be subtracted from</param> /// <param name="span">The Int16 to subtract</param> /// <returns>The calculated result</returns> public static SmartInt16 operator -(SmartInt16 start, Int16 span) { return new SmartInt16(start.Subtract(span), start.EmptyIsMin); } /// <summary> /// Subtracts an object of this type from another. /// </summary> /// <param name="start">The object of this type to be subtracted from</param> /// <param name="finish">The object of this type to subtract</param> /// <returns>The calculated result</returns> public static Int16 operator -(SmartInt16 start, SmartInt16 finish) { return start.Subtract(finish.Int); } /// <summary> /// Determines whether the first object of this type is greater than the second. /// </summary> /// <param name="obj1">The first object of this type to compare</param> /// <param name="obj2">The second object of this type to compare</param> /// <returns>Whether the first value is greater than the second</returns> public static bool operator >(SmartInt16 obj1, SmartInt16 obj2) { return obj1.CompareTo(obj2) > 0; } /// <summary> /// Determines whether the first object of this type is less than the second. /// </summary> /// <param name="obj1">The first object of this type to compare</param> /// <param name="obj2">The second object of this type to compare</param> /// <returns>Whether the first value is less than the second</returns> public static bool operator <(SmartInt16 obj1, SmartInt16 obj2) { return obj1.CompareTo(obj2) < 0; } /// <summary> /// Determines whether the first object of this type is greater than an Int16. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the first value is greater than the second</returns> public static bool operator >(SmartInt16 obj1, Int16 obj2) { return obj1.CompareTo(obj2) > 0; } /// <summary> /// Determines whether the first object of this type is less than an Int16. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the first value is less than the second</returns> public static bool operator <(SmartInt16 obj1, Int16 obj2) { return obj1.CompareTo(obj2) < 0; } /// <summary> /// Determines whether the first object of this type is less than the value in a string. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The string value to compare</param> /// <returns>Whether the first value is greater than the second</returns> public static bool operator >(SmartInt16 obj1, string obj2) { return obj1.CompareTo(obj2) > 0; } /// <summary> /// Determines whether the first object of this type is less than the value in a string. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The string value to compare</param> /// <returns>Whether the first value is less than the second</returns> public static bool operator <(SmartInt16 obj1, string obj2) { return obj1.CompareTo(obj2) < 0; } /// <summary> /// Determines whether the first object of this type is greater than or equal to the second. /// </summary> /// <param name="obj1">The first object of this type to compare</param> /// <param name="obj2">The second object of this type to compare</param> /// <returns>Whether the first value is greater than or equal to the second</returns> public static bool operator >=(SmartInt16 obj1, SmartInt16 obj2) { return obj1.CompareTo(obj2) >= 0; } /// <summary> /// Determines whether the first object of this type is less than or equal to the second. /// </summary> /// <param name="obj1">The first object of this type to compare</param> /// <param name="obj2">The second object of this type to compare</param> /// <returns>Whether the first value is less than or equal to the second</returns> public static bool operator <=(SmartInt16 obj1, SmartInt16 obj2) { return obj1.CompareTo(obj2) <= 0; } /// <summary> /// Determines whether the first object of this type is greater than or equal to an Int16. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the first value is greater than or equal to the second</returns> public static bool operator >=(SmartInt16 obj1, Int16 obj2) { return obj1.CompareTo(obj2) >= 0; } /// <summary> /// Determines whether the first object of this type is less than or equal to an Int16. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The Int16 to compare</param> /// <returns>Whether the first value is less than or equal to the second</returns> public static bool operator <=(SmartInt16 obj1, Int16 obj2) { return obj1.CompareTo(obj2) <= 0; } /// <summary> /// Determines whether the first object of this type is greater than or equal to the value of a string. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The string value to compare</param> /// <returns>Whether the first value is greater than or equal to the second</returns> public static bool operator >=(SmartInt16 obj1, string obj2) { return obj1.CompareTo(obj2) >= 0; } /// <summary> /// Determines whether the first object of this type is less than or equal to the value of a string. /// </summary> /// <param name="obj1">The object of this type to compare</param> /// <param name="obj2">The string value to compare</param> /// <returns>Whether the first value is less than or equal to the second</returns> public static bool operator <=(SmartInt16 obj1, string obj2) { return obj1.CompareTo(obj2) <= 0; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="ActiveXMessageFormatter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Messaging { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Text; using System.Runtime.Serialization; using System.Diagnostics; using System; using System.IO; using System.Globalization; using System.ComponentModel; using System.Messaging.Interop; /// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter"]/*' /> /// <devdoc> /// <para> /// Formatter class that serializes and deserializes /// primitives, classes, enumeration, and other objects into and from <see cref='System.Messaging.MessageQueue'/> /// messages using binary format. /// </para> /// </devdoc> public class ActiveXMessageFormatter : IMessageFormatter { internal const short VT_ARRAY = 0x2000; internal const short VT_BOOL = 11; internal const short VT_BSTR = 8; internal const short VT_CLSID = 72; internal const short VT_CY = 6; internal const short VT_DATE = 7; internal const short VT_I1 = 16; internal const short VT_I2 = 2; internal const short VT_I4 = 3; internal const short VT_I8 = 20; internal const short VT_LPSTR = 30; internal const short VT_LPWSTR = 31; internal const short VT_NULL = 1; internal const short VT_R4 = 4; internal const short VT_R8 = 5; internal const short VT_STREAMED_OBJECT = 68; internal const short VT_STORED_OBJECT = 69; internal const short VT_UI1 = 17; internal const short VT_UI2 = 18; internal const short VT_UI4 = 19; internal const short VT_UI8 = 21; internal const short VT_VECTOR = 0x1000; private byte[] internalBuffer; private UnicodeEncoding unicodeEncoding; private ASCIIEncoding asciiEncoding; private char[] internalCharBuffer; /// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.CanRead"]/*' /> /// <devdoc> /// When this method is called, the formatter will attempt to determine /// if the contents of the message are something the formatter can deal with. /// </devdoc> public bool CanRead(Message message) { if (message == null) throw new ArgumentNullException("message"); int variantType = message.BodyType; if (variantType != VT_BOOL && variantType != VT_CLSID && variantType != VT_CY && variantType != VT_DATE && variantType != VT_I1 && variantType != VT_UI1 && variantType != VT_I2 && variantType != VT_UI2 && variantType != VT_I4 && variantType != VT_UI4 && variantType != VT_I8 && variantType != VT_UI8 && variantType != VT_NULL && variantType != VT_R4 && variantType != VT_I8 && variantType != VT_STREAMED_OBJECT && variantType != VT_STORED_OBJECT && variantType != (VT_VECTOR | VT_UI1) && variantType != VT_LPSTR && variantType != VT_LPWSTR && variantType != VT_BSTR && variantType != VT_R8) return false; return true; } /// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.Clone"]/*' /> /// <devdoc> /// This method is needed to improve scalability on Receive and ReceiveAsync scenarios. Not requiring /// thread safety on read and write. /// </devdoc> public object Clone() { return new ActiveXMessageFormatter(); } /// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.InitStreamedObject"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static void InitStreamedObject(object streamedObject) { IPersistStreamInit persistStreamInit = streamedObject as IPersistStreamInit; if (persistStreamInit != null) persistStreamInit.InitNew(); } /// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.Read"]/*' /> /// <devdoc> /// This method is used to read the contents from the given message /// and create an object. /// </devdoc> public object Read(Message message) { if (message == null) throw new ArgumentNullException("message"); Stream stream; byte[] bytes; byte[] newBytes; int size; int variantType = message.BodyType; switch (variantType) { case VT_LPSTR: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); size = message.properties.GetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE); if (this.internalCharBuffer == null || this.internalCharBuffer.Length < size) this.internalCharBuffer = new char[size]; if (asciiEncoding == null) this.asciiEncoding = new ASCIIEncoding(); this.asciiEncoding.GetChars(bytes, 0, size, this.internalCharBuffer, 0); return new String(this.internalCharBuffer, 0, size); case VT_BSTR: case VT_LPWSTR: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); size = message.properties.GetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE) / 2; if (this.internalCharBuffer == null || this.internalCharBuffer.Length < size) this.internalCharBuffer = new char[size]; if (unicodeEncoding == null) this.unicodeEncoding = new UnicodeEncoding(); this.unicodeEncoding.GetChars(bytes, 0, size * 2, this.internalCharBuffer, 0); return new String(this.internalCharBuffer, 0, size); case VT_VECTOR | VT_UI1: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); size = message.properties.GetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE); newBytes = new byte[size]; Array.Copy(bytes, newBytes, size); return newBytes; case VT_BOOL: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[1]; Array.Copy(bytes, newBytes, 1); if (bytes[0] != 0) return true; return false; case VT_CLSID: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[16]; Array.Copy(bytes, newBytes, 16); return new Guid(newBytes); case VT_CY: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[8]; Array.Copy(bytes, newBytes, 8); return Decimal.FromOACurrency(BitConverter.ToInt64(newBytes, 0)); case VT_DATE: bytes = message.properties.GetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY); newBytes = new byte[8]; Array.Copy(bytes, newBytes, 8); return new DateTime(BitConverter.ToInt64(newBytes, 0)); case VT_I1: case VT_UI1: stream = message.BodyStream; bytes = new byte[1]; stream.Read(bytes, 0, 1); return bytes[0]; case VT_I2: stream = message.BodyStream; bytes = new byte[2]; stream.Read(bytes, 0, 2); return BitConverter.ToInt16(bytes, 0); case VT_UI2: stream = message.BodyStream; bytes = new byte[2]; stream.Read(bytes, 0, 2); return BitConverter.ToUInt16(bytes, 0); case VT_I4: stream = message.BodyStream; bytes = new byte[4]; stream.Read(bytes, 0, 4); return BitConverter.ToInt32(bytes, 0); case VT_UI4: stream = message.BodyStream; bytes = new byte[4]; stream.Read(bytes, 0, 4); return BitConverter.ToUInt32(bytes, 0); case VT_I8: stream = message.BodyStream; bytes = new byte[8]; stream.Read(bytes, 0, 8); return BitConverter.ToInt64(bytes, 0); case VT_UI8: stream = message.BodyStream; bytes = new byte[8]; stream.Read(bytes, 0, 8); return BitConverter.ToUInt64(bytes, 0); case VT_R4: stream = message.BodyStream; bytes = new byte[4]; stream.Read(bytes, 0, 4); return BitConverter.ToSingle(bytes, 0); case VT_R8: stream = message.BodyStream; bytes = new byte[8]; stream.Read(bytes, 0, 8); return BitConverter.ToDouble(bytes, 0); case VT_NULL: return null; case VT_STREAMED_OBJECT: stream = message.BodyStream; ComStreamFromDataStream comStream = new ComStreamFromDataStream(stream); return NativeMethods.OleLoadFromStream(comStream, ref NativeMethods.IID_IUnknown); case VT_STORED_OBJECT: throw new NotSupportedException(Res.GetString(Res.StoredObjectsNotSupported)); default: throw new InvalidOperationException(Res.GetString(Res.InvalidTypeDeserialization)); } } /// <include file='doc\ActiveXMessageFormatter.uex' path='docs/doc[@for="ActiveXMessageFormatter.Write"]/*' /> /// <devdoc> /// This method is used to write the given object into the given message. /// If the formatter cannot understand the given object, an exception is thrown. /// </devdoc> public void Write(Message message, object obj) { if (message == null) throw new ArgumentNullException("message"); Stream stream; int variantType; if (obj is string) { int size = ((string)obj).Length * 2; if (this.internalBuffer == null || this.internalBuffer.Length < size) this.internalBuffer = new byte[size]; if (unicodeEncoding == null) this.unicodeEncoding = new UnicodeEncoding(); this.unicodeEncoding.GetBytes(((string)obj).ToCharArray(), 0, size / 2, this.internalBuffer, 0); message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer); message.properties.AdjustSize(NativeMethods.MESSAGE_PROPID_BODY, size); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, size); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_LPWSTR); return; } else if (obj is byte[]) { byte[] bytes = (byte[])obj; if (this.internalBuffer == null || this.internalBuffer.Length < bytes.Length) this.internalBuffer = new byte[bytes.Length]; Array.Copy(bytes, this.internalBuffer, bytes.Length); message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer); message.properties.AdjustSize(NativeMethods.MESSAGE_PROPID_BODY, bytes.Length); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, bytes.Length); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_UI1 | VT_VECTOR); return; } else if (obj is char[]) { char[] chars = (char[])obj; int size = chars.Length * 2; if (this.internalBuffer == null || this.internalBuffer.Length < size) this.internalBuffer = new byte[size]; if (unicodeEncoding == null) this.unicodeEncoding = new UnicodeEncoding(); this.unicodeEncoding.GetBytes(chars, 0, size / 2, this.internalBuffer, 0); message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, size); message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_LPWSTR); return; } else if (obj is byte) { stream = new MemoryStream(1); stream.Write(new byte[] { (byte)obj }, 0, 1); variantType = VT_UI1; } else if (obj is bool) { stream = new MemoryStream(1); if ((bool)obj) stream.Write(new byte[] { 0xff }, 0, 1); else stream.Write(new byte[] { 0x00 }, 0, 1); variantType = VT_BOOL; } else if (obj is char) { stream = new MemoryStream(2); byte[] bytes = BitConverter.GetBytes((Char)obj); stream.Write(bytes, 0, 2); variantType = VT_UI2; } else if (obj is Decimal) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes(Decimal.ToOACurrency((Decimal)obj)); stream.Write(bytes, 0, 8); variantType = VT_CY; } else if (obj is DateTime) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes(((DateTime)obj).Ticks); stream.Write(bytes, 0, 8); variantType = VT_DATE; } else if (obj is Double) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes((Double)obj); stream.Write(bytes, 0, 8); variantType = VT_R8; } else if (obj is Int16) { stream = new MemoryStream(2); byte[] bytes = BitConverter.GetBytes((short)obj); stream.Write(bytes, 0, 2); variantType = VT_I2; } else if (obj is UInt16) { stream = new MemoryStream(2); byte[] bytes = BitConverter.GetBytes((UInt16)obj); stream.Write(bytes, 0, 2); variantType = VT_UI2; } else if (obj is Int32) { stream = new MemoryStream(4); byte[] bytes = BitConverter.GetBytes((int)obj); stream.Write(bytes, 0, 4); variantType = VT_I4; } else if (obj is UInt32) { stream = new MemoryStream(4); byte[] bytes = BitConverter.GetBytes((UInt32)obj); stream.Write(bytes, 0, 4); variantType = VT_UI4; } else if (obj is Int64) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes((Int64)obj); stream.Write(bytes, 0, 8); variantType = VT_I8; } else if (obj is UInt64) { stream = new MemoryStream(8); byte[] bytes = BitConverter.GetBytes((UInt64)obj); stream.Write(bytes, 0, 8); variantType = VT_UI8; } else if (obj is Single) { stream = new MemoryStream(4); byte[] bytes = BitConverter.GetBytes((float)obj); stream.Write(bytes, 0, 4); variantType = VT_R4; } else if (obj is IPersistStream) { IPersistStream pstream = (IPersistStream)obj; ComStreamFromDataStream comStream = new ComStreamFromDataStream(new MemoryStream()); NativeMethods.OleSaveToStream(pstream, comStream); stream = comStream.GetDataStream(); variantType = VT_STREAMED_OBJECT; } else if (obj == null) { stream = new MemoryStream(); variantType = VT_NULL; } else { throw new InvalidOperationException(Res.GetString(Res.InvalidTypeSerialization)); } message.BodyStream = stream; message.BodyType = variantType; } [ComVisible(false)] private class ComStreamFromDataStream : IStream { private Stream dataStream; // to support seeking ahead of the stream length... private long virtualPosition = -1; public ComStreamFromDataStream(Stream dataStream) { if (dataStream == null) throw new ArgumentNullException("dataStream"); this.dataStream = dataStream; } private void ActualizeVirtualPosition() { if (virtualPosition == -1) return; if (virtualPosition > dataStream.Length) dataStream.SetLength(virtualPosition); dataStream.Position = virtualPosition; virtualPosition = -1; } public IStream Clone() { NotImplemented(); return null; } public void Commit(int grfCommitFlags) { dataStream.Flush(); // Extend the length of the file if needed. ActualizeVirtualPosition(); } public long CopyTo(IStream pstm, long cb, long[] pcbRead) { int bufSize = 4096; IntPtr buffer = Marshal.AllocHGlobal((IntPtr)bufSize); if (buffer == IntPtr.Zero) throw new OutOfMemoryException(); long written = 0; try { while (written < cb) { int toRead = bufSize; if (written + toRead > cb) toRead = (int)(cb - written); int read = Read(buffer, toRead); if (read == 0) break; if (pstm.Write(buffer, read) != read) { throw EFail(Res.GetString(Res.IncorrectNumberOfBytes)); } written += read; } } finally { Marshal.FreeHGlobal(buffer); } if (pcbRead != null && pcbRead.Length > 0) { pcbRead[0] = written; } return written; } public Stream GetDataStream() { return dataStream; } public void LockRegion(long libOffset, long cb, int dwLockType) { } protected static ExternalException EFail(string msg) { ExternalException e = new ExternalException(msg, NativeMethods.E_FAIL); throw e; } protected static void NotImplemented() { ExternalException e = new ExternalException(Res.GetString(Res.NotImplemented), NativeMethods.E_NOTIMPL); throw e; } public int Read(IntPtr buf, int length) { byte[] buffer = new byte[length]; int count = Read(buffer, length); Marshal.Copy(buffer, 0, buf, length); return count; } public int Read(byte[] buffer, int length) { ActualizeVirtualPosition(); return dataStream.Read(buffer, 0, length); } public void Revert() { NotImplemented(); } public long Seek(long offset, int origin) { long pos = virtualPosition; if (virtualPosition == -1) { pos = dataStream.Position; } long len = dataStream.Length; switch (origin) { case NativeMethods.STREAM_SEEK_SET: if (offset <= len) { dataStream.Position = offset; virtualPosition = -1; } else { virtualPosition = offset; } break; case NativeMethods.STREAM_SEEK_END: if (offset <= 0) { dataStream.Position = len + offset; virtualPosition = -1; } else { virtualPosition = len + offset; } break; case NativeMethods.STREAM_SEEK_CUR: if (offset + pos <= len) { dataStream.Position = pos + offset; virtualPosition = -1; } else { virtualPosition = offset + pos; } break; } if (virtualPosition != -1) { return virtualPosition; } else { return dataStream.Position; } } public void SetSize(long value) { dataStream.SetLength(value); } public void Stat(IntPtr pstatstg, int grfStatFlag) { // GpStream has a partial implementation, but it's so partial rather // restrict it to use with GDI+ NotImplemented(); } public void UnlockRegion(long libOffset, long cb, int dwLockType) { } public int Write(IntPtr buf, int length) { byte[] buffer = new byte[length]; Marshal.Copy(buf, buffer, 0, length); return Write(buffer, length); } public int Write(byte[] buffer, int length) { ActualizeVirtualPosition(); dataStream.Write(buffer, 0, length); return length; } } } }
using System; using System.Collections.Generic; using System.Data.Linq; using System.Data.Linq.Provider; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.SqlClient { internal class SqlDuplicator { DuplicatingVisitor superDuper; internal SqlDuplicator() : this(true) { } internal SqlDuplicator(bool ignoreExternalRefs) { this.superDuper = new DuplicatingVisitor(ignoreExternalRefs); } internal static SqlNode Copy(SqlNode node) { if (node == null) return null; switch (node.NodeType) { case SqlNodeType.ColumnRef: case SqlNodeType.Value: case SqlNodeType.Parameter: case SqlNodeType.Variable: return node; default: return new SqlDuplicator().Duplicate(node); } } internal SqlNode Duplicate(SqlNode node) { return this.superDuper.Visit(node); } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification="These issues are related to our use of if-then and case statements for node types, which adds to the complexity count however when reviewed they are easy to navigate and understand.")] internal class DuplicatingVisitor : SqlVisitor { Dictionary<SqlNode, SqlNode> nodeMap; bool ingoreExternalRefs; internal DuplicatingVisitor(bool ignoreExternalRefs) { this.ingoreExternalRefs = ignoreExternalRefs; this.nodeMap = new Dictionary<SqlNode, SqlNode>(); } internal override SqlNode Visit(SqlNode node) { if (node == null) { return null; } SqlNode result = null; if (this.nodeMap.TryGetValue(node, out result)) { return result; } result = base.Visit(node); this.nodeMap[node] = result; return result; } internal override SqlExpression VisitDoNotVisit(SqlDoNotVisitExpression expr) { // duplicator can duplicate through a do-no-visit node return new SqlDoNotVisitExpression(this.VisitExpression(expr.Expression)); } internal override SqlAlias VisitAlias(SqlAlias a) { SqlAlias n = new SqlAlias(a.Node); this.nodeMap[a] = n; n.Node = this.Visit(a.Node); n.Name = a.Name; return n; } internal override SqlExpression VisitAliasRef(SqlAliasRef aref) { if (this.ingoreExternalRefs && !this.nodeMap.ContainsKey(aref.Alias)) { return aref; } return new SqlAliasRef((SqlAlias)this.Visit(aref.Alias)); } internal override SqlRowNumber VisitRowNumber(SqlRowNumber rowNumber) { List<SqlOrderExpression> orderBy = new List<SqlOrderExpression>(); foreach (SqlOrderExpression expr in rowNumber.OrderBy) { orderBy.Add(new SqlOrderExpression(expr.OrderType, (SqlExpression)this.Visit(expr.Expression))); } return new SqlRowNumber(rowNumber.ClrType, rowNumber.SqlType, orderBy, rowNumber.SourceExpression); } internal override SqlExpression VisitBinaryOperator(SqlBinary bo) { SqlExpression left = (SqlExpression)this.Visit(bo.Left); SqlExpression right = (SqlExpression)this.Visit(bo.Right); return new SqlBinary(bo.NodeType, bo.ClrType, bo.SqlType, left, right, bo.Method); } internal override SqlExpression VisitClientQuery(SqlClientQuery cq) { SqlSubSelect query = (SqlSubSelect) this.VisitExpression(cq.Query); SqlClientQuery nq = new SqlClientQuery(query); for (int i = 0, n = cq.Arguments.Count; i < n; i++) { nq.Arguments.Add(this.VisitExpression(cq.Arguments[i])); } for (int i = 0, n = cq.Parameters.Count; i < n; i++) { nq.Parameters.Add((SqlParameter)this.VisitExpression(cq.Parameters[i])); } return nq; } internal override SqlExpression VisitJoinedCollection(SqlJoinedCollection jc) { return new SqlJoinedCollection(jc.ClrType, jc.SqlType, this.VisitExpression(jc.Expression), this.VisitExpression(jc.Count), jc.SourceExpression); } internal override SqlExpression VisitClientArray(SqlClientArray scar) { SqlExpression[] exprs = new SqlExpression[scar.Expressions.Count]; for (int i = 0, n = exprs.Length; i < n; i++) { exprs[i] = this.VisitExpression(scar.Expressions[i]); } return new SqlClientArray(scar.ClrType, scar.SqlType, exprs, scar.SourceExpression); } internal override SqlExpression VisitTypeCase(SqlTypeCase tc) { SqlExpression disc = VisitExpression(tc.Discriminator); List<SqlTypeCaseWhen> whens = new List<SqlTypeCaseWhen>(); foreach(SqlTypeCaseWhen when in tc.Whens) { whens.Add(new SqlTypeCaseWhen(VisitExpression(when.Match), VisitExpression(when.TypeBinding))); } return new SqlTypeCase(tc.ClrType, tc.SqlType, tc.RowType, disc, whens, tc.SourceExpression); } internal override SqlExpression VisitNew(SqlNew sox) { SqlExpression[] args = new SqlExpression[sox.Args.Count]; SqlMemberAssign[] bindings = new SqlMemberAssign[sox.Members.Count]; for (int i = 0, n = args.Length; i < n; i++) { args[i] = this.VisitExpression(sox.Args[i]); } for (int i = 0, n = bindings.Length; i < n; i++) { bindings[i] = this.VisitMemberAssign(sox.Members[i]); } return new SqlNew(sox.MetaType, sox.SqlType, sox.Constructor, args, sox.ArgMembers, bindings, sox.SourceExpression); } internal override SqlNode VisitLink(SqlLink link) { SqlExpression[] exprs = new SqlExpression[link.KeyExpressions.Count]; for (int i = 0, n = exprs.Length; i < n; i++) { exprs[i] = this.VisitExpression(link.KeyExpressions[i]); } SqlLink newLink = new SqlLink(new object(), link.RowType, link.ClrType, link.SqlType, null, link.Member, exprs, null, link.SourceExpression); this.nodeMap[link] = newLink; // break the potential cyclic tree by visiting these after adding to the map newLink.Expression = this.VisitExpression(link.Expression); newLink.Expansion = this.VisitExpression(link.Expansion); return newLink; } internal override SqlExpression VisitColumn(SqlColumn col) { SqlColumn n = new SqlColumn(col.ClrType, col.SqlType, col.Name, col.MetaMember, null, col.SourceExpression); this.nodeMap[col] = n; n.Expression = this.VisitExpression(col.Expression); n.Alias = (SqlAlias)this.Visit(col.Alias); return n; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { if (this.ingoreExternalRefs && !this.nodeMap.ContainsKey(cref.Column)) { return cref; } return new SqlColumnRef((SqlColumn)this.Visit(cref.Column)); } internal override SqlStatement VisitDelete(SqlDelete sd) { return new SqlDelete((SqlSelect)this.Visit(sd.Select), sd.SourceExpression); } internal override SqlExpression VisitElement(SqlSubSelect elem) { return this.VisitMultiset(elem); } internal override SqlExpression VisitExists(SqlSubSelect sqlExpr) { return new SqlSubSelect(sqlExpr.NodeType, sqlExpr.ClrType, sqlExpr.SqlType, (SqlSelect)this.Visit(sqlExpr.Select)); } internal override SqlStatement VisitInsert(SqlInsert si) { SqlInsert n = new SqlInsert(si.Table, this.VisitExpression(si.Expression), si.SourceExpression); n.OutputKey = si.OutputKey; n.OutputToLocal = si.OutputToLocal; n.Row = this.VisitRow(si.Row); return n; } internal override SqlSource VisitJoin(SqlJoin join) { SqlSource left = this.VisitSource(join.Left); SqlSource right = this.VisitSource(join.Right); SqlExpression cond = (SqlExpression)this.Visit(join.Condition); return new SqlJoin(join.JoinType, left, right, cond, join.SourceExpression); } internal override SqlExpression VisitValue(SqlValue value) { return value; } internal override SqlNode VisitMember(SqlMember m) { return new SqlMember(m.ClrType, m.SqlType, (SqlExpression)this.Visit(m.Expression), m.Member); } internal override SqlMemberAssign VisitMemberAssign(SqlMemberAssign ma) { return new SqlMemberAssign(ma.Member, (SqlExpression)this.Visit(ma.Expression)); } internal override SqlExpression VisitMultiset(SqlSubSelect sms) { return new SqlSubSelect(sms.NodeType, sms.ClrType, sms.SqlType, (SqlSelect)this.Visit(sms.Select)); } internal override SqlExpression VisitParameter(SqlParameter p) { SqlParameter n = new SqlParameter(p.ClrType, p.SqlType, p.Name, p.SourceExpression); n.Direction = p.Direction; return n; } internal override SqlRow VisitRow(SqlRow row) { SqlRow nrow = new SqlRow(row.SourceExpression); foreach (SqlColumn c in row.Columns) { nrow.Columns.Add((SqlColumn)this.Visit(c)); } return nrow; } internal override SqlExpression VisitScalarSubSelect(SqlSubSelect ss) { return new SqlSubSelect(SqlNodeType.ScalarSubSelect, ss.ClrType, ss.SqlType, this.VisitSequence(ss.Select)); } internal override SqlSelect VisitSelect(SqlSelect select) { SqlSource from = this.VisitSource(select.From); List<SqlExpression> gex = null; if (select.GroupBy.Count > 0) { gex = new List<SqlExpression>(select.GroupBy.Count); foreach (SqlExpression sqlExpr in select.GroupBy) { gex.Add((SqlExpression)this.Visit(sqlExpr)); } } SqlExpression having = (SqlExpression)this.Visit(select.Having); List<SqlOrderExpression> lex = null; if (select.OrderBy.Count > 0) { lex = new List<SqlOrderExpression>(select.OrderBy.Count); foreach (SqlOrderExpression sox in select.OrderBy) { SqlOrderExpression nsox = new SqlOrderExpression(sox.OrderType, (SqlExpression)this.Visit(sox.Expression)); lex.Add(nsox); } } SqlExpression top = (SqlExpression)this.Visit(select.Top); SqlExpression where = (SqlExpression)this.Visit(select.Where); SqlRow row = (SqlRow)this.Visit(select.Row); SqlExpression selection = this.VisitExpression(select.Selection); SqlSelect n = new SqlSelect(selection, from, select.SourceExpression); if (gex != null) n.GroupBy.AddRange(gex); n.Having = having; if (lex != null) n.OrderBy.AddRange(lex); n.OrderingType = select.OrderingType; n.Row = row; n.Top = top; n.IsDistinct = select.IsDistinct; n.IsPercent = select.IsPercent; n.Where = where; n.DoNotOutput = select.DoNotOutput; return n; } internal override SqlTable VisitTable(SqlTable tab) { SqlTable nt = new SqlTable(tab.MetaTable, tab.RowType, tab.SqlRowType, tab.SourceExpression); this.nodeMap[tab] = nt; foreach (SqlColumn c in tab.Columns) { nt.Columns.Add((SqlColumn)this.Visit(c)); } return nt; } internal override SqlUserQuery VisitUserQuery(SqlUserQuery suq) { List<SqlExpression> args = new List<SqlExpression>(suq.Arguments.Count); foreach (SqlExpression expr in suq.Arguments) { args.Add(this.VisitExpression(expr)); } SqlExpression projection = this.VisitExpression(suq.Projection); SqlUserQuery n = new SqlUserQuery(suq.QueryText, projection, args, suq.SourceExpression); this.nodeMap[suq] = n; foreach (SqlUserColumn suc in suq.Columns) { SqlUserColumn dupSuc = new SqlUserColumn(suc.ClrType, suc.SqlType, suc.Query, suc.Name, suc.IsRequired, suc.SourceExpression); this.nodeMap[suc] = dupSuc; n.Columns.Add(dupSuc); } return n; } internal override SqlStoredProcedureCall VisitStoredProcedureCall(SqlStoredProcedureCall spc) { List<SqlExpression> args = new List<SqlExpression>(spc.Arguments.Count); foreach (SqlExpression expr in spc.Arguments) { args.Add(this.VisitExpression(expr)); } SqlExpression projection = this.VisitExpression(spc.Projection); SqlStoredProcedureCall n = new SqlStoredProcedureCall(spc.Function, projection, args, spc.SourceExpression); this.nodeMap[spc] = n; foreach (SqlUserColumn suc in spc.Columns) { n.Columns.Add((SqlUserColumn)this.Visit(suc)); } return n; } internal override SqlExpression VisitUserColumn(SqlUserColumn suc) { if (this.ingoreExternalRefs && !this.nodeMap.ContainsKey(suc)) { return suc; } return new SqlUserColumn(suc.ClrType, suc.SqlType, suc.Query, suc.Name, suc.IsRequired, suc.SourceExpression); } internal override SqlExpression VisitUserRow(SqlUserRow row) { return new SqlUserRow(row.RowType, row.SqlType, (SqlUserQuery)this.Visit(row.Query), row.SourceExpression); } internal override SqlExpression VisitTreat(SqlUnary t) { return new SqlUnary(SqlNodeType.Treat, t.ClrType, t.SqlType, (SqlExpression)this.Visit(t.Operand), t.SourceExpression); } internal override SqlExpression VisitUnaryOperator(SqlUnary uo) { return new SqlUnary(uo.NodeType, uo.ClrType, uo.SqlType, (SqlExpression)this.Visit(uo.Operand), uo.Method, uo.SourceExpression); } internal override SqlStatement VisitUpdate(SqlUpdate su) { SqlSelect ss = (SqlSelect)this.Visit(su.Select); List<SqlAssign> assignments = new List<SqlAssign>(su.Assignments.Count); foreach (SqlAssign sa in su.Assignments) { assignments.Add((SqlAssign)this.Visit(sa)); } return new SqlUpdate(ss, assignments, su.SourceExpression); } internal override SqlStatement VisitAssign(SqlAssign sa) { return new SqlAssign(this.VisitExpression(sa.LValue), this.VisitExpression(sa.RValue), sa.SourceExpression); } internal override SqlExpression VisitSearchedCase(SqlSearchedCase c) { SqlExpression @else = this.VisitExpression(c.Else); SqlWhen[] whens = new SqlWhen[c.Whens.Count]; for (int i = 0, n = whens.Length; i < n; i++) { SqlWhen when = c.Whens[i]; whens[i] = new SqlWhen(this.VisitExpression(when.Match), this.VisitExpression(when.Value)); } return new SqlSearchedCase(c.ClrType, whens, @else, c.SourceExpression); } internal override SqlExpression VisitClientCase(SqlClientCase c) { SqlExpression expr = this.VisitExpression(c.Expression); SqlClientWhen[] whens = new SqlClientWhen[c.Whens.Count]; for (int i = 0, n = whens.Length; i < n; i++) { SqlClientWhen when = c.Whens[i]; whens[i] = new SqlClientWhen(this.VisitExpression(when.Match), this.VisitExpression(when.Value)); } return new SqlClientCase(c.ClrType, expr, whens, c.SourceExpression); } internal override SqlExpression VisitSimpleCase(SqlSimpleCase c) { SqlExpression expr = this.VisitExpression(c.Expression); SqlWhen[] whens = new SqlWhen[c.Whens.Count]; for (int i = 0, n = whens.Length; i < n; i++) { SqlWhen when = c.Whens[i]; whens[i] = new SqlWhen(this.VisitExpression(when.Match), this.VisitExpression(when.Value)); } return new SqlSimpleCase(c.ClrType, expr, whens, c.SourceExpression); } internal override SqlNode VisitUnion(SqlUnion su) { return new SqlUnion(this.Visit(su.Left), this.Visit(su.Right), su.All); } internal override SqlExpression VisitExprSet(SqlExprSet xs) { SqlExpression[] exprs = new SqlExpression[xs.Expressions.Count]; for (int i = 0, n = exprs.Length; i < n; i++) { exprs[i] = this.VisitExpression(xs.Expressions[i]); } return new SqlExprSet(xs.ClrType, exprs, xs.SourceExpression); } internal override SqlBlock VisitBlock(SqlBlock block) { SqlBlock nb = new SqlBlock(block.SourceExpression); foreach (SqlStatement stmt in block.Statements) { nb.Statements.Add((SqlStatement)this.Visit(stmt)); } return nb; } internal override SqlExpression VisitVariable(SqlVariable v) { return v; } internal override SqlExpression VisitOptionalValue(SqlOptionalValue sov) { SqlExpression hasValue = this.VisitExpression(sov.HasValue); SqlExpression value = this.VisitExpression(sov.Value); return new SqlOptionalValue(hasValue, value); } internal override SqlExpression VisitBetween(SqlBetween between) { SqlBetween nbet = new SqlBetween( between.ClrType, between.SqlType, this.VisitExpression(between.Expression), this.VisitExpression(between.Start), this.VisitExpression(between.End), between.SourceExpression ); return nbet; } internal override SqlExpression VisitIn(SqlIn sin) { SqlIn nin = new SqlIn(sin.ClrType, sin.SqlType, this.VisitExpression(sin.Expression), sin.Values, sin.SourceExpression); for (int i = 0, n = nin.Values.Count; i < n; i++) { nin.Values[i] = this.VisitExpression(nin.Values[i]); } return nin; } internal override SqlExpression VisitLike(SqlLike like) { return new SqlLike( like.ClrType, like.SqlType, this.VisitExpression(like.Expression), this.VisitExpression(like.Pattern), this.VisitExpression(like.Escape), like.SourceExpression ); } internal override SqlExpression VisitFunctionCall(SqlFunctionCall fc) { SqlExpression[] args = new SqlExpression[fc.Arguments.Count]; for (int i = 0, n = fc.Arguments.Count; i < n; i++) { args[i] = this.VisitExpression(fc.Arguments[i]); } return new SqlFunctionCall(fc.ClrType, fc.SqlType, fc.Name, args, fc.SourceExpression); } internal override SqlExpression VisitTableValuedFunctionCall(SqlTableValuedFunctionCall fc) { SqlExpression[] args = new SqlExpression[fc.Arguments.Count]; for (int i = 0, n = fc.Arguments.Count; i < n; i++) { args[i] = this.VisitExpression(fc.Arguments[i]); } SqlTableValuedFunctionCall nfc = new SqlTableValuedFunctionCall(fc.RowType, fc.ClrType, fc.SqlType, fc.Name, args, fc.SourceExpression); this.nodeMap[fc] = nfc; foreach (SqlColumn c in fc.Columns) { nfc.Columns.Add((SqlColumn)this.Visit(c)); } return nfc; } internal override SqlExpression VisitMethodCall(SqlMethodCall mc) { SqlExpression[] args = new SqlExpression[mc.Arguments.Count]; for (int i = 0, n = mc.Arguments.Count; i < n; i++) { args[i] = this.VisitExpression(mc.Arguments[i]); } return new SqlMethodCall(mc.ClrType, mc.SqlType, mc.Method, this.VisitExpression(mc.Object), args, mc.SourceExpression); } internal override SqlExpression VisitSharedExpression(SqlSharedExpression sub) { SqlSharedExpression n = new SqlSharedExpression(sub.Expression); this.nodeMap[sub] = n; n.Expression = this.VisitExpression(sub.Expression); return n; } internal override SqlExpression VisitSharedExpressionRef(SqlSharedExpressionRef sref) { if (this.ingoreExternalRefs && !this.nodeMap.ContainsKey(sref.SharedExpression)) { return sref; } return new SqlSharedExpressionRef((SqlSharedExpression)this.Visit(sref.SharedExpression)); } internal override SqlExpression VisitSimpleExpression(SqlSimpleExpression simple) { SqlSimpleExpression n = new SqlSimpleExpression(this.VisitExpression(simple.Expression)); return n; } internal override SqlExpression VisitGrouping(SqlGrouping g) { SqlGrouping n = new SqlGrouping(g.ClrType, g.SqlType, this.VisitExpression(g.Key), this.VisitExpression(g.Group), g.SourceExpression ); return n; } internal override SqlExpression VisitDiscriminatedType(SqlDiscriminatedType dt) { return new SqlDiscriminatedType(dt.SqlType, this.VisitExpression(dt.Discriminator), dt.TargetType, dt.SourceExpression); } internal override SqlExpression VisitLift(SqlLift lift) { return new SqlLift(lift.ClrType, this.VisitExpression(lift.Expression), lift.SourceExpression); } internal override SqlExpression VisitDiscriminatorOf(SqlDiscriminatorOf dof) { return new SqlDiscriminatorOf(this.VisitExpression(dof.Object), dof.ClrType, dof.SqlType, dof.SourceExpression); } internal override SqlNode VisitIncludeScope(SqlIncludeScope scope) { return new SqlIncludeScope(this.Visit(scope.Child), scope.SourceExpression); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Qwack.Math.Solvers { //https://en.wikipedia.org/wiki/Nelder//E2//80//93Mead_method public static class NelderMead { public static double[] MethodSolve(Func<double[], double> fn, double[] startingPoint, double[] initialStep, double tollerance, int maxItterations) { var n = startingPoint == null ? 0 : startingPoint.Length; if (n < 1) throw new Exception("Must have at least one variable"); var konvge = 10; var xmin = new double[n]; var icount = 0; var numres = 0; var kcount = maxItterations; var ccoeff = 0.5; var ecoeff = 2.0; var eps = 0.001; var rcoeff = 1.0; var ynewlo = 0.0; // Check the input parameters. if (tollerance <= 0.0) throw new Exception("Tollerance must be positive"); var jcount = konvge; var nn = n + 1; var dnn = nn; var del = 1.0; var rq = tollerance * n; // Initial or restarted loop. var retCode = 0; while (retCode==0) { var p = new double[n, n + 1]; for (var i = 0; i < n; i++) p[i, nn - 1] = startingPoint[i]; var y = new double[nn]; y[nn - 1] = fn(startingPoint); icount ++; for (var j = 0; j < n; j++) { var x = startingPoint[j]; startingPoint[j] += initialStep[j] * del; for (var i = 0; i < n; i++) { p[i, j] = startingPoint[i]; } y[j] = fn(startingPoint); icount++; startingPoint[j] = x; } // The simplex construction is complete. //Find highest and lowest Y values.YNEWLO = Y(IHI) indicates //the vertex of the simplex to be replaced. var ylo = y[0]; var ilo = 0; for (var i = 1; i < nn; i++) { if (y[i] < ylo) { ylo = y[i]; ilo = i; } } // Inner loop. while (1 == 1) { if (kcount <= icount) break; ynewlo = y[0]; var ihi = 0; for (var i = 1; i < nn; i++) { if (ynewlo < y[i]) { ynewlo = y[i]; ihi = i; } } // Calculate PBAR, the centroid of the simplex vertices //excepting the vertex with Y value YNEWLO. var pbar = new double[n]; var pstar = new double[n]; for (var i = 0; i < pbar.Length; i++) { var z = 0.0; for (var j = 0; j < nn; j++) { z += p[i, j]; } z -= p[i, ihi]; pbar[i] = z / n; } // Reflection through the centroid. for (var i = 0; i < pstar.Length; i++) pstar[i] = pbar[i] + rcoeff * (pbar[i] - p[i, ihi]); var ystar = fn(pstar); icount++; // Successful reflection, so extension. if (ystar < ylo) { var p2star = new double[n]; for (var i = 0; i < p2star.Length; i++) p2star[i] = pbar[i] + ecoeff * (pstar[i] - pbar[i]); var y2star = fn(p2star); icount++; // Check extension. if (ystar < y2star) { for (var i = 0; i < pstar.Length; i++) p[i, ihi] = pstar[i]; y[ihi] = ystar; } else // Retain extension or contraction. { for (var i = 0; i < n; i++) p[i, ihi] = p2star[i]; y[ihi] = y2star; } } else // No extension. { var l = 0; for (var i = 0; i < nn; i++) if (ystar < y[i]) l++; if (1 < l) { for (var i = 0; i < pstar.Length; i++) p[i, ihi] = pstar[i]; y[ihi] = ystar; } else if (l == 0) // Contraction on the Y(IHI) side of the centroid. { var p2star = new double[n]; for (var i = 0; i < p2star.Length; i++) p2star[i] = pbar[i] + ccoeff * (p[i, ihi] - pbar[i]); var y2star = fn(p2star); icount++; // Contract the whole simplex. if (y[ihi] < y2star) { for (var j = 0; j < y.Length; j++) { for (var i = 0; i < n; i++) { p[i, j] = (p[i, j] + p[i, ilo]) * 0.5; xmin[i] = p[i, j]; } y[j] = fn(xmin); icount++; } ylo = y[0]; ilo = 0; for (var i = 1; i < y.Length; i++) { if (y[i] < ylo) { ylo = y[i]; ilo = i; } } continue; } //Retain contraction. else { for (var i = 0; i < n; i++) p[i, ihi] = p2star[i]; y[ihi] = y2star; } }// Contraction on the reflection side of the centroid. else if (l == 1) { var p2star = new double[n]; for (var i = 0; i < p2star.Length; i++) p2star[i] = pbar[i] + ccoeff * (pstar[i] - pbar[i]); var y2star = fn(p2star); icount++; // Retain reflection ? if (y2star <= ystar) { for (var i = 0; i < n; i++) p[i, ihi] = p2star[i]; y[ihi] = y2star; } else { for (var i = 0; i < n; i++) p[i, ihi] = pstar[i]; y[ihi] = ystar; } } } // // Check if YLO improved. // if (y[ihi] < ylo) { ylo = y[ihi]; ilo = ihi; } jcount--; if (0 < jcount) { continue; } // Check to see if minimum reached. if (icount <= kcount) { jcount = konvge; var z = 0.0; for (var i = 0; i < y.Length; i++) z+=y[i]; var x = z / nn; z = 0.0; for (var i = 0; i < y.Length; i++) z += (y[i] - x) * (y[i] - x); if (z <= rq) { break; } } } // // Factorial tests to check that YNEWLO is a local minimum. // for (var i = 0; i < n; i++) xmin[i] = p[i, ilo]; ynewlo = y[ilo]; if (kcount < icount) { retCode = 1; break; } for (var i = 0; i < n; i++) { del = initialStep[i] * eps; xmin[i] += del; var z = fn(xmin); icount++; if (z < ynewlo) { retCode = 1; break; } xmin[i] -= 2.0 * del; z = fn(xmin); icount++; if (z < ynewlo) { retCode = 1; break; } xmin[i] += del; } if (retCode == 0) break; // Restart the procedure. Array.Copy(xmin, startingPoint, n); del = eps; numres++; } return xmin; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Test; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using Xunit; namespace ResourceGroups.Tests { public class LiveDeploymentTests : TestBase { const string DummyTemplateUri = "https://testtemplates.blob.core.windows.net/templates/dummytemplate.js"; const string GoodWebsiteTemplateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/201-web-app-github-deploy/azuredeploy.json"; const string BadTemplateUri = "https://testtemplates.blob.core.windows.net/templates/bad-website-1.js"; const string GoodResourceId = "/subscriptions/a1bfa635-f2bf-42f1-86b5-848c674fc321/resourceGroups/TemplateSpecSDK/providers/Microsoft.Resources/TemplateSpecs/SdkTestTemplate/versions/1.0.0"; const string LocationWestEurope = "West Europe"; const string LocationSouthCentralUS = "South Central US"; public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler) { handler.IsPassThrough = true; return this.GetResourceManagementClientWithHandler(context, handler); } // TODO: Fix [Fact (Skip = "TODO: Re-record test")] public void CreateDummyDeploymentTemplateWorks() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; var dictionary = new Dictionary<string, object> { {"string", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"securestring", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"int", new Dictionary<string, object>() { {"value", 42}, }}, {"bool", new Dictionary<string, object>() { {"value", true}, }} }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = DummyTemplateUri }, Parameters = dictionary, Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); JObject json = JObject.Parse(handler.Request); Assert.NotNull(client.Deployments.Get(groupName, deploymentName)); } } [Fact()] public void CreateDeploymentWithStringTemplateAndParameters() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json")), Parameters = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account-parameters.json")), Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); var deployment = client.Deployments.Get(groupName, deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); } } [Fact] public void CreateDeploymentAndValidateProperties() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse( @"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"), Mode = DeploymentMode.Incremental, }, Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); Assert.NotNull(deploymentCreateResult.Id); Assert.Equal(deploymentName, deploymentCreateResult.Name); TestUtilities.Wait(1000); var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, null); var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult); Assert.Equal(deploymentName, deploymentGetResult.Name); Assert.Equal(deploymentName, deploymentListResult.First().Name); Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri); Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri); Assert.NotNull(deploymentGetResult.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Tags); Assert.True(deploymentListResult.First().Tags.ContainsKey("tagKey1")); } } [Fact] public void CreateDeploymentWithResourceId() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Id = GoodResourceId }, Parameters = JObject.Parse( @"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"), Mode = DeploymentMode.Incremental, }, Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); Assert.NotNull(deploymentCreateResult.Id); Assert.Equal(deploymentName, deploymentCreateResult.Name); TestUtilities.Wait(1000); var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, null); var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult); Assert.Equal(deploymentName, deploymentGetResult.Name); Assert.Equal(deploymentName, deploymentListResult.First().Name); Assert.Equal(GoodResourceId, deploymentGetResult.Properties.TemplateLink.Id); Assert.Equal(GoodResourceId, deploymentListResult.First().Properties.TemplateLink.Id); Assert.NotNull(deploymentGetResult.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Tags); Assert.True(deploymentListResult.First().Tags.ContainsKey("tagKey1")); } } [Fact] public void ValidateGoodDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csres"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); //Action var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty); } } [Fact] public void ValidateGoodDeploymentWithId() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csres"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Id = GoodResourceId, }, Parameters = JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); //Action var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty); } } //TODO: Fix [Fact(Skip = "TODO: Re-record test")] public void ValidateGoodDeploymentWithInlineTemplate() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = File.ReadAllText(Path.Combine("ScenarioTests", "good-website.json")), Parameters = JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); //Action var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty); } } [Fact] public void ValidateBadDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = BadTemplateUri, }, Parameters = JObject.Parse(@"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); var result = client.Deployments.Validate(groupName, deploymentName, parameters); Assert.NotNull(result); Assert.Equal("InvalidTemplate", result.Error.Code); } } [Fact] public void CreateDeploymentCheckSuccessOperations() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csres"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Id = GoodResourceId, }, Parameters = JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); //Wait for deployment to complete TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Any()); Assert.NotNull(operations.First().Id); Assert.NotNull(operations.First().OperationId); Assert.NotNull(operations.First().Properties); Assert.Null(operations.First().Properties.StatusMessage); } } // TODO: Fix [Fact(Skip = "TODO: Re-record test")] public void CreateDummyDeploymentProducesOperations() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; var dictionary = new Dictionary<string, object> { {"string", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"securestring", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"int", new Dictionary<string, object>() { {"value", 42}, }}, {"bool", new Dictionary<string, object>() { {"value", true}, }} }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = DummyTemplateUri }, Parameters = dictionary, Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); // Wait until deployment completes TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Any()); Assert.NotNull(operations.First().Id); Assert.NotNull(operations.First().OperationId); Assert.NotNull(operations.First().Properties); } } // TODO: Fix [Fact(Skip = "TODO: Re-record test")] public void ListDeploymentsWorksWithFilter() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"), Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Running")); if (null == deploymentListResult|| deploymentListResult.Count() == 0) { deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Accepted")); } var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult); Assert.Equal(deploymentName, deploymentGetResult.Name); Assert.Equal(deploymentName, deploymentListResult.First().Name); Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri); Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri); Assert.NotNull(deploymentGetResult.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Properties.CorrelationId); Assert.Contains("mctest0101", deploymentGetResult.Properties.Parameters.ToString()); Assert.Contains("mctest0101", deploymentListResult.First().Properties.Parameters.ToString()); } } [Fact] public void CreateLargeWebDeploymentTemplateWorks() { var handler = new RecordedDelegatingHandler(); using (MockContext context = MockContext.Start(this.GetType())) { string resourceName = TestUtilities.GenerateName("csmr"); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse("{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'sku': {'value': 'F1'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationSouthCentralUS }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); // Wait until deployment completes TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Any()); } } [Fact] public void SubscriptionLevelDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = "SDK-test"; string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "subscription_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'armbuilddemo1803'}}"), Mode = DeploymentMode.Incremental, }, Location = "WestUS", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" }); //Validate var validationResult = client.Deployments.ValidateAtSubscriptionScope(deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtSubscriptionScope(deploymentName, parameters); var deployment = client.Deployments.GetAtSubscriptionScope(deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); } } [Fact] public void ManagementGroupLevelDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupId = "tag-mg-sdk"; string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new ScopedDeployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "management_group_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'tagsa060120'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; //Validate var validationResult = client.Deployments.ValidateAtManagementGroupScope(groupId, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtManagementGroupScope(groupId, deploymentName, parameters); var deployment = client.Deployments.GetAtManagementGroupScope(groupId, deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); } } [Fact] public void TenantLevelDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new ScopedDeployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "tenant_level_template.json"))), Parameters = JObject.Parse("{'managementGroupId': {'value': 'gopremra-testmg'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US 2", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; //Validate var validationResult = client.Deployments.ValidateAtTenantScope(deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtTenantScope(deploymentName, parameters); var deployment = client.Deployments.GetAtTenantScope(deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtTenantScope(deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtTenant() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "tenant_level_template.json"))), Parameters = JObject.Parse("{'managementGroupId': {'value': 'gopremra-testmg'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US 2", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: "", deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: "", deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: "", deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: "", deploymentName: deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtManagementGroup() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupId = "tag-mg-sdk"; string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "management_group_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'tagsa1'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; var managementGroupScope = $"/providers/Microsoft.Management/managementGroups/{groupId}"; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: managementGroupScope, deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: managementGroupScope, deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: managementGroupScope, deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: managementGroupScope, deploymentName: deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtSubscription() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = "SDK-test"; string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "subscription_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'armbuilddemo1803'}}"), Mode = DeploymentMode.Incremental, }, Location = "WestUS", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" }); var subscriptionScope = $"/subscriptions/{client.SubscriptionId}"; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: subscriptionScope, deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: subscriptionScope, deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: subscriptionScope, deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: subscriptionScope, deploymentName: deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtResourceGroup() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = "SDK-test-01"; string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'sdkTestStorageAccount'}}"), Mode = DeploymentMode.Incremental, }, Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" }); var resourceGroupScope = $"/subscriptions/{client.SubscriptionId}/resourceGroups/{groupName}"; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: resourceGroupScope, deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: resourceGroupScope, deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: resourceGroupScope, deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: resourceGroupScope, deploymentName: deploymentName); Assert.Equal(2, deploymentOperations.Count()); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { 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> /// LoadBalancersOperations operations. /// </summary> internal partial class LoadBalancersOperations : IServiceOperations<NetworkClient>, ILoadBalancersOperations { /// <summary> /// Initializes a new instance of the LoadBalancersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancersOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _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<LoadBalancer>(_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> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <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<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _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<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _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<Page<LoadBalancer>>(_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> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _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 != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("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(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, 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 != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _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<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _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<Page<LoadBalancer>>(_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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** Purpose: Implements a generic, dynamically sized list as an ** array. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Runtime; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.ObjectModel; using System.Security.Permissions; // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T> { private const int _defaultCapacity = 4; private T[] _items; [ContractPublicPropertyName("Count")] private int _size; private int _version; [NonSerialized] private Object _syncRoot; static readonly T[] _emptyArray = new T[0]; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to _defaultCapacity, and then increased in multiples of two // as required. public List() { _items = _emptyArray; } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public List(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (capacity == 0) _items = _emptyArray; else _items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public List(IEnumerable<T> collection) { if (collection==null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if( c != null) { int count = c.Count; if (count == 0) { _items = _emptyArray; } else { _items = new T[count]; c.CopyTo(_items, 0); _size = count; } } else { _size = 0; _items = _emptyArray; // This enumerable could be empty. Let Add allocate a new array, if needed. // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using(IEnumerator<T> en = collection.GetEnumerator()) { while(en.MoveNext()) { Add(en.Current); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return _items.Length; } set { if (value < _size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity); } Contract.EndContractBlock(); if (value != _items.Length) { if (value > 0) { T[] newItems = new T[value]; if (_size > 0) { Array.Copy(_items, 0, newItems, 0, _size); } _items = newItems; } else { _items = _emptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } bool System.Collections.IList.IsFixedSize { get { return false; } } // Is this List read-only? bool ICollection<T>.IsReadOnly { get { return false; } } bool System.Collections.IList.IsReadOnly { get { return false; } } // Is this List synchronized (thread-safe)? bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. Object System.Collections.ICollection.SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Sets or Gets the element at the given index. // public T this[int index] { get { // Following trick can reduce the range check by one if ((uint) index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint) index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } Object System.Collections.IList.this[int index] { get { return this[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { this[index] = (T)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } int System.Collections.IList.Add(Object item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item); try { Add((T) item); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); } return Count - 1; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public void AddRange(IEnumerable<T> collection) { Contract.Ensures(Count >= Contract.OldValue(Count)); InsertRange(_size, collection); } public ReadOnlyCollection<T> AsReadOnly() { Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null); return new ReadOnlyCollection<T>(this); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. // public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (count < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() <= index + count); Contract.EndContractBlock(); return Array.BinarySearch<T>(_items, index, count, item, comparer); } public int BinarySearch(T item) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, null); } public int BinarySearch(T item, IComparer<T> comparer) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, comparer); } // Clears the contents of List. public void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // EqualityComparer<T>.Default.Equals(). public bool Contains(T item) { // PERF: IndexOf calls Array.IndexOf, which internally // calls EqualityComparer<T>.Default.IndexOf, which // is specialized for different types. This // boosts performance since instead of making a // virtual method call each iteration of the loop, // via EqualityComparer<T>.Default.Equals, we // only make one virtual call to EqualityComparer.IndexOf. return _size != 0 && IndexOf(item) != -1; } bool System.Collections.IList.Contains(Object item) { if(IsCompatibleObject(item)) { return Contains((T) item); } return false; } public List<TOutput> ConvertAll<TOutput>(Converter<T,TOutput> converter) { if( converter == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } Contract.EndContractBlock(); List<TOutput> list = new List<TOutput>(_size); for( int i = 0; i< _size; i++) { list._items[i] = converter(_items[i]); } list._size = _size; return list; } // Copies this List into array, which must be of a // compatible array type. // public void CopyTo(T[] array) { CopyTo(array, 0); } // Copies this List into array, which must be of a // compatible array type. // void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } Contract.EndContractBlock(); try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array, arrayIndex, _size); } catch(ArrayTypeMismatchException){ ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. // public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (_size - index < count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Ensures that the capacity of this list is at least the given minimum // value. If the currect capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } public bool Exists(Predicate<T> match) { return FindIndex(match) != -1; } public T Find(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); for(int i = 0 ; i < _size; i++) { if(match(_items[i])) { return _items[i]; } } return default(T); } public List<T> FindAll(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); List<T> list = new List<T>(); for(int i = 0 ; i < _size; i++) { if(match(_items[i])) { list.Add(_items[i]); } } return list; } public int FindIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindIndex(0, _size, match); } public int FindIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + Count); return FindIndex(startIndex, _size - startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { if( (uint)startIndex > (uint)_size ) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex > _size - count) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + count); Contract.EndContractBlock(); int endIndex = startIndex + count; for( int i = startIndex; i < endIndex; i++) { if( match(_items[i])) return i; } return -1; } public T FindLast(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); for(int i = _size - 1 ; i >= 0; i--) { if(match(_items[i])) { return _items[i]; } } return default(T); } public int FindLastIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindLastIndex(_size - 1, _size, match); } public int FindLastIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); return FindLastIndex(startIndex, startIndex + 1, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); Contract.EndContractBlock(); if(_size == 0) { // Special case for 0 length List if( startIndex != -1) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } else { // Make sure we're not out of range if ( (uint)startIndex >= (uint)_size) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int endIndex = startIndex - count; for( int i = startIndex; i > endIndex; i--) { if( match(_items[i])) { return i; } } return -1; } public void ForEach(Action<T> action) { if( action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } Contract.EndContractBlock(); int version = _version; for(int i = 0 ; i < _size; i++) { if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) { break; } action(_items[i]); } if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public List<T> GetRange(int index, int count) { if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } Contract.Ensures(Contract.Result<List<T>>() != null); Contract.EndContractBlock(); List<T> list = new List<T>(count); Array.Copy(_items, index, list._items, 0, count); list._size = count; return list; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); } int System.Collections.IList.IndexOf(Object item) { if(IsCompatibleObject(item)) { return IndexOf((T)item); } return -1; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index) { if (index > _size) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index, int count) { if (index > _size) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); if (count <0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, count); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint) index > (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = item; _size++; _version++; } void System.Collections.IList.Insert(int index, Object item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item); try { Insert(index, (T) item); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); } } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. // public void InsertRange(int index, IEnumerable<T> collection) { if (collection==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } if ((uint)index > (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if( c != null ) { // if collection is ICollection<T> int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } // If we're inserting a List into itself, we want to be able to deal with that. if (this == c) { // Copy first part of _items to insert location Array.Copy(_items, 0, _items, index, index); // Copy last part of _items back to inserted location Array.Copy(_items, index+count, _items, index*2, _size-index); } else { c.CopyTo(_items, index); } _size += count; } } else { using(IEnumerator<T> en = collection.GetEnumerator()) { while(en.MoveNext()) { Insert(index++, en.Current); } } } _version++; } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); if (_size == 0) { // Special case for empty list return -1; } else { return LastIndexOf(item, _size - 1, _size); } } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item, int index) { if (index >= _size) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); return LastIndexOf(item, index, index + 1); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item, int index, int count) { if ((Count != 0) && (index < 0)) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if ((Count !=0) && (count < 0)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); if (_size == 0) { // Special case for empty list return -1; } if (index >= _size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); } if (count > index + 1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); } return Array.LastIndexOf(_items, item, index, count); } // Removes the element at the given index. The size of the list is // decreased by one. // public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } void System.Collections.IList.Remove(Object item) { if(IsCompatibleObject(item)) { Remove((T) item); } } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count)); Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while( freeIndex < _size && !match(_items[freeIndex])) freeIndex++; if( freeIndex >= _size) return 0; int current = freeIndex + 1; while( current < _size) { // Find the first item which needs to be kept. while( current < _size && match(_items[current])) current++; if( current < _size) { // copy item to the free slot. _items[freeIndex++] = _items[current++]; } } Array.Clear(_items, freeIndex, _size - freeIndex); int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. // public void RemoveAt(int index) { if ((uint)index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = default(T); _version++; } // Removes a range of elements from this list. // public void RemoveRange(int index, int count) { if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count > 0) { int i = _size; _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } Array.Clear(_items, _size, count); _version++; } } // Reverses the elements in this list. public void Reverse() { Reverse(0, Count); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // public void Reverse(int index, int count) { if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); Array.Reverse(_items, index, count); _version++; } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() { Sort(0, Count, null); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort(IComparer<T> comparer) { Sort(0, Count, comparer); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. // public void Sort(int index, int count, IComparer<T> comparer) { if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); Array.Sort<T>(_items, index, count, comparer); _version++; } public void Sort(Comparison<T> comparison) { if( comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } Contract.EndContractBlock(); if( _size > 0) { IComparer<T> comparer = Comparer<T>.Create(comparison); Array.Sort(_items, 0, _size, comparer); } } // ToArray returns an array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { Contract.Ensures(Contract.Result<T[]>() != null); Contract.Ensures(Contract.Result<T[]>().Length == Count); #if FEATURE_CORECLR if (_size == 0) { return _emptyArray; } #endif T[] array = new T[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimExcess(); // public void TrimExcess() { int threshold = (int)(((double)_items.Length) * 0.9); if( _size < threshold ) { Capacity = _size; } } public bool TrueForAll(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); for(int i = 0 ; i < _size; i++) { if( !match(_items[i])) { return false; } } return true; } [Serializable] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private List<T> list; private int index; private int version; private T current; internal Enumerator(List<T> list) { this.list = list; index = 0; version = list._version; current = default(T); } public void Dispose() { } public bool MoveNext() { List<T> localList = list; if (version == localList._version && ((uint)index < (uint)localList._size)) { current = localList._items[index]; index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (version != list._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = list._size + 1; current = default(T); return false; } public T Current { get { return current; } } Object System.Collections.IEnumerator.Current { get { if( index == 0 || index == list._size + 1) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return Current; } } void System.Collections.IEnumerator.Reset() { if (version != list._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; current = default(T); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSLF.Model; using NPOI.ddf.EscherContainerRecord; using NPOI.ddf.EscherOptRecord; using NPOI.ddf.EscherProperties; using NPOI.ddf.EscherSimpleProperty; using NPOI.ddf.EscherSpRecord; using NPOI.ddf.EscherTextboxRecord; using NPOI.HSLF.exceptions.HSLFException; using NPOI.HSLF.record.EscherTextboxWrapper; using NPOI.HSLF.record.InteractiveInfo; using NPOI.HSLF.record.InteractiveInfoAtom; using NPOI.HSLF.record.OEPlaceholderAtom; using NPOI.HSLF.record.OutlineTextRefAtom; using NPOI.HSLF.record.PPDrawing; using NPOI.HSLF.record.Record; using NPOI.HSLF.record.RecordTypes; using NPOI.HSLF.record.StyleTextPropAtom; using NPOI.HSLF.record.TextCharsAtom; using NPOI.HSLF.record.TextHeaderAtom; using NPOI.HSLF.record.TxInteractiveInfoAtom; using NPOI.HSLF.usermodel.RichTextRun; using NPOI.util.POILogger; /** * A common superclass of all shapes that can hold text. * * @author Yegor Kozlov */ public abstract class TextShape : SimpleShape { /** * How to anchor the text */ public static int AnchorTop = 0; public static int AnchorMiddle = 1; public static int AnchorBottom = 2; public static int AnchorTopCentered = 3; public static int AnchorMiddleCentered = 4; public static int AnchorBottomCentered = 5; public static int AnchorTopBaseline = 6; public static int AnchorBottomBaseline = 7; public static int AnchorTopCenteredBaseline = 8; public static int AnchorBottomCenteredBaseline = 9; /** * How to wrap the text */ public static int WrapSquare = 0; public static int WrapByPoints = 1; public static int WrapNone = 2; public static int WrapTopBottom = 3; public static int WrapThrough = 4; /** * How to align the text */ public static int AlignLeft = 0; public static int AlignCenter = 1; public static int AlignRight = 2; public static int AlignJustify = 3; /** * TextRun object which holds actual text and format data */ protected TextRun _txtRun; /** * Escher Container which holds text attributes such as * TextHeaderAtom, TextBytesAtom ot TextCharsAtom, StyleTextPropAtom etc. */ protected EscherTextboxWrapper _txtbox; /** * Used to calculate text bounds */ protected static FontRenderContext _frc = new FontRenderContext(null, true, true); /** * Create a TextBox object and Initialize it from the supplied Record Container. * * @param escherRecord <code>EscherSpContainer</code> Container which holds information about this shape * @param parent the parent of the shape */ protected TextShape(EscherContainerRecord escherRecord, Shape parent){ base(escherRecord, parent); } /** * Create a new TextBox. This constructor is used when a new shape is Created. * * @param parent the parent of this Shape. For example, if this text box is a cell * in a table then the parent is Table. */ public TextShape(Shape parent){ base(null, parent); _escherContainer = CreateSpContainer(parent is ShapeGroup); } /** * Create a new TextBox. This constructor is used when a new shape is Created. * */ public TextShape(){ this(null); } public TextRun CreateTextRun(){ _txtbox = GetEscherTextboxWrapper(); if(_txtbox == null) _txtbox = new EscherTextboxWrapper(); _txtrun = GetTextRun(); if(_txtrun == null){ TextHeaderAtom tha = new TextHeaderAtom(); tha.SetParentRecord(_txtbox); _txtbox.AppendChildRecord(tha); TextCharsAtom tca = new TextCharsAtom(); _txtbox.AppendChildRecord(tca); StyleTextPropAtom sta = new StyleTextPropAtom(0); _txtbox.AppendChildRecord(sta); _txtrun = new TextRun(tha,tca,sta); _txtRun._records = new Record[]{tha, tca, sta}; _txtRun.SetText(""); _escherContainer.AddChildRecord(_txtbox.GetEscherRecord()); SetDefaultTextProperties(_txtRun); } return _txtRun; } /** * Set default properties for the TextRun. * Depending on the text and shape type the defaults are different: * TextBox: align=left, valign=top * AutoShape: align=center, valign=middle * */ protected void SetDefaultTextProperties(TextRun _txtRun){ } /** * Returns the text Contained in this text frame. * * @return the text string for this textbox. */ public String GetText(){ TextRun tx = GetTextRun(); return tx == null ? null : tx.GetText(); } /** * Sets the text Contained in this text frame. * * @param text the text string used by this object. */ public void SetText(String text){ TextRun tx = GetTextRun(); if(tx == null){ tx = CreateTextRun(); } tx.SetText(text); SetTextId(text.HashCode()); } /** * When a textbox is Added to a sheet we need to tell upper-level * <code>PPDrawing</code> about it. * * @param sh the sheet we are Adding to */ protected void afterInsert(Sheet sh){ super.afterInsert(sh); EscherTextboxWrapper _txtbox = GetEscherTextboxWrapper(); if(_txtbox != null){ PPDrawing ppdrawing = sh.GetPPDrawing(); ppdrawing.AddTextboxWrapper(_txtbox); // Ensure the escher layer knows about the Added records try { _txtbox.WriteOut(null); } catch (IOException e){ throw new HSLFException(e); } if(getAnchor().Equals(new Rectangle()) && !"".Equals(getText())) resizeToFitText(); } if(_txtrun != null) { _txtRun.SetShapeId(getShapeId()); sh.onAddTextShape(this); } } protected EscherTextboxWrapper GetEscherTextboxWrapper(){ if(_txtbox == null){ EscherTextboxRecord textRecord = (EscherTextboxRecord)Shape.GetEscherChild(_escherContainer, EscherTextboxRecord.RECORD_ID); if(textRecord != null) _txtbox = new EscherTextboxWrapper(textRecord); } return _txtbox; } /** * Adjust the size of the TextShape so it encompasses the text inside it. * * @return a <code>Rectangle2D</code> that is the bounds of this <code>TextShape</code>. */ public Rectangle2D resizeToFitText(){ String txt = GetText(); if(txt == null || txt.Length == 0) return new Rectangle2D.Float(); RichTextRun rt = GetTextRun().GetRichTextRuns()[0]; int size = rt.GetFontSize(); int style = 0; if (rt.IsBold()) style |= Font.BOLD; if (rt.IsItalic()) style |= Font.ITALIC; String fntname = rt.GetFontName(); Font font = new Font(fntname, style, size); float width = 0, height = 0, leading = 0; String[] lines = txt.split("\n"); for (int i = 0; i < lines.Length; i++) { if(lines[i].Length == 0) continue; TextLayout layout = new TextLayout(lines[i], font, _frc); leading = Math.max(leading, layout.GetLeading()); width = Math.max(width, layout.GetAdvance()); height = Math.max(height, (height + (layout.GetDescent() + layout.GetAscent()))); } // add one character to width Rectangle2D charBounds = font.GetMaxCharBounds(_frc); width += GetMarginLeft() + GetMarginRight() + charBounds.Width; // add leading to height height += GetMarginTop() + GetMarginBottom() + leading; Rectangle2D anchor = GetAnchor2D(); anchor.SetRect(anchor.GetX(), anchor.GetY(), width, height); SetAnchor(anchor); return anchor; } /** * Returns the type of vertical alignment for the text. * One of the <code>Anchor*</code> constants defined in this class. * * @return the type of alignment */ public int GetVerticalAlignment(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__ANCHORTEXT); int valign = TextShape.AnchorTop; if (prop == null){ /** * If vertical alignment was not found in the shape properties then try to * fetch the master shape and search for the align property there. */ int type = GetTextRun().GetRunType(); MasterSheet master = Sheet.GetMasterSheet(); if(master != null){ TextShape masterShape = master.GetPlaceholderByTextType(type); if(masterShape != null) valign = masterShape.GetVerticalAlignment(); } else { //not found in the master sheet. Use the hardcoded defaults. switch (type){ case TextHeaderAtom.TITLE_TYPE: case TextHeaderAtom.CENTER_TITLE_TYPE: valign = TextShape.AnchorMiddle; break; default: valign = TextShape.AnchorTop; break; } } } else { valign = prop.GetPropertyValue(); } return valign; } /** * Sets the type of vertical alignment for the text. * One of the <code>Anchor*</code> constants defined in this class. * * @param align - the type of alignment */ public void SetVerticalAlignment(int align){ SetEscherProperty(EscherProperties.TEXT__ANCHORTEXT, align); } /** * Sets the type of horizontal alignment for the text. * One of the <code>Align*</code> constants defined in this class. * * @param align - the type of horizontal alignment */ public void SetHorizontalAlignment(int align){ TextRun tx = GetTextRun(); if(tx != null) tx.GetRichTextRuns()[0].SetAlignment(align); } /** * Gets the type of horizontal alignment for the text. * One of the <code>Align*</code> constants defined in this class. * * @return align - the type of horizontal alignment */ public int GetHorizontalAlignment(){ TextRun tx = GetTextRun(); return tx == null ? -1 : tx.GetRichTextRuns()[0].GetAlignment(); } /** * Returns the distance (in points) between the bottom of the text frame * and the bottom of the inscribed rectangle of the shape that Contains the text. * Default value is 1/20 inch. * * @return the botom margin */ public float GetMarginBottom(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__TEXTBOTTOM); int val = prop == null ? EMU_PER_INCH/20 : prop.GetPropertyValue(); return (float)val/EMU_PER_POINT; } /** * Sets the botom margin. * @see #getMarginBottom() * * @param margin the bottom margin */ public void SetMarginBottom(float margin){ SetEscherProperty(EscherProperties.TEXT__TEXTBOTTOM, (int)(margin*EMU_PER_POINT)); } /** * Returns the distance (in points) between the left edge of the text frame * and the left edge of the inscribed rectangle of the shape that Contains * the text. * Default value is 1/10 inch. * * @return the left margin */ public float GetMarginLeft(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__TEXTLEFT); int val = prop == null ? EMU_PER_INCH/10 : prop.GetPropertyValue(); return (float)val/EMU_PER_POINT; } /** * Sets the left margin. * @see #getMarginLeft() * * @param margin the left margin */ public void SetMarginLeft(float margin){ SetEscherProperty(EscherProperties.TEXT__TEXTLEFT, (int)(margin*EMU_PER_POINT)); } /** * Returns the distance (in points) between the right edge of the * text frame and the right edge of the inscribed rectangle of the shape * that Contains the text. * Default value is 1/10 inch. * * @return the right margin */ public float GetMarginRight(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__TEXTRIGHT); int val = prop == null ? EMU_PER_INCH/10 : prop.GetPropertyValue(); return (float)val/EMU_PER_POINT; } /** * Sets the right margin. * @see #getMarginRight() * * @param margin the right margin */ public void SetMarginRight(float margin){ SetEscherProperty(EscherProperties.TEXT__TEXTRIGHT, (int)(margin*EMU_PER_POINT)); } /** * Returns the distance (in points) between the top of the text frame * and the top of the inscribed rectangle of the shape that Contains the text. * Default value is 1/20 inch. * * @return the top margin */ public float GetMarginTop(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__TEXTTOP); int val = prop == null ? EMU_PER_INCH/20 : prop.GetPropertyValue(); return (float)val/EMU_PER_POINT; } /** * Sets the top margin. * @see #getMarginTop() * * @param margin the top margin */ public void SetMarginTop(float margin){ SetEscherProperty(EscherProperties.TEXT__TEXTTOP, (int)(margin*EMU_PER_POINT)); } /** * Returns the value indicating word wrap. * * @return the value indicating word wrap. * Must be one of the <code>Wrap*</code> constants defined in this class. */ public int GetWordWrap(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__WRAPTEXT); return prop == null ? WrapSquare : prop.GetPropertyValue(); } /** * Specifies how the text should be wrapped * * @param wrap the value indicating how the text should be wrapped. * Must be one of the <code>Wrap*</code> constants defined in this class. */ public void SetWordWrap(int wrap){ SetEscherProperty(EscherProperties.TEXT__WRAPTEXT, wrap); } /** * @return id for the text. */ public int GetTextId(){ EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)getEscherProperty(opt, EscherProperties.TEXT__TEXTID); return prop == null ? 0 : prop.GetPropertyValue(); } /** * Sets text ID * * @param id of the text */ public void SetTextId(int id){ SetEscherProperty(EscherProperties.TEXT__TEXTID, id); } /** * @return the TextRun object for this text box */ public TextRun GetTextRun(){ if(_txtrun == null) InitTextRun(); return _txtRun; } public void SetSheet(Sheet sheet) { _sheet = sheet; // Initialize _txtrun object. // (We can't do it in the constructor because the sheet // is not assigned then, it's only built once we have // all the records) TextRun tx = GetTextRun(); if (tx != null) { // Supply the sheet to our child RichTextRuns tx.SetSheet(_sheet); RichTextRun[] rt = tx.GetRichTextRuns(); for (int i = 0; i < rt.Length; i++) { rt[i].supplySlideShow(_sheet.GetSlideShow()); } } } protected void InitTextRun(){ EscherTextboxWrapper txtbox = GetEscherTextboxWrapper(); Sheet sheet = Sheet; if(sheet == null || txtbox == null) return; OutlineTextRefAtom ota = null; Record[] child = txtbox.GetChildRecords(); for (int i = 0; i < child.Length; i++) { if (child[i] is OutlineTextRefAtom) { ota = (OutlineTextRefAtom)child[i]; break; } } TextRun[] Runs = _sheet.GetTextRuns(); if (ota != null) { int idx = ota.GetTextIndex(); for (int i = 0; i < Runs.Length; i++) { if(Runs[i].GetIndex() == idx){ _txtrun = Runs[i]; break; } } if(_txtrun == null) { logger.log(POILogger.WARN, "text run not found for OutlineTextRefAtom.TextIndex=" + idx); } } else { EscherSpRecord escherSpRecord = _escherContainer.GetChildById(EscherSpRecord.RECORD_ID); int shapeId = escherSpRecord.GetShapeId(); if(Runs != null) for (int i = 0; i < Runs.Length; i++) { if(Runs[i].GetShapeId() == shapeId){ _txtrun = Runs[i]; break; } } } // ensure the same references child records of TextRun if(_txtrun != null) for (int i = 0; i < child.Length; i++) { foreach (Record r in _txtRun.GetRecords()) { if (child[i].GetRecordType() == r.GetRecordType()) { child[i] = r; } } } } public void Draw(Graphics2D graphics){ AffineTransform at = graphics.GetTransform(); ShapePainter.paint(this, graphics); new TextPainter(this).paint(graphics); graphics.SetTransform(at); } /** * Return <code>OEPlaceholderAtom</code>, the atom that describes a placeholder. * * @return <code>OEPlaceholderAtom</code> or <code>null</code> if not found */ public OEPlaceholderAtom GetPlaceholderAtom(){ return (OEPlaceholderAtom)getClientDataRecord(RecordTypes.OEPlaceholderAtom.typeID); } /** * * Assigns a hyperlink to this text shape * * @param linkId id of the hyperlink, @see NPOI.HSLF.usermodel.SlideShow#AddHyperlink(Hyperlink) * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @see NPOI.HSLF.usermodel.SlideShow#AddHyperlink(Hyperlink) */ public void SetHyperlink(int linkId, int beginIndex, int endIndex){ //TODO validate beginIndex and endIndex and throw ArgumentException InteractiveInfo info = new InteractiveInfo(); InteractiveInfoAtom infoAtom = info.GetInteractiveInfoAtom(); infoAtom.SetAction(InteractiveInfoAtom.ACTION_HYPERLINK); infoAtom.SetHyperlinkType(InteractiveInfoAtom.LINK_Url); infoAtom.SetHyperlinkID(linkId); _txtbox.AppendChildRecord(info); TxInteractiveInfoAtom txiatom = new TxInteractiveInfoAtom(); txiatom.SetStartIndex(beginIndex); txiatom.SetEndIndex(endIndex); _txtbox.AppendChildRecord(txiatom); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class PartitionerStaticTests { [Fact] public static void TestStaticPartitioningIList() { RunTestWithAlgorithm(dataSize: 11, partitionCount: 8, algorithm: 0); RunTestWithAlgorithm(dataSize: 999, partitionCount: 1, algorithm: 0); RunTestWithAlgorithm(dataSize: 10000, partitionCount: 11, algorithm: 0); } [Fact] public static void TestStaticPartitioningArray() { RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 1); RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 1); RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 1); } [Fact] public static void TestLoadBalanceIList() { RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 2); RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 2); RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 2); } [Fact] public static void TestLoadBalanceArray() { RunTestWithAlgorithm(dataSize: 11, partitionCount: 8, algorithm: 3); RunTestWithAlgorithm(dataSize: 999, partitionCount: 1, algorithm: 3); RunTestWithAlgorithm(dataSize: 10000, partitionCount: 11, algorithm: 3); } [Fact] public static void TestLoadBalanceEnumerator() { RunTestWithAlgorithm(dataSize: 7, partitionCount: 4, algorithm: 4); RunTestWithAlgorithm(dataSize: 123, partitionCount: 1, algorithm: 4); RunTestWithAlgorithm(dataSize: 1000, partitionCount: 7, algorithm: 4); } #region Dispose tests. The dispose logic of PartitionerStatic // In the official dev unit test run, this test should be commented out // - Each time we call GetDynamicPartitions method, we create an internal "reader enumerator" to read the // source data, and we need to make sure that whenever the object returned by GetDynamicPartitions is disposed, // the "reader enumerator" is also disposed. [Fact] public static void TestDisposeException() { var data = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var enumerable = new DisposeTrackingEnumerable<int>(data); var partitioner = Partitioner.Create(enumerable); var partition = partitioner.GetDynamicPartitions(); IDisposable d = partition as IDisposable; Assert.NotNull(d); d.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var enum1 = partition.GetEnumerator(); }); } /// <summary> /// Race in Partitioner's dynamic partitioning Dispose logic /// After the fix, the partitioner created through Partitioner.Create(IEnumerable) has the following behavior: /// 1. reference counting in static partitioning. All partitions need to be disposed explicitly /// 2. no reference counting in dynamic partitioning. The partitioner need to be disposed explicitly /// </summary> /// <returns></returns> [Fact] public static void RunDynamicPartitioningDispose() { var p = Partitioner.Create(new int[] { 0, 1 }); var d = p.GetDynamicPartitions(); using (var e = d.GetEnumerator()) { while (e.MoveNext()) { } } // should not throw using (var e = d.GetEnumerator()) { }; } #endregion [Fact] public static void TestExceptions() { // Testing ArgumentNullException with data==null // Test ArgumentNullException of source data OrderablePartitioner<int> partitioner; for (int algorithm = 0; algorithm < 5; algorithm++) { Assert.Throws<ArgumentNullException>(() => { partitioner = PartitioningWithAlgorithm<int>(null, algorithm); }); } // Test NotSupportedException of Reset: already tested in RunTestWithAlgorithm // Test InvalidOperationException: already tested in TestPartitioningCore // Test ArgumentOutOfRangeException of partitionCount == 0 int[] data = new int[10000]; for (int i = 0; i < 10000; i++) data[i] = i; //test GetOrderablePartitions method for 0-4 algorithms, try to catch ArgumentOutOfRangeException for (int algorithm = 0; algorithm < 5; algorithm++) { partitioner = PartitioningWithAlgorithm<int>(data, algorithm); Assert.Throws<ArgumentOutOfRangeException>(() => { var partitions1 = partitioner.GetOrderablePartitions(0); }); } } [Fact] public static void TestEmptyPartitions() { int[] data = new int[0]; // Test ArgumentNullException of source data OrderablePartitioner<int> partitioner; for (int algorithm = 0; algorithm < 5; algorithm++) { partitioner = PartitioningWithAlgorithm<int>(data, algorithm); //test GetOrderablePartitions var partitions1 = partitioner.GetOrderablePartitions(4); //verify all partitions are empty for (int i = 0; i < 4; i++) { Assert.False(partitions1[i].MoveNext(), "Should not be able to move next in an empty partition."); } //test GetOrderableDynamicPartitions try { var partitions2 = partitioner.GetOrderableDynamicPartitions(); //verify all partitions are empty var newPartition = partitions2.GetEnumerator(); Assert.False(newPartition.MoveNext(), "Should not be able to move next in an empty partition."); } catch (NotSupportedException) { Assert.True(IsStaticPartition(algorithm), "TestEmptyPartitions: IsStaticPartition(algorithm) should have been true."); } } } private static void RunTestWithAlgorithm(int dataSize, int partitionCount, int algorithm) { //we set up the KeyValuePair in the way that keys and values should always be the same //for all partitioning algorithms. So that we can use a bitmap (boolarray) to check whether //any elements are missing in the end. int[] data = new int[dataSize]; for (int i = 0; i < dataSize; i++) data[i] = i; IEnumerator<KeyValuePair<long, int>>[] partitionsUnderTest = new IEnumerator<KeyValuePair<long, int>>[partitionCount]; //step 1: test GetOrderablePartitions OrderablePartitioner<int> partitioner = PartitioningWithAlgorithm<int>(data, algorithm); var partitions1 = partitioner.GetOrderablePartitions(partitionCount); //convert it to partition array for testing for (int i = 0; i < partitionCount; i++) partitionsUnderTest[i] = partitions1[i]; Assert.Equal(partitionCount, partitions1.Count); TestPartitioningCore(dataSize, partitionCount, data, IsStaticPartition(algorithm), partitionsUnderTest); //step 2: test GetOrderableDynamicPartitions bool gotException = false; try { var partitions2 = partitioner.GetOrderableDynamicPartitions(); for (int i = 0; i < partitionCount; i++) partitionsUnderTest[i] = partitions2.GetEnumerator(); TestPartitioningCore(dataSize, partitionCount, data, IsStaticPartition(algorithm), partitionsUnderTest); } catch (NotSupportedException) { //swallow this exception: static partitioning doesn't support GetOrderableDynamicPartitions gotException = true; } Assert.False(IsStaticPartition(algorithm) && !gotException, "TestLoadBalanceIList: Failure: didn't catch \"NotSupportedException\" for static partitioning"); } private static OrderablePartitioner<T> PartitioningWithAlgorithm<T>(T[] data, int algorithm) { switch (algorithm) { //static partitioning through IList case (0): return Partitioner.Create((IList<T>)data, false); //static partitioning through Array case (1): return Partitioner.Create(data, false); //dynamic partitioning through IList case (2): return Partitioner.Create((IList<T>)data, true); //dynamic partitioning through Arrray case (3): return Partitioner.Create(data, true); //dynamic partitioning through IEnumerator case (4): return Partitioner.Create((IEnumerable<T>)data); default: throw new InvalidOperationException("PartitioningWithAlgorithm: no such partitioning algorithm"); } } private static void TestPartitioningCore(int dataSize, int partitionCount, int[] data, bool staticPartitioning, IEnumerator<KeyValuePair<long, int>>[] partitions) { bool[] boolarray = new bool[dataSize]; bool keysOrderedWithinPartition = true, keysOrderedAcrossPartitions = true; int enumCount = 0; //count how many elements are enumerated by all partitions Task[] threadArray = new Task[partitionCount]; for (int i = 0; i < partitionCount; i++) { int my_i = i; threadArray[i] = Task.Run(() => { int localOffset = 0; int lastElement = -1; //variables to compute key/value consistency for static partitioning. int quotient, remainder; quotient = dataSize / partitionCount; remainder = dataSize % partitionCount; Assert.Throws<InvalidOperationException>(() => { var temp = partitions[my_i].Current; }); while (partitions[my_i].MoveNext()) { int key = (int)partitions[my_i].Current.Key, value = partitions[my_i].Current.Value; Assert.Equal(key, value); boolarray[key] = true; Interlocked.Increment(ref enumCount); //todo: check if keys are ordered increasingly within each partition. keysOrderedWithinPartition &= (lastElement >= key); lastElement = key; //Only check this with static partitioning //check keys are ordered across the partitions if (staticPartitioning) { int originalPosition; if (my_i < remainder) originalPosition = localOffset + my_i * (quotient + 1); else originalPosition = localOffset + remainder * (quotient + 1) + (my_i - remainder) * quotient; keysOrderedAcrossPartitions &= originalPosition == value; } localOffset++; } } ); } Task.WaitAll(threadArray); if (keysOrderedWithinPartition) Console.WriteLine("TestPartitioningCore: Keys are not strictly ordered within each partition"); // Only check this with static partitioning //check keys are ordered across the partitions Assert.False(staticPartitioning && !keysOrderedAcrossPartitions, "TestPartitioningCore: Keys are not strictly ordered across partitions"); //check data count Assert.Equal(enumCount, dataSize); //check if any elements are missing foreach (var item in boolarray) { Assert.True(item); } } // // Try calling MoveNext on a Partitioner enumerator after that enumerator has already returned false. // [Fact] public static void TestExtraMoveNext() { Partitioner<int>[] partitioners = new[] { Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}), Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}, false), Partitioner.Create(new int[] { 0 , 1, 2, 3, 4, 5}, true), Partitioner.Create(new int[] { 0 }), Partitioner.Create(new int[] { 0 }, false), Partitioner.Create(new int[] { 0 }, true), }; for (int i = 0; i < partitioners.Length; i++) { using (var ee = partitioners[i].GetPartitions(1)[0]) { while (ee.MoveNext()) { } Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": First extra MoveNext expected to return false."); Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": Second extra MoveNext expected to return false."); Assert.False(ee.MoveNext(), "TestExtraMoveNext: FAILED. Partitioner " + i + ": Third extra MoveNext expected to return false."); } } } #region Helper Methods / Classes private class DisposeTrackingEnumerable<T> : IEnumerable<T> { protected IEnumerable<T> m_data; List<DisposeTrackingEnumerator<T>> s_enumerators = new List<DisposeTrackingEnumerator<T>>(); public DisposeTrackingEnumerable(IEnumerable<T> enumerable) { m_data = enumerable; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { DisposeTrackingEnumerator<T> walker = new DisposeTrackingEnumerator<T>(m_data.GetEnumerator()); lock (s_enumerators) { s_enumerators.Add(walker); } return walker; } public IEnumerator<T> GetEnumerator() { DisposeTrackingEnumerator<T> walker = new DisposeTrackingEnumerator<T>(m_data.GetEnumerator()); lock (s_enumerators) { s_enumerators.Add(walker); } return walker; } public void AreEnumeratorsDisposed(string scenario) { for (int i = 0; i < s_enumerators.Count; i++) { Assert.True(s_enumerators[i].IsDisposed(), String.Format("AreEnumeratorsDisposed: FAILED. enumerator {0} was not disposed for SCENARIO: {1}.", i, scenario)); } } } /// <summary> /// This is the Enumerator that DisposeTrackingEnumerable generates when GetEnumerator is called. /// We are simply wrapping an Enumerator and tracking whether Dispose had been called or not. /// </summary> /// <typeparam name="T">The type of the element</typeparam> private class DisposeTrackingEnumerator<T> : IEnumerator<T> { IEnumerator<T> m_elements; bool disposed; public DisposeTrackingEnumerator(IEnumerator<T> enumerator) { m_elements = enumerator; disposed = false; } public Boolean MoveNext() { return m_elements.MoveNext(); } public T Current { get { return m_elements.Current; } } Object System.Collections.IEnumerator.Current { get { return m_elements.Current; } } /// <summary> /// Dispose the underlying Enumerator, and suppresses finalization /// so that we will not throw. /// </summary> public void Dispose() { GC.SuppressFinalize(this); m_elements.Dispose(); disposed = true; } public void Reset() { m_elements.Reset(); } public bool IsDisposed() { return disposed; } } private static bool IsStaticPartition(int algorithm) { return algorithm < 2; } #endregion } }
using System; using System.Threading; using System.Diagnostics; using M2SA.AppGenome.Logging; namespace M2SA.AppGenome.Threading.Internal { /// <summary> /// Holds a callback delegate and the state for that delegate. /// </summary> public partial class WorkItem : IHasWorkItemPriority { #region WorkItemState enum /// <summary> /// Indicates the state of the work item in the thread pool /// </summary> private enum WorkItemState { InQueue = 0, // Nexts: InProgress, Canceled InProgress = 1, // Nexts: Completed, Canceled Completed = 2, // Stays Completed Canceled = 3, // Stays Canceled } private static bool IsValidStatesTransition(WorkItemState currentState, WorkItemState nextState) { bool valid = false; switch (currentState) { case WorkItemState.InQueue: valid = (WorkItemState.InProgress == nextState) || (WorkItemState.Canceled == nextState); break; case WorkItemState.InProgress: valid = (WorkItemState.Completed == nextState) || (WorkItemState.Canceled == nextState); break; case WorkItemState.Completed: case WorkItemState.Canceled: // Cannot be changed break; default: // Unknown state Debug.Assert(false); break; } return valid; } #endregion #region Fields /// <summary> /// Action delegate for the callback. /// </summary> private readonly WorkItemCallback _callback; /// <summary> /// Items with which to call the callback delegate. /// </summary> private object _state; #if !(_WINDOWS_CE) && !(_SILVERLIGHT) /// <summary> /// Stores the caller's context /// </summary> private readonly CallerThreadContext _callerContext; #endif /// <summary> /// Holds the result of the mehtod /// </summary> private object _result; /// <summary> /// Hold the exception if the method threw it /// </summary> private Exception _exception; /// <summary> /// Hold the state of the work item /// </summary> private WorkItemState _workItemState; /// <summary> /// A ManualResetEvent to indicate that the result is ready /// </summary> private ManualResetEvent _workItemCompleted; /// <summary> /// A reference count to the _workItemCompleted. /// When it reaches to zero _workItemCompleted is Closed /// </summary> private int _workItemCompletedRefCount; /// <summary> /// Represents the result state of the work item /// </summary> private readonly WorkItemResult _workItemResult; /// <summary> /// Work item info /// </summary> private readonly WorkItemInfo _workItemInfo; /// <summary> /// Called when the WorkItem starts /// </summary> private event WorkItemStateCallback _workItemStartedEvent; /// <summary> /// Called when the WorkItem completes /// </summary> private event WorkItemStateCallback _workItemCompletedEvent; /// <summary> /// A reference to an object that indicates whatever the /// WorkItemsGroup has been canceled /// </summary> private CanceledWorkItemsGroup _canceledWorkItemsGroup = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup; /// <summary> /// A reference to an object that indicates whatever the /// SmartThreadPool has been canceled /// </summary> private CanceledWorkItemsGroup _canceledSmartThreadPool = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup; /// <summary> /// The work item group this work item belong to. /// </summary> private readonly IWorkItemsGroup _workItemsGroup; /// <summary> /// The thread that executes this workitem. /// This field is available for the period when the work item is executed, before and after it is null. /// </summary> private Thread _executingThread; /// <summary> /// The absulote time when the work item will be timeout /// </summary> private long _expirationTime; #region Performance Counter fields /// <summary> /// Stores how long the work item waited on the stp queue /// </summary> private Stopwatch _waitingOnQueueStopwatch; /// <summary> /// Stores how much time it took the work item to execute after it went out of the queue /// </summary> private Stopwatch _processingStopwatch; #endregion #endregion #region Properties /// <summary> /// /// </summary> public TimeSpan WaitingTime { get { return _waitingOnQueueStopwatch.Elapsed; } } /// <summary> /// /// </summary> public TimeSpan ProcessTime { get { return _processingStopwatch.Elapsed; } } /// <summary> /// /// </summary> internal WorkItemInfo WorkItemInfo { get { return _workItemInfo; } } #endregion #region Construction /// <summary> /// Initialize the callback holding object. /// </summary> /// <param name="workItemsGroup">The workItemGroup of the workitem</param> /// <param name="workItemInfo">The WorkItemInfo of te workitem</param> /// <param name="callback">Action delegate for the callback.</param> /// <param name="state">Items with which to call the callback delegate.</param> /// /// We assume that the WorkItem object is created within the thread /// that meant to run the callback public WorkItem( IWorkItemsGroup workItemsGroup, WorkItemInfo workItemInfo, WorkItemCallback callback, object state) { if (null == workItemInfo) throw new ArgumentNullException("workItemInfo"); _workItemsGroup = workItemsGroup; _workItemInfo = workItemInfo; #if !(_WINDOWS_CE) && !(_SILVERLIGHT) if (_workItemInfo.UseCallerCallContext || _workItemInfo.UseCallerHttpContext) { _callerContext = CallerThreadContext.Capture(_workItemInfo.UseCallerCallContext, _workItemInfo.UseCallerHttpContext); } #endif _callback = callback; _state = state; _workItemResult = new WorkItemResult(this); Initialize(); } internal void Initialize() { // The _workItemState is changed directly instead of using the SetWorkItemState // method since we don't want to go throught IsValidStateTransition. _workItemState = WorkItemState.InQueue; _workItemCompleted = null; _workItemCompletedRefCount = 0; _waitingOnQueueStopwatch = new Stopwatch(); _processingStopwatch = new Stopwatch(); _expirationTime = _workItemInfo.Timeout > 0 ? DateTime.UtcNow.Ticks + _workItemInfo.Timeout * TimeSpan.TicksPerMillisecond : long.MaxValue; } internal bool WasQueuedBy(IWorkItemsGroup workItemsGroup) { return (workItemsGroup == _workItemsGroup); } #endregion #region Methods internal CanceledWorkItemsGroup CanceledWorkItemsGroup { get { return _canceledWorkItemsGroup; } set { _canceledWorkItemsGroup = value; } } internal CanceledWorkItemsGroup CanceledSmartThreadPool { get { return _canceledSmartThreadPool; } set { _canceledSmartThreadPool = value; } } /// <summary> /// Change the state of the work item to in progress if it wasn't canceled. /// </summary> /// <returns> /// Return true on success or false in case the work item was canceled. /// If the work item needs to run a post execute then the method will return true. /// </returns> public bool StartingWorkItem() { _waitingOnQueueStopwatch.Stop(); _processingStopwatch.Start(); lock(this) { if (IsCanceled) { bool result = false; if ((_workItemInfo.PostExecuteWorkItemCallback != null) && ((_workItemInfo.CallToPostExecute & CallToPostExecute.WhenWorkItemCanceled) == CallToPostExecute.WhenWorkItemCanceled)) { result = true; } return result; } Debug.Assert(WorkItemState.InQueue == GetWorkItemState()); // No need for a lock yet, only after the state has changed to InProgress _executingThread = Thread.CurrentThread; SetWorkItemState(WorkItemState.InProgress); } return true; } /// <summary> /// Execute the work item and the post execute /// </summary> public void Execute() { CallToPostExecute currentCallToPostExecute = 0; // Execute the work item if we are in the correct state switch(GetWorkItemState()) { case WorkItemState.InProgress: currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled; ExecuteWorkItem(); break; case WorkItemState.Canceled: currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled; break; default: Debug.Assert(false); throw new NotSupportedException(); } // Run the post execute as needed if ((currentCallToPostExecute & _workItemInfo.CallToPostExecute) != 0) { PostExecute(); } _processingStopwatch.Stop(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal void FireWorkItemCompleted() { try { if (null != _workItemCompletedEvent) { _workItemCompletedEvent(this); } } catch // Suppress exceptions {} } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal void FireWorkItemStarted() { try { if (null != _workItemStartedEvent) { _workItemStartedEvent(this); } } catch // Suppress exceptions { } } /// <summary> /// Execute the work item /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ExecuteWorkItem() { #if !(_WINDOWS_CE) && !(_SILVERLIGHT) CallerThreadContext ctc = null; if (null != _callerContext) { ctc = CallerThreadContext.Capture(_callerContext.CapturedCallContext, _callerContext.CapturedHttpContext); CallerThreadContext.Apply(_callerContext); } #endif Exception exception = null; object result = null; try { try { result = _callback(_state); } catch (Exception ex) { // Save the exception so we can rethrow it later exception = ex; try { new TaskThreadException(ex).HandleException(); } catch { EffectiveFileLogger.WriteException(new TaskThreadException(ex)); } } // Remove the value of the execution thread, so it will be impossible to cancel the work item, // since it is already completed. // Cancelling a work item that already completed may cause the abortion of the next work item!!! Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread); if (null == executionThread) { // Oops! we are going to be aborted..., Wait here so we can catch the ThreadAbortException Thread.Sleep(60*1000); // If after 1 minute this thread was not aborted then let it continue working. } } // We must treat the ThreadAbortException or else it will be stored in the exception variable catch { // Check if the work item was cancelled // If we got a ThreadAbortException and the STP is not shutting down, it means the // work items was cancelled. if (!SmartThreadPool.CurrentThreadEntry.AssociatedSmartThreadPool.IsShuttingdown) { #if !(_WINDOWS_CE) && !(_SILVERLIGHT) Thread.ResetAbort(); #endif } } #if !(_WINDOWS_CE) && !(_SILVERLIGHT) if (null != _callerContext) { CallerThreadContext.Apply(ctc); } #endif if (!SmartThreadPool.IsWorkItemCanceled) { SetResult(result, exception); } } /// <summary> /// Runs the post execute callback /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void PostExecute() { if (null != _workItemInfo.PostExecuteWorkItemCallback) { try { _workItemInfo.PostExecuteWorkItemCallback(_workItemResult); } catch (Exception e) { Debug.Assert(null != e); } } } /// <summary> /// Set the result of the work item to return /// </summary> /// <param name="result">The result of the work item</param> /// <param name="exception">The exception that was throw while the workitem executed, null /// if there was no exception.</param> internal void SetResult(object result, Exception exception) { _result = result; _exception = exception; SignalComplete(false); } /// <summary> /// Returns the work item result /// </summary> /// <returns>The work item result</returns> internal IWorkItemResult GetWorkItemResult() { return _workItemResult; } /// <summary> /// Wait for all work items to complete /// </summary> /// <param name="waitableResults">Array of work item result objects</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param> /// <returns> /// true when every work item in waitableResults has completed; otherwise false. /// </returns> internal static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { if (0 == waitableResults.Length) { return true; } bool success; WaitHandle[] waitHandles = new WaitHandle[waitableResults.Length]; GetWaitHandles(waitableResults, waitHandles); if ((null == cancelWaitHandle) && (waitHandles.Length <= 64)) { success = STPEventWaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext); } else { success = true; int millisecondsLeft = millisecondsTimeout; Stopwatch stopwatch = Stopwatch.StartNew(); WaitHandle [] whs; if (null != cancelWaitHandle) { whs = new WaitHandle [] { null, cancelWaitHandle }; } else { whs = new WaitHandle [] { null }; } bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout); // Iterate over the wait handles and wait for each one to complete. // We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle // won't affect it. // Each iteration we update the time left for the timeout. for (int i = 0; i < waitableResults.Length; ++i) { // WaitAny don't work with negative numbers if (!waitInfinitely && (millisecondsLeft < 0)) { success = false; break; } whs[0] = waitHandles[i]; int result = STPEventWaitHandle.WaitAny(whs, millisecondsLeft, exitContext); if ((result > 0) || (STPEventWaitHandle.WaitTimeout == result)) { success = false; break; } if(!waitInfinitely) { // Update the time left to wait millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds; } } } // Release the wait handles ReleaseWaitHandles(waitableResults); return success; } /// <summary> /// Waits for any of the work items in the specified array to complete, cancel, or timeout /// </summary> /// <param name="waitableResults">Array of work item result objects</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param> /// <returns> /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled. /// </returns> internal static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { WaitHandle [] waitHandles; if (null != cancelWaitHandle) { waitHandles = new WaitHandle[waitableResults.Length + 1]; GetWaitHandles(waitableResults, waitHandles); waitHandles[waitableResults.Length] = cancelWaitHandle; } else { waitHandles = new WaitHandle[waitableResults.Length]; GetWaitHandles(waitableResults, waitHandles); } int result = STPEventWaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext); // Treat cancel as timeout if (null != cancelWaitHandle) { if (result == waitableResults.Length) { result = STPEventWaitHandle.WaitTimeout; } } ReleaseWaitHandles(waitableResults); return result; } /// <summary> /// Fill an array of wait handles with the work items wait handles. /// </summary> /// <param name="waitableResults">An array of work item results</param> /// <param name="waitHandles">An array of wait handles to fill</param> private static void GetWaitHandles( IWaitableResult[] waitableResults, WaitHandle [] waitHandles) { for (int i = 0; i < waitableResults.Length; ++i) { WorkItemResult wir = waitableResults[i].GetWorkItemResult() as WorkItemResult; Debug.Assert(null != wir, "All waitableResults must be WorkItemResult objects"); waitHandles[i] = wir.GetWorkItem().GetWaitHandle(); } } /// <summary> /// Release the work items' wait handles /// </summary> /// <param name="waitableResults">An array of work item results</param> private static void ReleaseWaitHandles(IWaitableResult[] waitableResults) { for (int i = 0; i < waitableResults.Length; ++i) { WorkItemResult wir = (WorkItemResult)waitableResults[i].GetWorkItemResult(); wir.GetWorkItem().ReleaseWaitHandle(); } } #endregion #region Private Members private WorkItemState GetWorkItemState() { lock (this) { if (WorkItemState.Completed == _workItemState) { return _workItemState; } long nowTicks = DateTime.UtcNow.Ticks; if (WorkItemState.Canceled != _workItemState && nowTicks > _expirationTime) { _workItemState = WorkItemState.Canceled; } if (WorkItemState.InProgress == _workItemState) { return _workItemState; } if (CanceledSmartThreadPool.IsCanceled || CanceledWorkItemsGroup.IsCanceled) { return WorkItemState.Canceled; } return _workItemState; } } /// <summary> /// Sets the work item's state /// </summary> /// <param name="workItemState">The state to set the work item to</param> private void SetWorkItemState(WorkItemState workItemState) { lock(this) { if (IsValidStatesTransition(_workItemState, workItemState)) { _workItemState = workItemState; } } } /// <summary> /// Signals that work item has been completed or canceled /// </summary> /// <param name="canceled">Indicates that the work item has been canceled</param> private void SignalComplete(bool canceled) { SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed); lock(this) { // If someone is waiting then signal. if (null != _workItemCompleted) { _workItemCompleted.Set(); } } } internal void WorkItemIsQueued() { _waitingOnQueueStopwatch.Start(); } #endregion #region Members exposed by WorkItemResult /// <summary> /// Cancel the work item if it didn't start running yet. /// </summary> /// <returns>Returns true on success or false if the work item is in progress or already completed</returns> private bool Cancel(bool abortExecution) { #if (_WINDOWS_CE) if(abortExecution) { throw new ArgumentOutOfRangeException("abortExecution", "WindowsCE doesn't support this feature"); } #endif bool success = false; bool signalComplete = false; lock (this) { switch(GetWorkItemState()) { case WorkItemState.Canceled: //Debug.WriteLine("Work item already canceled"); success = true; break; case WorkItemState.Completed: //Debug.WriteLine("Work item cannot be canceled"); break; case WorkItemState.InProgress: if (abortExecution) { Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread); if (null != executionThread) { executionThread.Abort(); // "Cancel" success = true; signalComplete = true; } } else { success = true; signalComplete = true; } break; case WorkItemState.InQueue: // Signal to the wait for completion that the work // item has been completed (canceled). There is no // reason to wait for it to get out of the queue signalComplete = true; //Debug.WriteLine("Work item canceled"); success = true; break; } if (signalComplete) { SignalComplete(true); } } return success; } /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel. /// In case of error the method throws and exception /// </summary> /// <returns>The result of the work item</returns> private object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { Exception e; object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e); if (null != e) { throw new WorkItemResultException("The work item caused an excpetion, see the inner exception for details", e); } return result; } /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel. /// In case of error the e argument is filled with the exception /// </summary> /// <returns>The result of the work item</returns> private object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { e = null; // Check for cancel if (WorkItemState.Canceled == GetWorkItemState()) { throw new WorkItemCancelException("Work item canceled"); } // Check for completion if (IsCompleted) { e = _exception; return _result; } // If no cancelWaitHandle is provided if (null == cancelWaitHandle) { WaitHandle wh = GetWaitHandle(); bool timeout = !STPEventWaitHandle.WaitOne(wh, millisecondsTimeout, exitContext); ReleaseWaitHandle(); if (timeout) { throw new WorkItemTimeoutException("Work item timeout"); } } else { WaitHandle wh = GetWaitHandle(); int result = STPEventWaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle }); ReleaseWaitHandle(); switch(result) { case 0: // The work item signaled // Note that the signal could be also as a result of canceling the // work item (not the get result) break; case 1: case STPEventWaitHandle.WaitTimeout: throw new WorkItemTimeoutException("Work item timeout"); default: Debug.Assert(false); break; } } // Check for cancel if (WorkItemState.Canceled == GetWorkItemState()) { throw new WorkItemCancelException("Work item canceled"); } Debug.Assert(IsCompleted); e = _exception; // Return the result return _result; } /// <summary> /// A wait handle to wait for completion, cancel, or timeout /// </summary> private WaitHandle GetWaitHandle() { lock(this) { if (null == _workItemCompleted) { _workItemCompleted = EventWaitHandleFactory.CreateManualResetEvent(IsCompleted); } ++_workItemCompletedRefCount; } return _workItemCompleted; } private void ReleaseWaitHandle() { lock(this) { if (null != _workItemCompleted) { --_workItemCompletedRefCount; if (0 == _workItemCompletedRefCount) { _workItemCompleted.Close(); _workItemCompleted = null; } } } } /// <summary> /// Returns true when the work item has completed or canceled /// </summary> private bool IsCompleted { get { lock(this) { WorkItemState workItemState = GetWorkItemState(); return ((workItemState == WorkItemState.Completed) || (workItemState == WorkItemState.Canceled)); } } } /// <summary> /// Returns true when the work item has canceled /// </summary> public bool IsCanceled { get { lock(this) { return (GetWorkItemState() == WorkItemState.Canceled); } } } #endregion #region IHasWorkItemPriority Members /// <summary> /// Returns the priority of the work item /// </summary> public WorkItemPriority WorkItemPriority { get { return _workItemInfo.WorkItemPriority; } } #endregion internal event WorkItemStateCallback OnWorkItemStarted { add { _workItemStartedEvent += value; } remove { _workItemStartedEvent -= value; } } internal event WorkItemStateCallback OnWorkItemCompleted { add { _workItemCompletedEvent += value; } remove { _workItemCompletedEvent -= value; } } /// <summary> /// /// </summary> public void DisposeOfState() { if (_workItemInfo.DisposeOfStateObjects) { IDisposable disp = _state as IDisposable; if (null != disp) { disp.Dispose(); _state = null; } } } } }
#if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabResultEvent<LoginResult> OnLoginResultEvent; public event PlayFabRequestEvent<GetPhotonAuthenticationTokenRequest> OnGetPhotonAuthenticationTokenRequestEvent; public event PlayFabResultEvent<GetPhotonAuthenticationTokenResult> OnGetPhotonAuthenticationTokenResultEvent; public event PlayFabRequestEvent<LoginWithAndroidDeviceIDRequest> OnLoginWithAndroidDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithCustomIDRequest> OnLoginWithCustomIDRequestEvent; public event PlayFabRequestEvent<LoginWithEmailAddressRequest> OnLoginWithEmailAddressRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookRequest> OnLoginWithFacebookRequestEvent; public event PlayFabRequestEvent<LoginWithGameCenterRequest> OnLoginWithGameCenterRequestEvent; public event PlayFabRequestEvent<LoginWithGoogleAccountRequest> OnLoginWithGoogleAccountRequestEvent; public event PlayFabRequestEvent<LoginWithIOSDeviceIDRequest> OnLoginWithIOSDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithKongregateRequest> OnLoginWithKongregateRequestEvent; public event PlayFabRequestEvent<LoginWithPlayFabRequest> OnLoginWithPlayFabRequestEvent; public event PlayFabRequestEvent<LoginWithSteamRequest> OnLoginWithSteamRequestEvent; public event PlayFabRequestEvent<LoginWithTwitchRequest> OnLoginWithTwitchRequestEvent; public event PlayFabRequestEvent<RegisterPlayFabUserRequest> OnRegisterPlayFabUserRequestEvent; public event PlayFabResultEvent<RegisterPlayFabUserResult> OnRegisterPlayFabUserResultEvent; public event PlayFabRequestEvent<AddGenericIDRequest> OnAddGenericIDRequestEvent; public event PlayFabResultEvent<AddGenericIDResult> OnAddGenericIDResultEvent; public event PlayFabRequestEvent<AddUsernamePasswordRequest> OnAddUsernamePasswordRequestEvent; public event PlayFabResultEvent<AddUsernamePasswordResult> OnAddUsernamePasswordResultEvent; public event PlayFabRequestEvent<GetAccountInfoRequest> OnGetAccountInfoRequestEvent; public event PlayFabResultEvent<GetAccountInfoResult> OnGetAccountInfoResultEvent; public event PlayFabRequestEvent<GetPlayerCombinedInfoRequest> OnGetPlayerCombinedInfoRequestEvent; public event PlayFabResultEvent<GetPlayerCombinedInfoResult> OnGetPlayerCombinedInfoResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookIDsRequest> OnGetPlayFabIDsFromFacebookIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookIDsResult> OnGetPlayFabIDsFromFacebookIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGameCenterIDsRequest> OnGetPlayFabIDsFromGameCenterIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGameCenterIDsResult> OnGetPlayFabIDsFromGameCenterIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGenericIDsRequest> OnGetPlayFabIDsFromGenericIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGenericIDsResult> OnGetPlayFabIDsFromGenericIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGoogleIDsRequest> OnGetPlayFabIDsFromGoogleIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGoogleIDsResult> OnGetPlayFabIDsFromGoogleIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromKongregateIDsRequest> OnGetPlayFabIDsFromKongregateIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromKongregateIDsResult> OnGetPlayFabIDsFromKongregateIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromSteamIDsRequest> OnGetPlayFabIDsFromSteamIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromSteamIDsResult> OnGetPlayFabIDsFromSteamIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromTwitchIDsRequest> OnGetPlayFabIDsFromTwitchIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromTwitchIDsResult> OnGetPlayFabIDsFromTwitchIDsResultEvent; public event PlayFabRequestEvent<GetUserCombinedInfoRequest> OnGetUserCombinedInfoRequestEvent; public event PlayFabResultEvent<GetUserCombinedInfoResult> OnGetUserCombinedInfoResultEvent; public event PlayFabRequestEvent<LinkAndroidDeviceIDRequest> OnLinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<LinkAndroidDeviceIDResult> OnLinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<LinkCustomIDRequest> OnLinkCustomIDRequestEvent; public event PlayFabResultEvent<LinkCustomIDResult> OnLinkCustomIDResultEvent; public event PlayFabRequestEvent<LinkFacebookAccountRequest> OnLinkFacebookAccountRequestEvent; public event PlayFabResultEvent<LinkFacebookAccountResult> OnLinkFacebookAccountResultEvent; public event PlayFabRequestEvent<LinkGameCenterAccountRequest> OnLinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<LinkGameCenterAccountResult> OnLinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<LinkGoogleAccountRequest> OnLinkGoogleAccountRequestEvent; public event PlayFabResultEvent<LinkGoogleAccountResult> OnLinkGoogleAccountResultEvent; public event PlayFabRequestEvent<LinkIOSDeviceIDRequest> OnLinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<LinkIOSDeviceIDResult> OnLinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<LinkKongregateAccountRequest> OnLinkKongregateRequestEvent; public event PlayFabResultEvent<LinkKongregateAccountResult> OnLinkKongregateResultEvent; public event PlayFabRequestEvent<LinkSteamAccountRequest> OnLinkSteamAccountRequestEvent; public event PlayFabResultEvent<LinkSteamAccountResult> OnLinkSteamAccountResultEvent; public event PlayFabRequestEvent<LinkTwitchAccountRequest> OnLinkTwitchRequestEvent; public event PlayFabResultEvent<LinkTwitchAccountResult> OnLinkTwitchResultEvent; public event PlayFabRequestEvent<RemoveGenericIDRequest> OnRemoveGenericIDRequestEvent; public event PlayFabResultEvent<RemoveGenericIDResult> OnRemoveGenericIDResultEvent; public event PlayFabRequestEvent<ReportPlayerClientRequest> OnReportPlayerRequestEvent; public event PlayFabResultEvent<ReportPlayerClientResult> OnReportPlayerResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<UnlinkAndroidDeviceIDRequest> OnUnlinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkAndroidDeviceIDResult> OnUnlinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkCustomIDRequest> OnUnlinkCustomIDRequestEvent; public event PlayFabResultEvent<UnlinkCustomIDResult> OnUnlinkCustomIDResultEvent; public event PlayFabRequestEvent<UnlinkFacebookAccountRequest> OnUnlinkFacebookAccountRequestEvent; public event PlayFabResultEvent<UnlinkFacebookAccountResult> OnUnlinkFacebookAccountResultEvent; public event PlayFabRequestEvent<UnlinkGameCenterAccountRequest> OnUnlinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<UnlinkGameCenterAccountResult> OnUnlinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<UnlinkGoogleAccountRequest> OnUnlinkGoogleAccountRequestEvent; public event PlayFabResultEvent<UnlinkGoogleAccountResult> OnUnlinkGoogleAccountResultEvent; public event PlayFabRequestEvent<UnlinkIOSDeviceIDRequest> OnUnlinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkIOSDeviceIDResult> OnUnlinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkKongregateAccountRequest> OnUnlinkKongregateRequestEvent; public event PlayFabResultEvent<UnlinkKongregateAccountResult> OnUnlinkKongregateResultEvent; public event PlayFabRequestEvent<UnlinkSteamAccountRequest> OnUnlinkSteamAccountRequestEvent; public event PlayFabResultEvent<UnlinkSteamAccountResult> OnUnlinkSteamAccountResultEvent; public event PlayFabRequestEvent<UnlinkTwitchAccountRequest> OnUnlinkTwitchRequestEvent; public event PlayFabResultEvent<UnlinkTwitchAccountResult> OnUnlinkTwitchResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardRequest> OnGetFriendLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetFriendLeaderboardResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardAroundPlayerRequest> OnGetFriendLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetFriendLeaderboardAroundPlayerResult> OnGetFriendLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetLeaderboardRequest> OnGetLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetLeaderboardResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundPlayerRequest> OnGetLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundPlayerResult> OnGetLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticsRequest> OnGetPlayerStatisticsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticsResult> OnGetPlayerStatisticsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticsRequest> OnUpdatePlayerStatisticsRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticsResult> OnUpdatePlayerStatisticsResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTimeRequest> OnGetTimeRequestEvent; public event PlayFabResultEvent<GetTimeResult> OnGetTimeResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleNewsRequest> OnGetTitleNewsRequestEvent; public event PlayFabResultEvent<GetTitleNewsResult> OnGetTitleNewsResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<ConfirmPurchaseRequest> OnConfirmPurchaseRequestEvent; public event PlayFabResultEvent<ConfirmPurchaseResult> OnConfirmPurchaseResultEvent; public event PlayFabRequestEvent<ConsumeItemRequest> OnConsumeItemRequestEvent; public event PlayFabResultEvent<ConsumeItemResult> OnConsumeItemResultEvent; public event PlayFabRequestEvent<GetCharacterInventoryRequest> OnGetCharacterInventoryRequestEvent; public event PlayFabResultEvent<GetCharacterInventoryResult> OnGetCharacterInventoryResultEvent; public event PlayFabRequestEvent<GetPurchaseRequest> OnGetPurchaseRequestEvent; public event PlayFabResultEvent<GetPurchaseResult> OnGetPurchaseResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnGetUserInventoryResultEvent; public event PlayFabRequestEvent<PayForPurchaseRequest> OnPayForPurchaseRequestEvent; public event PlayFabResultEvent<PayForPurchaseResult> OnPayForPurchaseResultEvent; public event PlayFabRequestEvent<PurchaseItemRequest> OnPurchaseItemRequestEvent; public event PlayFabResultEvent<PurchaseItemResult> OnPurchaseItemResultEvent; public event PlayFabRequestEvent<RedeemCouponRequest> OnRedeemCouponRequestEvent; public event PlayFabResultEvent<RedeemCouponResult> OnRedeemCouponResultEvent; public event PlayFabRequestEvent<StartPurchaseRequest> OnStartPurchaseRequestEvent; public event PlayFabResultEvent<StartPurchaseResult> OnStartPurchaseResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<UnlockContainerInstanceRequest> OnUnlockContainerInstanceRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerInstanceResultEvent; public event PlayFabRequestEvent<UnlockContainerItemRequest> OnUnlockContainerItemRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerItemResultEvent; public event PlayFabRequestEvent<AddFriendRequest> OnAddFriendRequestEvent; public event PlayFabResultEvent<AddFriendResult> OnAddFriendResultEvent; public event PlayFabRequestEvent<GetFriendsListRequest> OnGetFriendsListRequestEvent; public event PlayFabResultEvent<GetFriendsListResult> OnGetFriendsListResultEvent; public event PlayFabRequestEvent<RemoveFriendRequest> OnRemoveFriendRequestEvent; public event PlayFabResultEvent<RemoveFriendResult> OnRemoveFriendResultEvent; public event PlayFabRequestEvent<SetFriendTagsRequest> OnSetFriendTagsRequestEvent; public event PlayFabResultEvent<SetFriendTagsResult> OnSetFriendTagsResultEvent; public event PlayFabRequestEvent<RegisterForIOSPushNotificationRequest> OnRegisterForIOSPushNotificationRequestEvent; public event PlayFabResultEvent<RegisterForIOSPushNotificationResult> OnRegisterForIOSPushNotificationResultEvent; public event PlayFabRequestEvent<RestoreIOSPurchasesRequest> OnRestoreIOSPurchasesRequestEvent; public event PlayFabResultEvent<RestoreIOSPurchasesResult> OnRestoreIOSPurchasesResultEvent; public event PlayFabRequestEvent<ValidateIOSReceiptRequest> OnValidateIOSReceiptRequestEvent; public event PlayFabResultEvent<ValidateIOSReceiptResult> OnValidateIOSReceiptResultEvent; public event PlayFabRequestEvent<CurrentGamesRequest> OnGetCurrentGamesRequestEvent; public event PlayFabResultEvent<CurrentGamesResult> OnGetCurrentGamesResultEvent; public event PlayFabRequestEvent<GameServerRegionsRequest> OnGetGameServerRegionsRequestEvent; public event PlayFabResultEvent<GameServerRegionsResult> OnGetGameServerRegionsResultEvent; public event PlayFabRequestEvent<MatchmakeRequest> OnMatchmakeRequestEvent; public event PlayFabResultEvent<MatchmakeResult> OnMatchmakeResultEvent; public event PlayFabRequestEvent<StartGameRequest> OnStartGameRequestEvent; public event PlayFabResultEvent<StartGameResult> OnStartGameResultEvent; public event PlayFabRequestEvent<AndroidDevicePushNotificationRegistrationRequest> OnAndroidDevicePushNotificationRegistrationRequestEvent; public event PlayFabResultEvent<AndroidDevicePushNotificationRegistrationResult> OnAndroidDevicePushNotificationRegistrationResultEvent; public event PlayFabRequestEvent<ValidateGooglePlayPurchaseRequest> OnValidateGooglePlayPurchaseRequestEvent; public event PlayFabResultEvent<ValidateGooglePlayPurchaseResult> OnValidateGooglePlayPurchaseResultEvent; public event PlayFabRequestEvent<WriteClientCharacterEventRequest> OnWriteCharacterEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteCharacterEventResultEvent; public event PlayFabRequestEvent<WriteClientPlayerEventRequest> OnWritePlayerEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWritePlayerEventResultEvent; public event PlayFabRequestEvent<WriteTitleEventRequest> OnWriteTitleEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteTitleEventResultEvent; public event PlayFabRequestEvent<AddSharedGroupMembersRequest> OnAddSharedGroupMembersRequestEvent; public event PlayFabResultEvent<AddSharedGroupMembersResult> OnAddSharedGroupMembersResultEvent; public event PlayFabRequestEvent<CreateSharedGroupRequest> OnCreateSharedGroupRequestEvent; public event PlayFabResultEvent<CreateSharedGroupResult> OnCreateSharedGroupResultEvent; public event PlayFabRequestEvent<GetSharedGroupDataRequest> OnGetSharedGroupDataRequestEvent; public event PlayFabResultEvent<GetSharedGroupDataResult> OnGetSharedGroupDataResultEvent; public event PlayFabRequestEvent<RemoveSharedGroupMembersRequest> OnRemoveSharedGroupMembersRequestEvent; public event PlayFabResultEvent<RemoveSharedGroupMembersResult> OnRemoveSharedGroupMembersResultEvent; public event PlayFabRequestEvent<UpdateSharedGroupDataRequest> OnUpdateSharedGroupDataRequestEvent; public event PlayFabResultEvent<UpdateSharedGroupDataResult> OnUpdateSharedGroupDataResultEvent; public event PlayFabRequestEvent<ExecuteCloudScriptRequest> OnExecuteCloudScriptRequestEvent; public event PlayFabResultEvent<ExecuteCloudScriptResult> OnExecuteCloudScriptResultEvent; public event PlayFabRequestEvent<GetContentDownloadUrlRequest> OnGetContentDownloadUrlRequestEvent; public event PlayFabResultEvent<GetContentDownloadUrlResult> OnGetContentDownloadUrlResultEvent; public event PlayFabRequestEvent<ListUsersCharactersRequest> OnGetAllUsersCharactersRequestEvent; public event PlayFabResultEvent<ListUsersCharactersResult> OnGetAllUsersCharactersResultEvent; public event PlayFabRequestEvent<GetCharacterLeaderboardRequest> OnGetCharacterLeaderboardRequestEvent; public event PlayFabResultEvent<GetCharacterLeaderboardResult> OnGetCharacterLeaderboardResultEvent; public event PlayFabRequestEvent<GetCharacterStatisticsRequest> OnGetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<GetCharacterStatisticsResult> OnGetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundCharacterRequest> OnGetLeaderboardAroundCharacterRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundCharacterResult> OnGetLeaderboardAroundCharacterResultEvent; public event PlayFabRequestEvent<GetLeaderboardForUsersCharactersRequest> OnGetLeaderboardForUserCharactersRequestEvent; public event PlayFabResultEvent<GetLeaderboardForUsersCharactersResult> OnGetLeaderboardForUserCharactersResultEvent; public event PlayFabRequestEvent<GrantCharacterToUserRequest> OnGrantCharacterToUserRequestEvent; public event PlayFabResultEvent<GrantCharacterToUserResult> OnGrantCharacterToUserResultEvent; public event PlayFabRequestEvent<UpdateCharacterStatisticsRequest> OnUpdateCharacterStatisticsRequestEvent; public event PlayFabResultEvent<UpdateCharacterStatisticsResult> OnUpdateCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterDataResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterReadOnlyDataResultEvent; public event PlayFabRequestEvent<UpdateCharacterDataRequest> OnUpdateCharacterDataRequestEvent; public event PlayFabResultEvent<UpdateCharacterDataResult> OnUpdateCharacterDataResultEvent; public event PlayFabRequestEvent<ValidateAmazonReceiptRequest> OnValidateAmazonIAPReceiptRequestEvent; public event PlayFabResultEvent<ValidateAmazonReceiptResult> OnValidateAmazonIAPReceiptResultEvent; public event PlayFabRequestEvent<AcceptTradeRequest> OnAcceptTradeRequestEvent; public event PlayFabResultEvent<AcceptTradeResponse> OnAcceptTradeResultEvent; public event PlayFabRequestEvent<CancelTradeRequest> OnCancelTradeRequestEvent; public event PlayFabResultEvent<CancelTradeResponse> OnCancelTradeResultEvent; public event PlayFabRequestEvent<GetPlayerTradesRequest> OnGetPlayerTradesRequestEvent; public event PlayFabResultEvent<GetPlayerTradesResponse> OnGetPlayerTradesResultEvent; public event PlayFabRequestEvent<GetTradeStatusRequest> OnGetTradeStatusRequestEvent; public event PlayFabResultEvent<GetTradeStatusResponse> OnGetTradeStatusResultEvent; public event PlayFabRequestEvent<OpenTradeRequest> OnOpenTradeRequestEvent; public event PlayFabResultEvent<OpenTradeResponse> OnOpenTradeResultEvent; public event PlayFabRequestEvent<AttributeInstallRequest> OnAttributeInstallRequestEvent; public event PlayFabResultEvent<AttributeInstallResult> OnAttributeInstallResultEvent; public event PlayFabRequestEvent<GetPlayerSegmentsRequest> OnGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnGetPlayerTagsResultEvent; } } #endif
#region FilteredColumns // Used by CSLA Objects Guid public bool IsGuid(IColumn column){ return(column.LanguageType=="timestamp");} public ArrayList Guid(IColumns columns){ return FilteredColumns(columns,new Filter(IsGuid));} // Used in CSLA Business Objects AutoKey public bool AutoKey(IColumn column){ return(column.IsAutoKey);} public ArrayList AutoKey(IColumns columns){ return FilteredColumns(columns,new Filter(AutoKey));} public ArrayList AutoKey(IForeignKey fk){ ArrayList l = new ArrayList(); foreach(IColumn column in fk.ForeignTable.Columns){ if(column.IsAutoKey && !IsIn(column,fk.ForeignColumns))l.Add(column);} return l;} // Used in CSLA Stored Procedures private ArrayList AutoKey(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(AutoKey));} // Used in CSLA Stored Procedures Updatable public bool Updatable(IColumn column){ return(!NotUpdatable(column));} private ArrayList Updatable(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(Updatable));} // Used in CSLA Stored Procedures Not Updatable public bool NotUpdatable(IColumn column){ return(column.IsInPrimaryKey || column.IsAutoKey || column.IsComputed);} private ArrayList NotUpdatable(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(NotUpdatable));} // Used in CSLA Stored Procedures PrimaryKey public bool PrimaryKey(IColumn column){ return(column.IsInPrimaryKey);} private ArrayList PrimaryKey(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(PrimaryKey));} // Used in CSLA Stored Procedures Insertable public bool Insertable(IColumn column){ return(!NotInsertable(column));} private ArrayList Insertable(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(Insertable));} // Used in CSLA Stored Procedures Not Insertable public bool NotInsertable(IColumn column){ return(column.IsAutoKey || column.IsComputed);} private ArrayList NotInsertable(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(NotInsertable));} // Used in CSLA Stored Procedures & CSLA Business Objects Computed public bool Computed(IColumn column){ return(column.IsComputed);} private ArrayList Computed(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(Computed)); } // Used in CSLA Stored Procedures Not TimeStamp public bool NotTimestamp(IColumn column){ return(!Timestamp(column));} private ArrayList NotTimestamp(ITable tbl){ return FilteredColumns(tbl.Columns,new Filter(NotTimestamp));} private ArrayList NotTimestamp(IColumns cols){ return FilteredColumns(cols,new Filter(NotTimestamp));} // Used in CSLA Business Objects public bool IsRequired(IColumn column) { if(column.IsNullable) return false; if(!column.HasDefault) return true; // If it is the parent column it is required return IsParentColumn(column); // return false; } // public bool ForeignKey(IColumn column) // { // return(column.IsInForeignKey); // } // Used in CSLA Business Objects Automatic public bool IsAutomatic(IColumn column) { bool retval=column.Description.IndexOf("{auto}") >= 0; return retval; } // Used in CSLA Business Objects TimeStamp public bool Timestamp(IColumn column){ return(column.DataTypeName=="timestamp");} public ArrayList IsTimestamp(IColumns columns){ return FilteredColumns(columns,new Filter(Timestamp));} // Used in CSLA Stored Procedures and Business Objects public ArrayList FilteredColumns(IColumns columns,Filter f){ ArrayList l = new ArrayList(); foreach(IColumn column in columns) { if(f(column))l.Add(column); } return l; } // Used in CSLA Business Objects public ArrayList ExcludedColumns(IColumns columns,Filter f){ ArrayList l = new ArrayList(); foreach(IColumn column in columns) { if(!f(column))l.Add(column); } return l; } private int CountRequiredFields( IColumns Columns ){ return Columns.Count - CountNullableFields( Columns );} private int CountNullableFields( IColumns Columns ) { int i = 0; foreach( IColumn c in Columns ) { if( c.IsNullable ) { i++; } } return i; } private int CountUniqueFields( IColumns Columns ) { int i = 0; foreach( IColumn c in Columns ) { if( !c.IsNullable && c.IsInPrimaryKey ) { i++; } } return i; } public ArrayList MakeList(IColumns columns) { ArrayList l = new ArrayList(); foreach(IColumn column in columns) if(!column.IsAutoKey && !IsAutomatic(column) && !column.IsComputed) l.Add(column); return l; } public ArrayList MakeList4(IColumns columns) { ArrayList l = new ArrayList(); foreach(IColumn column in columns) if((!column.IsAutoKey && !IsAutomatic(column) && !column.IsComputed ) && (column.HasDefault==false || column.ForeignKeys.Count != 0)) l.Add(column); return l; } public ArrayList ReqList(IColumns columns) { ArrayList l = new ArrayList(); foreach(IColumn column in columns) if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey) l.Add(column); return l; } public ArrayList ReqListNoDefault(IColumns columns) { ArrayList l = new ArrayList(); foreach(IColumn column in columns) if(IsRequired(column) && !column.IsComputed && !column.IsAutoKey && column.HasDefault) l.Add(column); return l; } public ArrayList MakeList2(IColumns columns) { ArrayList l = new ArrayList(); foreach(IColumn column in columns) if(!column.IsAutoKey && !column.IsComputed) l.Add(column); return l; } public ArrayList MakeList3(IColumns columns) { ArrayList l = new ArrayList(); foreach(IColumn column in columns) if(IsAutomatic(column)) l.Add(column); return l; } public void BuildLists(IList cols,ref string sMakeListParamTypes, ref string sMakeListParams, ref string sSetTmp, ref string sParentCheck) { string sep = ""; string sepSet = ""; string sPrefixType=""; string sPrefix=""; string sPrefixSet=""; string sCheckSep = "if( "; sMakeListParamTypes = ""; sMakeListParams = ""; sSetTmp = ""; sParentCheck=""; // ArrayList parentCols = new ArrayList(); foreach(IColumn col in cols) { sMakeListParamTypes += sep + FormatColumn("{!rtype} {!local}",col); sMakeListParams += sep + FormatColumn("{!local}",col); sSetTmp += sepSet + FormatColumn("\t\t\ttmp.{!memberprop} = {!local};",col); sep=", "; sepSet="\r\n"; if(IsRelObj(col)) // If item is null, don't look it up { sParentCheck += sCheckSep + LocalName(RelObjProp(col)) + " != null "; sCheckSep = "|| "; } } if(sParentCheck != "")sParentCheck += ") "; sMakeListParamTypes = sPrefixType + sMakeListParamTypes; sMakeListParams = sPrefix + sMakeListParams; sSetTmp = sPrefixSet + sSetTmp; //sParentCheck=FormatColumns("{!rtype} {!local} = {autoseed};\r\n\t\t\tif (parent != null)\r\n\t\t\t{\r\n\t\t\t\t{!local} = parent;\r\n\t\t\t}\r\n\t\t\t",parentCols,"\r\n",""); //sParentCheck=""; } public bool SameList(IList lst1, IList lst2) { ArrayList l = new ArrayList(); foreach(IColumn col in lst1)l.Add(col.Name); foreach(IColumn col in lst2) if(l.Contains(col.Name))l.Remove(col.Name); else return false; return l.Count ==0; } public string SameList2(IList lst1, IList lst2) { ArrayList l = new ArrayList(); foreach(IColumn col in lst1)l.Add(col.Name); foreach(IColumn col in lst2)l.Remove(col.Name); string sList=""; string sep="Difference: "; foreach(string ss in l){ sList+=sep+ss; sep=", "; } return sList; } public bool SameTypes(IList lst1, IList lst2) { if(lst1.Count != lst2.Count) return false; for(int i=0;i<lst1.Count;i++) { IColumn col1 = (IColumn)(lst1[i]); IColumn col2 = (IColumn)(lst2[i]); if(CSLAType(col1)!=CSLAType(col2)) return false; } return true; } public string FieldName(IColumn col) { return col.Table.Name + "." + col.Name; } public bool SameFields(IList lst1, IList lst2) { if(lst1.Count != lst2.Count) return false; for(int i=0;i<lst1.Count;i++) { IColumn col1 = (IColumn)(lst1[i]); IColumn col2 = (IColumn)(lst2[i]); if(FieldName(col1)!=FieldName(col2)) return false; } return true; } // public ArrayList IsNotAutoKey(IColumns columns) // { // return ExcludedColumns(columns,new Filter(AutoKey)); // } // public bool TypeString(IColumn column) // { // return(CSLAType(column)=="string"); // } public bool HasDefault(IColumn column) { return column.HasDefault; } public ArrayList HasDefaults(IColumns columns) { return FilteredColumns(columns,new Filter(HasDefault)); } public ArrayList HasDefaults(IForeignKey fk) { ArrayList l = new ArrayList(); foreach(IColumn column in fk.ForeignTable.Columns) { if(column.HasDefault && !IsIn(column,fk.ForeignColumns))l.Add(column); } return l; } private string RelatedObject(IForeignKey fk, IColumn column){ if(column.ForeignKeys.Count == 1){ IForeignKey pk = column.ForeignKeys[0]; string sObj = _nameSpace + "." + ClassName( pk.PrimaryTable ); return FormatColumn(sObj + ".Get" + "({local})",column); } else { return FormatColumn("{local}",column); } } private string RelatedObjectType(IColumn column){ if(column.ForeignKeys.Count == 1){ IForeignKey pk = column.ForeignKeys[0]; string sObj = ClassName( pk.PrimaryTable ); return sObj + " " + LocalName(sObj); } else { return FormatColumn("{ctype} {local}",column); } } public string GetNewAlias2(IForeignKey fk,IForeignKey pk) { // First determine if there are more than one key linking two tables int iCount = 0; foreach(IForeignKey tk in fk.ForeignTable.ForeignKeys) { // WriteLine("fk {0} pk {1} pk.PrimaryTable.Name {2} pk.ForeignTable.Name {3} fk.ForeignTable.Name {4}", // fk.Name,pk.Name,pk.PrimaryTable.Name,pk.ForeignTable.Name,fk.ForeignTable.Name); if(tk.PrimaryTable == pk.PrimaryTable)iCount++; } if(iCount==0)return ""; return pk.ForeignColumns[0].Name; } public string GetNewAlias(IForeignKey fk,IForeignKey pk) { // First determine if there are more than one key linking two tables int iCount = 0; // WriteLine("fk {0} fk.Primary {1} fk.Foreign {2}",fk.Name,fk.PrimaryTable.Name,fk.ForeignTable.Name); // WriteLine(" pk {0} pk.Primary {1} pk.Foreign {2}",pk.Name,pk.PrimaryTable.Name,pk.ForeignTable.Name); foreach(IForeignKey tk in fk.ForeignTable.ForeignKeys) { if(tk.ForeignTable == pk.ForeignTable && tk.PrimaryTable == pk.PrimaryTable){ // WriteLine(" tk {0} tk.Primary {1} tk.Foreign {2}",tk.Name,tk.PrimaryTable.Name,tk.ForeignTable.Name); iCount++; } } if(iCount==1)return ""; // WriteLine("iCount {0}",iCount); return pk.ForeignColumns[0].Name; } private string RelatedObjectType2(IForeignKey fk,IColumn column){ if(column.ForeignKeys.Count == 1){ IForeignKey pk = column.ForeignKeys[0]; string sObj = ClassName( pk.PrimaryTable ); //return sObj + " " + LocalName(sObj) + column.Name; return sObj + " " + LocalName(sObj) + GetNewAlias(fk,pk); } else { return FormatColumn("{ctype} {local}",column); } } private bool IsPrimaryKey(IColumn col) { return (col.IsInPrimaryKey && col.Table.PrimaryKeys.Count == 1); } private IForeignKey RelObjFK(IColumn col) { if(!col.IsComputed && !col.IsAutoKey && !IsPrimaryKey(col) && col.ForeignKeys.Count==1) { IForeignKey fk = col.ForeignKeys[0]; // if(fk.PrimaryTable.Name != fk.ForeignTable.Name) // { // return (col.Name=="RangeID"?fk:null); return fk; // } } return null; } private bool IsRelObj(IColumn col) { if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1) return true; IForeignKey fk = RelObjFK(col); if(fk != null) return true; else return false; } private string RelObjType(IColumn col) { if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1) return ClassName( col.Table ); IForeignKey fk = RelObjFK(col); if(fk != null) return ClassName( fk.PrimaryTable ); else return CSLAType(col); } private string RelObjProp(IColumn col) { if(col.Table.Name != _workingTable.Name && col.IsInPrimaryKey && col.Table.PrimaryKeys.Count ==1) return "My" + ClassName( col.Table ); IForeignKey fk = RelObjFK(col); if(fk != null) if(fk.PrimaryTable.Name == fk.ForeignTable.Name) return "My" + ParentName(fk) + GetNewAlias(fk,fk); else return "My" + ClassName( fk.PrimaryTable ) + GetNewAlias(fk,fk); else return PropertyName(col); } private string RelObjCol(IColumn col) { IForeignKey fk = RelObjFK(col); if(fk != null) return PropertyName(fk.PrimaryColumns[0]); else return PropertyName(col); } private string RelObjEmpty(IColumn col) { IForeignKey fk = RelObjFK(col); if(col.IsNullable)return "null"; if(fk != null && fk.PrimaryTable.Name == fk.ForeignTable.Name) return MemberName(fk.PrimaryColumns[0]); if(CSLAType(col)=="string")return "null"; return "0"; } private string RelObjTypeCast(IColumn col) { IForeignKey fk = RelObjFK(col); if(col.IsNullable)return "(" + CSLAType(col,"") + ")"; return ""; } private ArrayList _TableStack = new ArrayList(); private void PushTable(ITable tbl) { _TableStack.Add(_workingTable); _workingTable=tbl; } private void PopTable() { if(_TableStack.Count > 0) { _workingTable=(ITable) _TableStack[_TableStack.Count-1]; _TableStack.RemoveAt(_TableStack.Count-1); } } private bool ForeignRequired(IForeignKey pk) { bool bRequired=true; foreach(IColumn col in pk.ForeignColumns) bRequired &= !col.IsNullable; return bRequired; } private bool ForeignPrimary(IForeignKey fk) { bool bPrimary=true; foreach(IColumn col in fk.ForeignColumns) { bPrimary &= col.IsInPrimaryKey; } return bPrimary; } public int FindColumn(IList cols, IColumn col) { for(int i=0;i<cols.Count;i++) if(((IColumn) cols[i]).Name==col.Name) return i; return -1; } public ArrayList FindUniqueChildren(IForeignKey fk){ ArrayList retval = new ArrayList(); foreach(IIndex ind in fk.ForeignTable.Indexes) { if(ind.Unique) { ArrayList uniqueColumns = new ArrayList(); foreach(IColumn col in ind.Columns) { uniqueColumns.Add(col); } foreach(IColumn col in fk.ForeignColumns) { int ii = FindColumn(uniqueColumns,col); if(ii >= 0) { uniqueColumns.RemoveAt(ii); } else { uniqueColumns.Clear(); } } if(uniqueColumns.Count > 0)// This is a uniqueIndex which includes the parent columns { //ShowColumns(uniqueColumns,4,"Unique Index " + ind.Name); retval.Add(uniqueColumns); } } } return retval; } public bool ContainsList(IList lst1, IList lst2) { foreach(IColumn col in lst2) if(FindColumn(lst1,col)<0)return false; return true; } public IList FindUnique(ArrayList lst, IList cols) { foreach(IList lstcols in lst) { if(ContainsList(cols,lstcols))return lstcols; } return null; } //public ArrayList zzFilteredColumnsAny(IColumns columns,Filter [] fs){ // ArrayList l = new ArrayList(); // foreach(IColumn column in columns) // { // bool check = false; // foreach(Filter f in fs)check |= f(column); // if(check)l.Add(column); // } // return l; //} //public ArrayList zzExcludedColumnsAny(IColumns columns,Filter [] fs){ // ArrayList l = new ArrayList(); // foreach(IColumn column in columns) // { // bool check = false; // foreach(Filter f in fs)check |= f(column); // if(!check)l.Add(column); // } // return l; //} #endregion
using System; using AutoFixture.Idioms; using Xunit; namespace AutoFixture.IdiomsUnitTest { public class EmptyStringBehaviorExpectationTest { [Fact] public void SutIsBehaviorExpectation() { // Arrange var expectation = new EmptyStringBehaviorExpectation(); // Act & Assert Assert.IsAssignableFrom<IBehaviorExpectation>(expectation); } [Fact] public void VerifyNullCommandThrows() { // Arrange var expectation = new EmptyStringBehaviorExpectation(); // Act & Assert Assert.Throws<ArgumentNullException>(() => expectation.Verify(default)); } [Fact] public void VerifyExecutesCommandWhenRequestedTypeIsString() { // Arrange var commandExecuted = false; var command = new DelegatingGuardClauseCommand { OnExecute = (v) => { commandExecuted = true; throw new ArgumentException(string.Empty, "paramName"); }, RequestedType = typeof(string), RequestedParameterName = "paramName" }; var expectation = new EmptyStringBehaviorExpectation(); // Act expectation.Verify(command); // Assert Assert.True(commandExecuted); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(Guid))] [InlineData(typeof(object))] [InlineData(typeof(Version))] [InlineData(typeof(decimal))] public void VerifyDoesNotExecuteCommandWhenRequestedTypeNotString(Type type) { // Arrange var commandExecuted = false; var command = new DelegatingGuardClauseCommand { OnExecute = (v) => commandExecuted = true, RequestedType = type }; var expectation = new EmptyStringBehaviorExpectation(); // Act expectation.Verify(command); // Assert Assert.False(commandExecuted); } [Fact] public void VerifyDoesNotThrowWhenCommandThrowsArgumentExceptionWithMatchingParameterName() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new ArgumentException(string.Empty, "paramName"), RequestedType = typeof(string), RequestedParameterName = "paramName" }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Null(actual); } [Fact] public void VerifyThrowsExpectedExceptionWhenCommandDoesNotThrow() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => { }, OnCreateException = v => expected, RequestedType = typeof(string) }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual); } [Fact] public void VerifyThrowsExceptionWithExpectedValueWhenCommandDoesNotThrow() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => { }, OnCreateException = v => new Exception(v), RequestedType = typeof(string) }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal("<empty string>", actual.Message); } [Fact] public void VerifyThrowsExpectedExceptionWhenCommandThrowsNonArgumentException() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new Exception(), OnCreateExceptionWithInner = (v, e) => expected, RequestedType = typeof(string) }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual); } [Fact] public void VerifyThrowsWithExpectedValueWhenCommandThrowsNonArgumentException() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new Exception(), OnCreateExceptionWithInner = (v, e) => new Exception(v, e), RequestedType = typeof(string) }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal("<empty string>", actual.Message); } [Fact] public void VerifyThrowsWithExpectedInnerExceptionWhenCommandThrowsNonArgumentException() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw expected, OnCreateExceptionWithInner = (v, e) => new Exception(v, e), RequestedType = typeof(string) }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual.InnerException); } [Fact] public void VerifyThrowsExpectedExceptionWhenCommandThrowsArgumentExceptionWithWrongParameterName() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new ArgumentException(string.Empty, "wrongParamName"), OnCreateExceptionWithFailureReason = (v, m, e) => expected, RequestedType = typeof(string), RequestedParameterName = "expectedParamName" }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual); } [Fact] public void VerifyThrowsExceptionWithExpectedMessageWhenCommandThrowsArgumentExceptionWithWrongParameterName() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new ArgumentException(string.Empty, "wrongParamName"), OnCreateExceptionWithFailureReason = (v, m, e) => new Exception(m, e), RequestedType = typeof(string), RequestedParameterName = "expectedParamName" }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.EndsWith( $"Expected parameter name: expectedParamName{Environment.NewLine}Actual parameter name: wrongParamName", actual.Message); } [Fact] public void VerifyThrowsExceptionWithExpectedInnerWhenCommandThrowsArgumentExceptionWithWrongParameterName() { // Arrange var expected = new ArgumentException(string.Empty, "wrongParamName"); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw expected, OnCreateExceptionWithFailureReason = (v, m, e) => new Exception(m, e), RequestedType = typeof(string), RequestedParameterName = "expectedParamName" }; var expectation = new EmptyStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual.InnerException); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>AdGroupAudienceView</c> resource.</summary> public sealed partial class AdGroupAudienceViewName : gax::IResourceName, sys::IEquatable<AdGroupAudienceViewName> { /// <summary>The possible contents of <see cref="AdGroupAudienceViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> CustomerAdGroupCriterion = 1, } private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/adGroupAudienceViews/{ad_group_id_criterion_id}"); /// <summary>Creates a <see cref="AdGroupAudienceViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AdGroupAudienceViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupAudienceViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupAudienceViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupAudienceViewName"/> with the pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="AdGroupAudienceViewName"/> constructed from the provided ids. /// </returns> public static AdGroupAudienceViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => new AdGroupAudienceViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string criterionId) => FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupAudienceViewName"/> if successful.</returns> public static AdGroupAudienceViewName Parse(string adGroupAudienceViewName) => Parse(adGroupAudienceViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AdGroupAudienceViewName"/> if successful.</returns> public static AdGroupAudienceViewName Parse(string adGroupAudienceViewName, bool allowUnparsed) => TryParse(adGroupAudienceViewName, allowUnparsed, out AdGroupAudienceViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAudienceViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAudienceViewName, out AdGroupAudienceViewName result) => TryParse(adGroupAudienceViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAudienceViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAudienceViewName, bool allowUnparsed, out AdGroupAudienceViewName result) { gax::GaxPreconditions.CheckNotNull(adGroupAudienceViewName, nameof(adGroupAudienceViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupCriterion.TryParseName(adGroupAudienceViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupAudienceViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupAudienceViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupAudienceViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupAudienceViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AdGroupAudienceViewName); /// <inheritdoc/> public bool Equals(AdGroupAudienceViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupAudienceViewName a, AdGroupAudienceViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupAudienceViewName a, AdGroupAudienceViewName b) => !(a == b); } public partial class AdGroupAudienceView { /// <summary> /// <see cref="AdGroupAudienceViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupAudienceViewName ResourceNameAsAdGroupAudienceViewName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAudienceViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text.Json; using Microsoft.AspNetCore.Components.Infrastructure; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Infrastructure; using Microsoft.AspNetCore.Components.WebAssembly.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.JSInterop; using static Microsoft.AspNetCore.Internal.LinkerFlags; namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting { /// <summary> /// A builder for configuring and creating a <see cref="WebAssemblyHost"/>. /// </summary> public sealed class WebAssemblyHostBuilder { private readonly JsonSerializerOptions _jsonOptions; private Func<IServiceProvider> _createServiceProvider; private RootComponentTypeCache? _rootComponentCache; private string? _persistedState; /// <summary> /// Creates an instance of <see cref="WebAssemblyHostBuilder"/> using the most common /// conventions and settings. /// </summary> /// <param name="args">The argument passed to the application's main method.</param> /// <returns>A <see cref="WebAssemblyHostBuilder"/>.</returns> [DynamicDependency(nameof(JSInteropMethods.NotifyLocationChanged), typeof(JSInteropMethods))] [DynamicDependency(JsonSerialized, typeof(WebEventDescriptor))] // The following dependency prevents HeadOutlet from getting trimmed away in // WebAssembly prerendered apps. [DynamicDependency(Component, typeof(HeadOutlet))] public static WebAssemblyHostBuilder CreateDefault(string[]? args = default) { // We don't use the args for anything right now, but we want to accept them // here so that it shows up this way in the project templates. var jsRuntime = DefaultWebAssemblyJSRuntime.Instance; var builder = new WebAssemblyHostBuilder( jsRuntime, jsRuntime.ReadJsonSerializerOptions()); WebAssemblyCultureProvider.Initialize(); // Right now we don't have conventions or behaviors that are specific to this method // however, making this the default for the template allows us to add things like that // in the future, while giving `new WebAssemblyHostBuilder` as an opt-out of opinionated // settings. return builder; } /// <summary> /// Creates an instance of <see cref="WebAssemblyHostBuilder"/> with the minimal configuration. /// </summary> internal WebAssemblyHostBuilder(IJSUnmarshalledRuntime jsRuntime, JsonSerializerOptions jsonOptions) { // Private right now because we don't have much reason to expose it. This can be exposed // in the future if we want to give people a choice between CreateDefault and something // less opinionated. _jsonOptions = jsonOptions; Configuration = new WebAssemblyHostConfiguration(); RootComponents = new RootComponentMappingCollection(); Services = new ServiceCollection(); Logging = new LoggingBuilder(Services); // Retrieve required attributes from JSRuntimeInvoker InitializeNavigationManager(jsRuntime); InitializeRegisteredRootComponents(jsRuntime); InitializePersistedState(jsRuntime); InitializeDefaultServices(); var hostEnvironment = InitializeEnvironment(jsRuntime); HostEnvironment = hostEnvironment; _createServiceProvider = () => { return Services.BuildServiceProvider(validateScopes: WebAssemblyHostEnvironmentExtensions.IsDevelopment(hostEnvironment)); }; } private void InitializeRegisteredRootComponents(IJSUnmarshalledRuntime jsRuntime) { var componentsCount = jsRuntime.InvokeUnmarshalled<int>(RegisteredComponentsInterop.GetRegisteredComponentsCount); if (componentsCount == 0) { return; } var registeredComponents = new WebAssemblyComponentMarker[componentsCount]; for (var i = 0; i < componentsCount; i++) { var id = jsRuntime.InvokeUnmarshalled<int, int>(RegisteredComponentsInterop.GetId, i); var assembly = jsRuntime.InvokeUnmarshalled<int, string>(RegisteredComponentsInterop.GetAssembly, id); var typeName = jsRuntime.InvokeUnmarshalled<int, string>(RegisteredComponentsInterop.GetTypeName, id); var serializedParameterDefinitions = jsRuntime.InvokeUnmarshalled<int, object?, object?, string>(RegisteredComponentsInterop.GetParameterDefinitions, id, null, null); var serializedParameterValues = jsRuntime.InvokeUnmarshalled<int, object?, object?, string>(RegisteredComponentsInterop.GetParameterValues, id, null, null); registeredComponents[i] = new WebAssemblyComponentMarker(WebAssemblyComponentMarker.ClientMarkerType, assembly, typeName, serializedParameterDefinitions, serializedParameterValues, id.ToString(CultureInfo.InvariantCulture)); } var componentDeserializer = WebAssemblyComponentParameterDeserializer.Instance; foreach (var registeredComponent in registeredComponents) { _rootComponentCache = new RootComponentTypeCache(); var componentType = _rootComponentCache.GetRootComponent(registeredComponent.Assembly!, registeredComponent.TypeName!); if (componentType is null) { throw new InvalidOperationException( $"Root component type '{registeredComponent.TypeName}' could not be found in the assembly '{registeredComponent.Assembly}'. " + $"This is likely a result of trimming (tree shaking)."); } var definitions = componentDeserializer.GetParameterDefinitions(registeredComponent.ParameterDefinitions!); var values = componentDeserializer.GetParameterValues(registeredComponent.ParameterValues!); var parameters = componentDeserializer.DeserializeParameters(definitions, values); RootComponents.Add(componentType, registeredComponent.PrerenderId!, parameters); } } private void InitializePersistedState(IJSUnmarshalledRuntime jsRuntime) { _persistedState = jsRuntime.InvokeUnmarshalled<string>("Blazor._internal.getPersistedState"); } private void InitializeNavigationManager(IJSUnmarshalledRuntime jsRuntime) { var baseUri = jsRuntime.InvokeUnmarshalled<string>(BrowserNavigationManagerInterop.GetBaseUri); var uri = jsRuntime.InvokeUnmarshalled<string>(BrowserNavigationManagerInterop.GetLocationHref); WebAssemblyNavigationManager.Instance = new WebAssemblyNavigationManager(baseUri, uri); } private WebAssemblyHostEnvironment InitializeEnvironment(IJSUnmarshalledRuntime jsRuntime) { var applicationEnvironment = jsRuntime.InvokeUnmarshalled<string>("Blazor._internal.getApplicationEnvironment"); var hostEnvironment = new WebAssemblyHostEnvironment(applicationEnvironment, WebAssemblyNavigationManager.Instance.BaseUri); Services.AddSingleton<IWebAssemblyHostEnvironment>(hostEnvironment); var configFiles = new[] { "appsettings.json", $"appsettings.{applicationEnvironment}.json" }; foreach (var configFile in configFiles) { var appSettingsJson = jsRuntime.InvokeUnmarshalled<string, byte[]>( "Blazor._internal.getConfig", configFile); if (appSettingsJson != null) { // Perf: Using this over AddJsonStream. This allows the linker to trim out the "File"-specific APIs and assemblies // for Configuration, of where there are several. Configuration.Add<JsonStreamConfigurationSource>(s => s.Stream = new MemoryStream(appSettingsJson)); } } return hostEnvironment; } /// <summary> /// Gets an <see cref="WebAssemblyHostConfiguration"/> that can be used to customize the application's /// configuration sources and read configuration attributes. /// </summary> public WebAssemblyHostConfiguration Configuration { get; } /// <summary> /// Gets the collection of root component mappings configured for the application. /// </summary> public RootComponentMappingCollection RootComponents { get; } /// <summary> /// Gets the service collection. /// </summary> public IServiceCollection Services { get; } /// <summary> /// Gets information about the app's host environment. /// </summary> public IWebAssemblyHostEnvironment HostEnvironment { get; } /// <summary> /// Gets the logging builder for configuring logging services. /// </summary> public ILoggingBuilder Logging { get; } /// <summary> /// Registers a <see cref="IServiceProviderFactory{TBuilder}" /> instance to be used to create the <see cref="IServiceProvider" />. /// </summary> /// <param name="factory">The <see cref="IServiceProviderFactory{TBuilder}" />.</param> /// <param name="configure"> /// A delegate used to configure the <typeparamref T="TBuilder" />. This can be used to configure services using /// APIS specific to the <see cref="IServiceProviderFactory{TBuilder}" /> implementation. /// </param> /// <typeparam name="TBuilder">The type of builder provided by the <see cref="IServiceProviderFactory{TBuilder}" />.</typeparam> /// <remarks> /// <para> /// <see cref="ConfigureContainer{TBuilder}(IServiceProviderFactory{TBuilder}, Action{TBuilder})"/> is called by <see cref="Build"/> /// and so the delegate provided by <paramref name="configure"/> will run after all other services have been registered. /// </para> /// <para> /// Multiple calls to <see cref="ConfigureContainer{TBuilder}(IServiceProviderFactory{TBuilder}, Action{TBuilder})"/> will replace /// the previously stored <paramref name="factory"/> and <paramref name="configure"/> delegate. /// </para> /// </remarks> public void ConfigureContainer<TBuilder>(IServiceProviderFactory<TBuilder> factory, Action<TBuilder>? configure = null) where TBuilder : notnull { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } _createServiceProvider = () => { var container = factory.CreateBuilder(Services); configure?.Invoke(container); return factory.CreateServiceProvider(container); }; } /// <summary> /// Builds a <see cref="WebAssemblyHost"/> instance based on the configuration of this builder. /// </summary> /// <returns>A <see cref="WebAssemblyHost"/> object.</returns> public WebAssemblyHost Build() { // Intentionally overwrite configuration with the one we're creating. Services.AddSingleton<IConfiguration>(Configuration); // A Blazor application always runs in a scope. Since we want to make it possible for the user // to configure services inside *that scope* inside their startup code, we create *both* the // service provider and the scope here. var services = _createServiceProvider(); var scope = services.GetRequiredService<IServiceScopeFactory>().CreateAsyncScope(); return new WebAssemblyHost(this, services, scope, _persistedState); } internal void InitializeDefaultServices() { Services.AddSingleton<IJSRuntime>(DefaultWebAssemblyJSRuntime.Instance); Services.AddSingleton<NavigationManager>(WebAssemblyNavigationManager.Instance); Services.AddSingleton<INavigationInterception>(WebAssemblyNavigationInterception.Instance); Services.AddSingleton(new LazyAssemblyLoader(DefaultWebAssemblyJSRuntime.Instance)); Services.AddSingleton<ComponentStatePersistenceManager>(); Services.AddSingleton<PersistentComponentState>(sp => sp.GetRequiredService<ComponentStatePersistenceManager>().State); Services.AddSingleton<IErrorBoundaryLogger, WebAssemblyErrorBoundaryLogger>(); Services.AddLogging(builder => { builder.AddProvider(new WebAssemblyConsoleLoggerProvider(DefaultWebAssemblyJSRuntime.Instance)); }); } } }
using UnityEngine; namespace UnitySampleAssets.Vehicles.Car { [RequireComponent(typeof (WheelCollider))] public class Wheel : MonoBehaviour { public Transform wheelModel; public float Rpm { get; private set; } public float MaxRpm { get; private set; } public float SkidFactor { get; private set; } public bool OnGround { get; private set; } public Transform Hub { get; set; } public WheelCollider wheelCollider { get; private set; } public CarController car { get; private set; } public Transform skidTrailPrefab; public static Transform skidTrailsDetachedParent; public float loQualDist = 100; public bool steerable = false; public bool powered = false; [SerializeField] private float particleRate = 3; [SerializeField] private float slideThreshold = 10f; public float suspensionSpringPos { get; private set; } private float spinAngle; private float particleEmit; private float sidewaysStiffness; private float forwardStiffness; private float spinoutFactor; private float sideSlideFactor; private float springCompression; private ParticleSystem skidSmokeSystem; private Rigidbody rb; private WheelFrictionCurve sidewaysFriction; private WheelFrictionCurve forwardFriction; private Transform skidTrail; private bool leavingSkidTrail; private RaycastHit hit; private Vector3 relativeVelocity; private float sideSlideFactorTarget; private float spinoutFactorTarget; private float accelAmount; private float burnoutFactor; private float burnoutGrip; private float spinoutGrip; private float sideSlideGrip; private float minGrip; private float springCompressionGripModifier; private float burnoutRpm; private float skidFactorTarget; private bool ignore; private Vector3 originalWheelModelPosition; private void Start() { car = transform.parent.GetComponent<CarController>(); wheelCollider = GetComponent<Collider>() as WheelCollider; if (wheelModel != null) { originalWheelModelPosition = wheelModel.localPosition; transform.position = wheelModel.position; // - wheelCollider.suspensionDistance*0.5f*transform.up; } // store initial starting values of wheelCollider sidewaysFriction = wheelCollider.sidewaysFriction; forwardFriction = wheelCollider.forwardFriction; sidewaysStiffness = wheelCollider.sidewaysFriction.stiffness; forwardStiffness = wheelCollider.forwardFriction.stiffness; // nominal max rpm at Car's top speed (can be more if Car is rolling downhill!) MaxRpm = (car.MaxSpeed/(Mathf.PI*wheelCollider.radius*2))*60; // get a reference to the particle system for the tire smoke skidSmokeSystem = car.GetComponentInChildren<ParticleSystem>(); rb = wheelCollider.attachedRigidbody; if (skidTrailsDetachedParent == null) { skidTrailsDetachedParent = new GameObject("Skid Trails - Detached").transform; } } // called in sync with the physics system private void FixedUpdate() { // calculate if the wheel is sliding sideways relativeVelocity = transform.InverseTransformDirection(rb.velocity); // sideways slide is considered at maximum if 10% or more of the wheel's velocity is perpendicular to its forward direction: sideSlideFactorTarget = Mathf.Clamp01(Mathf.Abs(relativeVelocity.x*slideThreshold/car.MaxSpeed)*(car.SpeedFactor*.5f + .5f)); sideSlideFactor = sideSlideFactorTarget > sideSlideFactor ? sideSlideFactorTarget : Mathf.Lerp(sideSlideFactor, sideSlideFactorTarget, Time.deltaTime); spinoutFactorTarget = Mathf.Clamp01((rb.angularVelocity.magnitude*Mathf.Rad2Deg*.01f)*(((1 - car.SpeedFactor)*.5f) + .5f)); spinoutFactorTarget = Mathf.Lerp(0, spinoutFactorTarget, car.SpeedFactor + (powered ? car.AccelInput : 0)); spinoutFactor = spinoutFactorTarget > spinoutFactor ? spinoutFactorTarget : Mathf.Lerp(spinoutFactor, spinoutFactorTarget, Time.deltaTime); // calculate if burnout slip should be occuring accelAmount = (wheelCollider.motorTorque/car.MaxTorque); burnoutFactor = 0; if (powered) { burnoutFactor = (accelAmount - (1 - car.BurnoutTendency))/(1 - car.BurnoutTendency); } burnoutGrip = Mathf.Lerp(1, 1 - car.BurnoutSlipEffect, burnoutFactor); spinoutGrip = Mathf.Lerp(1, 1 - car.SpinoutSlipEffect, spinoutFactor); sideSlideGrip = Mathf.Lerp(1, 1 - car.SideSlideEffect, sideSlideFactor); // doing it this way stops the GC alloc minGrip = Mathf.Min(burnoutGrip, spinoutGrip); minGrip = Mathf.Min(sideSlideGrip, minGrip); springCompressionGripModifier = springCompression + 0.6f; springCompressionGripModifier *= springCompressionGripModifier; sidewaysFriction.stiffness = sidewaysStiffness*minGrip*springCompressionGripModifier; forwardFriction.stiffness = forwardStiffness*burnoutGrip*springCompressionGripModifier; wheelCollider.sidewaysFriction = sidewaysFriction; wheelCollider.forwardFriction = forwardFriction; burnoutRpm = (car.MaxSpeed*car.BurnoutTendency/(Mathf.PI*wheelCollider.radius*2))*60; Rpm = burnoutRpm > wheelCollider.rpm ? Mathf.Lerp(wheelCollider.rpm, burnoutRpm, burnoutFactor) : wheelCollider.rpm; // if the car is on the ground deal with skid trails and ture smoke if (OnGround) { // overall skid factor, for drawing skid particles skidFactorTarget = Mathf.Max(burnoutFactor*2, sideSlideFactor*rb.velocity.magnitude*.05f); skidFactorTarget = Mathf.Max(skidFactorTarget, spinoutFactor*rb.velocity.magnitude*.05f); skidFactorTarget = Mathf.Clamp01(-.1f + skidFactorTarget*1.1f); SkidFactor = Mathf.MoveTowards(SkidFactor, skidFactorTarget, Time.deltaTime*2); if (skidSmokeSystem != null) { particleEmit += SkidFactor*Time.deltaTime; if (particleEmit > particleRate) { particleEmit = 0; skidSmokeSystem.transform.position = transform.position - transform.up*wheelCollider.radius; skidSmokeSystem.Emit(1); } } } if (skidTrailPrefab != null) { if (SkidFactor > 0.5f && OnGround) { if (!leavingSkidTrail) { skidTrail = Instantiate(skidTrailPrefab) as Transform; if (skidTrail != null) { skidTrail.parent = transform; skidTrail.localPosition = -Vector3.up*(wheelCollider.radius - 0.1f); } leavingSkidTrail = true; } } else { if (leavingSkidTrail) { skidTrail.parent = skidTrailsDetachedParent; Destroy(skidTrail.gameObject, 10); leavingSkidTrail = false; } } } // *6 converts RPM to Degrees per second (i.e. *360 and /60 ) spinAngle += Rpm*6*Time.deltaTime; var distToCamSq = (Camera.main.transform.position - transform.position).sqrMagnitude; var checkThisFrame = true; if (distToCamSq > loQualDist*loQualDist) { // far from camera - use infrequent ground detection, once every five frames var checkProbability = Mathf.Lerp(1, 0.2f, Mathf.InverseLerp(loQualDist*loQualDist, loQualDist*loQualDist*4, distToCamSq)); checkThisFrame = Random.value < checkProbability; } if (!checkThisFrame) return; if (Physics.Raycast(transform.position, -transform.up, out hit, wheelCollider.suspensionDistance + wheelCollider.radius)) { suspensionSpringPos = -(hit.distance - wheelCollider.radius); springCompression = Mathf.InverseLerp(-wheelCollider.suspensionDistance, wheelCollider.suspensionDistance, suspensionSpringPos); OnGround = true; } else { suspensionSpringPos = -(wheelCollider.suspensionDistance); OnGround = false; springCompression = 0; SkidFactor = 0; } // update wheel model position and rotation if (wheelModel != null) { wheelModel.localPosition = originalWheelModelPosition + Vector3.up*suspensionSpringPos; wheelModel.localRotation = Quaternion.AngleAxis(wheelCollider.steerAngle, Vector3.up)* Quaternion.Euler(spinAngle, 0, 0); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SampleIdentityTokenLayer.Areas.HelpPage.ModelDescriptions; using SampleIdentityTokenLayer.Areas.HelpPage.Models; namespace SampleIdentityTokenLayer.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal partial class CMemberLookupResults { public partial class CMethodIterator { private SymbolLoader _pSymbolLoader; private CSemanticChecker _pSemanticChecker; // Inputs. private AggregateType _pCurrentType; private MethodOrPropertySymbol _pCurrentSym; private Declaration _pContext; private TypeArray _pContainingTypes; private CType _pQualifyingType; private Name _pName; private int _nArity; private symbmask_t _mask; private EXPRFLAG _flags; // Internal state. private int _nCurrentTypeCount; private bool _bIsCheckingInstanceMethods; private bool _bAtEnd; private bool _bAllowBogusAndInaccessible; // Flags for the current sym. private bool _bCurrentSymIsBogus; private bool _bCurrentSymIsInaccessible; // if Extension can be part of the results that are returned by the iterator // this may be false if an applicable instance method was found by bindgrptoArgs private bool _bcanIncludeExtensionsInResults; // we have found a applicable extension and only continue to the end of the current // Namespace's extension methodlist private bool _bEndIterationAtCurrentExtensionList; public CMethodIterator(CSemanticChecker checker, SymbolLoader symLoader, Name name, TypeArray containingTypes, CType @object, CType qualifyingType, Declaration context, bool allowBogusAndInaccessible, bool allowExtensionMethods, int arity, EXPRFLAG flags, symbmask_t mask) { Debug.Assert(name != null); Debug.Assert(symLoader != null); Debug.Assert(checker != null); Debug.Assert(containingTypes != null); _pSemanticChecker = checker; _pSymbolLoader = symLoader; _pCurrentType = null; _pCurrentSym = null; _pName = name; _pContainingTypes = containingTypes; _pQualifyingType = qualifyingType; _pContext = context; _bAllowBogusAndInaccessible = allowBogusAndInaccessible; _nArity = arity; _flags = flags; _mask = mask; _nCurrentTypeCount = 0; _bIsCheckingInstanceMethods = true; _bAtEnd = false; _bCurrentSymIsBogus = false; _bCurrentSymIsInaccessible = false; _bcanIncludeExtensionsInResults = allowExtensionMethods; _bEndIterationAtCurrentExtensionList = false; } public MethodOrPropertySymbol GetCurrentSymbol() { return _pCurrentSym; } public AggregateType GetCurrentType() { return _pCurrentType; } public bool IsCurrentSymbolInaccessible() { return _bCurrentSymIsInaccessible; } public bool IsCurrentSymbolBogus() { return _bCurrentSymIsBogus; } public bool MoveNext(bool canIncludeExtensionsInResults, bool endatCurrentExtensionList) { if (_bcanIncludeExtensionsInResults) { _bcanIncludeExtensionsInResults = canIncludeExtensionsInResults; } if (!_bEndIterationAtCurrentExtensionList) { _bEndIterationAtCurrentExtensionList = endatCurrentExtensionList; } if (_bAtEnd) { return false; } if (_pCurrentType == null) // First guy. { if (_pContainingTypes.size == 0) { // No instance methods, only extensions. _bIsCheckingInstanceMethods = false; _bAtEnd = true; return false; } else { if (!FindNextTypeForInstanceMethods()) { // No instance or extensions. _bAtEnd = true; return false; } } } if (!FindNextMethod()) { _bAtEnd = true; return false; } return true; } public bool AtEnd() { return _pCurrentSym == null; } private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; } private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; } public bool CanUseCurrentSymbol() { _bCurrentSymIsInaccessible = false; _bCurrentSymIsBogus = false; // Make sure that whether we're seeing a ctor is consistent with the flag. // The only properties we handle are indexers. if (_mask == symbmask_t.MASK_MethodSymbol && ( 0 == (_flags & EXPRFLAG.EXF_CTOR) != !_pCurrentSym.AsMethodSymbol().IsConstructor() || 0 == (_flags & EXPRFLAG.EXF_OPERATOR) != !_pCurrentSym.AsMethodSymbol().isOperator) || _mask == symbmask_t.MASK_PropertySymbol && !_pCurrentSym.AsPropertySymbol().isIndexer()) { // Get the next symbol. return false; } // If our arity is non-0, we must match arity with this symbol. if (_nArity > 0) { if (_mask == symbmask_t.MASK_MethodSymbol && _pCurrentSym.AsMethodSymbol().typeVars.size != _nArity) { return false; } } // If this guy's not callable, no good. if (!ExpressionBinder.IsMethPropCallable(_pCurrentSym, (_flags & EXPRFLAG.EXF_USERCALLABLE) != 0)) { return false; } // Check access. if (!GetSemanticChecker().CheckAccess(_pCurrentSym, _pCurrentType, _pContext, _pQualifyingType)) { // Sym is not accessible. However, if we're allowing inaccessible, then let it through and mark it. if (_bAllowBogusAndInaccessible) { _bCurrentSymIsInaccessible = true; } else { return false; } } // Check bogus. if (GetSemanticChecker().CheckBogus(_pCurrentSym)) { // Sym is bogus, but if we're allow it, then let it through and mark it. if (_bAllowBogusAndInaccessible) { _bCurrentSymIsBogus = true; } else { return false; } } // if we are done checking all the instance types ensure that currentsym is an // extension method and not a simple static method if (!_bIsCheckingInstanceMethods) { if (!_pCurrentSym.AsMethodSymbol().IsExtension()) { return false; } } return true; } private bool FindNextMethod() { while (true) { if (_pCurrentSym == null) { _pCurrentSym = GetSymbolLoader().LookupAggMember( _pName, _pCurrentType.getAggregate(), _mask).AsMethodOrPropertySymbol(); } else { _pCurrentSym = GetSymbolLoader().LookupNextSym( _pCurrentSym, _pCurrentType.getAggregate(), _mask).AsMethodOrPropertySymbol(); } // If we couldn't find a sym, we look up the type chain and get the next type. if (_pCurrentSym == null) { if (_bIsCheckingInstanceMethods) { if (!FindNextTypeForInstanceMethods() && _bcanIncludeExtensionsInResults) { // We didn't find any more instance methods, set us into extension mode. _bIsCheckingInstanceMethods = false; } else if (_pCurrentType == null && !_bcanIncludeExtensionsInResults) { return false; } else { // Found an instance method. continue; } } continue; } // Note that we do not filter the current symbol for the user. They must do that themselves. // This is because for instance, BindGrpToArgs wants to filter on arguments before filtering // on bogosity. // If we're here, we're good to go. break; } return true; } private bool FindNextTypeForInstanceMethods() { // Otherwise, search through other types listed as well as our base class. if (_pContainingTypes.size > 0) { if (_nCurrentTypeCount >= _pContainingTypes.size) { // No more types to check. _pCurrentType = null; } else { _pCurrentType = _pContainingTypes.Item(_nCurrentTypeCount++).AsAggregateType(); } } else { // We have no more types to consider, so check out the base class. _pCurrentType = _pCurrentType.GetBaseClass(); } return _pCurrentType != null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { /// <summary> /// Represents the Macro Service, which is an easy access to operations involving <see cref="IMacro"/> /// </summary> public class MacroService : ScopeRepositoryService, IMacroService { public MacroService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory) : base(provider, repositoryFactory, logger, eventMessagesFactory) { } /// <summary> /// Returns an enum <see cref="MacroTypes"/> based on the properties on the Macro /// </summary> /// <returns><see cref="MacroTypes"/></returns> internal static MacroTypes GetMacroType(IMacro macro) { if (string.IsNullOrEmpty(macro.XsltPath) == false) return MacroTypes.Xslt; if (string.IsNullOrEmpty(macro.ScriptPath) == false) { //we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is //a partial view macro, not a script macro //we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view. return (macro.ScriptPath.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/") || (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase))) ? MacroTypes.PartialView : MacroTypes.Script; } if (string.IsNullOrEmpty(macro.ControlType) == false && macro.ControlType.InvariantContains(".ascx")) return MacroTypes.UserControl; if (string.IsNullOrEmpty(macro.ControlType) == false && string.IsNullOrEmpty(macro.ControlAssembly) == false) return MacroTypes.CustomControl; return MacroTypes.Unknown; } /// <summary> /// Gets an <see cref="IMacro"/> object by its alias /// </summary> /// <param name="alias">Alias to retrieve an <see cref="IMacro"/> for</param> /// <returns>An <see cref="IMacro"/> object</returns> public IMacro GetByAlias(string alias) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroRepository(uow); var q = new Query<IMacro>(); q.Where(macro => macro.Alias == alias); return repository.GetByQuery(q).FirstOrDefault(); } } ///// <summary> ///// Gets a list all available <see cref="IMacro"/> objects ///// </summary> ///// <param name="aliases">Optional array of aliases to limit the results</param> ///// <returns>An enumerable list of <see cref="IMacro"/> objects</returns> //public IEnumerable<IMacro> GetAll(params string[] aliases) //{ // using (var repository = RepositoryFactory.CreateMacroRepository(UowProvider.GetReadOnlyUnitOfWork())) // { // if (aliases.Any()) // { // return GetAllByAliases(repository, aliases); // } // return repository.GetAll(); // } //} public IEnumerable<IMacro> GetAll() { return GetAll(new int[0]); } public IEnumerable<IMacro> GetAll(params int[] ids) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroRepository(uow); return repository.GetAll(ids); } } public IEnumerable<IMacro> GetAll(params Guid[] ids) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroRepository(uow); return repository.GetAll(ids); } } public IMacro GetById(int id) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroRepository(uow); return repository.Get(id); } } public IMacro GetById(Guid id) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroRepository(uow); return repository.Get(id); } } //private IEnumerable<IMacro> GetAllByAliases(IMacroRepository repo, IEnumerable<string> aliases) //{ // foreach (var alias in aliases) // { // var q = new Query<IMacro>(); // q.Where(macro => macro.Alias == alias); // yield return repo.GetByQuery(q).FirstOrDefault(); // } //} /// <summary> /// Deletes an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to delete</param> /// <param name="userId">Optional id of the user deleting the macro</param> public void Delete(IMacro macro, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var deleteEventArgs = new DeleteEventArgs<IMacro>(macro); if (uow.Events.DispatchCancelable(Deleting, this, deleteEventArgs)) { uow.Commit(); return; } var repository = RepositoryFactory.CreateMacroRepository(uow); repository.Delete(macro); deleteEventArgs.CanCancel = false; uow.Events.Dispatch(Deleted, this, deleteEventArgs); Audit(uow, AuditType.Delete, "Delete Macro performed by user", userId, -1); uow.Commit(); } } /// <summary> /// Saves an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to save</param> /// <param name="userId">Optional Id of the user deleting the macro</param> public void Save(IMacro macro, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs<IMacro>(macro); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return; } if (string.IsNullOrWhiteSpace(macro.Name)) { throw new ArgumentException("Cannot save macro with empty name."); } var repository = RepositoryFactory.CreateMacroRepository(uow); repository.AddOrUpdate(macro); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); Audit(uow, AuditType.Save, "Save Macro performed by user", userId, -1); uow.Commit(); } } ///// <summary> ///// Gets a list all available <see cref="IMacroPropertyType"/> plugins ///// </summary> ///// <returns>An enumerable list of <see cref="IMacroPropertyType"/> objects</returns> //public IEnumerable<IMacroPropertyType> GetMacroPropertyTypes() //{ // return MacroPropertyTypeResolver.Current.MacroPropertyTypes; //} ///// <summary> ///// Gets an <see cref="IMacroPropertyType"/> by its alias ///// </summary> ///// <param name="alias">Alias to retrieve an <see cref="IMacroPropertyType"/> for</param> ///// <returns>An <see cref="IMacroPropertyType"/> object</returns> //public IMacroPropertyType GetMacroPropertyTypeByAlias(string alias) //{ // return MacroPropertyTypeResolver.Current.MacroPropertyTypes.FirstOrDefault(x => x.Alias == alias); //} private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId) { var repository = RepositoryFactory.CreateAuditRepository(uow); repository.AddOrUpdate(new AuditItem(objectId, message, type, userId)); } #region Event Handlers /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IMacroService, DeleteEventArgs<IMacro>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IMacroService, DeleteEventArgs<IMacro>> Deleted; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IMacroService, SaveEventArgs<IMacro>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IMacroService, SaveEventArgs<IMacro>> Saved; #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using webfolio.Areas.HelpPage.ModelDescriptions; using webfolio.Areas.HelpPage.Models; namespace webfolio.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: DocumentPageView.cs // // Description: Provides a view port for a page of content for a DocumentPage. // //--------------------------------------------------------------------------- using System.Windows.Automation; // AutomationPattern using System.Windows.Automation.Peers; // AutomationPeer using System.Windows.Controls; // StretchDirection using System.Windows.Controls.Primitives; // DocumentViewerBase using System.Windows.Documents; // DocumentPaginator using System.Windows.Media; // Visual using System.Windows.Media.Imaging; // RenderTargetBitmap using System.Windows.Threading; // Dispatcher using MS.Internal; // Invariant using MS.Internal.Documents; // DocumentPageHost, DocumentPageTextView using MS.Internal.Automation; // TextAdaptor using MS.Internal.KnownBoxes; // BooleanBoxes namespace System.Windows.Controls.Primitives { /// <summary> /// Provides a view port for a page of content for a DocumentPage. /// </summary> public class DocumentPageView : FrameworkElement, IServiceProvider, IDisposable { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Create an instance of a DocumentPageView. /// </summary> /// <remarks> /// This does basic initialization of the DocumentPageView. All subclasses /// must call the base constructor to perform this initialization. /// </remarks> public DocumentPageView() : base() { _pageZoom = 1.0; } /// <summary> /// Static ctor. Initializes property metadata. /// </summary> static DocumentPageView() { ClipToBoundsProperty.OverrideMetadata(typeof(DocumentPageView), new PropertyMetadata(BooleanBoxes.TrueBox)); } #endregion //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// The Paginator from which this DocumentPageView retrieves pages. /// </summary> public DocumentPaginator DocumentPaginator { get { return _documentPaginator; } set { CheckDisposed(); if (_documentPaginator != value) { // Cleanup all state associated with old Paginator. if (_documentPaginator != null) { _documentPaginator.GetPageCompleted -= new GetPageCompletedEventHandler(HandleGetPageCompleted); _documentPaginator.PagesChanged -= new PagesChangedEventHandler(HandlePagesChanged); DisposeCurrentPage(); DisposeAsyncPage(); } Invariant.Assert(_documentPage == null); Invariant.Assert(_documentPageAsync == null); _documentPaginator = value; _textView = null; // Register for events on new Paginator and invalidate // measure to force content update. if (_documentPaginator != null) { _documentPaginator.GetPageCompleted += new GetPageCompletedEventHandler(HandleGetPageCompleted); _documentPaginator.PagesChanged += new PagesChangedEventHandler(HandlePagesChanged); } InvalidateMeasure(); } } } /// <summary> /// The DocumentPage for the displayed page. /// </summary> public DocumentPage DocumentPage { get { return (_documentPage == null) ? DocumentPage.Missing : _documentPage; } } /// <summary> /// The page number displayed; no content is displayed if this number is negative. /// PageNumber is zero-based. /// </summary> public int PageNumber { get { return (int) GetValue(PageNumberProperty); } set { SetValue(PageNumberProperty, value); } } /// <summary> /// Controls the stretching behavior for the page. /// </summary> public Stretch Stretch { get { return (Stretch)GetValue(StretchProperty); } set { SetValue(StretchProperty, value); } } /// <summary> /// Specifies the directions in which page may be stretched. /// </summary> public StretchDirection StretchDirection { get { return (StretchDirection)GetValue(StretchDirectionProperty); } set { SetValue(StretchDirectionProperty, value); } } #region Public Dynamic Properties /// <summary> /// <see cref="PageNumber"/> /// </summary> public static readonly DependencyProperty PageNumberProperty = DependencyProperty.Register( "PageNumber", typeof(int), typeof(DocumentPageView), new FrameworkPropertyMetadata( 0, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnPageNumberChanged))); /// <summary> /// <see cref="Stretch" /> /// </summary> public static readonly DependencyProperty StretchProperty = Viewbox.StretchProperty.AddOwner( typeof(DocumentPageView), new FrameworkPropertyMetadata( Stretch.Uniform, FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// <see cref="StretchDirection" /> /// </summary> public static readonly DependencyProperty StretchDirectionProperty = Viewbox.StretchDirectionProperty.AddOwner( typeof(DocumentPageView), new FrameworkPropertyMetadata( StretchDirection.DownOnly, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion Public Dynamic Properties #endregion Public Properties //------------------------------------------------------------------- // // Public Events // //------------------------------------------------------------------- #region Public Events /// <summary> /// Fired after a DocumentPage.Visual is connected. /// </summary> public event EventHandler PageConnected; /// <summary> /// Fired after a DocumentPage.Visual is disconnected. /// </summary> public event EventHandler PageDisconnected; #endregion Public Events //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods /// <summary> /// Content measurement. /// </summary> /// <param name="availableSize">Available size that parent can give to the child. This is soft constraint.</param> /// <returns>The DocumentPageView's desired size.</returns> protected override sealed Size MeasureOverride(Size availableSize) { Size newPageSize, pageZoom; Size pageSize; Size desiredSize = new Size(); // If no page is available, return (0,0) as size. CheckDisposed(); if (_suspendLayout) { desiredSize = this.DesiredSize; } else if (_documentPaginator != null) { // Reflow content if needed. if (ShouldReflowContent()) { // Reflow is disabled when dealing with infinite size in both directions. // If only one dimention is infinte, calculate value based on PageSize of the // document and Stretching properties. if (!Double.IsInfinity(availableSize.Width) || !Double.IsInfinity(availableSize.Height)) { pageSize = _documentPaginator.PageSize; if (Double.IsInfinity(availableSize.Width)) { newPageSize = new Size(); newPageSize.Height = availableSize.Height / _pageZoom; newPageSize.Width = newPageSize.Height * (pageSize.Width / pageSize.Height); // Keep aspect ratio. } else if (Double.IsInfinity(availableSize.Height)) { newPageSize = new Size(); newPageSize.Width = availableSize.Width / _pageZoom; newPageSize.Height = newPageSize.Width * (pageSize.Height / pageSize.Width); // Keep aspect ratio. } else { newPageSize = new Size(availableSize.Width / _pageZoom, availableSize.Height / _pageZoom); } if (!DoubleUtil.AreClose(pageSize, newPageSize)) { _documentPaginator.PageSize = newPageSize; } } } // If the main page or pending async page are not available yet, // asynchronously request new page from Paginator. if (_documentPage == null && _documentPageAsync == null) { if (PageNumber >= 0) { if (_useAsynchronous) { _documentPaginator.GetPageAsync(PageNumber, this); } else { _documentPageAsync = _documentPaginator.GetPage(PageNumber); if (_documentPageAsync == null) { _documentPageAsync = DocumentPage.Missing; } } } else { _documentPage = DocumentPage.Missing; } } // If pending async page is available, discard the main page and // set _documentPage to _documentPageAsync. if (_documentPageAsync != null) { // Do cleanup for currently used page, because it gets replaced. DisposeCurrentPage(); // DisposeCurrentPage raises PageDisposed and DocumentPage.PageDestroyed events. // Handlers for those events may dispose _documentPageAsync. Treat this situation // as missing page. if (_documentPageAsync == null) { _documentPageAsync = DocumentPage.Missing; } if (_pageVisualClone != null) { RemoveDuplicateVisual(); } // Replace the main page with cached async page. _documentPage = _documentPageAsync; if (_documentPage != DocumentPage.Missing) { _documentPage.PageDestroyed += new EventHandler(HandlePageDestroyed); _documentPageAsync.PageDestroyed -= new EventHandler(HandleAsyncPageDestroyed); } _documentPageAsync = null; // Set a flag that will indicate that a PageConnected must be fired in // ArrangeOverride _newPageConnected = true; } // If page is available, return its size as desired size. if (_documentPage != null && _documentPage != DocumentPage.Missing) { pageSize = new Size(_documentPage.Size.Width * _pageZoom, _documentPage.Size.Height * _pageZoom); pageZoom = Viewbox.ComputeScaleFactor(availableSize, pageSize, this.Stretch, this.StretchDirection); desiredSize = new Size(pageSize.Width * pageZoom.Width, pageSize.Height * pageZoom.Height); } if (_pageVisualClone != null) { desiredSize = _visualCloneSize; } } return desiredSize; } /// <summary> /// Content arrangement. /// </summary> /// <param name="finalSize">The final size that element should use to arrange itself and its children.</param> protected override sealed Size ArrangeOverride(Size finalSize) { Transform pageTransform; ScaleTransform pageScaleTransform; Visual pageVisual; Size pageSize, pageZoom; CheckDisposed(); if (_pageVisualClone == null) { if (_pageHost == null) { _pageHost = new DocumentPageHost(); this.AddVisualChild(_pageHost); } Invariant.Assert(_pageHost != null); pageVisual = (_documentPage == null) ? null : _documentPage.Visual; if (pageVisual == null) { // Remove existing visiual children. _pageHost.PageVisual = null; // Reset offset and transform on the page host before Arrange _pageHost.CachedOffset = new Point(); _pageHost.RenderTransform = null; // Size for the page host needs to be set to finalSize _pageHost.Arrange(new Rect(_pageHost.CachedOffset, finalSize)); } else { // Add visual representing the page contents. For performance reasons // first check if it is already insered there. if (_pageHost.PageVisual != pageVisual) { // There might be a case where a visual associated with a page was // inserted to a visual tree before. It got removed later, but GC did not // destroy its parent yet. To workaround this case always check for the parent // of page visual and disconnect it, when necessary. DocumentPageHost.DisconnectPageVisual(pageVisual); _pageHost.PageVisual = pageVisual; } // Compute transform to be applied to the page visual. First take into account // mirroring transform, if necessary. Apply also scaling transform. pageSize = _documentPage.Size; pageTransform = Transform.Identity; // DocumentPage.Visual is always LeftToRight, so if the current // FlowDirection is RightToLeft, need to unmirror the child visual. if (FlowDirection == FlowDirection.RightToLeft) { pageTransform = new MatrixTransform(-1.0, 0.0, 0.0, 1.0, pageSize.Width, 0.0); } // Apply zooming if (!DoubleUtil.IsOne(_pageZoom)) { pageScaleTransform = new ScaleTransform(_pageZoom, _pageZoom); if (pageTransform == Transform.Identity) { pageTransform = pageScaleTransform; } else { pageTransform = new MatrixTransform(pageTransform.Value * pageScaleTransform.Value); } pageSize = new Size(pageSize.Width * _pageZoom, pageSize.Height * _pageZoom); } // Apply stretch properties pageZoom = Viewbox.ComputeScaleFactor(finalSize, pageSize, this.Stretch, this.StretchDirection); if (!DoubleUtil.IsOne(pageZoom.Width) || !DoubleUtil.IsOne(pageZoom.Height)) { pageScaleTransform = new ScaleTransform(pageZoom.Width, pageZoom.Height); if (pageTransform == Transform.Identity) { pageTransform = pageScaleTransform; } else { pageTransform = new MatrixTransform(pageTransform.Value * pageScaleTransform.Value); } pageSize = new Size(pageSize.Width * pageZoom.Width, pageSize.Height * pageZoom.Height); } // Set offset and transform on the page host before Arrange _pageHost.CachedOffset = new Point((finalSize.Width - pageSize.Width) / 2, (finalSize.Height - pageSize.Height) / 2); _pageHost.RenderTransform = pageTransform; // Arrange pagehost to original size of the page. _pageHost.Arrange(new Rect(_pageHost.CachedOffset, _documentPage.Size)); } // Fire [....] notification if new page was connected. if (_newPageConnected) { OnPageConnected(); } // Transform for the page has been changed, need to notify TextView about the changes. OnTransformChangedAsync(); } else { if (_pageHost.PageVisual != _pageVisualClone) { // Remove existing visiual children. _pageHost.PageVisual = _pageVisualClone; // Size for the page host needs to be set to finalSize // Use previous offset and transform _pageHost.Arrange(new Rect(_pageHost.CachedOffset, finalSize)); } } return base.ArrangeOverride(finalSize); } /// <summary> /// Derived class must implement to support Visual children. The method must return /// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1. /// </summary> protected override Visual GetVisualChild(int index) { if (index != 0 || _pageHost == null) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } return _pageHost; } /// <summary> /// Dispose the object. /// </summary> protected void Dispose() { if (!_disposed) { _disposed = true; // Cleanup all state associated with Paginator. if (_documentPaginator != null) { _documentPaginator.GetPageCompleted -= new GetPageCompletedEventHandler(HandleGetPageCompleted); _documentPaginator.PagesChanged -= new PagesChangedEventHandler(HandlePagesChanged); _documentPaginator.CancelAsync(this); DisposeCurrentPage(); DisposeAsyncPage(); } Invariant.Assert(_documentPage == null); Invariant.Assert(_documentPageAsync == null); _documentPaginator = null; _textView = null; } } /// <summary> /// Returns service objects associated with this control. /// This method should be called by IServiceProvider.GetService implementation /// for DocumentPageView or subclasses. /// </summary> /// <param name="serviceType">Specifies the type of service object to get.</param> protected object GetService(Type serviceType) { object service = null; if (serviceType == null) { throw new ArgumentNullException("serviceType"); } CheckDisposed(); // No service is available if the Content does not provide // any services. if (_documentPaginator != null && _documentPaginator is IServiceProvider) { // Following services are available: // (1) TextView - wrapper for TextView exposed by the current page. // (2) TextContainer - the service object is retrieved from DocumentPaginator. if (serviceType == typeof(ITextView)) { if (_textView == null) { ITextContainer tc = ((IServiceProvider)_documentPaginator).GetService(typeof(ITextContainer)) as ITextContainer; if (tc != null) { _textView = new DocumentPageTextView(this, tc); } } service = _textView; } else if (serviceType == typeof(TextContainer) || serviceType == typeof(ITextContainer)) { service = ((IServiceProvider)_documentPaginator).GetService(serviceType); } } return service; } /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new DocumentPageViewAutomationPeer(this); } #endregion Protected Methods //------------------------------------------------------------------- // // Protected Properties // //------------------------------------------------------------------- #region Protected Properties /// <summary> /// Whether this DocumentPageView has been disposed. /// </summary> protected bool IsDisposed { get { return _disposed; } } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// </summary> protected override int VisualChildrenCount { get { return _pageHost != null ? 1 : 0; } } #endregion Protected Properties //------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// Sets the zoom applied to the page being displayed. /// </summary> /// <param name="pageZoom">Page zooom value.</param> internal void SetPageZoom(double pageZoom) { Invariant.Assert(!DoubleUtil.LessThanOrClose(pageZoom, 0d) && !Double.IsInfinity(pageZoom)); Invariant.Assert(!_disposed); if (!DoubleUtil.AreClose(_pageZoom, pageZoom)) { _pageZoom = pageZoom; InvalidateMeasure(); } } /// <summary> /// Suspends page layout. /// </summary> internal void SuspendLayout() { _suspendLayout = true; _pageVisualClone = DuplicatePageVisual(); _visualCloneSize = this.DesiredSize; } /// <summary> /// Resumes page layout. /// </summary> internal void ResumeLayout() { _suspendLayout = false; _pageVisualClone = null; InvalidateMeasure(); } /// <summary> /// Duplicates the current page visual, if possible /// </summary> internal void DuplicateVisual() { if (_documentPage != null && _pageVisualClone == null) { _pageVisualClone = DuplicatePageVisual(); _visualCloneSize = this.DesiredSize; InvalidateArrange(); } } /// <summary> /// Clears the duplicated page visual, if one exists. /// </summary> internal void RemoveDuplicateVisual() { if (_pageVisualClone != null) { _pageVisualClone = null; InvalidateArrange(); } } #endregion Internal Methods //------------------------------------------------------------------- // // Internal Properties // //------------------------------------------------------------------- #region Internal Properties /// <summary> /// Default is true. Controls whether we use asynchronous mode to /// request the DocumentPage. In some cases, such as synchronous /// printing, we don't want to wait for the asynchronous events. /// </summary> internal bool UseAsynchronousGetPage { get { return _useAsynchronous; } set { _useAsynchronous = value; } } /// <summary> /// The DocumentPage for the displayed page. /// </summary> internal DocumentPage DocumentPageInternal { get { return _documentPage; } } #endregion Internal Properties //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods /// <summary> /// Handles PageDestroyed event raised for the current DocumentPage. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Not used.</param> private void HandlePageDestroyed(object sender, EventArgs e) { if (!_disposed) { InvalidateMeasure(); DisposeCurrentPage(); } } /// <summary> /// Handles PageDestroyed event raised for the cached async DocumentPage. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Not used.</param> private void HandleAsyncPageDestroyed(object sender, EventArgs e) { if (!_disposed) { DisposeAsyncPage(); } } /// <summary> /// Handles GetPageCompleted event raised by the DocumentPaginator. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Details about this event.</param> private void HandleGetPageCompleted(object sender, GetPageCompletedEventArgs e) { if (!_disposed && (e != null) && !e.Cancelled && e.Error == null) { if (e.PageNumber == this.PageNumber && e.UserState == this) { if (_documentPageAsync != null && _documentPageAsync != DocumentPage.Missing) { _documentPageAsync.PageDestroyed -= new EventHandler(HandleAsyncPageDestroyed); } _documentPageAsync = e.DocumentPage; if (_documentPageAsync == null) { _documentPageAsync = DocumentPage.Missing; } if (_documentPageAsync != DocumentPage.Missing) { _documentPageAsync.PageDestroyed += new EventHandler(HandleAsyncPageDestroyed); } InvalidateMeasure(); } // else; the page is not ours } } /// <summary> /// Handles PagesChanged event raised by the DocumentPaginator. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Details about this event.</param> private void HandlePagesChanged(object sender, PagesChangedEventArgs e) { if (!_disposed && (e != null)) { if (this.PageNumber >= e.Start && (e.Count == int.MaxValue || this.PageNumber <= e.Start + e.Count)) { OnPageContentChanged(); } } } /// <summary> /// Async notification about transform changes for embedded page. /// </summary> private void OnTransformChangedAsync() { Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(OnTransformChanged), null); } /// <summary> /// Notification about transform changes for embedded page. /// </summary> /// <param name="arg">Not used.</param> /// <returns>Not used.</returns> private object OnTransformChanged(object arg) { if (_textView != null && _documentPage != null) { _textView.OnTransformChanged(); } return null; } /// <summary> /// Raises PageConnected event. /// </summary> private void OnPageConnected() { _newPageConnected = false; if (_textView != null) { _textView.OnPageConnected(); } if (this.PageConnected != null && _documentPage != null) { this.PageConnected(this, EventArgs.Empty); } } /// <summary> /// Raises PageDisconnected event. /// </summary> private void OnPageDisconnected() { if (_textView != null) { _textView.OnPageDisconnected(); } if (this.PageDisconnected != null) { this.PageDisconnected(this, EventArgs.Empty); } } /// <summary> /// Responds to page content change. /// </summary> private void OnPageContentChanged() { // Force remeasure which will cause to reget DocumentPage InvalidateMeasure(); // Do cleanup for currently used page, because it gets replaced. DisposeCurrentPage(); DisposeAsyncPage(); } /// <summary> /// Disposes the current DocumentPage. /// </summary> private void DisposeCurrentPage() { // Do cleanup for currently used page, because it gets replaced. if (_documentPage != null) { // Remove visual for currently used page. if (_pageHost != null) { _pageHost.PageVisual = null; } // Clear TextView & DocumentPage if (_documentPage != DocumentPage.Missing) { _documentPage.PageDestroyed -= new EventHandler(HandlePageDestroyed); } if (_documentPage is IDisposable) { ((IDisposable)_documentPage).Dispose(); } _documentPage = null; OnPageDisconnected(); } } /// <summary> /// Disposes pending async DocumentPage. /// </summary> private void DisposeAsyncPage() { // Do cleanup for cached async page. if (_documentPageAsync != null) { if (_documentPageAsync != DocumentPage.Missing) { _documentPageAsync.PageDestroyed -= new EventHandler(HandleAsyncPageDestroyed); } if (_documentPageAsync is IDisposable) { ((IDisposable)_documentPageAsync).Dispose(); } _documentPageAsync = null; } } /// <summary> /// Checks if the instance is already disposed. /// </summary> private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(typeof(DocumentPageView).ToString()); } } /// <summary> /// Check whether content needs to be reflowed. /// </summary> /// <returns>True, if content needs to be reflowed.</returns> private bool ShouldReflowContent() { bool shouldReflow = false; DocumentViewerBase hostViewer; if (DocumentViewerBase.GetIsMasterPage(this)) { hostViewer = GetHostViewer(); if (hostViewer != null) { shouldReflow = hostViewer.IsMasterPageView(this); } } return shouldReflow; } /// <summary> /// Retrieves DocumentViewerBase that hosts this view. /// </summary> /// <returns>DocumentViewerBase that hosts this view.</returns> private DocumentViewerBase GetHostViewer() { DocumentViewerBase hostViewer = null; Visual visualParent; // First do quick check for TemplatedParent. It will cover good // amount of cases, because static viewers will have their // DocumentPageViews defined in the style. // If quick check does not work, do a visual tree walk. if (this.TemplatedParent is DocumentViewerBase) { hostViewer = (DocumentViewerBase)this.TemplatedParent; } else { // Check if hosted by DocumentViewerBase. visualParent = VisualTreeHelper.GetParent(this) as Visual; while (visualParent != null) { if (visualParent is DocumentViewerBase) { hostViewer = (DocumentViewerBase)visualParent; break; } visualParent = VisualTreeHelper.GetParent(visualParent) as Visual; } } return hostViewer; } /// <summary> /// The PageNumber has changed and needs to be updated. /// </summary> private static void OnPageNumberChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Invariant.Assert(d != null && d is DocumentPageView); ((DocumentPageView)d).OnPageContentChanged(); } /// <summary> /// Duplicates content of the PageVisual. /// </summary> private DrawingVisual DuplicatePageVisual() { DrawingVisual drawingVisual = null; if (_pageHost != null && _pageHost.PageVisual != null && _documentPage.Size != Size.Empty) { const double maxWidth = 4096.0; const double maxHeight = maxWidth; Rect pageVisualRect = new Rect(_documentPage.Size); pageVisualRect.Width = Math.Min(pageVisualRect.Width, maxWidth); pageVisualRect.Height = Math.Min(pageVisualRect.Height, maxHeight); drawingVisual = new DrawingVisual(); try { if(pageVisualRect.Width > 1.0 && pageVisualRect.Height > 1.0) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)pageVisualRect.Width, (int)pageVisualRect.Height, 96.0, 96.0, PixelFormats.Pbgra32); renderTargetBitmap.Render(_pageHost.PageVisual); ImageBrush imageBrush = new ImageBrush(renderTargetBitmap); drawingVisual.Opacity = 0.50; using (DrawingContext dc = drawingVisual.RenderOpen()) { dc.DrawRectangle(imageBrush, null, pageVisualRect); } } } catch(System.OverflowException) { // Ignore overflow exception - caused by render target creation not possible under current memory conditions. } } return drawingVisual; } #endregion Private Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields private DocumentPaginator _documentPaginator; private double _pageZoom; private DocumentPage _documentPage; private DocumentPage _documentPageAsync; private DocumentPageTextView _textView; private DocumentPageHost _pageHost; private Visual _pageVisualClone; private Size _visualCloneSize; private bool _useAsynchronous = true; private bool _suspendLayout; private bool _disposed; private bool _newPageConnected; #endregion Private Fields //------------------------------------------------------------------- // // IServiceProvider Members // //------------------------------------------------------------------- #region IServiceProvider Members /// <summary> /// Returns service objects associated with this control. /// </summary> /// <param name="serviceType">Specifies the type of service object to get.</param> object IServiceProvider.GetService(Type serviceType) { return this.GetService(serviceType); } #endregion IServiceProvider Members //------------------------------------------------------------------- // // IDisposable Members // //------------------------------------------------------------------- #region IDisposable Members /// <summary> /// Dispose the object. /// </summary> void IDisposable.Dispose() { this.Dispose(); } #endregion IDisposable Members } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { public static partial class ProtectionContainerOperationsExtensions { /// <summary> /// Discovers a protectable item. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='input'> /// Required. Discover Protectable Item Request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDiscoverProtectableItem(this IProtectionContainerOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerOperations)s).BeginDiscoverProtectableItemAsync(fabricName, protectionContainerName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Discovers a protectable item. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='input'> /// Required. Discover Protectable Item Request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDiscoverProtectableItemAsync(this IProtectionContainerOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest input, CustomRequestHeaders customRequestHeaders) { return operations.BeginDiscoverProtectableItemAsync(fabricName, protectionContainerName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Discovers a protectable item. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='input'> /// Required. Discover Protectable Item Request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse DiscoverProtectableItem(this IProtectionContainerOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerOperations)s).DiscoverProtectableItemAsync(fabricName, protectionContainerName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Discovers a protectable item. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='input'> /// Required. Discover Protectable Item Request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> DiscoverProtectableItemAsync(this IProtectionContainerOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest input, CustomRequestHeaders customRequestHeaders) { return operations.DiscoverProtectableItemAsync(fabricName, protectionContainerName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the protected container by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection Container Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Protection Container object. /// </returns> public static ProtectionContainerResponse Get(this IProtectionContainerOperations operations, string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerOperations)s).GetAsync(fabricName, protectionContainerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the protected container by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection Container Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Protection Container object. /// </returns> public static Task<ProtectionContainerResponse> GetAsync(this IProtectionContainerOperations operations, string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(fabricName, protectionContainerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetDiscoverProtectableItemStatus(this IProtectionContainerOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerOperations)s).GetDiscoverProtectableItemStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetDiscoverProtectableItemStatusAsync(this IProtectionContainerOperations operations, string operationStatusLink) { return operations.GetDiscoverProtectableItemStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Get the list of all ProtectionContainers for the given server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Unique name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list ProtectionContainers operation. /// </returns> public static ProtectionContainerListResponse List(this IProtectionContainerOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerOperations)s).ListAsync(fabricName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all ProtectionContainers for the given server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Unique name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list ProtectionContainers operation. /// </returns> public static Task<ProtectionContainerListResponse> ListAsync(this IProtectionContainerOperations operations, string fabricName, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(fabricName, customRequestHeaders, CancellationToken.None); } } }
/* ==================================================================== 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.Collections.Generic; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using System; using System.Text; using NPOI.SS.Util; namespace NPOI.XSSF.UserModel { /** * @author <a href="rjankiraman@emptoris.com">Radhakrishnan J</a> * */ public class XSSFDataValidation : IDataValidation { private CT_DataValidation ctDdataValidation; private XSSFDataValidationConstraint validationConstraint; private CellRangeAddressList regions; internal static Dictionary<int, ST_DataValidationOperator> operatorTypeMappings = new Dictionary<int, ST_DataValidationOperator>(); internal static Dictionary<ST_DataValidationOperator, int> operatorTypeReverseMappings = new Dictionary<ST_DataValidationOperator, int>(); internal static Dictionary<int, ST_DataValidationType> validationTypeMappings = new Dictionary<int, ST_DataValidationType>(); internal static Dictionary<ST_DataValidationType, int> validationTypeReverseMappings = new Dictionary<ST_DataValidationType, int>(); internal static Dictionary<int, ST_DataValidationErrorStyle> errorStyleMappings = new Dictionary<int, ST_DataValidationErrorStyle>(); static XSSFDataValidation() { errorStyleMappings[ERRORSTYLE.INFO]= ST_DataValidationErrorStyle.information; errorStyleMappings[ERRORSTYLE.STOP]= ST_DataValidationErrorStyle.stop; errorStyleMappings[ERRORSTYLE.WARNING]= ST_DataValidationErrorStyle.warning; operatorTypeMappings[OperatorType.BETWEEN] = ST_DataValidationOperator.between; operatorTypeMappings[OperatorType.NOT_BETWEEN] = ST_DataValidationOperator.notBetween; operatorTypeMappings[OperatorType.EQUAL] = ST_DataValidationOperator.equal; operatorTypeMappings[OperatorType.NOT_EQUAL] = ST_DataValidationOperator.notEqual; operatorTypeMappings[OperatorType.GREATER_THAN] = ST_DataValidationOperator.greaterThan; operatorTypeMappings[OperatorType.GREATER_OR_EQUAL] = ST_DataValidationOperator.greaterThanOrEqual; operatorTypeMappings[OperatorType.LESS_THAN] = ST_DataValidationOperator.lessThan; operatorTypeMappings[OperatorType.LESS_OR_EQUAL] = ST_DataValidationOperator.lessThanOrEqual; foreach (KeyValuePair<int, ST_DataValidationOperator> entry in operatorTypeMappings) { operatorTypeReverseMappings[entry.Value]=entry.Key; } validationTypeMappings[ValidationType.FORMULA] = ST_DataValidationType.custom; validationTypeMappings[ValidationType.DATE] = ST_DataValidationType.date; validationTypeMappings[ValidationType.DECIMAL] = ST_DataValidationType.@decimal; validationTypeMappings[ValidationType.LIST] = ST_DataValidationType.list; validationTypeMappings[ValidationType.ANY] = ST_DataValidationType.none; validationTypeMappings[ValidationType.TEXT_LENGTH] = ST_DataValidationType.textLength; validationTypeMappings[ValidationType.TIME] = ST_DataValidationType.time; validationTypeMappings[ValidationType.INTEGER] = ST_DataValidationType.whole; foreach (KeyValuePair<int, ST_DataValidationType> entry in validationTypeMappings) { validationTypeReverseMappings[entry.Value]= entry.Key; } } public XSSFDataValidation(CellRangeAddressList regions, CT_DataValidation ctDataValidation) : this(GetConstraint(ctDataValidation), regions, ctDataValidation) { } public XSSFDataValidation(XSSFDataValidationConstraint constraint, CellRangeAddressList regions, CT_DataValidation ctDataValidation) : base() { this.validationConstraint = constraint; this.ctDdataValidation = ctDataValidation; this.regions = regions; } internal CT_DataValidation GetCTDataValidation() { return ctDdataValidation; } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidation#CreateErrorBox(java.lang.String, java.lang.String) */ public void CreateErrorBox(String title, String text) { ctDdataValidation.errorTitle = (title); ctDdataValidation.error = (text); } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidation#CreatePromptBox(java.lang.String, java.lang.String) */ public void CreatePromptBox(String title, String text) { ctDdataValidation.promptTitle = (title); ctDdataValidation.prompt = (text); } public bool EmptyCellAllowed { get { return ctDdataValidation.allowBlank; } set { ctDdataValidation.allowBlank =value; } } public String ErrorBoxText { get { return ctDdataValidation.error; } } public String ErrorBoxTitle { get { return ctDdataValidation.errorTitle; } } public int ErrorStyle { get { return (int)ctDdataValidation.errorStyle; } set { ctDdataValidation.errorStyle = (errorStyleMappings[value]); } } public String PromptBoxText { get { return ctDdataValidation.prompt; } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidation#getPromptBoxTitle() */ public String PromptBoxTitle { get { return ctDdataValidation.promptTitle; } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidation#getShowErrorBox() */ public bool ShowErrorBox { get { return ctDdataValidation.showErrorMessage; } set { ctDdataValidation.showErrorMessage = value; } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidation#getShowPromptBox() */ public bool ShowPromptBox { get { return ctDdataValidation.showInputMessage; } set { ctDdataValidation.showInputMessage = value; } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidation#getSuppressDropDownArrow() */ public bool SuppressDropDownArrow { get { return !ctDdataValidation.showDropDown; } set { if (validationConstraint.GetValidationType() == ValidationType.LIST) { ctDdataValidation.showDropDown = (!value); } } } public IDataValidationConstraint ValidationConstraint { get { return validationConstraint; } } public CellRangeAddressList Regions { get { return regions; } } public String PrettyPrint() { StringBuilder builder = new StringBuilder(); foreach (CellRangeAddress Address in regions.CellRangeAddresses) { builder.Append(Address.FormatAsString()); } builder.Append(" => "); builder.Append(this.validationConstraint.PrettyPrint()); return builder.ToString(); } private static XSSFDataValidationConstraint GetConstraint(CT_DataValidation ctDataValidation) { XSSFDataValidationConstraint constraint = null; String formula1 = ctDataValidation.formula1; String formula2 = ctDataValidation.formula2; ST_DataValidationOperator operator1 = ctDataValidation.@operator; ST_DataValidationType type = ctDataValidation.type; int validationType = XSSFDataValidation.validationTypeReverseMappings[type]; int operatorType = XSSFDataValidation.operatorTypeReverseMappings[operator1]; constraint = new XSSFDataValidationConstraint(validationType, operatorType, formula1, formula2); return constraint; } } }
using System; using System.Collections; using Org.BouncyCastle.Asn1; namespace Org.BouncyCastle.Asn1.Cms { /** * a signed data object. */ public class SignedData : Asn1Encodable { private readonly DerInteger version; private readonly Asn1Set digestAlgorithms; private readonly ContentInfo contentInfo; private readonly Asn1Set certificates; private readonly Asn1Set crls; private readonly Asn1Set signerInfos; private readonly bool certsBer; private readonly bool crlsBer; public static SignedData GetInstance( object obj) { if (obj is SignedData) return (SignedData) obj; if (obj is Asn1Sequence) return new SignedData((Asn1Sequence) obj); throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); } public SignedData( Asn1Set digestAlgorithms, ContentInfo contentInfo, Asn1Set certificates, Asn1Set crls, Asn1Set signerInfos) { this.version = CalculateVersion(contentInfo.ContentType, certificates, crls, signerInfos); this.digestAlgorithms = digestAlgorithms; this.contentInfo = contentInfo; this.certificates = certificates; this.crls = crls; this.signerInfos = signerInfos; this.crlsBer = crls is BerSet; this.certsBer = certificates is BerSet; } // RFC3852, section 5.1: // IF ((certificates is present) AND // (any certificates with a type of other are present)) OR // ((crls is present) AND // (any crls with a type of other are present)) // THEN version MUST be 5 // ELSE // IF (certificates is present) AND // (any version 2 attribute certificates are present) // THEN version MUST be 4 // ELSE // IF ((certificates is present) AND // (any version 1 attribute certificates are present)) OR // (any SignerInfo structures are version 3) OR // (encapContentInfo eContentType is other than id-data) // THEN version MUST be 3 // ELSE version MUST be 1 // private DerInteger CalculateVersion( DerObjectIdentifier contentOid, Asn1Set certs, Asn1Set crls, Asn1Set signerInfs) { bool otherCert = false; bool otherCrl = false; bool attrCertV1Found = false; bool attrCertV2Found = false; if (certs != null) { foreach (object obj in certs) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)obj; if (tagged.TagNo == 1) { attrCertV1Found = true; } else if (tagged.TagNo == 2) { attrCertV2Found = true; } else if (tagged.TagNo == 3) { otherCert = true; break; } } } } if (otherCert) { return new DerInteger(5); } if (crls != null) { foreach (object obj in crls) { if (obj is Asn1TaggedObject) { otherCrl = true; break; } } } if (otherCrl) { return new DerInteger(5); } if (attrCertV2Found) { return new DerInteger(4); } if (attrCertV1Found || !CmsObjectIdentifiers.Data.Equals(contentOid) || CheckForVersion3(signerInfs)) { return new DerInteger(3); } return new DerInteger(1); } private bool CheckForVersion3( Asn1Set signerInfs) { foreach (object obj in signerInfs) { SignerInfo s = SignerInfo.GetInstance(obj); if (s.Version.Value.IntValue == 3) { return true; } } return false; } private SignedData( Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); e.MoveNext(); version = (DerInteger)e.Current; e.MoveNext(); digestAlgorithms = ((Asn1Set)e.Current); e.MoveNext(); contentInfo = ContentInfo.GetInstance(e.Current); while (e.MoveNext()) { Asn1Object o = (Asn1Object)e.Current; // // an interesting feature of SignedData is that there appear // to be varying implementations... // for the moment we ignore anything which doesn't fit. // if (o is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)o; switch (tagged.TagNo) { case 0: certsBer = tagged is BerTaggedObject; certificates = Asn1Set.GetInstance(tagged, false); break; case 1: crlsBer = tagged is BerTaggedObject; crls = Asn1Set.GetInstance(tagged, false); break; default: throw new ArgumentException("unknown tag value " + tagged.TagNo); } } else { signerInfos = (Asn1Set) o; } } } public DerInteger Version { get { return version; } } public Asn1Set DigestAlgorithms { get { return digestAlgorithms; } } public ContentInfo EncapContentInfo { get { return contentInfo; } } public Asn1Set Certificates { get { return certificates; } } public Asn1Set CRLs { get { return crls; } } public Asn1Set SignerInfos { get { return signerInfos; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * SignedData ::= Sequence { * version CMSVersion, * digestAlgorithms DigestAlgorithmIdentifiers, * encapContentInfo EncapsulatedContentInfo, * certificates [0] IMPLICIT CertificateSet OPTIONAL, * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, * signerInfos SignerInfos * } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector( version, digestAlgorithms, contentInfo); if (certificates != null) { if (certsBer) { v.Add(new BerTaggedObject(false, 0, certificates)); } else { v.Add(new DerTaggedObject(false, 0, certificates)); } } if (crls != null) { if (crlsBer) { v.Add(new BerTaggedObject(false, 1, crls)); } else { v.Add(new DerTaggedObject(false, 1, crls)); } } v.Add(signerInfos); return new BerSequence(v); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text; using System.Threading; using System.Xml; namespace System.Security.Cryptography.Xml { internal class Utils { // The maximum number of characters in an XML document (0 means no limit). internal const int MaxCharactersInDocument = 0; // The entity expansion limit. This is used to prevent entity expansion denial of service attacks. internal const long MaxCharactersFromEntities = (long)1e7; // The default XML Dsig recursion limit. // This should be within limits of real world scenarios. // Keeping this number low will preserve some stack space internal const int XmlDsigSearchDepth = 20; private Utils() { } private static bool HasNamespace(XmlElement element, string prefix, string value) { if (IsCommittedNamespace(element, prefix, value)) return true; if (element.Prefix == prefix && element.NamespaceURI == value) return true; return false; } // A helper function that determines if a namespace node is a committed attribute internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value) { if (element == null) throw new ArgumentNullException(nameof(element)); string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns"); if (element.HasAttribute(name) && element.GetAttribute(name) == value) return true; return false; } internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value) { if (element == null) throw new ArgumentNullException(nameof(element)); XmlNode ancestorNode = ((XmlNode)element).ParentNode; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement != null) if (HasNamespace(ancestorElement, prefix, value)) return true; ancestorNode = ancestorNode.ParentNode; } return false; } internal static string GetAttribute(XmlElement element, string localName, string namespaceURI) { string s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null); if (s == null && element.HasAttribute(localName, namespaceURI)) s = element.GetAttribute(localName, namespaceURI); return s; } internal static bool HasAttribute(XmlElement element, string localName, string namespaceURI) { return element.HasAttribute(localName) || element.HasAttribute(localName, namespaceURI); } internal static bool IsNamespaceNode(XmlNode n) { return n.NodeType == XmlNodeType.Attribute && (n.Prefix.Equals("xmlns") || (n.Prefix.Length == 0 && n.LocalName.Equals("xmlns"))); } internal static bool IsXmlNamespaceNode(XmlNode n) { return n.NodeType == XmlNodeType.Attribute && n.Prefix.Equals("xml"); } // We consider xml:space style attributes as default namespace nodes since they obey the same propagation rules internal static bool IsDefaultNamespaceNode(XmlNode n) { bool b1 = n.NodeType == XmlNodeType.Attribute && n.Prefix.Length == 0 && n.LocalName.Equals("xmlns"); bool b2 = IsXmlNamespaceNode(n); return b1 || b2; } internal static bool IsEmptyDefaultNamespaceNode(XmlNode n) { return IsDefaultNamespaceNode(n) && n.Value.Length == 0; } internal static string GetNamespacePrefix(XmlAttribute a) { Debug.Assert(IsNamespaceNode(a) || IsXmlNamespaceNode(a)); return a.Prefix.Length == 0 ? string.Empty : a.LocalName; } internal static bool HasNamespacePrefix(XmlAttribute a, string nsPrefix) { return GetNamespacePrefix(a).Equals(nsPrefix); } internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute nearestAncestorWithSamePrefix) { if (nearestAncestorWithSamePrefix == null) return !IsEmptyDefaultNamespaceNode(a); else return !nearestAncestorWithSamePrefix.Value.Equals(a.Value); } internal static bool IsXmlPrefixDefinitionNode(XmlAttribute a) { return false; // return a.Prefix.Equals("xmlns") && a.LocalName.Equals("xml") && a.Value.Equals(NamespaceUrlForXmlPrefix); } internal static string DiscardWhiteSpaces(string inputBuffer) { return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length); } internal static string DiscardWhiteSpaces(string inputBuffer, int inputOffset, int inputCount) { int i, iCount = 0; for (i = 0; i < inputCount; i++) if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++; char[] rgbOut = new char[inputCount - iCount]; iCount = 0; for (i = 0; i < inputCount; i++) if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i])) { rgbOut[iCount++] = inputBuffer[inputOffset + i]; } return new string(rgbOut); } internal static void SBReplaceCharWithString(StringBuilder sb, char oldChar, string newString) { int i = 0; int newStringLength = newString.Length; while (i < sb.Length) { if (sb[i] == oldChar) { sb.Remove(i, 1); sb.Insert(i, newString); i += newStringLength; } else i++; } } internal static XmlReader PreProcessStreamInput(Stream inputStream, XmlResolver xmlResolver, string baseUri) { XmlReaderSettings settings = GetSecureXmlReaderSettings(xmlResolver); XmlReader reader = XmlReader.Create(inputStream, settings, baseUri); return reader; } internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlResolver) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; settings.DtdProcessing = DtdProcessing.Parse; settings.MaxCharactersFromEntities = MaxCharactersFromEntities; settings.MaxCharactersInDocument = MaxCharactersInDocument; return settings; } internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri) { if (document == null) throw new ArgumentNullException(nameof(document)); MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = document.PreserveWhitespace; // Normalize the document using (TextReader stringReader = new StringReader(document.OuterXml)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; settings.DtdProcessing = DtdProcessing.Parse; settings.MaxCharactersFromEntities = MaxCharactersFromEntities; settings.MaxCharactersInDocument = MaxCharactersInDocument; XmlReader reader = XmlReader.Create(stringReader, settings, baseUri); doc.Load(reader); } return doc; } internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri) { if (elem == null) throw new ArgumentNullException(nameof(elem)); MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = true; // Normalize the document using (TextReader stringReader = new StringReader(elem.OuterXml)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; settings.DtdProcessing = DtdProcessing.Parse; settings.MaxCharactersFromEntities = MaxCharactersFromEntities; settings.MaxCharactersInDocument = MaxCharactersInDocument; XmlReader reader = XmlReader.Create(stringReader, settings, baseUri); doc.Load(reader); } return doc; } internal static XmlDocument DiscardComments(XmlDocument document) { XmlNodeList nodeList = document.SelectNodes("//comment()"); if (nodeList != null) { foreach (XmlNode node1 in nodeList) { node1.ParentNode.RemoveChild(node1); } } return document; } internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments) { CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); CanonicalXmlNodeList elementList = new CanonicalXmlNodeList(); CanonicalXmlNodeList attribList = new CanonicalXmlNodeList(); CanonicalXmlNodeList namespaceList = new CanonicalXmlNodeList(); int index = 0; elementList.Add(node); do { XmlNode rootNode = (XmlNode)elementList[index]; // Add the children nodes XmlNodeList childNodes = rootNode.ChildNodes; if (childNodes != null) { foreach (XmlNode node1 in childNodes) { if (includeComments || (!(node1 is XmlComment))) { elementList.Add(node1); } } } // Add the attribute nodes XmlAttributeCollection attribNodes = rootNode.Attributes; if (attribNodes != null) { foreach (XmlNode attribNode in rootNode.Attributes) { if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns") namespaceList.Add(attribNode); else attribList.Add(attribNode); } } index++; } while (index < elementList.Count); foreach (XmlNode elementNode in elementList) { nodeList.Add(elementNode); } foreach (XmlNode attribNode in attribList) { nodeList.Add(attribNode); } foreach (XmlNode namespaceNode in namespaceList) { nodeList.Add(namespaceNode); } return nodeList; } internal static bool NodeInList(XmlNode node, XmlNodeList nodeList) { foreach (XmlNode nodeElem in nodeList) { if (nodeElem == node) return true; } return false; } internal static string GetIdFromLocalUri(string uri, out bool discardComments) { string idref = uri.Substring(1); // initialize the return value discardComments = true; // Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) { int startId = idref.IndexOf("id(", StringComparison.Ordinal); int endId = idref.IndexOf(")", StringComparison.Ordinal); if (endId < 0 || endId < startId + 3) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); idref = idref.Substring(startId + 3, endId - startId - 3); idref = idref.Replace("\'", ""); idref = idref.Replace("\"", ""); discardComments = false; } return idref; } internal static string ExtractIdFromLocalUri(string uri) { string idref = uri.Substring(1); // Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) { int startId = idref.IndexOf("id(", StringComparison.Ordinal); int endId = idref.IndexOf(")", StringComparison.Ordinal); if (endId < 0 || endId < startId + 3) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); idref = idref.Substring(startId + 3, endId - startId - 3); idref = idref.Replace("\'", ""); idref = idref.Replace("\"", ""); } return idref; } // This removes all children of an element. internal static void RemoveAllChildren(XmlElement inputElement) { XmlNode child = inputElement.FirstChild; XmlNode sibling = null; while (child != null) { sibling = child.NextSibling; inputElement.RemoveChild(child); child = sibling; } } // Writes one stream (starting from the current position) into // an output stream, connecting them up and reading until // hitting the end of the input stream. // returns the number of bytes copied internal static long Pump(Stream input, Stream output) { // Use MemoryStream's WriteTo(Stream) method if possible MemoryStream inputMS = input as MemoryStream; if (inputMS != null && inputMS.Position == 0) { inputMS.WriteTo(output); return inputMS.Length; } const int count = 4096; byte[] bytes = new byte[count]; int numBytes; long totalBytes = 0; while ((numBytes = input.Read(bytes, 0, count)) > 0) { output.Write(bytes, 0, numBytes); totalBytes += numBytes; } return totalBytes; } internal static Hashtable TokenizePrefixListString(string s) { Hashtable set = new Hashtable(); if (s != null) { string[] prefixes = s.Split(null); foreach (string prefix in prefixes) { if (prefix.Equals("#default")) { set.Add(string.Empty, true); } else if (prefix.Length > 0) { set.Add(prefix, true); } } } return set; } internal static string EscapeWhitespaceData(string data) { StringBuilder sb = new StringBuilder(); sb.Append(data); Utils.SBReplaceCharWithString(sb, (char)13, "&#xD;"); return sb.ToString(); ; } internal static string EscapeTextData(string data) { StringBuilder sb = new StringBuilder(); sb.Append(data); sb.Replace("&", "&amp;"); sb.Replace("<", "&lt;"); sb.Replace(">", "&gt;"); SBReplaceCharWithString(sb, (char)13, "&#xD;"); return sb.ToString(); ; } internal static string EscapeCData(string data) { return EscapeTextData(data); } internal static string EscapeAttributeValue(string value) { StringBuilder sb = new StringBuilder(); sb.Append(value); sb.Replace("&", "&amp;"); sb.Replace("<", "&lt;"); sb.Replace("\"", "&quot;"); SBReplaceCharWithString(sb, (char)9, "&#x9;"); SBReplaceCharWithString(sb, (char)10, "&#xA;"); SBReplaceCharWithString(sb, (char)13, "&#xD;"); return sb.ToString(); } internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList) { foreach (XmlNode node in nodeList) { if (node.OwnerDocument != null) return node.OwnerDocument; } return null; } internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) { if (namespaces != null) { foreach (XmlNode attrib in namespaces) { string name = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); // Skip the attribute if one with the same qualified name already exists if (elem.HasAttribute(name) || (name.Equals("xmlns") && elem.Prefix.Length == 0)) continue; XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.Value; elem.SetAttributeNode(nsattrib); } } } internal static void AddNamespaces(XmlElement elem, Hashtable namespaces) { if (namespaces != null) { foreach (string key in namespaces.Keys) { if (elem.HasAttribute(key)) continue; XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(key); nsattrib.Value = namespaces[key] as string; elem.SetAttributeNode(nsattrib); } } } // This method gets the attributes that should be propagated internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { if (elem == null) return null; CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); XmlNode ancestorNode = elem; if (ancestorNode == null) return null; bool bDefNamespaceToAdd = true; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement == null) { ancestorNode = ancestorNode.ParentNode; continue; } if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = ancestorElement.NamespaceURI; namespaces.Add(nsattrib); } } if (ancestorElement.HasAttributes) { XmlAttributeCollection attribs = ancestorElement.Attributes; foreach (XmlAttribute attrib in attribs) { // Add a default namespace if necessary if (bDefNamespaceToAdd && attrib.LocalName == "xmlns") { XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns"); nsattrib.Value = attrib.Value; namespaces.Add(nsattrib); bDefNamespaceToAdd = false; continue; } // retain the declarations of type 'xml:*' as well if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml") { namespaces.Add(attrib); continue; } if (attrib.NamespaceURI.Length > 0) { if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.NamespaceURI; namespaces.Add(nsattrib); } } } } } ancestorNode = ancestorNode.ParentNode; } return namespaces; } // output of this routine is always big endian internal static byte[] ConvertIntToByteArray(int dwInput) { byte[] rgbTemp = new byte[8]; // int can never be greater than Int64 int t1; // t1 is remaining value to account for int t2; // t2 is t1 % 256 int i = 0; if (dwInput == 0) return new byte[1]; t1 = dwInput; while (t1 > 0) { t2 = t1 % 256; rgbTemp[i] = (byte)t2; t1 = (t1 - t2) / 256; i++; } // Now, copy only the non-zero part of rgbTemp and reverse byte[] rgbOutput = new byte[i]; // copy and reverse in one pass for (int j = 0; j < i; j++) { rgbOutput[j] = rgbTemp[i - j - 1]; } return rgbOutput; } internal static int ConvertByteArrayToInt(byte[] input) { // Input to this routine is always big endian int dwOutput = 0; for (int i = 0; i < input.Length; i++) { dwOutput *= 256; dwOutput += input[i]; } return (dwOutput); } internal static int GetHexArraySize(byte[] hex) { int index = hex.Length; while (index-- > 0) { if (hex[index] != 0) break; } return index + 1; } internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType) { X509Certificate2Collection collection = new X509Certificate2Collection(); ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null); if (keyInfoX509Data.Certificates != null) { foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) { switch (certUsageType) { case CertUsageType.Verification: collection.Add(certificate); break; case CertUsageType.Decryption: decryptionIssuerSerials.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber)); break; } } } if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null && keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null) return collection; // Open LocalMachine and CurrentUser "Other People"/"My" stores. X509Store[] stores = new X509Store[2]; string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My"); stores[0] = new X509Store(storeName, StoreLocation.CurrentUser); stores[1] = new X509Store(storeName, StoreLocation.LocalMachine); for (int index = 0; index < stores.Length; index++) { if (stores[index] != null) { X509Certificate2Collection filters = null; // We don't care if we can't open the store. try { stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); filters = stores[index].Certificates; stores[index].Close(); if (keyInfoX509Data.SubjectNames != null) { foreach (string subjectName in keyInfoX509Data.SubjectNames) { filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false); } } if (keyInfoX509Data.IssuerSerials != null) { foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials) { filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false); filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } if (keyInfoX509Data.SubjectKeyIds != null) { foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds) { string hex = EncodeHexString(ski); filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false); } } if (decryptionIssuerSerials != null) { foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials) { filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false); filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } } catch (CryptographicException) { } if (filters != null) collection.AddRange(filters); } } return collection; } private static readonly char[] s_hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; internal static string EncodeHexString(byte[] sArray) { return EncodeHexString(sArray, 0, (uint)sArray.Length); } internal static string EncodeHexString(byte[] sArray, uint start, uint end) { string result = null; if (sArray != null) { char[] hexOrder = new char[(end - start) * 2]; uint digit; for (uint i = start, j = 0; i < end; i++) { digit = (uint)((sArray[i] & 0xf0) >> 4); hexOrder[j++] = s_hexValues[digit]; digit = (uint)(sArray[i] & 0x0f); hexOrder[j++] = s_hexValues[digit]; } result = new String(hexOrder); } return result; } internal static byte[] DecodeHexString(string s) { string hexString = Utils.DiscardWhiteSpaces(s); uint cbHex = (uint)hexString.Length / 2; byte[] hex = new byte[cbHex]; int i = 0; for (int index = 0; index < cbHex; index++) { hex[index] = (byte)((HexToByte(hexString[i]) << 4) | HexToByte(hexString[i + 1])); i += 2; } return hex; } internal static byte HexToByte(char val) { if (val <= '9' && val >= '0') return (byte)(val - '0'); else if (val >= 'a' && val <= 'f') return (byte)((val - 'a') + 10); else if (val >= 'A' && val <= 'F') return (byte)((val - 'A') + 10); else return 0xFF; } internal static bool IsSelfSigned(X509Chain chain) { X509ChainElementCollection elements = chain.ChainElements; if (elements.Count != 1) return false; X509Certificate2 certificate = elements[0].Certificate; if (String.Compare(certificate.SubjectName.Name, certificate.IssuerName.Name, StringComparison.OrdinalIgnoreCase) == 0) return true; return false; } internal static AsymmetricAlgorithm GetAnyPublicKey(X509Certificate2 certificate) { return (AsymmetricAlgorithm)certificate.GetRSAPublicKey() ?? certificate.GetDSAPublicKey(); } } }
namespace KingSurvival.ConsoleClient { using System; using System.Threading; using KingSurvival.GameLogic.Commons; using KingSurvival.GameLogic.Contracts; using KingSurvival.GameLogic.Models; public class KingSurvivalGame : BaseGame { private static bool gameOver = false; // to move someware else public static void PrintBoard() { Console.WriteLine(); for (int row = 0; row < GetField.GetLength(0); row++) { for (int col = 0; col < GetField.GetLength(1); col++) { Position coordinates = new Position(row, col); bool isCellIn = Validator.IsPositionOnTheBoard(coordinates); if (isCellIn) { if (row % 2 == 0) { if (col % 4 == 0) { ConsoleColor backgroundColor = ConsoleColor.Green; BaseGame.SetConsoleColor(backgroundColor, row, col); } else if (col % 2 == 0) { ConsoleColor backgroundColor = ConsoleColor.Blue; BaseGame.SetConsoleColor(backgroundColor, row, col); } else if (col % 2 != 0) { Console.Write(BaseGame.GetField[row, col]); } } else if (col % 4 == 0) { ConsoleColor backgroundColor = ConsoleColor.Blue; BaseGame.SetConsoleColor(backgroundColor, row, col); } else if (col % 2 == 0) { ConsoleColor backgroundColor = ConsoleColor.Green; BaseGame.SetConsoleColor(backgroundColor, row, col); } else if (col % 2 != 0) { Console.Write(BaseGame.GetField[row, col]); } } else { Console.Write(BaseGame.GetField[row, col]); } } Console.WriteLine(); Console.ResetColor(); } Console.WriteLine(); } public static void Start(int moveCounter) { if (!gameOver) { Console.Clear(); PrintBoard(); bool isKingTurn = moveCounter % 2 == 0; if (isKingTurn) { ProcessKingTurn(); } else { ProcessPawnTurn(); } } else { Console.WriteLine(MessageConstants.FinishGameMessage); Thread.Sleep(400); return; } } public static void PawnDirection(char pawn, char direction, int pawnNumber) { var oldCoordinates = PawnPositions[pawnNumber]; var coords = CheckNextPawnPosition(oldCoordinates, direction, pawn); if (coords != null) { BaseGame.PawnPositions[pawnNumber] = coords; } } public static void KingDirection(char downUpDirection, char leftRightDirection) { var oldCoordinates = new Position(KingPosition.Row, KingPosition.Col); var coords = CheckNextKingPosition(oldCoordinates, downUpDirection, leftRightDirection); if (coords != null) { BaseGame.KingPosition = coords; } } public static void ProcessKingTurn() { bool shouldAskForInput = true; while (shouldAskForInput) { Printer.PrintMessage(ConsoleColor.DarkGreen, MessageConstants.KingTurnMessage); string input = GetInput(); if (input == string.Empty) { Printer.PrintMessage(ConsoleColor.DarkRed, MessageConstants.EmptyStringMessage); Thread.Sleep(400); continue; } bool isValidDirection = CheckIfValidKingDirection(input); if (!isValidDirection) { Printer.PrintMessage(ConsoleColor.Red, MessageConstants.InvalidCommandMessage); Thread.Sleep(400); continue; } shouldAskForInput = false; // Does a lot of magic. Basically, if the king can move to the new position, it moves. The Counter is updated and // it's pawns' turn. If the king can't move to the new position, the Counter is not updated and ProcessKingSide() // is called again. KingDirection(input[1], input[2]); } Start(BaseGame.Counter); } public static void ProcessPawnTurn() { bool shouldAskForInput = true; while (shouldAskForInput) { Printer.PrintMessage(ConsoleColor.Blue, MessageConstants.PawnTurnMessage); string input = GetInput(); if (input == string.Empty) { Printer.PrintMessage(ConsoleColor.DarkRed, MessageConstants.EmptyStringMessage); Thread.Sleep(400); continue; } bool isValidDirection = CheckIfValidPawnDirection(input); if (!isValidDirection) { Printer.PrintMessage(ConsoleColor.Red, MessageConstants.InvalidCommandMessage); Thread.Sleep(400); continue; } shouldAskForInput = false; // I suppose it works in a way similar to KingDirection() char pawnName = input[0]; char directionLeftRight = input[2]; int pawnNumber = pawnName - 65; PawnDirection(pawnName, directionLeftRight, pawnNumber); } Start(BaseGame.Counter); } public static void CheckForKingExit(int currentKingXAxe) { if (currentKingXAxe == 2) { Console.WriteLine("========================="); Console.WriteLine(MessageConstants.KingVictoryMessage, BaseGame.Counter / 2); gameOver = true; } } public static void SwitchCurrentPawnExistingMoves(char currentPawn) { switch (currentPawn) { case 'A': GameConstants.PawnExistingMoves[0, 0] = true; GameConstants.PawnExistingMoves[0, 1] = true; break; case 'B': GameConstants.PawnExistingMoves[1, 0] = true; GameConstants.PawnExistingMoves[1, 1] = true; break; case 'C': GameConstants.PawnExistingMoves[2, 0] = true; GameConstants.PawnExistingMoves[2, 1] = true; break; case 'D': GameConstants.PawnExistingMoves[3, 0] = true; GameConstants.PawnExistingMoves[3, 1] = true; break; default: Console.WriteLine(MessageConstants.ErrorMessage); break; } } public static bool CheckingAllPawnMoves() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 2; j++) { if (GameConstants.PawnExistingMoves[i, j]) { return false; } } } return true; } public static IPosition CheckNextPawnPosition(IPosition currentCoordinates, char checkDirection, char currentPawn) { int[] displacementDownLeft = { 1, -2 }; int[] displacementDownRight = { 1, 2 }; var newCoordinates = new Position(); if (checkDirection == 'L') { newCoordinates.Row = currentCoordinates.Row + displacementDownLeft[0]; newCoordinates.Col = currentCoordinates.Col + displacementDownLeft[1]; bool isEmptyCurrentCell = GetField[newCoordinates.Row, newCoordinates.Col] == ' '; if (Validator.IsPositionOnTheBoard(newCoordinates) && isEmptyCurrentCell) { MoveFigure(currentCoordinates, newCoordinates); BaseGame.Counter++; SwitchCurrentPawnExistingMoves(currentPawn); return newCoordinates; } else { bool allAreFalse = true; switch (currentPawn) { case 'A': GameConstants.PawnExistingMoves[0, 0] = false; break; case 'B': GameConstants.PawnExistingMoves[1, 0] = false; break; case 'C': GameConstants.PawnExistingMoves[2, 0] = false; break; case 'D': GameConstants.PawnExistingMoves[3, 0] = false; break; default: Console.WriteLine(MessageConstants.ErrorMessage); break; } allAreFalse = CheckingAllPawnMoves(); if (allAreFalse) { gameOver = true; Console.WriteLine(MessageConstants.KingVictoryMessage, BaseGame.Counter / 2); gameOver = true; return null; } Printer.PrintMessage(ConsoleColor.DarkYellow, MessageConstants.WrongDirectionMessage); Thread.Sleep(400); return null; } } else { newCoordinates.Row = currentCoordinates.Row + displacementDownRight[0]; newCoordinates.Col = currentCoordinates.Col + displacementDownRight[1]; bool isEmptyCurrentCell = GetField[newCoordinates.Row, newCoordinates.Col] == ' '; if (Validator.IsPositionOnTheBoard(newCoordinates) && isEmptyCurrentCell) { MoveFigure(currentCoordinates, newCoordinates); BaseGame.Counter++; SwitchCurrentPawnExistingMoves(currentPawn); return newCoordinates; } else { bool allAreFalse = true; switch (currentPawn) { case 'A': GameConstants.PawnExistingMoves[0, 1] = false; break; case 'B': GameConstants.PawnExistingMoves[1, 1] = false; break; case 'C': GameConstants.PawnExistingMoves[2, 1] = false; break; case 'D': GameConstants.PawnExistingMoves[3, 1] = false; break; default: Console.WriteLine(MessageConstants.ErrorMessage); break; } allAreFalse = CheckingAllPawnMoves(); if (allAreFalse) { gameOver = true; Console.WriteLine(MessageConstants.KingVictoryMessage, BaseGame.Counter / 2); gameOver = true; return null; } Printer.PrintMessage(ConsoleColor.DarkYellow, MessageConstants.WrongDirectionMessage); Thread.Sleep(400); return null; } } } public static void MoveFigure(IPosition currentCoordinates, IPosition newCoordinates) { char currentPos = GetField[currentCoordinates.Row, currentCoordinates.Col]; BaseGame.GetField[currentCoordinates.Row, currentCoordinates.Col] = ' '; BaseGame.GetField[newCoordinates.Row, newCoordinates.Col] = currentPos; } public static IPosition CheckNextKingPosition(IPosition currentCoordinates, char firstDirection, char secondDirection) { int[] displacementDownLeft = { 1, -2 }; int[] displacementDownRight = { 1, 2 }; int[] displacementUpLeft = { -1, -2 }; int[] displacementUpRight = { -1, 2 }; var newCoordinates = new Position(); if (firstDirection == 'U') { if (secondDirection == 'L') { newCoordinates.Row = currentCoordinates.Row + displacementUpLeft[0]; newCoordinates.Col = currentCoordinates.Col + displacementUpLeft[1]; bool isEmptyCurrentCell = GetField[newCoordinates.Row, newCoordinates.Col] == ' '; if (Validator.IsPositionOnTheBoard(newCoordinates) && isEmptyCurrentCell) { MoveFigure(currentCoordinates, newCoordinates); BaseGame.Counter++; for (int i = 0; i < 4; i++) { GameConstants.KingExistingMoves[i] = true; } CheckForKingExit(newCoordinates.Row); return newCoordinates; } else { bool allAreFalse = KingExistingMovesMethod(0); if (allAreFalse) { gameOver = true; CommandPrintKingLosing(); return null; } Printer.PrintMessage(ConsoleColor.DarkYellow, MessageConstants.WrongDirectionMessage); Thread.Sleep(400); return null; } } else { newCoordinates.Row = currentCoordinates.Row + displacementUpRight[0]; newCoordinates.Col = currentCoordinates.Col + displacementUpRight[1]; bool isEmptyCurrentCell = GetField[newCoordinates.Row, newCoordinates.Col] == ' '; if (Validator.IsPositionOnTheBoard(newCoordinates) && isEmptyCurrentCell) { MoveFigure(currentCoordinates, newCoordinates); BaseGame.Counter++; for (int i = 0; i < 4; i++) { GameConstants.KingExistingMoves[i] = true; } CheckForKingExit(newCoordinates.Row); return newCoordinates; } else { bool allAreFalse = KingExistingMovesMethod(1); if (allAreFalse) { gameOver = true; CommandPrintKingLosing(); return null; } Printer.PrintMessage(ConsoleColor.DarkYellow, MessageConstants.WrongDirectionMessage); Thread.Sleep(400); return null; } } } else { if (secondDirection == 'L') { newCoordinates.Row = currentCoordinates.Row + displacementDownLeft[0]; newCoordinates.Col = currentCoordinates.Col + displacementDownLeft[1]; bool isEmptyCurrentCell = GetField[newCoordinates.Row, newCoordinates.Col] == ' '; if (Validator.IsPositionOnTheBoard(newCoordinates) && isEmptyCurrentCell) { MoveFigure(currentCoordinates, newCoordinates); BaseGame.Counter++; for (int i = 0; i < 4; i++) { GameConstants.KingExistingMoves[i] = true; } CheckForKingExit(newCoordinates.Row); return newCoordinates; } else { bool allAreFalse = KingExistingMovesMethod(2); if (allAreFalse) { gameOver = true; CommandPrintKingLosing(); return null; } Printer.PrintMessage(ConsoleColor.DarkYellow, MessageConstants.WrongDirectionMessage); Thread.Sleep(400); return null; } } else { newCoordinates.Row = currentCoordinates.Row + displacementDownRight[0]; newCoordinates.Col = currentCoordinates.Col + displacementDownRight[1]; bool isEmptyCurrentCell = GetField[newCoordinates.Row, newCoordinates.Col] == ' '; if (Validator.IsPositionOnTheBoard(newCoordinates) && isEmptyCurrentCell) { MoveFigure(currentCoordinates, newCoordinates); BaseGame.Counter++; for (int i = 0; i < 4; i++) { GameConstants.KingExistingMoves[i] = true; } CheckForKingExit(newCoordinates.Row); return newCoordinates; } else { bool allAreFalse = KingExistingMovesMethod(3); if (allAreFalse) { gameOver = true; CommandPrintKingLosing(); return null; } Printer.PrintMessage(ConsoleColor.DarkYellow, MessageConstants.WrongDirectionMessage); Thread.Sleep(400); return null; } } } } public static void CommandPrintKingLosing() { Console.WriteLine(MessageConstants.KingLostMessage, BaseGame.Counter / 2); } public static void Main() { Start(BaseGame.Counter); Console.WriteLine(MessageConstants.GoodbyeMessage); Console.ReadLine(); } private static bool KingExistingMovesMethod(int someMagicNumber) { GameConstants.KingExistingMoves[someMagicNumber] = false; bool allAreFalse = true; for (int i = 0; i < 4; i++) { if (GameConstants.KingExistingMoves[i]) { allAreFalse = false; } } return allAreFalse; } // Checks if command is KDR, KUL, etc. private static bool CheckIfValidKingDirection(string direction) { bool isValidDirection = false; foreach (var possibleDirection in GameConstants.KingPossibleDirections) { if (direction == possibleDirection) { isValidDirection = true; break; } } return isValidDirection; } // Checks if command is ADR, ADL, BDR, etc. private static bool CheckIfValidPawnDirection(string direction) { bool isValidDirection = Validator.IsValidPawnMove(direction); return isValidDirection; } // Returns user input after trimming and making it to upper case. Returns empty string if input is only white spaces. private static string GetInput() { string result = string.Empty; string input = Console.ReadLine(); if (string.IsNullOrWhiteSpace(input)) { return result; } else { string inputTrimmed = input.Trim(); result = inputTrimmed.ToUpper(); return result; } } } }
//----------------------------------------------------------------------------- // <copyright file="TimeSystem.cs" company="WheelMUD Development Team"> // Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is // subject to the Microsoft Public License. All other rights reserved. // </copyright> // <summary> // Provides a world time system to the mud. Actions can be scheduled to // occur at various times, with 1-second resolution, without spawning // new timers for each event. Necessary because there could be thousands // of temporary effects, delayed commands, and so on. // </summary> // <remarks> // This class was originally to be a custom calendar for the game, which // would differ from real-world time system and broadcast periodic updates // about the current time. Custom calendars are game-specific and usually // can be implemented by transforming DateTime.Now and scheduling // occasional broadcasts if desired. // </remarks> //----------------------------------------------------------------------------- namespace WheelMUD.Core { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using WheelMUD.Core.Events; using WheelMUD.Interfaces; /// <summary> /// Provides a world time system to the mud. Actions can be scheduled to occur at various times, with /// a rounded off resolution, without spawning new timers for each event. Grouped processing like this /// is necessary because there could be thousands of temporary effects, delayed commands, and so on. /// </summary> public class TimeSystem : ManagerSystem { /// <summary>The singleton instance of this class.</summary> private static readonly Lazy<TimeSystem> SingletonInstance = new Lazy<TimeSystem>(() => new TimeSystem()); /// <summary>The callback queue.</summary> private TimerQueue callbackQueue = new TimerQueue(); /// <summary>The timer provides a "heartbeat".</summary> private Timer timer; /// <summary>The interval between ticks of the shared timer, in milliseconds.</summary> /// <remarks>TODO: Test and tweak the default for this value based on typical gameplay timer loads.</remarks> private int interval = 250; /// <summary>Gets the singleton instance of this class.</summary> public static TimeSystem Instance { get { return SingletonInstance.Value; } } /// <summary>Start the time system.</summary> public override void Start() { this.SystemHost.UpdateSystemHost(this, "Starting..."); if (this.timer == null) { this.timer = new Timer(this.DoCallbacks, null, this.interval, this.interval); } this.SystemHost.UpdateSystemHost(this, "Started"); } /// <summary>Stops the time system.</summary> public override void Stop() { this.SystemHost.UpdateSystemHost(this, "Stopping..."); this.timer.Change(Timeout.Infinite, Timeout.Infinite); this.timer.Dispose(); this.SystemHost.UpdateSystemHost(this, "Stopped"); } /// <summary>Schedules an action according to the supplied <see cref="WheelMUD.Core.TimeEvent"/>.</summary> /// <param name="timeEventArgs">The <see cref="WheelMUD.Core.TimeEvent"/> instance containing the event data.</param> public void ScheduleEvent(TimeEvent timeEventArgs) { if (timeEventArgs == null) { throw new ArgumentException("Cannot schedule a null event.", "args"); } lock (this.callbackQueue) { this.callbackQueue.Enqueue(timeEventArgs); } } /// <summary>Calls any callbacks that have become due.</summary> /// <param name="state">Currently unused.</param> private void DoCallbacks(object state) { lock (this.callbackQueue) { // Loop over all events that have expired. DateTime currentTime = DateTime.Now; TimeEvent timeEvent = this.callbackQueue.Peek(); while (timeEvent != null && timeEvent.EndTime <= currentTime) { var callback = this.callbackQueue.Dequeue().Callback; if (!timeEvent.IsCancelled) { if (callback != null) { callback(); } } timeEvent = this.callbackQueue.Peek(); } } } /// <summary>A class for exporting/importing system singleton through MEF.</summary> [ExportSystem] public class TimeSystemExporter : SystemExporter { /// <summary>Gets the singleton system instance.</summary> /// <returns>A new instance of the singleton system.</returns> public override ISystem Instance { get { return TimeSystem.Instance; } } /// <summary>Gets the Type of the singleton system, without instantiating it.</summary> /// <returns>The Type of the singleton system.</returns> public override Type SystemType { get { return typeof(TimeSystem); } } } /// <summary> /// Bare-bones priority queue for use with the timekeeping system. /// Associates an Action with a DateTime expiration, and every Peek/Dequeue operation /// will return the Action with the earliest expiration time in the collection. /// </summary> private class TimerQueue { /// <summary>Collection to store the timed events.</summary> private List<TimeEvent> heap = new List<TimeEvent>(); /// <summary>Enqueues the specified element and the associated expiration DateTime.</summary> /// <param name="timeEventArgs">The <see cref="WheelMUD.Core.TimeEvent"/> instance containing the event data.</param> public void Enqueue(TimeEvent timeEventArgs) { lock (this.heap) { this.heap.Add(timeEventArgs); this.UpHeap(); } } /// <summary>Returns the highest-priority <see cref="WheelMUD.Core.TimeEvent"/> item without removing it from the heap.</summary> /// <returns>The highest-priority <see cref="WheelMUD.Core.TimeEvent"/> item.</returns> public TimeEvent Peek() { lock (this.heap) { return (this.heap.Count > 0) ? this.heap[0] : null; } } /// <summary>Returns the highest-priority <see cref="WheelMUD.Core.TimeEvent"/> item and removes it from the heap.</summary> /// <returns>The highest-priority <see cref="WheelMUD.Core.TimeEvent"/> item.</returns> public TimeEvent Dequeue() { lock (this.heap) { if (this.heap.Count > 0) { var result = this.heap[0]; this.heap[0] = this.heap.Last(); this.heap.RemoveAt(this.heap.Count - 1); this.DownHeap(); return result; } return null; } } /// <summary>Adjusts the heap for the case where a new item was added.</summary> private void UpHeap() { if (this.heap.Count < 2) { return; } int child = this.heap.Count - 1; int parent = (child - 1) / 2; var newest = this.heap[child]; while (newest.EndTime < this.heap[parent].EndTime) { this.heap[child] = this.heap[parent]; child = parent; if (parent == 0) { break; } parent = (parent - 1) / 2; } this.heap[child] = newest; } /// <summary>Adjusts the heap for the case where the highest-priority item was removed.</summary> private void DownHeap() { if (this.heap.Count < 2) { return; } int parent = 0; int leftChild = 1; int rightChild = leftChild + 1; var item = this.heap[parent]; if (rightChild < this.heap.Count - 1 && this.heap[rightChild].EndTime < this.heap[leftChild].EndTime) { leftChild = rightChild; } while (leftChild < this.heap.Count - 1 && this.heap[leftChild].EndTime < item.EndTime) { this.heap[parent] = this.heap[leftChild]; parent = leftChild; leftChild = (parent * 2) + 1; rightChild = leftChild + 1; if (rightChild < this.heap.Count - 1 && this.heap[rightChild].EndTime < this.heap[leftChild].EndTime) { leftChild = rightChild; } } this.heap[parent] = item; } } } }
// // 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading.Tasks; using Cassandra.Connections; using Cassandra.Connections.Control; using Cassandra.Helpers; using Moq; using NUnit.Framework; namespace Cassandra.Tests.Connections { [TestFixture] public class SniContactPointAndResolverTests { private readonly IEnumerable<string> _serverNames = new[] { "host1", "host2", "host3" }; private readonly IPEndPoint _proxyEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.3"), SniContactPointAndResolverTests.ProxyPort); private readonly IPEndPoint _proxyResolvedEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.4"), SniContactPointAndResolverTests.ProxyPort); private const int Port = 100; private const int ProxyPort = 213; [Test] public async Task Should_NotDnsResolveProxy_When_ProxyIpAddressIsProvided() { var result = Create(_proxyEndPoint.Address); var target = result.SniContactPoint; await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Never); } [Test] public async Task Should_DnsResolveProxy_When_ProxyNameIsProvided() { var result = Create(name: "proxy"); var target = result.SniContactPoint; Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Never); await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Once); } [Test] public async Task Should_BuildEndPointCorrectly_When_ProxyIpAddressIsProvided() { var result = Create(_proxyEndPoint.Address, serverNames: new [] { "host1" }); var target = result.SniContactPoint; var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); Assert.AreEqual(1, resolved.Count); Assert.AreEqual(_proxyEndPoint, resolved[0].GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyEndPoint, resolved[0].SocketIpEndPoint); Assert.AreEqual($"{_proxyEndPoint} (host1)", resolved[0].EndpointFriendlyName); Assert.AreEqual(_proxyEndPoint, resolved[0].GetHostIpEndPointWithFallback()); } [Test] public async Task Should_BuildEndPointCorrectly_When_ProxyNameIsProvided() { var result = Create(name: "proxy", serverNames: new [] { "host1" }); var target = result.SniContactPoint; var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); Assert.AreEqual(1, resolved.Count); Assert.AreEqual(_proxyResolvedEndPoint, resolved[0].GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyResolvedEndPoint, resolved[0].SocketIpEndPoint); Assert.AreEqual($"{_proxyResolvedEndPoint} (host1)", resolved[0].EndpointFriendlyName); Assert.AreEqual(_proxyResolvedEndPoint, resolved[0].GetHostIpEndPointWithFallback()); } [Test] public async Task Should_DnsResolveProxyTwice_When_RefreshIsTrue() { var result = Create(name: "proxy"); var target = result.SniContactPoint; Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Never); await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); await target.GetConnectionEndPointsAsync(true).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Exactly(2)); } [Test] public async Task Should_NotDnsResolveProxyTwice_When_RefreshIsFalse() { var result = Create(name: "proxy"); var target = result.SniContactPoint; Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Never); await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); } [Test] public async Task Should_EndPointResolver_DnsResolveProxyTwice_When_RefreshIsTrue() { var result = Create(name: "proxy"); var target = result.EndPointResolver; var host = CreateHost("127.0.0.1", SniContactPointAndResolverTests.Port); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Never); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); await target.GetConnectionEndPointAsync(host, true).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Exactly(2)); } [Test] public async Task Should_EndPointResolver_NotDnsResolveProxyTwice_When_RefreshIsFalse() { var result = Create(name: "proxy"); var target = result.EndPointResolver; var host = CreateHost("127.0.0.1", SniContactPointAndResolverTests.Port); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Never); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxy"), Times.Once); } [Test] public async Task Should_ReturnNewResolvedAddress_When_RefreshIsTrue() { var result = Create(name: "proxy", serverNames: new [] { "cp1" }); var target = result.SniContactPoint; var oldResolvedResults = await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false); result.ResolveResults[0] = IPAddress.Parse("123.10.10.10"); var newResolvedResults = (await target.GetConnectionEndPointsAsync(true).ConfigureAwait(false)).ToList(); Assert.AreNotEqual(IPAddress.Parse("123.10.10.10"), oldResolvedResults.Single().SocketIpEndPoint.Address); Assert.AreEqual(IPAddress.Parse("123.10.10.10"), newResolvedResults.Single().SocketIpEndPoint.Address); } [Test] public async Task Should_GetCorrectServerName() { var result = Create(_proxyEndPoint.Address); var target = result.SniContactPoint; var resolved = (await target.GetConnectionEndPointsAsync(false).ConfigureAwait(false)).ToList(); Assert.AreEqual(_serverNames.Count(), resolved.Count); var tasks = resolved.Select(r => r.GetServerNameAsync()).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); var resolvedNames = tasks.Select(t => t.Result); CollectionAssert.AreEquivalent(_serverNames, resolvedNames); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Never); } [Test] public async Task Should_NotDnsResolve_When_ResolvingHostButProxyIsIpAddress() { var result = Create(_proxyEndPoint.Address); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Never); } [Test] public async Task Should_BuildEndPointCorrectly_When_ResolvingHostButProxyIsIpAddress() { var result = Create(_proxyEndPoint.Address); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolved = await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Assert.AreEqual(host.HostId.ToString("D"), await resolved.GetServerNameAsync().ConfigureAwait(false)); Assert.AreEqual(host.Address, resolved.GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyEndPoint, resolved.SocketIpEndPoint); } [Test] public async Task Should_BuildEndPointCorrectly_When_ResolvingHostAndProxyIsHostname() { var result = Create(name: "proxy"); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolved = await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Assert.AreEqual(host.HostId.ToString("D"), await resolved.GetServerNameAsync().ConfigureAwait(false)); Assert.AreEqual(host.Address, resolved.GetHostIpEndPointWithFallback()); Assert.AreEqual(_proxyResolvedEndPoint, resolved.SocketIpEndPoint); } [Test] public async Task Should_CycleThroughResolvedAddresses_When_ResolvingHostAndProxyResolutionReturnsMultipleAddresses() { var result = Create(name: "proxyMultiple"); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolvedCollection = new[] { await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false), await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false), await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false), await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false) }; async Task AssertResolved(IConnectionEndPoint endPoint, string proxyAddress) { var proxyEndPoint = new IPEndPoint(IPAddress.Parse(proxyAddress), SniContactPointAndResolverTests.ProxyPort); Assert.AreEqual(host.HostId.ToString("D"), await endPoint.GetServerNameAsync().ConfigureAwait(false)); Assert.AreEqual(host.Address, endPoint.GetHostIpEndPointWithFallback()); Assert.AreEqual(proxyEndPoint, endPoint.SocketIpEndPoint); Assert.AreEqual(host.Address, endPoint.GetHostIpEndPointWithFallback()); } var resolvedFirst = resolvedCollection.Where(pt => pt.SocketIpEndPoint.Address.ToString() == "127.0.0.5").ToList(); var resolvedSecond = resolvedCollection.Where(pt => pt.SocketIpEndPoint.Address.ToString() == "127.0.0.6").ToList(); Assert.AreEqual(2, resolvedFirst.Count); Assert.AreEqual(2, resolvedSecond.Count); await AssertResolved(resolvedFirst[0], "127.0.0.5").ConfigureAwait(false); await AssertResolved(resolvedFirst[1], "127.0.0.5").ConfigureAwait(false); await AssertResolved(resolvedSecond[0], "127.0.0.6").ConfigureAwait(false); await AssertResolved(resolvedSecond[1], "127.0.0.6").ConfigureAwait(false); } [Test] public async Task Should_NotCallDnsResolve_When_CyclingThroughResolvedProxyAddresses() { var result = Create(name: "proxyMultiple"); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Never); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync(It.IsAny<string>()), Times.Once); Mock.Get(result.DnsResolver).Verify(x => x.GetHostEntryAsync("proxyMultiple"), Times.Once); } [Test] public async Task Should_UseNewResolution_When_ResolveSucceeds() { var logLevel = Diagnostics.CassandraTraceSwitch.Level; try { Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info; var listener = new TestTraceListener(); Trace.Listeners.Add(listener); var result = Create(name: "proxyMultiple"); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolvedCollection = new List<IConnectionEndPoint>(); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); Mock.Get(result.DnsResolver).Verify(m => m.GetHostEntryAsync(It.IsAny<string>()), Times.Once); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, true).ConfigureAwait(false)); Mock.Get(result.DnsResolver).Verify(m => m.GetHostEntryAsync(It.IsAny<string>()), Times.Exactly(2)); Assert.AreEqual(0, listener.Queue.Count); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); Assert.AreNotSame(resolvedCollection[0].SocketIpEndPoint, resolvedCollection[2].SocketIpEndPoint); Assert.AreNotSame(resolvedCollection[0].SocketIpEndPoint, resolvedCollection[3].SocketIpEndPoint); Assert.AreNotSame(resolvedCollection[0].SocketIpEndPoint, resolvedCollection[4].SocketIpEndPoint); Assert.AreNotSame(resolvedCollection[1].SocketIpEndPoint, resolvedCollection[2].SocketIpEndPoint); Assert.AreNotSame(resolvedCollection[1].SocketIpEndPoint, resolvedCollection[3].SocketIpEndPoint); Assert.AreNotSame(resolvedCollection[1].SocketIpEndPoint, resolvedCollection[4].SocketIpEndPoint); } finally { Diagnostics.CassandraTraceSwitch.Level = logLevel; } } [Test] public async Task Should_ReusePreviousResolution_When_ResolveFails() { var logLevel = Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info; try { var listener = new TestTraceListener(); Trace.Listeners.Add(listener); var result = Create(name: "proxyMultiple"); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolvedCollection = new List<IConnectionEndPoint> { await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false), await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false) }; Assert.AreEqual(0, listener.Queue.Count); Mock.Get(result.DnsResolver).Verify(m => m.GetHostEntryAsync(It.IsAny<string>()), Times.Once); Mock.Get(result.DnsResolver).Setup(m => m.GetHostEntryAsync("proxyMultiple")).ThrowsAsync(new Exception()); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, true).ConfigureAwait(false)); Mock.Get(result.DnsResolver).Verify(m => m.GetHostEntryAsync(It.IsAny<string>()), Times.Exactly(2)); Assert.AreEqual(1, listener.Queue.Count); Assert.IsTrue(listener.Queue.ToArray()[0].Contains( "Could not resolve endpoint \"proxyMultiple\". Falling back to the result of the previous DNS resolution.")); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); resolvedCollection.Add(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); Assert.AreSame(resolvedCollection[0].SocketIpEndPoint, resolvedCollection[2].SocketIpEndPoint); Assert.AreSame(resolvedCollection[1].SocketIpEndPoint, resolvedCollection[3].SocketIpEndPoint); Assert.AreSame(resolvedCollection[0].SocketIpEndPoint, resolvedCollection[4].SocketIpEndPoint); } finally { Cassandra.Diagnostics.CassandraTraceSwitch.Level = logLevel; } } [Test] [Repeat(10)] public async Task Should_CycleThroughAddressesCorrectly_When_ConcurrentCalls() { var result = Create(name: "proxyMultiple"); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolvedCollection = new ConcurrentQueue<IConnectionEndPoint>(); var tasks = Enumerable.Range(0, 1000) .Select(i => Task.Run(async () => { await Task.Delay(1).ConfigureAwait(false); resolvedCollection.Enqueue(await target.GetConnectionEndPointAsync(host, false).ConfigureAwait(false)); })) .ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); var resolvedArray = resolvedCollection.ToArray(); var resolvedFirst = resolvedArray.Count(pt => pt.SocketIpEndPoint.Address.ToString() == "127.0.0.5"); var resolvedSecond = resolvedArray.Count(pt => pt.SocketIpEndPoint.Address.ToString() == "127.0.0.6"); Assert.AreEqual(500, resolvedFirst); Assert.AreEqual(500, resolvedSecond); } [Test] public async Task Should_CycleThroughAddressesCorrectly_When_ConcurrentCallsWithRefresh() { var result = Create(name: "proxyMultiple", randValue: 1); var target = result.EndPointResolver; var host = CreateHost("163.10.10.10", SniContactPointAndResolverTests.Port); var resolvedCollection = new ConcurrentQueue<IConnectionEndPoint>(); var tasks = Enumerable.Range(0, 16) .Select(i => Task.Run(async () => { foreach (var j in Enumerable.Range(0, 10000)) { resolvedCollection.Enqueue( await target.GetConnectionEndPointAsync(host, (i+j) % 2 == 0).ConfigureAwait(false)); } })).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); var resolvedArray = resolvedCollection.ToArray(); var resolvedFirst = resolvedArray.Count(pt => pt.SocketIpEndPoint.Address.ToString() == "127.0.0.5"); var resolvedSecond = resolvedArray.Count(pt => pt.SocketIpEndPoint.Address.ToString() == "127.0.0.6"); Assert.AreNotEqual(resolvedFirst, resolvedSecond); Assert.AreEqual(160000, resolvedFirst + resolvedSecond); Assert.Greater(resolvedFirst, 0); Assert.Greater(resolvedSecond, 0); } private CreateResult Create(IPAddress ip = null, string name = null, IEnumerable<string> serverNames = null, int? randValue = null) { if (ip == null && name == null) { throw new Exception("ip and name are null"); } if (ip != null && name != null) { throw new Exception("ip and name are both different than null"); } if (serverNames == null) { serverNames = _serverNames; } var sniOptionsProvider = Mock.Of<ISniOptionsProvider>(); var dnsResolver = Mock.Of<IDnsResolver>(); var resolveResults = new[] { IPAddress.Parse("127.0.0.4") }; var multipleResolveResults = new[] { IPAddress.Parse("127.0.0.5"), IPAddress.Parse("127.0.0.6") }; Mock.Get(dnsResolver).Setup(m => m.GetHostEntryAsync("proxy")) .ReturnsAsync(new IPHostEntry { AddressList = resolveResults }); Mock.Get(dnsResolver).Setup(m => m.GetHostEntryAsync("proxyMultiple")) .ReturnsAsync(new IPHostEntry { AddressList = multipleResolveResults }); Mock.Get(sniOptionsProvider).Setup(m => m.IsInitialized()).Returns(true); Mock.Get(sniOptionsProvider).Setup(m => m.GetAsync(It.IsAny<bool>())).ReturnsAsync( new SniOptions(ip, SniContactPointAndResolverTests.ProxyPort, name, new SortedSet<string>(serverNames))); var sniResolver = new SniEndPointResolver( sniOptionsProvider, dnsResolver, randValue == null ? (IRandom) new DefaultRandom() : new FixedRandom(randValue.Value)); return new CreateResult { DnsResolver = dnsResolver, ResolveResults = resolveResults, MultipleResolveResults = multipleResolveResults, EndPointResolver = sniResolver, SniContactPoint = new SniContactPoint(sniResolver) }; } private Host CreateHost(string ipAddress, int port, Guid? nullableHostId = null) { var hostAddress = new IPEndPoint(IPAddress.Parse("163.10.10.10"), SniContactPointAndResolverTests.Port); var host = new Host(hostAddress, contactPoint: null); var hostId = nullableHostId ?? Guid.NewGuid(); var row = BuildRow(hostId); host.SetInfo(row); return host; } private IRow BuildRow(Guid? hostId) { return new TestHelper.DictionaryBasedRow(new Dictionary<string, object> { { "host_id", hostId }, { "data_center", "dc1"}, { "rack", "rack1" }, { "release_version", "3.11.1" }, { "tokens", new List<string> { "1" }} }); } private class CreateResult { public IDnsResolver DnsResolver { get; set; } public IPAddress[] ResolveResults { get; set; } public IPAddress[] MultipleResolveResults { get; set; } public IEndPointResolver EndPointResolver { get; set; } public SniContactPoint SniContactPoint { get; set; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dataproc.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.LongRunning; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedBatchControllerClientSnippets { /// <summary>Snippet for CreateBatch</summary> public void CreateBatchRequestObject() { // Snippet: CreateBatch(CreateBatchRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) CreateBatchRequest request = new CreateBatchRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Batch = new Batch(), BatchId = "", RequestId = "", }; // Make the request Operation<Batch, BatchOperationMetadata> response = batchControllerClient.CreateBatch(request); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = batchControllerClient.PollOnceCreateBatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatchAsync</summary> public async Task CreateBatchRequestObjectAsync() { // Snippet: CreateBatchAsync(CreateBatchRequest, CallSettings) // Additional: CreateBatchAsync(CreateBatchRequest, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) CreateBatchRequest request = new CreateBatchRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Batch = new Batch(), BatchId = "", RequestId = "", }; // Make the request Operation<Batch, BatchOperationMetadata> response = await batchControllerClient.CreateBatchAsync(request); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = await batchControllerClient.PollOnceCreateBatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatch</summary> public void CreateBatch() { // Snippet: CreateBatch(string, Batch, string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = batchControllerClient.CreateBatch(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = batchControllerClient.PollOnceCreateBatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatchAsync</summary> public async Task CreateBatchAsync() { // Snippet: CreateBatchAsync(string, Batch, string, CallSettings) // Additional: CreateBatchAsync(string, Batch, string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = await batchControllerClient.CreateBatchAsync(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = await batchControllerClient.PollOnceCreateBatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatch</summary> public void CreateBatchResourceNames() { // Snippet: CreateBatch(LocationName, Batch, string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = batchControllerClient.CreateBatch(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = batchControllerClient.PollOnceCreateBatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatchAsync</summary> public async Task CreateBatchResourceNamesAsync() { // Snippet: CreateBatchAsync(LocationName, Batch, string, CallSettings) // Additional: CreateBatchAsync(LocationName, Batch, string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = await batchControllerClient.CreateBatchAsync(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = await batchControllerClient.PollOnceCreateBatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for GetBatch</summary> public void GetBatchRequestObject() { // Snippet: GetBatch(GetBatchRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) GetBatchRequest request = new GetBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request Batch response = batchControllerClient.GetBatch(request); // End snippet } /// <summary>Snippet for GetBatchAsync</summary> public async Task GetBatchRequestObjectAsync() { // Snippet: GetBatchAsync(GetBatchRequest, CallSettings) // Additional: GetBatchAsync(GetBatchRequest, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) GetBatchRequest request = new GetBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request Batch response = await batchControllerClient.GetBatchAsync(request); // End snippet } /// <summary>Snippet for GetBatch</summary> public void GetBatch() { // Snippet: GetBatch(string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request Batch response = batchControllerClient.GetBatch(name); // End snippet } /// <summary>Snippet for GetBatchAsync</summary> public async Task GetBatchAsync() { // Snippet: GetBatchAsync(string, CallSettings) // Additional: GetBatchAsync(string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request Batch response = await batchControllerClient.GetBatchAsync(name); // End snippet } /// <summary>Snippet for GetBatch</summary> public void GetBatchResourceNames() { // Snippet: GetBatch(BatchName, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request Batch response = batchControllerClient.GetBatch(name); // End snippet } /// <summary>Snippet for GetBatchAsync</summary> public async Task GetBatchResourceNamesAsync() { // Snippet: GetBatchAsync(BatchName, CallSettings) // Additional: GetBatchAsync(BatchName, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request Batch response = await batchControllerClient.GetBatchAsync(name); // End snippet } /// <summary>Snippet for ListBatches</summary> public void ListBatchesRequestObject() { // Snippet: ListBatches(ListBatchesRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) ListBatchesRequest request = new ListBatchesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatches(request); // Iterate over all response items, lazily performing RPCs as required foreach (Batch item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBatchesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatchesAsync</summary> public async Task ListBatchesRequestObjectAsync() { // Snippet: ListBatchesAsync(ListBatchesRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) ListBatchesRequest request = new ListBatchesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedAsyncEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatchesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Batch item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBatchesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatches</summary> public void ListBatches() { // Snippet: ListBatches(string, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatches(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Batch item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBatchesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatchesAsync</summary> public async Task ListBatchesAsync() { // Snippet: ListBatchesAsync(string, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatchesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Batch item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBatchesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatches</summary> public void ListBatchesResourceNames() { // Snippet: ListBatches(LocationName, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatches(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Batch item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBatchesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatchesAsync</summary> public async Task ListBatchesResourceNamesAsync() { // Snippet: ListBatchesAsync(LocationName, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatchesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Batch item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBatchesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteBatch</summary> public void DeleteBatchRequestObject() { // Snippet: DeleteBatch(DeleteBatchRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) DeleteBatchRequest request = new DeleteBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request batchControllerClient.DeleteBatch(request); // End snippet } /// <summary>Snippet for DeleteBatchAsync</summary> public async Task DeleteBatchRequestObjectAsync() { // Snippet: DeleteBatchAsync(DeleteBatchRequest, CallSettings) // Additional: DeleteBatchAsync(DeleteBatchRequest, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) DeleteBatchRequest request = new DeleteBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request await batchControllerClient.DeleteBatchAsync(request); // End snippet } /// <summary>Snippet for DeleteBatch</summary> public void DeleteBatch() { // Snippet: DeleteBatch(string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request batchControllerClient.DeleteBatch(name); // End snippet } /// <summary>Snippet for DeleteBatchAsync</summary> public async Task DeleteBatchAsync() { // Snippet: DeleteBatchAsync(string, CallSettings) // Additional: DeleteBatchAsync(string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request await batchControllerClient.DeleteBatchAsync(name); // End snippet } /// <summary>Snippet for DeleteBatch</summary> public void DeleteBatchResourceNames() { // Snippet: DeleteBatch(BatchName, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request batchControllerClient.DeleteBatch(name); // End snippet } /// <summary>Snippet for DeleteBatchAsync</summary> public async Task DeleteBatchResourceNamesAsync() { // Snippet: DeleteBatchAsync(BatchName, CallSettings) // Additional: DeleteBatchAsync(BatchName, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request await batchControllerClient.DeleteBatchAsync(name); // End snippet } } }
// // 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 Hyak.Common; using System; using System.Net.Http; namespace Microsoft.Azure.Internal.Subscriptions { public partial class SubscriptionClient : ServiceClient<SubscriptionClient>, ISubscriptionClient { 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 CloudCredentials _credentials; /// <summary> /// Credentials used to authenticate requests. /// </summary> public CloudCredentials Credentials { get { return this._credentials; } set { this._credentials = value; } } 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 ISubscriptionOperations _subscriptions; /// <summary> /// Operations for managing subscriptions. /// </summary> public virtual ISubscriptionOperations Subscriptions { get { return this._subscriptions; } } private ITenantOperations _tenants; /// <summary> /// Operations for managing tenants. /// </summary> public virtual ITenantOperations Tenants { get { return this._tenants; } } /// <summary> /// Initializes a new instance of the SubscriptionClient class. /// </summary> public SubscriptionClient() : base() { this._subscriptions = new SubscriptionOperations(this); this._tenants = new TenantOperations(this); this._apiVersion = "2014-04-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SubscriptionClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials used to authenticate requests. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public SubscriptionClient(CloudCredentials 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 SubscriptionClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials used to authenticate requests. /// </param> public SubscriptionClient(CloudCredentials 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 SubscriptionClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public SubscriptionClient(HttpClient httpClient) : base(httpClient) { this._subscriptions = new SubscriptionOperations(this); this._tenants = new TenantOperations(this); this._apiVersion = "2014-04-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SubscriptionClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials used to authenticate requests. /// </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 SubscriptionClient(CloudCredentials 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 SubscriptionClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials used to authenticate requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SubscriptionClient(CloudCredentials 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 /// SubscriptionClient instance /// </summary> /// <param name='client'> /// Instance of SubscriptionClient to clone to /// </param> protected override void Clone(ServiceClient<SubscriptionClient> client) { base.Clone(client); if (client is SubscriptionClient) { SubscriptionClient clonedClient = ((SubscriptionClient)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); } } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IBillingCodeApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Create a billingCode /// </summary> /// <remarks> /// Inserts a new billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>BillingCode</returns> BillingCode AddBillingCode (BillingCode body); /// <summary> /// Create a billingCode /// </summary> /// <remarks> /// Inserts a new billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>ApiResponse of BillingCode</returns> ApiResponse<BillingCode> AddBillingCodeWithHttpInfo (BillingCode body); /// <summary> /// Delete a billingCode /// </summary> /// <remarks> /// Deletes the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns></returns> void DeleteBillingCode (int? billingCodeId); /// <summary> /// Delete a billingCode /// </summary> /// <remarks> /// Deletes the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeleteBillingCodeWithHttpInfo (int? billingCodeId); /// <summary> /// Search billingCodes by filter /// </summary> /// <remarks> /// Returns the list of billingCodes that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;BillingCode&gt;</returns> List<BillingCode> GetBillingCodeByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search billingCodes by filter /// </summary> /// <remarks> /// Returns the list of billingCodes that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;BillingCode&gt;</returns> ApiResponse<List<BillingCode>> GetBillingCodeByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a billingCode by id /// </summary> /// <remarks> /// Returns the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>BillingCode</returns> BillingCode GetBillingCodeById (int? billingCodeId); /// <summary> /// Get a billingCode by id /// </summary> /// <remarks> /// Returns the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>ApiResponse of BillingCode</returns> ApiResponse<BillingCode> GetBillingCodeByIdWithHttpInfo (int? billingCodeId); /// <summary> /// Update a billingCode /// </summary> /// <remarks> /// Updates an existing billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns></returns> void UpdateBillingCode (BillingCode body); /// <summary> /// Update a billingCode /// </summary> /// <remarks> /// Updates an existing billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> UpdateBillingCodeWithHttpInfo (BillingCode body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Create a billingCode /// </summary> /// <remarks> /// Inserts a new billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>Task of BillingCode</returns> System.Threading.Tasks.Task<BillingCode> AddBillingCodeAsync (BillingCode body); /// <summary> /// Create a billingCode /// </summary> /// <remarks> /// Inserts a new billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>Task of ApiResponse (BillingCode)</returns> System.Threading.Tasks.Task<ApiResponse<BillingCode>> AddBillingCodeAsyncWithHttpInfo (BillingCode body); /// <summary> /// Delete a billingCode /// </summary> /// <remarks> /// Deletes the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeleteBillingCodeAsync (int? billingCodeId); /// <summary> /// Delete a billingCode /// </summary> /// <remarks> /// Deletes the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeleteBillingCodeAsyncWithHttpInfo (int? billingCodeId); /// <summary> /// Search billingCodes by filter /// </summary> /// <remarks> /// Returns the list of billingCodes that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;BillingCode&gt;</returns> System.Threading.Tasks.Task<List<BillingCode>> GetBillingCodeByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search billingCodes by filter /// </summary> /// <remarks> /// Returns the list of billingCodes that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;BillingCode&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<BillingCode>>> GetBillingCodeByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a billingCode by id /// </summary> /// <remarks> /// Returns the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>Task of BillingCode</returns> System.Threading.Tasks.Task<BillingCode> GetBillingCodeByIdAsync (int? billingCodeId); /// <summary> /// Get a billingCode by id /// </summary> /// <remarks> /// Returns the billingCode identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>Task of ApiResponse (BillingCode)</returns> System.Threading.Tasks.Task<ApiResponse<BillingCode>> GetBillingCodeByIdAsyncWithHttpInfo (int? billingCodeId); /// <summary> /// Update a billingCode /// </summary> /// <remarks> /// Updates an existing billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task UpdateBillingCodeAsync (BillingCode body); /// <summary> /// Update a billingCode /// </summary> /// <remarks> /// Updates an existing billingCode using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> UpdateBillingCodeAsyncWithHttpInfo (BillingCode body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class BillingCodeApi : IBillingCodeApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="BillingCodeApi"/> class. /// </summary> /// <returns></returns> public BillingCodeApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="BillingCodeApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public BillingCodeApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Create a billingCode Inserts a new billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>BillingCode</returns> public BillingCode AddBillingCode (BillingCode body) { ApiResponse<BillingCode> localVarResponse = AddBillingCodeWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create a billingCode Inserts a new billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>ApiResponse of BillingCode</returns> public ApiResponse< BillingCode > AddBillingCodeWithHttpInfo (BillingCode body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling BillingCodeApi->AddBillingCode"); var localVarPath = "/v1.0/billingCode"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddBillingCode", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<BillingCode>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (BillingCode) Configuration.ApiClient.Deserialize(localVarResponse, typeof(BillingCode))); } /// <summary> /// Create a billingCode Inserts a new billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>Task of BillingCode</returns> public async System.Threading.Tasks.Task<BillingCode> AddBillingCodeAsync (BillingCode body) { ApiResponse<BillingCode> localVarResponse = await AddBillingCodeAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create a billingCode Inserts a new billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be inserted.</param> /// <returns>Task of ApiResponse (BillingCode)</returns> public async System.Threading.Tasks.Task<ApiResponse<BillingCode>> AddBillingCodeAsyncWithHttpInfo (BillingCode body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling BillingCodeApi->AddBillingCode"); var localVarPath = "/v1.0/billingCode"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddBillingCode", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<BillingCode>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (BillingCode) Configuration.ApiClient.Deserialize(localVarResponse, typeof(BillingCode))); } /// <summary> /// Delete a billingCode Deletes the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns></returns> public void DeleteBillingCode (int? billingCodeId) { DeleteBillingCodeWithHttpInfo(billingCodeId); } /// <summary> /// Delete a billingCode Deletes the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeleteBillingCodeWithHttpInfo (int? billingCodeId) { // verify the required parameter 'billingCodeId' is set if (billingCodeId == null) throw new ApiException(400, "Missing required parameter 'billingCodeId' when calling BillingCodeApi->DeleteBillingCode"); var localVarPath = "/v1.0/billingCode/{billingCodeId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (billingCodeId != null) localVarPathParams.Add("billingCodeId", Configuration.ApiClient.ParameterToString(billingCodeId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteBillingCode", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete a billingCode Deletes the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeleteBillingCodeAsync (int? billingCodeId) { await DeleteBillingCodeAsyncWithHttpInfo(billingCodeId); } /// <summary> /// Delete a billingCode Deletes the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be deleted.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteBillingCodeAsyncWithHttpInfo (int? billingCodeId) { // verify the required parameter 'billingCodeId' is set if (billingCodeId == null) throw new ApiException(400, "Missing required parameter 'billingCodeId' when calling BillingCodeApi->DeleteBillingCode"); var localVarPath = "/v1.0/billingCode/{billingCodeId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (billingCodeId != null) localVarPathParams.Add("billingCodeId", Configuration.ApiClient.ParameterToString(billingCodeId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteBillingCode", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Search billingCodes by filter Returns the list of billingCodes that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;BillingCode&gt;</returns> public List<BillingCode> GetBillingCodeByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<BillingCode>> localVarResponse = GetBillingCodeByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search billingCodes by filter Returns the list of billingCodes that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;BillingCode&gt;</returns> public ApiResponse< List<BillingCode> > GetBillingCodeByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/billingCode/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBillingCodeByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<BillingCode>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<BillingCode>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<BillingCode>))); } /// <summary> /// Search billingCodes by filter Returns the list of billingCodes that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;BillingCode&gt;</returns> public async System.Threading.Tasks.Task<List<BillingCode>> GetBillingCodeByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<BillingCode>> localVarResponse = await GetBillingCodeByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search billingCodes by filter Returns the list of billingCodes that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;BillingCode&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<BillingCode>>> GetBillingCodeByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/billingCode/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBillingCodeByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<BillingCode>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<BillingCode>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<BillingCode>))); } /// <summary> /// Get a billingCode by id Returns the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>BillingCode</returns> public BillingCode GetBillingCodeById (int? billingCodeId) { ApiResponse<BillingCode> localVarResponse = GetBillingCodeByIdWithHttpInfo(billingCodeId); return localVarResponse.Data; } /// <summary> /// Get a billingCode by id Returns the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>ApiResponse of BillingCode</returns> public ApiResponse< BillingCode > GetBillingCodeByIdWithHttpInfo (int? billingCodeId) { // verify the required parameter 'billingCodeId' is set if (billingCodeId == null) throw new ApiException(400, "Missing required parameter 'billingCodeId' when calling BillingCodeApi->GetBillingCodeById"); var localVarPath = "/v1.0/billingCode/{billingCodeId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (billingCodeId != null) localVarPathParams.Add("billingCodeId", Configuration.ApiClient.ParameterToString(billingCodeId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBillingCodeById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<BillingCode>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (BillingCode) Configuration.ApiClient.Deserialize(localVarResponse, typeof(BillingCode))); } /// <summary> /// Get a billingCode by id Returns the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>Task of BillingCode</returns> public async System.Threading.Tasks.Task<BillingCode> GetBillingCodeByIdAsync (int? billingCodeId) { ApiResponse<BillingCode> localVarResponse = await GetBillingCodeByIdAsyncWithHttpInfo(billingCodeId); return localVarResponse.Data; } /// <summary> /// Get a billingCode by id Returns the billingCode identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="billingCodeId">Id of the billingCode to be returned.</param> /// <returns>Task of ApiResponse (BillingCode)</returns> public async System.Threading.Tasks.Task<ApiResponse<BillingCode>> GetBillingCodeByIdAsyncWithHttpInfo (int? billingCodeId) { // verify the required parameter 'billingCodeId' is set if (billingCodeId == null) throw new ApiException(400, "Missing required parameter 'billingCodeId' when calling BillingCodeApi->GetBillingCodeById"); var localVarPath = "/v1.0/billingCode/{billingCodeId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (billingCodeId != null) localVarPathParams.Add("billingCodeId", Configuration.ApiClient.ParameterToString(billingCodeId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetBillingCodeById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<BillingCode>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (BillingCode) Configuration.ApiClient.Deserialize(localVarResponse, typeof(BillingCode))); } /// <summary> /// Update a billingCode Updates an existing billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns></returns> public void UpdateBillingCode (BillingCode body) { UpdateBillingCodeWithHttpInfo(body); } /// <summary> /// Update a billingCode Updates an existing billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> UpdateBillingCodeWithHttpInfo (BillingCode body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling BillingCodeApi->UpdateBillingCode"); var localVarPath = "/v1.0/billingCode"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateBillingCode", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Update a billingCode Updates an existing billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task UpdateBillingCodeAsync (BillingCode body) { await UpdateBillingCodeAsyncWithHttpInfo(body); } /// <summary> /// Update a billingCode Updates an existing billingCode using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">BillingCode to be updated.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateBillingCodeAsyncWithHttpInfo (BillingCode body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling BillingCodeApi->UpdateBillingCode"); var localVarPath = "/v1.0/billingCode"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateBillingCode", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: List for exceptions. ** ** ===========================================================*/ namespace System.Collections { /// This is a simple implementation of IDictionary that is empty and readonly. internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary { // Note that this class must be agile with respect to AppDomains. See its usage in // System.Exception to understand why this is the case. public EmptyReadOnlyDictionaryInternal() { } // IEnumerable members IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(); } // ICollection members public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); // the actual copy is a NOP } public int Count { get { return 0; } } public Object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } // IDictionary members public Object this[Object key] { get { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } public ICollection Keys { get { return Array.Empty<Object>(); } } public ICollection Values { get { return Array.Empty<Object>(); } } public bool Contains(Object key) { return false; } public void Add(Object key, Object value) { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } public void Clear() { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } public bool IsReadOnly { get { return true; } } public bool IsFixedSize { get { return true; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(); } public void Remove(Object key) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } private sealed class NodeEnumerator : IDictionaryEnumerator { public NodeEnumerator() { } // IEnumerator members public bool MoveNext() { return false; } public Object Current { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public void Reset() { } // IDictionaryEnumerator members public Object Key { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public Object Value { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } public DictionaryEntry Entry { get { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using OpenCvSharp.Internal; using OpenCvSharp.Internal.Vectors; // ReSharper disable UnusedMember.Global // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming // ReSharper disable CommentTypo namespace OpenCvSharp.Dnn { /// <inheritdoc /> /// <summary> /// This class allows to create and manipulate comprehensive artificial neural networks. /// </summary> /// <remarks> /// Neural network is presented as directed acyclic graph(DAG), where vertices are Layer instances, /// and edges specify relationships between layers inputs and outputs. /// /// Each network layer has unique integer id and unique string name inside its network. /// LayerId can store either layer name or layer id. /// This class supports reference counting of its instances, i.e.copies point to the same instance. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1724: Type names should not match namespaces")] public class Net : DisposableCvObject { #region Init & Disposal /// <inheritdoc /> /// <summary> /// Default constructor. /// </summary> public Net() { NativeMethods.HandleException( NativeMethods.dnn_Net_new(out ptr)); } /// <inheritdoc /> /// <summary> /// </summary> protected Net(IntPtr ptr) { this.ptr = ptr; } /// <inheritdoc /> /// <summary> /// </summary> protected override void DisposeUnmanaged() { NativeMethods.HandleException( NativeMethods.dnn_Net_delete(ptr)); base.DisposeUnmanaged(); } /// <summary> /// Create a network from Intel's Model Optimizer intermediate representation (IR). /// Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine backend. /// </summary> /// <param name="xml">XML configuration file with network's topology.</param> /// <param name="bin">Binary file with trained weights.</param> /// <returns></returns> public static Net? ReadFromModelOptimizer(string xml, string bin) { if (xml == null) throw new ArgumentNullException(nameof(xml)); if (bin == null) throw new ArgumentNullException(nameof(bin)); NativeMethods.HandleException( NativeMethods.dnn_Net_readFromModelOptimizer(xml, bin, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Reads a network model stored in Darknet (https://pjreddie.com/darknet/) model files. /// </summary> /// <param name="cfgFile">path to the .cfg file with text description of the network architecture.</param> /// <param name="darknetModel">path to the .weights file with learned network.</param> /// <returns>Network object that ready to do forward, throw an exception in failure cases.</returns> /// <remarks>This is shortcut consisting from DarknetImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromDarknet(string cfgFile, string? darknetModel = null) { if (cfgFile == null) throw new ArgumentNullException(nameof(cfgFile)); NativeMethods.HandleException( NativeMethods.dnn_readNetFromDarknet(cfgFile, darknetModel, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Reads a network model stored in Caffe model files from memory. /// </summary> /// <param name="bufferCfg">A buffer contains a content of .cfg file with text description of the network architecture.</param> /// <param name="bufferModel">A buffer contains a content of .weights file with learned network.</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createCaffeImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromDarknet(byte[] bufferCfg, byte[]? bufferModel = null) { if (bufferCfg == null) throw new ArgumentNullException(nameof(bufferCfg)); var ret = ReadNetFromDarknet( new ReadOnlySpan<byte>(bufferCfg), bufferModel == null ? ReadOnlySpan<byte>.Empty : new ReadOnlySpan<byte>(bufferModel)); GC.KeepAlive(bufferCfg); GC.KeepAlive(bufferModel); return ret; } /// <summary> /// Reads a network model stored in Caffe model files from memory. /// </summary> /// <param name="bufferCfg">A buffer contains a content of .cfg file with text description of the network architecture.</param> /// <param name="bufferModel">A buffer contains a content of .weights file with learned network.</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createCaffeImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromDarknet(ReadOnlySpan<byte> bufferCfg, ReadOnlySpan<byte> bufferModel = default) { if (bufferCfg.IsEmpty) throw new ArgumentException("Empty span", nameof(bufferCfg)); unsafe { fixed (byte* bufferCfgPtr = bufferCfg) fixed (byte* bufferModelPtr = bufferModel) { NativeMethods.HandleException( NativeMethods.dnn_readNetFromDarknet( bufferCfgPtr, new IntPtr(bufferCfg.Length), bufferModelPtr, new IntPtr(bufferModel.Length), out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } } } /// <summary> /// Reads a network model stored in Caffe model files. /// </summary> /// <param name="prototxt">path to the .prototxt file with text description of the network architecture.</param> /// <param name="caffeModel">path to the .caffemodel file with learned network.</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createCaffeImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromCaffe(string prototxt, string? caffeModel = null) { if (prototxt == null) throw new ArgumentNullException(nameof(prototxt)); NativeMethods.HandleException( NativeMethods.dnn_readNetFromCaffe(prototxt, caffeModel, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Reads a network model stored in Caffe model in memory. /// </summary> /// <param name="bufferProto">buffer containing the content of the .prototxt file</param> /// <param name="bufferModel">buffer containing the content of the .caffemodel file</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createCaffeImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromCaffe(byte[] bufferProto, byte[]? bufferModel = null) { if (bufferProto == null) throw new ArgumentNullException(nameof(bufferProto)); var ret = ReadNetFromCaffe( new ReadOnlySpan<byte>(bufferProto), bufferModel == null ? ReadOnlySpan<byte>.Empty : new ReadOnlySpan<byte>(bufferModel)); GC.KeepAlive(bufferProto); GC.KeepAlive(bufferModel); return ret; } /// <summary> /// Reads a network model stored in Caffe model files from memory. /// </summary> /// <param name="bufferProto">buffer containing the content of the .prototxt file</param> /// <param name="bufferModel">buffer containing the content of the .caffemodel file</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createCaffeImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromCaffe(ReadOnlySpan<byte> bufferProto, ReadOnlySpan<byte> bufferModel = default) { if (bufferProto.IsEmpty) throw new ArgumentException("Empty span", nameof(bufferProto)); unsafe { fixed (byte* bufferProtoPtr = bufferProto) fixed (byte* bufferModelPtr = bufferModel) { NativeMethods.HandleException( NativeMethods.dnn_readNetFromCaffe( bufferProtoPtr, new IntPtr(bufferProto.Length), bufferModelPtr, new IntPtr(bufferModel.Length), out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } } } /// <summary> /// Reads a network model stored in Tensorflow model file. /// </summary> /// <param name="model">path to the .pb file with binary protobuf description of the network architecture</param> /// <param name="config">path to the .pbtxt file that contains text graph definition in protobuf format.</param> /// <returns>Resulting Net object is built by text graph using weights from a binary one that /// let us make it more flexible.</returns> /// <remarks>This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromTensorflow(string model, string? config = null) { if (model == null) throw new ArgumentNullException(nameof(model)); NativeMethods.HandleException( NativeMethods.dnn_readNetFromTensorflow(model, config, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Reads a network model stored in Tensorflow model from memory. /// </summary> /// <param name="bufferModel">buffer containing the content of the pb file</param> /// <param name="bufferConfig">buffer containing the content of the pbtxt file (optional)</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromTensorflow(byte[] bufferModel, byte[]? bufferConfig = null) { if (bufferModel == null) throw new ArgumentNullException(nameof(bufferModel)); var ret = ReadNetFromTensorflow( new ReadOnlySpan<byte>(bufferModel), bufferConfig == null ? ReadOnlySpan<byte>.Empty : new ReadOnlySpan<byte>(bufferConfig)); GC.KeepAlive(bufferModel); GC.KeepAlive(bufferConfig); return ret; } /// <summary> /// Reads a network model stored in Tensorflow model from memory. /// </summary> /// <param name="bufferModel">buffer containing the content of the pb file</param> /// <param name="bufferConfig">buffer containing the content of the pbtxt file (optional)</param> /// <returns></returns> /// <remarks>This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromTensorflow(ReadOnlySpan<byte> bufferModel, ReadOnlySpan<byte> bufferConfig = default) { if (bufferModel.IsEmpty) throw new ArgumentException("Empty span", nameof(bufferModel)); unsafe { fixed (byte* bufferModelPtr = bufferModel) fixed (byte* bufferConfigPtr = bufferConfig) { NativeMethods.HandleException( NativeMethods.dnn_readNetFromTensorflow( bufferModelPtr, new IntPtr(bufferModel.Length), bufferConfigPtr, new IntPtr(bufferConfig.Length), out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } } } /// <summary> /// Reads a network model stored in Torch model file. /// </summary> /// <param name="model"></param> /// <param name="isBinary"></param> /// <returns></returns> /// <remarks>This is shortcut consisting from createTorchImporter and Net::populateNet calls.</remarks> public static Net? ReadNetFromTorch(string model, bool isBinary = true) { if (model == null) throw new ArgumentNullException(nameof(model)); NativeMethods.HandleException( NativeMethods.dnn_readNetFromTorch(model, isBinary ? 1 : 0, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Read deep learning network represented in one of the supported formats. /// /// This function automatically detects an origin framework of trained model /// and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, /// </summary> /// <param name="model">Binary file contains trained weights. The following file /// * extensions are expected for models from different frameworks: /// * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) /// * * `*.pb` (TensorFlow, https://www.tensorflow.org/) /// * * `*.t7` | `*.net` (Torch, http://torch.ch/) /// * * `*.weights` (Darknet, https://pjreddie.com/darknet/) /// * * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit)</param> /// <param name="config">Text file contains network configuration. It could be a /// * file with the following extensions: /// * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) /// * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) /// * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) /// * * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit)</param> /// <param name="framework">Explicit framework name tag to determine a format.</param> /// <returns></returns> public static Net ReadNet(string model, string config = "", string framework = "") { if (string.IsNullOrEmpty(model)) throw new ArgumentException("message is null or empty", nameof(model)); config ??= ""; framework ??= ""; NativeMethods.HandleException( NativeMethods.dnn_readNet(model, config, framework, out var p)); return new Net(p); } /// <summary> /// Load a network from Intel's Model Optimizer intermediate representation. /// Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine backend. /// </summary> /// <param name="xml">XML configuration file with network's topology.</param> /// <param name="bin">Binary file with trained weights.</param> /// <returns></returns> public static Net? ReadNetFromModelOptimizer(string xml, string bin) { if (xml == null) throw new ArgumentNullException(nameof(xml)); if (bin == null) throw new ArgumentNullException(nameof(bin)); NativeMethods.HandleException( NativeMethods.dnn_readNetFromModelOptimizer(xml, bin, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Reads a network model ONNX https://onnx.ai/ /// </summary> /// <param name="onnxFile">path to the .onnx file with text description of the network architecture.</param> /// <returns>Network object that ready to do forward, throw an exception in failure cases.</returns> // ReSharper disable once InconsistentNaming public static Net? ReadNetFromONNX(string onnxFile) { if (onnxFile == null) throw new ArgumentNullException(nameof(onnxFile)); NativeMethods.HandleException( NativeMethods.dnn_readNetFromONNX(onnxFile, out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } /// <summary> /// Reads a network model ONNX https://onnx.ai/ from memory /// </summary> /// <param name="onnxFileData">memory of the first byte of the buffer.</param> /// <returns>Network object that ready to do forward, throw an exception in failure cases.</returns> // ReSharper disable once InconsistentNaming public static Net? ReadNetFromONNX(byte[] onnxFileData) { if (onnxFileData == null) throw new ArgumentNullException(nameof(onnxFileData)); var ret = ReadNetFromONNX( new ReadOnlySpan<byte>(onnxFileData)); GC.KeepAlive(onnxFileData); return ret; } /// <summary> /// Reads a network model ONNX https://onnx.ai/ from memory /// </summary> /// <param name="onnxFileData">memory of the first byte of the buffer.</param> /// <returns>Network object that ready to do forward, throw an exception in failure cases.</returns> // ReSharper disable once InconsistentNaming public static Net? ReadNetFromONNX(ReadOnlySpan<byte> onnxFileData) { if (onnxFileData.IsEmpty) throw new ArgumentException("Empty span", nameof(onnxFileData)); unsafe { fixed (byte* onnxFileDataPtr = onnxFileData) { NativeMethods.HandleException( NativeMethods.dnn_readNetFromONNX( onnxFileDataPtr, new IntPtr(onnxFileData.Length), out var p)); return (p == IntPtr.Zero) ? null : new Net(p); } } } #endregion #region Methods /// <summary> /// Returns true if there are no layers in the network. /// </summary> /// <returns></returns> public bool Empty() { ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.dnn_Net_empty(ptr, out var ret)); GC.KeepAlive(this); return ret != 0; } /// <summary> /// Dump net to String. /// Call method after setInput(). To see correct backend, target and fusion run after forward(). /// </summary> /// <returns>String with structure, hyperparameters, backend, target and fusion</returns> public string Dump() { ThrowIfDisposed(); using var stdString = new StdString(); NativeMethods.HandleException( NativeMethods.dnn_Net_dump(ptr, stdString.CvPtr)); GC.KeepAlive(this); return stdString.ToString(); } /// <summary> /// Dump net structure, hyperparameters, backend, target and fusion to dot file /// </summary> /// <param name="path">path to output file with .dot extension</param> public void DumpToFile(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); NativeMethods.HandleException( NativeMethods.dnn_Net_dumpToFile(ptr, path)); GC.KeepAlive(this); } /// <summary> /// Converts string name of the layer to the integer identifier. /// </summary> /// <param name="layer"></param> /// <returns>id of the layer, or -1 if the layer wasn't found.</returns> public int GetLayerId(string layer) { if (layer == null) throw new ArgumentNullException(nameof(layer)); ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.dnn_Net_getLayerId(ptr, layer, out var ret)); GC.KeepAlive(this); return ret; } /// <summary> /// /// </summary> /// <returns></returns> public string?[] GetLayerNames() { using var namesVec = new VectorOfString(); NativeMethods.HandleException( NativeMethods.dnn_Net_getLayerNames(ptr, namesVec.CvPtr)); GC.KeepAlive(this); return namesVec.ToArray(); } /// <summary> /// Connects output of the first layer to input of the second layer. /// </summary> /// <param name="outPin">descriptor of the first layer output.</param> /// <param name="inpPin">descriptor of the second layer input.</param> public void Connect(string outPin, string inpPin) { if (outPin == null) throw new ArgumentNullException(nameof(outPin)); if (inpPin == null) throw new ArgumentNullException(nameof(inpPin)); NativeMethods.HandleException( NativeMethods.dnn_Net_connect1(ptr, outPin, inpPin)); GC.KeepAlive(this); } /// <summary> /// Connects #@p outNum output of the first layer to #@p inNum input of the second layer. /// </summary> /// <param name="outLayerId">identifier of the first layer</param> /// <param name="outNum">identifier of the second layer</param> /// <param name="inpLayerId">number of the first layer output</param> /// <param name="inpNum">number of the second layer input</param> public void Connect(int outLayerId, int outNum, int inpLayerId, int inpNum) { NativeMethods.HandleException( NativeMethods.dnn_Net_connect2(ptr, outLayerId, outNum, inpLayerId, inpNum)); GC.KeepAlive(this); } /// <summary> /// Sets outputs names of the network input pseudo layer. /// </summary> /// <param name="inputBlobNames"></param> /// <remarks> /// * Each net always has special own the network input pseudo layer with id=0. /// * This layer stores the user blobs only and don't make any computations. /// * In fact, this layer provides the only way to pass user data into the network. /// * As any other layer, this layer can label its outputs and this function provides an easy way to do this. /// </remarks> public void SetInputsNames(IEnumerable<string> inputBlobNames) { if (inputBlobNames == null) throw new ArgumentNullException(nameof(inputBlobNames)); var inputBlobNamesArray = inputBlobNames.ToArray(); NativeMethods.HandleException( NativeMethods.dnn_Net_setInputsNames(ptr, inputBlobNamesArray, inputBlobNamesArray.Length)); GC.KeepAlive(this); } /// <summary> /// Runs forward pass to compute output of layer with name @p outputName. /// By default runs forward pass for the whole network. /// </summary> /// <param name="outputName">name for layer which output is needed to get</param> /// <returns>blob for first output of specified layer.</returns> public Mat Forward(string? outputName = null) { NativeMethods.HandleException( NativeMethods.dnn_Net_forward1(ptr, outputName, out var ret)); GC.KeepAlive(this); return new Mat(ret); } /// <summary> /// Runs forward pass to compute output of layer with name @p outputName. /// </summary> /// <param name="outputBlobs">contains all output blobs for specified layer.</param> /// <param name="outputName">name for layer which output is needed to get. /// If outputName is empty, runs forward pass for the whole network.</param> public void Forward(IEnumerable<Mat> outputBlobs, string? outputName = null) { if (outputBlobs == null) throw new ArgumentNullException(nameof(outputBlobs)); var outputBlobsPtrs = outputBlobs.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( NativeMethods.dnn_Net_forward2(ptr, outputBlobsPtrs, outputBlobsPtrs.Length, outputName)); GC.KeepAlive(outputBlobs); GC.KeepAlive(this); } /// <summary> /// Runs forward pass to compute outputs of layers listed in @p outBlobNames. /// </summary> /// <param name="outputBlobs">contains blobs for first outputs of specified layers.</param> /// <param name="outBlobNames">names for layers which outputs are needed to get</param> public void Forward(IEnumerable<Mat> outputBlobs, IEnumerable<string> outBlobNames) { if (outputBlobs == null) throw new ArgumentNullException(nameof(outputBlobs)); if (outBlobNames == null) throw new ArgumentNullException(nameof(outBlobNames)); var outputBlobsPtrs = outputBlobs.Select(x => x.CvPtr).ToArray(); var outBlobNamesArray = outBlobNames.ToArray(); NativeMethods.HandleException( NativeMethods.dnn_Net_forward3( ptr, outputBlobsPtrs, outputBlobsPtrs.Length, outBlobNamesArray, outBlobNamesArray.Length)); GC.KeepAlive(outputBlobs); GC.KeepAlive(this); } /// <summary> /// Compile Halide layers. /// Schedule layers that support Halide backend. Then compile them for /// specific target.For layers that not represented in scheduling file /// or if no manual scheduling used at all, automatic scheduling will be applied. /// </summary> /// <param name="scheduler">Path to YAML file with scheduling directives.</param> public void SetHalideScheduler(string scheduler) { ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.dnn_Net_setHalideScheduler(ptr, scheduler)); GC.KeepAlive(this); } /// <summary> /// Ask network to use specific computation backend where it supported. /// </summary> /// <param name="backendId">backend identifier.</param> public void SetPreferableBackend(Backend backendId) { ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.dnn_Net_setPreferableBackend(ptr, (int)backendId)); GC.KeepAlive(this); } /// <summary> /// Ask network to make computations on specific target device. /// </summary> /// <param name="targetId">target identifier.</param> public void SetPreferableTarget(Target targetId) { ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.dnn_Net_setPreferableTarget(ptr, (int)targetId)); GC.KeepAlive(this); } /// <summary> /// Sets the new value for the layer output blob /// </summary> /// <param name="blob">new blob.</param> /// <param name="name">descriptor of the updating layer output blob.</param> /// <remarks> /// connect(String, String) to know format of the descriptor. /// If updating blob is not empty then @p blob must have the same shape, /// because network reshaping is not implemented yet. /// </remarks> public void SetInput(Mat blob, string name = "") { if (blob == null) throw new ArgumentNullException(nameof(blob)); NativeMethods.HandleException( NativeMethods.dnn_Net_setInput(ptr, blob.CvPtr, name)); GC.KeepAlive(this); } /// <summary> /// Returns indexes of layers with unconnected outputs. /// </summary> /// <returns></returns> public int[] GetUnconnectedOutLayers() { ThrowIfDisposed(); using var resultVec = new VectorOfInt32(); NativeMethods.HandleException( NativeMethods.dnn_Net_getUnconnectedOutLayers(ptr, resultVec.CvPtr)); GC.KeepAlive(this); return resultVec.ToArray(); } /// <summary> /// Returns names of layers with unconnected outputs. /// </summary> /// <returns></returns> public string?[] GetUnconnectedOutLayersNames() { ThrowIfDisposed(); using var resultVec = new VectorOfString(); NativeMethods.HandleException( NativeMethods.dnn_Net_getUnconnectedOutLayersNames(ptr, resultVec.CvPtr)); GC.KeepAlive(this); return resultVec.ToArray(); } /// <summary> /// Enables or disables layer fusion in the network. /// </summary> /// <param name="fusion">true to enable the fusion, false to disable. The fusion is enabled by default.</param> public void EnableFusion(bool fusion) { ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.dnn_Net_enableFusion(ptr, fusion ? 1 : 0)); GC.KeepAlive(this); } /// <summary> /// Returns overall time for inference and timings (in ticks) for layers. /// Indexes in returned vector correspond to layers ids.Some layers can be fused with others, /// in this case zero ticks count will be return for that skipped layers. /// </summary> /// <param name="timings">vector for tick timings for all layers.</param> /// <returns>overall ticks for model inference.</returns> public long GetPerfProfile(out double[] timings) { ThrowIfDisposed(); using var timingsVec = new VectorOfDouble(); NativeMethods.HandleException( NativeMethods.dnn_Net_getPerfProfile(ptr, timingsVec.CvPtr, out var ret)); GC.KeepAlive(this); timings = timingsVec.ToArray(); return ret; } #endregion } }
namespace Epi.Windows.Analysis.Dialogs { partial class ComplexSampleFrequencyDialog { /// <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(ComplexSampleFrequencyDialog)); this.pbxFreq = new System.Windows.Forms.PictureBox(); this.cmbWeight = new System.Windows.Forms.ComboBox(); this.lblWeight = new System.Windows.Forms.Label(); this.lblOutput = new System.Windows.Forms.Label(); this.txtOutput = new System.Windows.Forms.TextBox(); this.cmbVariables = new System.Windows.Forms.ComboBox(); this.lblFreqOf = new System.Windows.Forms.Label(); this.cmbStratifyBy = new System.Windows.Forms.ComboBox(); this.lblStratifyBy = new System.Windows.Forms.Label(); this.cbxAllExcept = new System.Windows.Forms.CheckBox(); this.lbxVariables = new System.Windows.Forms.ListBox(); this.lbxStratifyBy = new System.Windows.Forms.ListBox(); this.btnHelp = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.btnSettings = new System.Windows.Forms.Button(); this.cmbPSU = new System.Windows.Forms.ComboBox(); this.lblPSU = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pbxFreq)).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, ""); // // pbxFreq // resources.ApplyResources(this.pbxFreq, "pbxFreq"); this.pbxFreq.Name = "pbxFreq"; this.pbxFreq.TabStop = false; // // 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); // // lblWeight // this.lblWeight.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblWeight, "lblWeight"); this.lblWeight.Name = "lblWeight"; // // 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"; // // cmbVariables // this.cmbVariables.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbVariables.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbVariables.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbVariables, "cmbVariables"); this.cmbVariables.Name = "cmbVariables"; this.cmbVariables.Sorted = true; this.cmbVariables.SelectedIndexChanged += new System.EventHandler(this.cmbVariables_SelectedIndexChanged); // // lblFreqOf // this.lblFreqOf.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblFreqOf, "lblFreqOf"); this.lblFreqOf.Name = "lblFreqOf"; // // 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"; // // cbxAllExcept // resources.ApplyResources(this.cbxAllExcept, "cbxAllExcept"); this.cbxAllExcept.Name = "cbxAllExcept"; // // lbxVariables // resources.ApplyResources(this.lbxVariables, "lbxVariables"); this.lbxVariables.Name = "lbxVariables"; this.lbxVariables.TabStop = false; this.lbxVariables.SelectedIndexChanged += new System.EventHandler(this.lbxVariables_SelectedIndexChanged); // // lbxStratifyBy // resources.ApplyResources(this.lbxStratifyBy, "lbxStratifyBy"); this.lbxStratifyBy.Name = "lbxStratifyBy"; this.lbxStratifyBy.TabStop = false; this.lbxStratifyBy.SelectedIndexChanged += new System.EventHandler(this.lbxStratifyBy_SelectedIndexChanged); // // 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); // // 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"; // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // 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"; // // ComplexSampleFrequencyDialog // 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.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.lbxStratifyBy); this.Controls.Add(this.lbxVariables); this.Controls.Add(this.cbxAllExcept); this.Controls.Add(this.cmbStratifyBy); this.Controls.Add(this.lblStratifyBy); this.Controls.Add(this.cmbVariables); this.Controls.Add(this.lblFreqOf); this.Controls.Add(this.lblOutput); this.Controls.Add(this.txtOutput); this.Controls.Add(this.cmbWeight); this.Controls.Add(this.lblWeight); this.Controls.Add(this.pbxFreq); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ComplexSampleFrequencyDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.ComplexSampleFrequencyDialog_Load); ((System.ComponentModel.ISupportInitialize)(this.pbxFreq)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pbxFreq; private System.Windows.Forms.ComboBox cmbWeight; private System.Windows.Forms.Label lblWeight; private System.Windows.Forms.Label lblOutput; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.ComboBox cmbVariables; private System.Windows.Forms.Label lblFreqOf; private System.Windows.Forms.ComboBox cmbStratifyBy; private System.Windows.Forms.Label lblStratifyBy; private System.Windows.Forms.ListBox lbxVariables; private System.Windows.Forms.ListBox lbxStratifyBy; 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.Button btnSaveOnly; private System.Windows.Forms.CheckBox cbxAllExcept; private System.Windows.Forms.Button btnSettings; private System.Windows.Forms.ComboBox cmbPSU; private System.Windows.Forms.Label lblPSU; } }
using System; using System.Runtime.Remoting.Messaging; using JetBrains.Annotations; using Kontur.Tracing.Core.Config; using Kontur.Tracing.Core.Impl; namespace Kontur.Tracing.Core { public static class Trace { [NotNull] public static ITraceContext CreateRootContext([NotNull] string contextName, string traceId = null, bool? activate = null) { if (string.IsNullOrEmpty(contextName)) throw new InvalidOperationException("ContextName is empty"); InitializeIfNeeded(); if (!configProvider.GetConfig().IsEnabled) return NoOpTraceContext.Instance; var isSampled = activate ?? tracingEnvironment.TraceSampler.CanSampleTrace(); if (!isSampled) return NoOpTraceContext.Instance; if (string.IsNullOrEmpty(traceId)) traceId = TraceIdGenerator.CreateTraceId(); var rootContextId = TraceIdGenerator.CreateTraceContextId(); var rootContext = new RealTraceContext(traceId, rootContextId, contextName, null, tracingEnvironment, isRoot: true); SetRealTraceContext(rootContext); return rootContext; } [NotNull] public static ITraceContext CreateChildContext([NotNull] string contextName, string contextId = null) { if (string.IsNullOrEmpty(contextName)) throw new InvalidOperationException("ContextName is empty"); var currentContext = TryGetRealTraceContext(); if (currentContext == null) return NoOpTraceContext.Instance; InitializeIfNeeded(); if (!configProvider.GetConfig().IsEnabled) return NoOpTraceContext.Instance; if (string.IsNullOrEmpty(contextId)) contextId = TraceIdGenerator.CreateTraceContextId(); var childContext = new RealTraceContext(currentContext.TraceId, contextId, contextName, currentContext.ContextId, tracingEnvironment, isRoot: false); SetRealTraceContext(childContext); return childContext; } public static ITraceContext CreateChildContext([NotNull] string contextName, [NotNull] string traceId, [NotNull] string parentContextId, bool? activate = null) { if (string.IsNullOrEmpty(contextName)) throw new InvalidOperationException("ContextName is empty"); if (string.IsNullOrEmpty(traceId)) throw new InvalidOperationException("TraceId is empty"); if (string.IsNullOrEmpty(parentContextId)) throw new InvalidOperationException("ParentContextId is empty"); InitializeIfNeeded(); if (!configProvider.GetConfig().IsEnabled) return NoOpTraceContext.Instance; var isSampled = activate ?? tracingEnvironment.TraceSampler.CanSampleTrace(); if (!isSampled) return NoOpTraceContext.Instance; var childContextId = TraceIdGenerator.CreateTraceContextId(); var childContext = new RealTraceContext(traceId, childContextId, contextName, parentContextId, tracingEnvironment, isRoot: false); SetRealTraceContext(childContext); return childContext; } [NotNull] public static ITraceContext ContinueContext([NotNull] string traceId, [NotNull] string contextId, bool isActive, bool isRoot) { if (!isActive) return NoOpTraceContext.Instance; if (string.IsNullOrEmpty(traceId)) throw new InvalidOperationException("TraceId is empty"); if (string.IsNullOrEmpty(contextId)) throw new InvalidOperationException("ContextId is empty"); InitializeIfNeeded(); if (!configProvider.GetConfig().IsEnabled) return NoOpTraceContext.Instance; var currentContext = new RealTraceContext(traceId, contextId, null, null, tracingEnvironment, isRoot); SetRealTraceContext(currentContext); return currentContext; } public static void FinishCurrentContext() { var currentContext = TryGetRealTraceContext(); if (currentContext == null) return; InitializeIfNeeded(); if (!configProvider.GetConfig().IsEnabled) return; currentContext.Finish(); } internal static void PopRealTraceContext([CanBeNull] RealTraceContext previousContext) { SetRealTraceContext(previousContext); } [CanBeNull] private static RealTraceContext TryGetRealTraceContext() { return (RealTraceContext)CallContext.LogicalGetData(realTraceContextStorageKey); } private static void SetRealTraceContext([CanBeNull] RealTraceContext newCurrentContext) { if (newCurrentContext == null) { CallContext.FreeNamedDataSlot(AnnotatorStorageKey); CallContext.FreeNamedDataSlot(realTraceContextStorageKey); CallContext.FreeNamedDataSlot(dTraceIdPublicStorageKey); } else { CallContext.LogicalSetData(AnnotatorStorageKey, newCurrentContext); CallContext.LogicalSetData(realTraceContextStorageKey, newCurrentContext); CallContext.LogicalSetData(dTraceIdPublicStorageKey, newCurrentContext.TraceId); } } public static bool IsInitialized { get { return isInitialized; } } public static void Initialize([NotNull] IConfigurationProvider theConfigProvider) { Initialize(theConfigProvider, null); } internal static void Initialize([NotNull] IConfigurationProvider theConfigProvider, [CanBeNull] ITracingEnvironment theTracingEnvironment) { lock (initializationSync) { if (isInitialized) throw new InvalidOperationException(string.Format("Tracing system is already initialized with configuration provider of type '{0}'!", configProvider.GetType().FullName)); DoInitialize(theConfigProvider, theTracingEnvironment); } } private static void InitializeIfNeeded() { if (isInitialized) return; lock (initializationSync) { if (!isInitialized) DoInitialize(null, null); } } private static void DoInitialize([CanBeNull] IConfigurationProvider theConfigProvider, [CanBeNull] ITracingEnvironment theTracingEnvironment) { configProvider = theConfigProvider ?? StaticConfigurationProvider.Disabled; if (configProvider.GetConfig().IsEnabled == false) return; tracingEnvironment = theTracingEnvironment ?? new TracingEnvironment(); tracingEnvironment.Start(configProvider); isInitialized = true; } public static void Stop() { lock (initializationSync) { if (!isInitialized) return; tracingEnvironment.Stop(); tracingEnvironment = null; configProvider = null; isInitialized = false; } } public static readonly string AnnotatorStorageKey = Guid.NewGuid().ToString(); private static readonly string realTraceContextStorageKey = Guid.NewGuid().ToString(); // dTraceIdPublicStorageKey is shared with log4stash library private const string dTraceIdPublicStorageKey = "DTraceId-PublicStorageKey-33115BA6-3CC9-4BC5-A540-D2EA133B0B7F"; private static IConfigurationProvider configProvider; private static ITracingEnvironment tracingEnvironment; private static readonly object initializationSync = new object(); private static volatile bool isInitialized; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; namespace System { // Provides Unix-based support for System.Console. // // NOTE: The test class reflects over this class to run the tests due to limitations in // the test infrastructure that prevent OS-specific builds of test binaries. If you // change any of the class / struct / function names, parameters, etc then you need // to also change the test class. internal static class ConsolePal { public static Stream OpenStandardInput() { return new UnixConsoleStream(SafeFileHandle.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDIN_FILENO)), FileAccess.Read); } public static Stream OpenStandardOutput() { return new UnixConsoleStream(SafeFileHandle.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDOUT_FILENO)), FileAccess.Write); } public static Stream OpenStandardError() { return new UnixConsoleStream(SafeFileHandle.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDERR_FILENO)), FileAccess.Write); } public static Encoding InputEncoding { get { return GetConsoleEncoding(); } } public static Encoding OutputEncoding { get { return GetConsoleEncoding(); } } private static SyncTextReader s_stdInReader; private const int DefaultBufferSize = 255; private static SyncTextReader StdInReader { get { EnsureInitialized(); return Volatile.Read(ref s_stdInReader) ?? Console.EnsureInitialized( ref s_stdInReader, () => SyncTextReader.GetSynchronizedTextReader( new StdInReader( encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream. bufferSize: DefaultBufferSize))); } } private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers internal static TextReader GetOrCreateReader() { if (Console.IsInputRedirected) { Stream inputStream = OpenStandardInput(); return SyncTextReader.GetSynchronizedTextReader( inputStream == Stream.Null ? StreamReader.Null : new StreamReader( stream: inputStream, encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream. detectEncodingFromByteOrderMarks: false, bufferSize: DefaultConsoleBufferSize, leaveOpen: true) ); } else { return StdInReader; } } public static bool KeyAvailable { get { return StdInReader.KeyAvailable; } } public static ConsoleKeyInfo ReadKey(bool intercept) { if (Console.IsInputRedirected) { // We could leverage Console.Read() here however // windows fails when stdin is redirected. throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile); } bool previouslyProcessed; ConsoleKeyInfo keyInfo = StdInReader.ReadKey(out previouslyProcessed); if (!intercept && !previouslyProcessed) Console.Write(keyInfo.KeyChar); return keyInfo; } public static bool TreatControlCAsInput { get { if (Console.IsInputRedirected) return false; EnsureInitialized(); return !Interop.Sys.GetSignalForBreak(); } set { if (!Console.IsInputRedirected) { EnsureInitialized(); if (!Interop.Sys.SetSignalForBreak(signalForBreak: !value)) throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo()); } } } private static ConsoleColor s_trackedForegroundColor = Console.UnknownColor; private static ConsoleColor s_trackedBackgroundColor = Console.UnknownColor; public static ConsoleColor ForegroundColor { get { return s_trackedForegroundColor; } set { RefreshColors(ref s_trackedForegroundColor, value); } } public static ConsoleColor BackgroundColor { get { return s_trackedBackgroundColor; } set { RefreshColors(ref s_trackedBackgroundColor, value); } } public static void ResetColor() { lock (Console.Out) // synchronize with other writers { s_trackedForegroundColor = Console.UnknownColor; s_trackedBackgroundColor = Console.UnknownColor; WriteResetColorString(); } } public static bool NumberLock { get { throw new PlatformNotSupportedException(); } } public static bool CapsLock { get { throw new PlatformNotSupportedException(); } } public static int CursorSize { get { return 100; } set { throw new PlatformNotSupportedException(); } } public static string Title { get { throw new PlatformNotSupportedException(); } set { if (Console.IsOutputRedirected) return; string titleFormat = TerminalFormatStrings.Instance.Title; if (!string.IsNullOrEmpty(titleFormat)) { string ansiStr = TermInfo.ParameterizedStrings.Evaluate(titleFormat, value); WriteStdoutAnsiString(ansiStr); } } } public static void Beep() { if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(TerminalFormatStrings.Instance.Bell); } } public static void Beep(int frequency, int duration) { throw new PlatformNotSupportedException(); } public static void Clear() { if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(TerminalFormatStrings.Instance.Clear); } } public static void SetCursorPosition(int left, int top) { if (Console.IsOutputRedirected) return; string cursorAddressFormat = TerminalFormatStrings.Instance.CursorAddress; if (!string.IsNullOrEmpty(cursorAddressFormat)) { string ansiStr = TermInfo.ParameterizedStrings.Evaluate(cursorAddressFormat, top, left); WriteStdoutAnsiString(ansiStr); } } public static int BufferWidth { get { return WindowWidth; } set { throw new PlatformNotSupportedException(); } } public static int BufferHeight { get { return WindowHeight; } set { throw new PlatformNotSupportedException(); } } public static void SetBufferSize(int width, int height) { throw new PlatformNotSupportedException(); } public static int LargestWindowWidth { get { return WindowWidth; } set { throw new PlatformNotSupportedException(); } } public static int LargestWindowHeight { get { return WindowHeight; } set { throw new PlatformNotSupportedException(); } } public static int WindowLeft { get { return 0; } set { throw new PlatformNotSupportedException(); } } public static int WindowTop { get { return 0; } set { throw new PlatformNotSupportedException(); } } public static int WindowWidth { get { Interop.Sys.WinSize winsize; return Interop.Sys.GetWindowSize(out winsize) == 0 ? winsize.Col : TerminalFormatStrings.Instance.Columns; } set { throw new PlatformNotSupportedException(); } } public static int WindowHeight { get { Interop.Sys.WinSize winsize; return Interop.Sys.GetWindowSize(out winsize) == 0 ? winsize.Row : TerminalFormatStrings.Instance.Lines; } set { throw new PlatformNotSupportedException(); } } public static void SetWindowPosition(int left, int top) { throw new PlatformNotSupportedException(); } public static void SetWindowSize(int width, int height) { throw new PlatformNotSupportedException(); } public static bool CursorVisible { get { throw new PlatformNotSupportedException(); } set { if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(value ? TerminalFormatStrings.Instance.CursorVisible : TerminalFormatStrings.Instance.CursorInvisible); } } } // TODO: It's quite expensive to use the request/response protocol each time CursorLeft/Top is accessed. // We should be able to (mostly) track the position of the cursor in locals, doing the request/response infrequently. public static int CursorLeft { get { int left, top; GetCursorPosition(out left, out top); return left; } } public static int CursorTop { get { int left, top; GetCursorPosition(out left, out top); return top; } } /// <summary>Gets the current cursor position. This involves both writing to stdout and reading stdin.</summary> private static unsafe void GetCursorPosition(out int left, out int top) { left = top = 0; // Getting the cursor position involves both writing out a request string and // parsing a response string from the terminal. So if anything is redirected, bail. if (Console.IsInputRedirected || Console.IsOutputRedirected) return; // Get the cursor position request format string. Debug.Assert(!string.IsNullOrEmpty(TerminalFormatStrings.CursorPositionReport)); // Synchronize with all other stdin readers. We need to do this in case multiple threads are // trying to read/write concurrently, and to minimize the chances of resulting conflicts. // This does mean that Console.get_CursorLeft/Top can't be used concurrently Console.Read*, etc.; // attempting to do so will block one of them until the other completes, but in doing so we prevent // one thread's get_CursorLeft/Top from providing input to the other's Console.Read*. lock (StdInReader) { Interop.Sys.InitializeConsoleBeforeRead(minChars: 0, decisecondsTimeout: 10); try { // Write out the cursor position report request. WriteStdoutAnsiString(TerminalFormatStrings.CursorPositionReport); // Read the response. There's a race condition here if the user is typing, // or if other threads are accessing the console; there's relatively little // we can do about that, but we try not to lose any data. StdInReader r = StdInReader.Inner; const int BufferSize = 1024; byte* bytes = stackalloc byte[BufferSize]; int bytesRead = 0, i = 0; // Response expected in the form "\ESC[row;colR". However, user typing concurrently // with the request/response sequence can result in other characters, and potentially // other escape sequences (e.g. for an arrow key) being entered concurrently with // the response. To avoid garbage showing up in the user's input, we are very liberal // with regards to eating all input from this point until all aspects of the sequence // have been consumed. // Find the ESC as the start of the sequence. if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => b == 0x1B)) return; i++; // move past the ESC // Find the '[' if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => b == '[')) return; // Find the first Int32 and parse it. if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => IsDigit((char)b))) return; int row = ParseInt32(bytes, bytesRead, ref i); if (row >= 1) top = row - 1; // Find the second Int32 and parse it. if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => IsDigit((char)b))) return; int col = ParseInt32(bytes, bytesRead, ref i); if (col >= 1) left = col - 1; // Find the ending 'R' if (!ReadStdinUntil(r, bytes, BufferSize, ref bytesRead, ref i, b => b == 'R')) return; } finally { Interop.Sys.UninitializeConsoleAfterRead(); } } } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { throw new PlatformNotSupportedException(); } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { throw new PlatformNotSupportedException(); } /// <summary>Reads from the stdin reader, unbuffered, until the specified condition is met.</summary> /// <returns>true if the condition was met; otherwise, false.</returns> private static unsafe bool ReadStdinUntil( StdInReader reader, byte* buffer, int bufferSize, ref int bytesRead, ref int pos, Func<byte, bool> condition) { while (true) { for (; pos < bytesRead && !condition(buffer[pos]); pos++) ; if (pos < bytesRead) return true; bytesRead = reader.ReadStdin(buffer, bufferSize); if (bytesRead == 0) return false; pos = 0; } } /// <summary>Parses the Int32 at the specified position in the buffer.</summary> /// <param name="buffer">The buffer.</param> /// <param name="bufferSize">The length of the buffer.</param> /// <param name="pos">The current position in the buffer.</param> /// <returns>The parsed result, or 0 if nothing could be parsed.</returns> private static unsafe int ParseInt32(byte* buffer, int bufferSize, ref int pos) { int result = 0; for (; pos < bufferSize; pos++) { char c = (char)buffer[pos]; if (!IsDigit(c)) break; result = (result * 10) + (c - '0'); } return result; } /// <summary>Gets whether the specified character is a digit 0-9.</summary> private static bool IsDigit(char c) { return c >= '0' && c <= '9'; } /// <summary> /// Gets whether the specified file descriptor was redirected. /// It's considered redirected if it doesn't refer to a terminal. /// </summary> private static bool IsHandleRedirected(SafeFileHandle fd) { return !Interop.Sys.IsATty(fd); } /// <summary> /// Gets whether Console.In is redirected. /// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device. /// </summary> public static bool IsInputRedirectedCore() { return IsHandleRedirected(Interop.Sys.FileDescriptors.STDIN_FILENO); } /// <summary>Gets whether Console.Out is redirected. /// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device. /// </summary> public static bool IsOutputRedirectedCore() { return IsHandleRedirected(Interop.Sys.FileDescriptors.STDOUT_FILENO); } /// <summary>Gets whether Console.Error is redirected. /// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device. /// </summary> public static bool IsErrorRedirectedCore() { return IsHandleRedirected(Interop.Sys.FileDescriptors.STDERR_FILENO); } /// <summary>Creates an encoding from the current environment.</summary> /// <returns>The encoding.</returns> private static Encoding GetConsoleEncoding() { Encoding enc = EncodingHelper.GetEncodingFromCharset(); return enc ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); } public static void SetConsoleInputEncoding(Encoding enc) { // No-op. // There is no good way to set the terminal console encoding. } public static void SetConsoleOutputEncoding(Encoding enc) { // No-op. // There is no good way to set the terminal console encoding. } /// <summary> /// Refreshes the foreground and background colors in use by the terminal by resetting /// the colors and then reissuing commands for both foreground and background, if necessary. /// Before doing so, the <paramref name="toChange"/> ref is changed to <paramref name="value"/> /// if <paramref name="value"/> is valid. /// </summary> private static void RefreshColors(ref ConsoleColor toChange, ConsoleColor value) { if (((int)value & ~0xF) != 0 && value != Console.UnknownColor) { throw new ArgumentException(SR.Arg_InvalidConsoleColor); } lock (Console.Out) { toChange = value; // toChange is either s_trackedForegroundColor or s_trackedBackgroundColor WriteResetColorString(); if (s_trackedForegroundColor != Console.UnknownColor) { WriteSetColorString(foreground: true, color: s_trackedForegroundColor); } if (s_trackedBackgroundColor != Console.UnknownColor) { WriteSetColorString(foreground: false, color: s_trackedBackgroundColor); } } } /// <summary>Outputs the format string evaluated and parameterized with the color.</summary> /// <param name="foreground">true for foreground; false for background.</param> /// <param name="color">The color to store into the field and to use as an argument to the format string.</param> private static void WriteSetColorString(bool foreground, ConsoleColor color) { // Changing the color involves writing an ANSI character sequence out to the output stream. // We only want to do this if we know that sequence will be interpreted by the output. // rather than simply displayed visibly. if (Console.IsOutputRedirected) return; // See if we've already cached a format string for this foreground/background // and specific color choice. If we have, just output that format string again. int fgbgIndex = foreground ? 0 : 1; int ccValue = (int)color; string evaluatedString = s_fgbgAndColorStrings[fgbgIndex, ccValue]; // benign race if (evaluatedString != null) { WriteStdoutAnsiString(evaluatedString); return; } // We haven't yet computed a format string. Compute it, use it, then cache it. string formatString = foreground ? TerminalFormatStrings.Instance.Foreground : TerminalFormatStrings.Instance.Background; if (!string.IsNullOrEmpty(formatString)) { int maxColors = TerminalFormatStrings.Instance.MaxColors; // often 8 or 16; 0 is invalid if (maxColors > 0) { int ansiCode = _consoleColorToAnsiCode[ccValue] % maxColors; evaluatedString = TermInfo.ParameterizedStrings.Evaluate(formatString, ansiCode); WriteStdoutAnsiString(evaluatedString); s_fgbgAndColorStrings[fgbgIndex, ccValue] = evaluatedString; // benign race } } } /// <summary>Writes out the ANSI string to reset colors.</summary> private static void WriteResetColorString() { // We only want to send the reset string if we're targeting a TTY device if (!Console.IsOutputRedirected) { WriteStdoutAnsiString(TerminalFormatStrings.Instance.Reset); } } /// <summary> /// The values of the ConsoleColor enums unfortunately don't map to the /// corresponding ANSI values. We need to do the mapping manually. /// See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors /// </summary> private static readonly int[] _consoleColorToAnsiCode = new int[] { // Dark/Normal colors 0, // Black, 4, // DarkBlue, 2, // DarkGreen, 6, // DarkCyan, 1, // DarkRed, 5, // DarkMagenta, 3, // DarkYellow, 7, // Gray, // Bright colors 8, // DarkGray, 12, // Blue, 10, // Green, 14, // Cyan, 9, // Red, 13, // Magenta, 11, // Yellow, 15 // White }; /// <summary>Cache of the format strings for foreground/background and ConsoleColor.</summary> private static readonly string[,] s_fgbgAndColorStrings = new string[2, 16]; // 2 == fg vs bg, 16 == ConsoleColor values public static bool TryGetSpecialConsoleKey(char[] givenChars, int startIndex, int endIndex, out ConsoleKeyInfo key, out int keyLength) { int unprocessedCharCount = endIndex - startIndex; // First process special control character codes. These override anything from terminfo. if (unprocessedCharCount > 0) { // Is this an erase / backspace? char c = givenChars[startIndex]; if (c != s_posixDisableValue && c == s_veraseCharacter) { key = new ConsoleKeyInfo(c, ConsoleKey.Backspace, shift: false, alt: false, control: false); keyLength = 1; return true; } } // Then process terminfo mappings. int minRange = TerminalFormatStrings.Instance.MinKeyFormatLength; if (unprocessedCharCount >= minRange) { int maxRange = Math.Min(unprocessedCharCount, TerminalFormatStrings.Instance.MaxKeyFormatLength); for (int i = maxRange; i >= minRange; i--) { var currentString = new StringOrCharArray(givenChars, startIndex, i); // Check if the string prefix matches. if (TerminalFormatStrings.Instance.KeyFormatToConsoleKey.TryGetValue(currentString, out key)) { keyLength = currentString.Length; return true; } } } // Otherwise, not a known special console key. key = default(ConsoleKeyInfo); keyLength = 0; return false; } /// <summary>Whether keypad_xmit has already been written out to the terminal.</summary> private static volatile bool s_initialized; /// <summary>Value used to indicate that a special character code isn't available.</summary> internal static byte s_posixDisableValue; /// <summary>Special control character code used to represent an erase (backspace).</summary> private static byte s_veraseCharacter; /// <summary>Special control character that represents the end of a line.</summary> internal static byte s_veolCharacter; /// <summary>Special control character that represents the end of a line.</summary> internal static byte s_veol2Character; /// <summary>Special control character that represents the end of a file.</summary> internal static byte s_veofCharacter; /// <summary>Ensures that the console has been initialized for use.</summary> private static void EnsureInitialized() { if (!s_initialized) { EnsureInitializedCore(); // factored out for inlinability } } /// <summary>Ensures that the console has been initialized for use.</summary> private static void EnsureInitializedCore() { lock (Console.Out) // ensure that writing the ANSI string and setting initialized to true are done atomically { if (!s_initialized) { // Ensure the console is configured appropriately. This will start // signal handlers, etc. if (!Interop.Sys.InitializeConsole()) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo()); } // Provide the native lib with the correct code from the terminfo to transition us into // "application mode". This will both transition it immediately, as well as allow // the native lib later to handle signals that require re-entering the mode. if (!Console.IsOutputRedirected) { string keypadXmit = TerminalFormatStrings.Instance.KeypadXmit; if (keypadXmit != null) { Interop.Sys.SetKeypadXmit(keypadXmit); } } // Load special control character codes used for input processing var controlCharacterNames = new Interop.Sys.ControlCharacterNames[4] { Interop.Sys.ControlCharacterNames.VERASE, Interop.Sys.ControlCharacterNames.VEOL, Interop.Sys.ControlCharacterNames.VEOL2, Interop.Sys.ControlCharacterNames.VEOF }; var controlCharacterValues = new byte[controlCharacterNames.Length]; Interop.Sys.GetControlCharacters(controlCharacterNames, controlCharacterValues, controlCharacterNames.Length, out s_posixDisableValue); s_veraseCharacter = controlCharacterValues[0]; s_veolCharacter = controlCharacterValues[1]; s_veol2Character = controlCharacterValues[2]; s_veofCharacter = controlCharacterValues[3]; // Mark us as initialized s_initialized = true; } } } /// <summary>Provides format strings and related information for use with the current terminal.</summary> internal class TerminalFormatStrings { /// <summary>Gets the lazily-initialized terminal information for the terminal.</summary> public static TerminalFormatStrings Instance { get { return s_instance.Value; } } private readonly static Lazy<TerminalFormatStrings> s_instance = new Lazy<TerminalFormatStrings>(() => new TerminalFormatStrings(TermInfo.Database.ReadActiveDatabase())); /// <summary>The format string to use to change the foreground color.</summary> public readonly string Foreground; /// <summary>The format string to use to change the background color.</summary> public readonly string Background; /// <summary>The format string to use to reset the foreground and background colors.</summary> public readonly string Reset; /// <summary>The maximum number of colors supported by the terminal.</summary> public readonly int MaxColors; /// <summary>The number of columns in a format.</summary> public readonly int Columns; /// <summary>The number of lines in a format.</summary> public readonly int Lines; /// <summary>The format string to use to make cursor visible.</summary> public readonly string CursorVisible; /// <summary>The format string to use to make cursor invisible</summary> public readonly string CursorInvisible; /// <summary>The format string to use to set the window title.</summary> public readonly string Title; /// <summary>The format string to use for an audible bell.</summary> public readonly string Bell; /// <summary>The format string to use to clear the terminal.</summary> public readonly string Clear; /// <summary>The format string to use to set the position of the cursor.</summary> public readonly string CursorAddress; /// <summary>The format string to use to move the cursor to the left.</summary> public readonly string CursorLeft; /// <summary>The ANSI-compatible string for the Cursor Position report request.</summary> /// <remarks> /// This should really be in user string 7 in the terminfo file, but some terminfo databases /// are missing it. As this is defined to be supported by any ANSI-compatible terminal, /// we assume it's available; doing so means CursorTop/Left will work even if the terminfo database /// doesn't contain it (as appears to be the case with e.g. screen and tmux on Ubuntu), at the risk /// of outputting the sequence on some terminal that's not compatible. /// </remarks> public const string CursorPositionReport = "\x1B[6n"; /// <summary> /// The dictionary of keystring to ConsoleKeyInfo. /// Only some members of the ConsoleKeyInfo are used; in particular, the actual char is ignored. /// </summary> public readonly Dictionary<StringOrCharArray, ConsoleKeyInfo> KeyFormatToConsoleKey = new Dictionary<StringOrCharArray, ConsoleKeyInfo>(); /// <summary> Max key length </summary> public readonly int MaxKeyFormatLength; /// <summary> Min key length </summary> public readonly int MinKeyFormatLength; /// <summary>The ANSI string used to enter "application" / "keypad transmit" mode.</summary> public readonly string KeypadXmit; public TerminalFormatStrings(TermInfo.Database db) { if (db == null) return; KeypadXmit = db.GetString(TermInfo.WellKnownStrings.KeypadXmit); Foreground = db.GetString(TermInfo.WellKnownStrings.SetAnsiForeground); Background = db.GetString(TermInfo.WellKnownStrings.SetAnsiBackground); Reset = db.GetString(TermInfo.WellKnownStrings.OrigPairs) ?? db.GetString(TermInfo.WellKnownStrings.OrigColors); Bell = db.GetString(TermInfo.WellKnownStrings.Bell); Clear = db.GetString(TermInfo.WellKnownStrings.Clear); Columns = db.GetNumber(TermInfo.WellKnownNumbers.Columns); Lines = db.GetNumber(TermInfo.WellKnownNumbers.Lines); CursorVisible = db.GetString(TermInfo.WellKnownStrings.CursorVisible); CursorInvisible = db.GetString(TermInfo.WellKnownStrings.CursorInvisible); CursorAddress = db.GetString(TermInfo.WellKnownStrings.CursorAddress); CursorLeft = db.GetString(TermInfo.WellKnownStrings.CursorLeft); Title = GetTitle(db); Debug.WriteLineIf(db.GetString(TermInfo.WellKnownStrings.CursorPositionReport) != CursorPositionReport, "Getting the cursor position will only work if the terminal supports the CPR sequence," + "but the terminfo database does not contain an entry for it."); int maxColors = db.GetNumber(TermInfo.WellKnownNumbers.MaxColors); MaxColors = // normalize to either the full range of all ANSI colors, just the dark ones, or none maxColors >= 16 ? 16 : maxColors >= 8 ? 8 : 0; AddKey(db, TermInfo.WellKnownStrings.KeyF1, ConsoleKey.F1); AddKey(db, TermInfo.WellKnownStrings.KeyF2, ConsoleKey.F2); AddKey(db, TermInfo.WellKnownStrings.KeyF3, ConsoleKey.F3); AddKey(db, TermInfo.WellKnownStrings.KeyF4, ConsoleKey.F4); AddKey(db, TermInfo.WellKnownStrings.KeyF5, ConsoleKey.F5); AddKey(db, TermInfo.WellKnownStrings.KeyF6, ConsoleKey.F6); AddKey(db, TermInfo.WellKnownStrings.KeyF7, ConsoleKey.F7); AddKey(db, TermInfo.WellKnownStrings.KeyF8, ConsoleKey.F8); AddKey(db, TermInfo.WellKnownStrings.KeyF9, ConsoleKey.F9); AddKey(db, TermInfo.WellKnownStrings.KeyF10, ConsoleKey.F10); AddKey(db, TermInfo.WellKnownStrings.KeyF11, ConsoleKey.F11); AddKey(db, TermInfo.WellKnownStrings.KeyF12, ConsoleKey.F12); AddKey(db, TermInfo.WellKnownStrings.KeyF13, ConsoleKey.F13); AddKey(db, TermInfo.WellKnownStrings.KeyF14, ConsoleKey.F14); AddKey(db, TermInfo.WellKnownStrings.KeyF15, ConsoleKey.F15); AddKey(db, TermInfo.WellKnownStrings.KeyF16, ConsoleKey.F16); AddKey(db, TermInfo.WellKnownStrings.KeyF17, ConsoleKey.F17); AddKey(db, TermInfo.WellKnownStrings.KeyF18, ConsoleKey.F18); AddKey(db, TermInfo.WellKnownStrings.KeyF19, ConsoleKey.F19); AddKey(db, TermInfo.WellKnownStrings.KeyF20, ConsoleKey.F20); AddKey(db, TermInfo.WellKnownStrings.KeyF21, ConsoleKey.F21); AddKey(db, TermInfo.WellKnownStrings.KeyF22, ConsoleKey.F22); AddKey(db, TermInfo.WellKnownStrings.KeyF23, ConsoleKey.F23); AddKey(db, TermInfo.WellKnownStrings.KeyF24, ConsoleKey.F24); AddKey(db, TermInfo.WellKnownStrings.KeyBackspace, ConsoleKey.Backspace); AddKey(db, TermInfo.WellKnownStrings.KeyBackTab, ConsoleKey.Tab, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeyBegin, ConsoleKey.Home); AddKey(db, TermInfo.WellKnownStrings.KeyClear, ConsoleKey.Clear); AddKey(db, TermInfo.WellKnownStrings.KeyDelete, ConsoleKey.Delete); AddKey(db, TermInfo.WellKnownStrings.KeyDown, ConsoleKey.DownArrow); AddKey(db, TermInfo.WellKnownStrings.KeyEnd, ConsoleKey.End); AddKey(db, TermInfo.WellKnownStrings.KeyEnter, ConsoleKey.Enter); AddKey(db, TermInfo.WellKnownStrings.KeyHelp, ConsoleKey.Help); AddKey(db, TermInfo.WellKnownStrings.KeyHome, ConsoleKey.Home); AddKey(db, TermInfo.WellKnownStrings.KeyInsert, ConsoleKey.Insert); AddKey(db, TermInfo.WellKnownStrings.KeyLeft, ConsoleKey.LeftArrow); AddKey(db, TermInfo.WellKnownStrings.KeyPageDown, ConsoleKey.PageDown); AddKey(db, TermInfo.WellKnownStrings.KeyPageUp, ConsoleKey.PageUp); AddKey(db, TermInfo.WellKnownStrings.KeyPrint, ConsoleKey.Print); AddKey(db, TermInfo.WellKnownStrings.KeyRight, ConsoleKey.RightArrow); AddKey(db, TermInfo.WellKnownStrings.KeyScrollForward, ConsoleKey.PageDown, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeyScrollReverse, ConsoleKey.PageUp, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySBegin, ConsoleKey.Home, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySDelete, ConsoleKey.Delete, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySHome, ConsoleKey.Home, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySelect, ConsoleKey.Select); AddKey(db, TermInfo.WellKnownStrings.KeySLeft, ConsoleKey.LeftArrow, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySPrint, ConsoleKey.Print, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeySRight, ConsoleKey.RightArrow, shift: true, alt: false, control: false); AddKey(db, TermInfo.WellKnownStrings.KeyUp, ConsoleKey.UpArrow); AddPrefixKey(db, "kLFT", ConsoleKey.LeftArrow); AddPrefixKey(db, "kRIT", ConsoleKey.RightArrow); AddPrefixKey(db, "kUP", ConsoleKey.UpArrow); AddPrefixKey(db, "kDN", ConsoleKey.DownArrow); AddPrefixKey(db, "kDC", ConsoleKey.Delete); AddPrefixKey(db, "kEND", ConsoleKey.End); AddPrefixKey(db, "kHOM", ConsoleKey.Home); AddPrefixKey(db, "kNXT", ConsoleKey.PageDown); AddPrefixKey(db, "kPRV", ConsoleKey.PageUp); if (KeyFormatToConsoleKey.Count > 0) { MaxKeyFormatLength = int.MinValue; MinKeyFormatLength = int.MaxValue; foreach (KeyValuePair<StringOrCharArray, ConsoleKeyInfo> entry in KeyFormatToConsoleKey) { if (entry.Key.Length > MaxKeyFormatLength) { MaxKeyFormatLength = entry.Key.Length; } if (entry.Key.Length < MinKeyFormatLength) { MinKeyFormatLength = entry.Key.Length; } } } } private static string GetTitle(TermInfo.Database db) { // Try to get the format string from tsl/fsl and use it if they're available string tsl = db.GetString(TermInfo.WellKnownStrings.ToStatusLine); string fsl = db.GetString(TermInfo.WellKnownStrings.FromStatusLine); if (tsl != null && fsl != null) { return tsl + "%p1%s" + fsl; } string term = db.Term; if (term == null) { return string.Empty; } if (term.StartsWith("xterm", StringComparison.Ordinal)) // normalize all xterms to enable easier matching { term = "xterm"; } switch (term) { case "aixterm": case "dtterm": case "linux": case "rxvt": case "xterm": return "\x1B]0;%p1%s\x07"; case "cygwin": return "\x1B];%p1%s\x07"; case "konsole": return "\x1B]30;%p1%s\x07"; case "screen": return "\x1Bk%p1%s\x1B"; default: return string.Empty; } } private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key) { AddKey(db, keyId, key, shift: false, alt: false, control: false); } private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key, bool shift, bool alt, bool control) { string keyFormat = db.GetString(keyId); if (!string.IsNullOrEmpty(keyFormat)) KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control); } private void AddPrefixKey(TermInfo.Database db, string extendedNamePrefix, ConsoleKey key) { AddKey(db, extendedNamePrefix + "3", key, shift: false, alt: true, control: false); AddKey(db, extendedNamePrefix + "4", key, shift: true, alt: true, control: false); AddKey(db, extendedNamePrefix + "5", key, shift: false, alt: false, control: true); AddKey(db, extendedNamePrefix + "6", key, shift: true, alt: false, control: true); AddKey(db, extendedNamePrefix + "7", key, shift: false, alt: false, control: true); } private void AddKey(TermInfo.Database db, string extendedName, ConsoleKey key, bool shift, bool alt, bool control) { string keyFormat = db.GetExtendedString(extendedName); if (!string.IsNullOrEmpty(keyFormat)) KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control); } } /// <summary>Reads data from the file descriptor into the buffer.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset at which to start writing into the buffer.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The number of bytes read, or a negative value if there's an error.</returns> internal static unsafe int Read(SafeFileHandle fd, byte[] buffer, int offset, int count) { fixed (byte* bufPtr = buffer) { int result = Interop.CheckIo(Interop.Sys.Read(fd, (byte*)bufPtr + offset, count)); Debug.Assert(result <= count); return result; } } /// <summary>Writes data from the buffer into the file descriptor.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="buffer">The buffer from which to write data.</param> /// <param name="offset">The offset at which the data to write starts in the buffer.</param> /// <param name="count">The number of bytes to write.</param> private static unsafe void Write(SafeFileHandle fd, byte[] buffer, int offset, int count) { fixed (byte* bufPtr = buffer) { Write(fd, bufPtr + offset, count); } } private static unsafe void Write(SafeFileHandle fd, byte* bufPtr, int count) { while (count > 0) { int bytesWritten = Interop.Sys.Write(fd, bufPtr, count); if (bytesWritten < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) { // Broken pipe... likely due to being redirected to a program // that ended, so simply pretend we were successful. return; } else { // Something else... fail. throw Interop.GetExceptionForIoErrno(errorInfo); } } count -= bytesWritten; bufPtr += bytesWritten; } } /// <summary>Writes a terminfo-based ANSI escape string to stdout.</summary> /// <param name="value">The string to write.</param> private static unsafe void WriteStdoutAnsiString(string value) { if (string.IsNullOrEmpty(value)) return; // Except for extremely rare cases, ANSI escape strings should be very short. const int StackAllocThreshold = 256; if (value.Length <= StackAllocThreshold) { int dataLen = Encoding.UTF8.GetMaxByteCount(value.Length); byte* data = stackalloc byte[dataLen]; fixed (char* chars = value) { int bytesToWrite = Encoding.UTF8.GetBytes(chars, value.Length, data, dataLen); Debug.Assert(bytesToWrite <= dataLen); lock (Console.Out) // synchronize with other writers { Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, bytesToWrite); } } } else { byte[] data = Encoding.UTF8.GetBytes(value); lock (Console.Out) // synchronize with other writers { Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, 0, data.Length); } } } /// <summary>Provides a stream to use for Unix console input or output.</summary> private sealed class UnixConsoleStream : ConsoleStream { /// <summary>The file descriptor for the opened file.</summary> private readonly SafeFileHandle _handle; /// <summary>The type of the underlying file descriptor.</summary> internal readonly int _handleType; /// <summary>Initialize the stream.</summary> /// <param name="handle">The file handle wrapped by this stream.</param> /// <param name="access">FileAccess.Read or FileAccess.Write.</param> internal UnixConsoleStream(SafeFileHandle handle, FileAccess access) : base(access) { Debug.Assert(handle != null, "Expected non-null console handle"); Debug.Assert(!handle.IsInvalid, "Expected valid console handle"); _handle = handle; // Determine the type of the descriptor (e.g. regular file, character file, pipe, etc.) Interop.Sys.FileStatus buf; _handleType = Interop.Sys.FStat(_handle, out buf) == 0 ? (buf.Mode & Interop.Sys.FileTypes.S_IFMT) : Interop.Sys.FileTypes.S_IFREG; // if something goes wrong, don't fail, just say it's a regular file } protected override void Dispose(bool disposing) { if (disposing) { _handle.Dispose(); } base.Dispose(disposing); } public override int Read(byte[] buffer, int offset, int count) { ValidateRead(buffer, offset, count); return ConsolePal.Read(_handle, buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { ValidateWrite(buffer, offset, count); ConsolePal.Write(_handle, buffer, offset, count); } public override void Flush() { if (_handle.IsClosed) { throw Error.GetFileNotOpen(); } base.Flush(); } } internal sealed class ControlCHandlerRegistrar { private static readonly Interop.Sys.CtrlCallback _handler = c => Console.HandleBreakEvent(c == Interop.Sys.CtrlCode.Break ? ConsoleSpecialKey.ControlBreak : ConsoleSpecialKey.ControlC); private bool _handlerRegistered; internal void Register() { EnsureInitialized(); Debug.Assert(!_handlerRegistered); Interop.Sys.RegisterForCtrl(_handler); _handlerRegistered = true; } internal void Unregister() { Debug.Assert(_handlerRegistered); _handlerRegistered = false; Interop.Sys.UnregisterForCtrl(); } } } }
using Lucene.Net.Documents; using Lucene.Net.Support; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Threading; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using Query = Lucene.Net.Search.Query; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; using Attributes; /* Verify we can read the pre-2.1 file format, do searches against it, and add documents to it. */ [TestFixture] public class TestDeletionPolicy : LuceneTestCase { private void VerifyCommitOrder<T>(IList<T> commits) where T : IndexCommit { if (commits.Count == 0) { return; } IndexCommit firstCommit = commits[0]; long last = SegmentInfos.GenerationFromSegmentsFileName(firstCommit.SegmentsFileName); Assert.AreEqual(last, firstCommit.Generation); for (int i = 1; i < commits.Count; i++) { IndexCommit commit = commits[i]; long now = SegmentInfos.GenerationFromSegmentsFileName(commit.SegmentsFileName); Assert.IsTrue(now > last, "SegmentInfos commits are out-of-order"); Assert.AreEqual(now, commit.Generation); last = now; } } internal class KeepAllDeletionPolicy : IndexDeletionPolicy { private readonly TestDeletionPolicy OuterInstance; internal int NumOnInit; internal int NumOnCommit; internal Directory Dir; internal KeepAllDeletionPolicy(TestDeletionPolicy outerInstance, Directory dir) { this.OuterInstance = outerInstance; this.Dir = dir; } public override void OnInit<T>(IList<T> commits) { OuterInstance.VerifyCommitOrder(commits); NumOnInit++; } public override void OnCommit<T>(IList<T> commits) { IndexCommit lastCommit = commits[commits.Count - 1]; DirectoryReader r = DirectoryReader.Open(Dir); Assert.AreEqual(r.Leaves.Count, lastCommit.SegmentCount, "lastCommit.segmentCount()=" + lastCommit.SegmentCount + " vs IndexReader.segmentCount=" + r.Leaves.Count); r.Dispose(); OuterInstance.VerifyCommitOrder(commits); NumOnCommit++; } } /// <summary> /// this is useful for adding to a big index when you know /// readers are not using it. /// </summary> internal class KeepNoneOnInitDeletionPolicy : IndexDeletionPolicy { private readonly TestDeletionPolicy OuterInstance; public KeepNoneOnInitDeletionPolicy(TestDeletionPolicy outerInstance) { this.OuterInstance = outerInstance; } internal int NumOnInit; internal int NumOnCommit; public override void OnInit<T>(IList<T> commits) { OuterInstance.VerifyCommitOrder(commits); NumOnInit++; // On init, delete all commit points: foreach (IndexCommit commit in commits) { commit.Delete(); Assert.IsTrue(commit.IsDeleted); } } public override void OnCommit<T>(IList<T> commits) { OuterInstance.VerifyCommitOrder(commits); int size = commits.Count; // Delete all but last one: for (int i = 0; i < size - 1; i++) { ((IndexCommit)commits[i]).Delete(); } NumOnCommit++; } } internal class KeepLastNDeletionPolicy : IndexDeletionPolicy { private readonly TestDeletionPolicy OuterInstance; internal int NumOnInit; internal int NumOnCommit; internal int NumToKeep; internal int NumDelete; internal HashSet<string> Seen = new HashSet<string>(); public KeepLastNDeletionPolicy(TestDeletionPolicy outerInstance, int numToKeep) { this.OuterInstance = outerInstance; this.NumToKeep = numToKeep; } public override void OnInit<T>(IList<T> commits) { if (VERBOSE) { Console.WriteLine("TEST: onInit"); } OuterInstance.VerifyCommitOrder(commits); NumOnInit++; // do no deletions on init DoDeletes(commits, false); } public override void OnCommit<T>(IList<T> commits) { if (VERBOSE) { Console.WriteLine("TEST: onCommit"); } OuterInstance.VerifyCommitOrder(commits); DoDeletes(commits, true); } internal virtual void DoDeletes<T>(IList<T> commits, bool isCommit) where T : IndexCommit { // Assert that we really are only called for each new // commit: if (isCommit) { string fileName = ((IndexCommit)commits[commits.Count - 1]).SegmentsFileName; if (Seen.Contains(fileName)) { throw new Exception("onCommit was called twice on the same commit point: " + fileName); } Seen.Add(fileName); NumOnCommit++; } int size = commits.Count; for (int i = 0; i < size - NumToKeep; i++) { ((IndexCommit)commits[i]).Delete(); NumDelete++; } } } internal static long GetCommitTime(IndexCommit commit) { return Convert.ToInt64(commit.UserData["commitTime"]); } /* * Delete a commit only when it has been obsoleted by N * seconds. */ internal class ExpirationTimeDeletionPolicy : IndexDeletionPolicy { private readonly TestDeletionPolicy OuterInstance; internal Directory Dir; internal double ExpirationTimeSeconds; internal int NumDelete; public ExpirationTimeDeletionPolicy(TestDeletionPolicy outerInstance, Directory dir, double seconds) { this.OuterInstance = outerInstance; this.Dir = dir; this.ExpirationTimeSeconds = seconds; } public override void OnInit<T>(IList<T> commits) { if (commits.Count == 0) { return; } OuterInstance.VerifyCommitOrder(commits); OnCommit(commits); } public override void OnCommit<T>(IList<T> commits) { OuterInstance.VerifyCommitOrder(commits); IndexCommit lastCommit = commits[commits.Count - 1]; // Any commit older than expireTime should be deleted: double expireTime = GetCommitTime(lastCommit) / 1000.0 - ExpirationTimeSeconds; foreach (IndexCommit commit in commits) { double modTime = GetCommitTime(commit) / 1000.0; if (commit != lastCommit && modTime < expireTime) { commit.Delete(); NumDelete += 1; } } } } /* * Test "by time expiration" deletion policy: */ [Test] public virtual void TestExpirationTimeDeletionPolicy() { const double SECONDS = 2.0; Directory dir = NewDirectory(); IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(new ExpirationTimeDeletionPolicy(this, dir, SECONDS)); MergePolicy mp = conf.MergePolicy; mp.NoCFSRatio = 1.0; IndexWriter writer = new IndexWriter(dir, conf); ExpirationTimeDeletionPolicy policy = (ExpirationTimeDeletionPolicy)writer.Config.IndexDeletionPolicy; IDictionary<string, string> commitData = new Dictionary<string, string>(); commitData["commitTime"] = Convert.ToString(Environment.TickCount); writer.SetCommitData(commitData); writer.Commit(); writer.Dispose(); long lastDeleteTime = 0; int targetNumDelete = TestUtil.NextInt(Random(), 1, 5); while (policy.NumDelete < targetNumDelete) { // Record last time when writer performed deletes of // past commits lastDeleteTime = Environment.TickCount; conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetIndexDeletionPolicy(policy); mp = conf.MergePolicy; mp.NoCFSRatio = 1.0; writer = new IndexWriter(dir, conf); policy = (ExpirationTimeDeletionPolicy)writer.Config.IndexDeletionPolicy; for (int j = 0; j < 17; j++) { AddDoc(writer); } commitData = new Dictionary<string, string>(); commitData["commitTime"] = Convert.ToString(Environment.TickCount); writer.SetCommitData(commitData); writer.Commit(); writer.Dispose(); Thread.Sleep((int)(1000.0 * (SECONDS / 5.0))); } // Then simplistic check: just verify that the // segments_N's that still exist are in fact within SECONDS // seconds of the last one's mod time, and, that I can // open a reader on each: long gen = SegmentInfos.GetLastCommitGeneration(dir); string fileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen); dir.DeleteFile(IndexFileNames.SEGMENTS_GEN); bool oneSecondResolution = true; while (gen > 0) { try { IndexReader reader = DirectoryReader.Open(dir); reader.Dispose(); fileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen); // if we are on a filesystem that seems to have only // 1 second resolution, allow +1 second in commit // age tolerance: SegmentInfos sis = new SegmentInfos(); sis.Read(dir, fileName); long modTime = Convert.ToInt64(sis.UserData["commitTime"]); oneSecondResolution &= (modTime % 1000) == 0; long leeway = (long)((SECONDS + (oneSecondResolution ? 1.0 : 0.0)) * 1000); Assert.IsTrue(lastDeleteTime - modTime <= leeway, "commit point was older than " + SECONDS + " seconds (" + (lastDeleteTime - modTime) + " msec) but did not get deleted "); } #pragma warning disable 168 catch (IOException e) #pragma warning restore 168 { // OK break; } dir.DeleteFile(IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen)); gen--; } dir.Dispose(); } /* * Test a silly deletion policy that keeps all commits around. */ [Test] public virtual void TestKeepAllDeletionPolicy() { for (int pass = 0; pass < 2; pass++) { if (VERBOSE) { Console.WriteLine("TEST: cycle pass=" + pass); } bool useCompoundFile = (pass % 2) != 0; Directory dir = NewDirectory(); IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(new KeepAllDeletionPolicy(this, dir)).SetMaxBufferedDocs(10).SetMergeScheduler(new SerialMergeScheduler()); MergePolicy mp = conf.MergePolicy; mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0; IndexWriter writer = new IndexWriter(dir, conf); KeepAllDeletionPolicy policy = (KeepAllDeletionPolicy)writer.Config.IndexDeletionPolicy; for (int i = 0; i < 107; i++) { AddDoc(writer); } writer.Dispose(); bool needsMerging; { DirectoryReader r = DirectoryReader.Open(dir); needsMerging = r.Leaves.Count != 1; r.Dispose(); } if (needsMerging) { conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetIndexDeletionPolicy(policy); mp = conf.MergePolicy; mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0; if (VERBOSE) { Console.WriteLine("TEST: open writer for forceMerge"); } writer = new IndexWriter(dir, conf); policy = (KeepAllDeletionPolicy)writer.Config.IndexDeletionPolicy; writer.ForceMerge(1); writer.Dispose(); } Assert.AreEqual(needsMerging ? 2 : 1, policy.NumOnInit); // If we are not auto committing then there should // be exactly 2 commits (one per close above): Assert.AreEqual(1 + (needsMerging ? 1 : 0), policy.NumOnCommit); // Test listCommits ICollection<IndexCommit> commits = DirectoryReader.ListCommits(dir); // 2 from closing writer Assert.AreEqual(1 + (needsMerging ? 1 : 0), commits.Count); // Make sure we can open a reader on each commit: foreach (IndexCommit commit in commits) { IndexReader r = DirectoryReader.Open(commit); r.Dispose(); } // Simplistic check: just verify all segments_N's still // exist, and, I can open a reader on each: dir.DeleteFile(IndexFileNames.SEGMENTS_GEN); long gen = SegmentInfos.GetLastCommitGeneration(dir); while (gen > 0) { IndexReader reader = DirectoryReader.Open(dir); reader.Dispose(); dir.DeleteFile(IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen)); gen--; if (gen > 0) { // Now that we've removed a commit point, which // should have orphan'd at least one index file. // Open & close a writer and assert that it // actually removed something: int preCount = dir.ListAll().Length; writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetIndexDeletionPolicy(policy)); writer.Dispose(); int postCount = dir.ListAll().Length; Assert.IsTrue(postCount < preCount); } } dir.Dispose(); } } /* Uses KeepAllDeletionPolicy to keep all commits around, * then, opens a new IndexWriter on a previous commit * point. */ [Test] public virtual void TestOpenPriorSnapshot() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(new KeepAllDeletionPolicy(this, dir)).SetMaxBufferedDocs(2).SetMergePolicy(NewLogMergePolicy(10))); KeepAllDeletionPolicy policy = (KeepAllDeletionPolicy)writer.Config.IndexDeletionPolicy; for (int i = 0; i < 10; i++) { AddDoc(writer); if ((1 + i) % 2 == 0) { writer.Commit(); } } writer.Dispose(); ICollection<IndexCommit> commits = DirectoryReader.ListCommits(dir); Assert.AreEqual(5, commits.Count); IndexCommit lastCommit = null; foreach (IndexCommit commit in commits) { if (lastCommit == null || commit.Generation > lastCommit.Generation) { lastCommit = commit; } } Assert.IsTrue(lastCommit != null); // Now add 1 doc and merge writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(policy)); AddDoc(writer); Assert.AreEqual(11, writer.NumDocs); writer.ForceMerge(1); writer.Dispose(); Assert.AreEqual(6, DirectoryReader.ListCommits(dir).Count); // Now open writer on the commit just before merge: writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(policy).SetIndexCommit(lastCommit)); Assert.AreEqual(10, writer.NumDocs); // Should undo our rollback: writer.Rollback(); DirectoryReader r = DirectoryReader.Open(dir); // Still merged, still 11 docs Assert.AreEqual(1, r.Leaves.Count); Assert.AreEqual(11, r.NumDocs); r.Dispose(); writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(policy).SetIndexCommit(lastCommit)); Assert.AreEqual(10, writer.NumDocs); // Commits the rollback: writer.Dispose(); // Now 8 because we made another commit Assert.AreEqual(7, DirectoryReader.ListCommits(dir).Count); r = DirectoryReader.Open(dir); // Not fully merged because we rolled it back, and now only // 10 docs Assert.IsTrue(r.Leaves.Count > 1); Assert.AreEqual(10, r.NumDocs); r.Dispose(); // Re-merge writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexDeletionPolicy(policy)); writer.ForceMerge(1); writer.Dispose(); r = DirectoryReader.Open(dir); Assert.AreEqual(1, r.Leaves.Count); Assert.AreEqual(10, r.NumDocs); r.Dispose(); // Now open writer on the commit just before merging, // but this time keeping only the last commit: writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetIndexCommit(lastCommit)); Assert.AreEqual(10, writer.NumDocs); // Reader still sees fully merged index, because writer // opened on the prior commit has not yet committed: r = DirectoryReader.Open(dir); Assert.AreEqual(1, r.Leaves.Count); Assert.AreEqual(10, r.NumDocs); r.Dispose(); writer.Dispose(); // Now reader sees not-fully-merged index: r = DirectoryReader.Open(dir); Assert.IsTrue(r.Leaves.Count > 1); Assert.AreEqual(10, r.NumDocs); r.Dispose(); dir.Dispose(); } /* Test keeping NO commit points. this is a viable and * useful case eg where you want to build a big index and * you know there are no readers. */ [Test] public virtual void TestKeepNoneOnInitDeletionPolicy() { for (int pass = 0; pass < 2; pass++) { bool useCompoundFile = (pass % 2) != 0; Directory dir = NewDirectory(); IndexWriterConfig conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetIndexDeletionPolicy(new KeepNoneOnInitDeletionPolicy(this)).SetMaxBufferedDocs(10); MergePolicy mp = conf.MergePolicy; mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0; IndexWriter writer = new IndexWriter(dir, conf); KeepNoneOnInitDeletionPolicy policy = (KeepNoneOnInitDeletionPolicy)writer.Config.IndexDeletionPolicy; for (int i = 0; i < 107; i++) { AddDoc(writer); } writer.Dispose(); conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetIndexDeletionPolicy(policy); mp = conf.MergePolicy; mp.NoCFSRatio = 1.0; writer = new IndexWriter(dir, conf); policy = (KeepNoneOnInitDeletionPolicy)writer.Config.IndexDeletionPolicy; writer.ForceMerge(1); writer.Dispose(); Assert.AreEqual(2, policy.NumOnInit); // If we are not auto committing then there should // be exactly 2 commits (one per close above): Assert.AreEqual(2, policy.NumOnCommit); // Simplistic check: just verify the index is in fact // readable: IndexReader reader = DirectoryReader.Open(dir); reader.Dispose(); dir.Dispose(); } } /* * Test a deletion policy that keeps last N commits. */ [Test] public virtual void TestKeepLastNDeletionPolicy() { const int N = 5; for (int pass = 0; pass < 2; pass++) { bool useCompoundFile = (pass % 2) != 0; Directory dir = NewDirectory(); KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(this, N); for (int j = 0; j < N + 1; j++) { IndexWriterConfig conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetIndexDeletionPolicy(policy).SetMaxBufferedDocs(10); MergePolicy mp = conf.MergePolicy; mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0; IndexWriter writer = new IndexWriter(dir, conf); policy = (KeepLastNDeletionPolicy)writer.Config.IndexDeletionPolicy; for (int i = 0; i < 17; i++) { AddDoc(writer); } writer.ForceMerge(1); writer.Dispose(); } Assert.IsTrue(policy.NumDelete > 0); Assert.AreEqual(N + 1, policy.NumOnInit); Assert.AreEqual(N + 1, policy.NumOnCommit); // Simplistic check: just verify only the past N segments_N's still // exist, and, I can open a reader on each: dir.DeleteFile(IndexFileNames.SEGMENTS_GEN); long gen = SegmentInfos.GetLastCommitGeneration(dir); for (int i = 0; i < N + 1; i++) { try { IndexReader reader = DirectoryReader.Open(dir); reader.Dispose(); if (i == N) { Assert.Fail("should have failed on commits prior to last " + N); } } catch (IOException e) { if (i != N) { throw e; } } if (i < N) { dir.DeleteFile(IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen)); } gen--; } dir.Dispose(); } } /* * Test a deletion policy that keeps last N commits * around, through creates. */ [Test, LongRunningTest] public virtual void TestKeepLastNDeletionPolicyWithCreates() { const int N = 10; for (int pass = 0; pass < 2; pass++) { bool useCompoundFile = (pass % 2) != 0; Directory dir = NewDirectory(); IndexWriterConfig conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetIndexDeletionPolicy(new KeepLastNDeletionPolicy(this, N)).SetMaxBufferedDocs(10); MergePolicy mp = conf.MergePolicy; mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0; IndexWriter writer = new IndexWriter(dir, conf); KeepLastNDeletionPolicy policy = (KeepLastNDeletionPolicy)writer.Config.IndexDeletionPolicy; writer.Dispose(); Term searchTerm = new Term("content", "aaa"); Query query = new TermQuery(searchTerm); for (int i = 0; i < N + 1; i++) { conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND).SetIndexDeletionPolicy(policy).SetMaxBufferedDocs(10); mp = conf.MergePolicy; mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0; writer = new IndexWriter(dir, conf); policy = (KeepLastNDeletionPolicy)writer.Config.IndexDeletionPolicy; for (int j = 0; j < 17; j++) { AddDocWithID(writer, i * (N + 1) + j); } // this is a commit writer.Dispose(); conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetIndexDeletionPolicy(policy).SetMergePolicy(NoMergePolicy.COMPOUND_FILES); writer = new IndexWriter(dir, conf); policy = (KeepLastNDeletionPolicy)writer.Config.IndexDeletionPolicy; writer.DeleteDocuments(new Term("id", "" + (i * (N + 1) + 3))); // this is a commit writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); IndexSearcher searcher = NewSearcher(reader); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(16, hits.Length); reader.Dispose(); writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetIndexDeletionPolicy(policy)); policy = (KeepLastNDeletionPolicy)writer.Config.IndexDeletionPolicy; // this will not commit: there are no changes // pending because we opened for "create": writer.Dispose(); } Assert.AreEqual(3 * (N + 1) + 1, policy.NumOnInit); Assert.AreEqual(3 * (N + 1) + 1, policy.NumOnCommit); IndexReader rwReader = DirectoryReader.Open(dir); IndexSearcher searcher_ = NewSearcher(rwReader); ScoreDoc[] hits_ = searcher_.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits_.Length); // Simplistic check: just verify only the past N segments_N's still // exist, and, I can open a reader on each: long gen = SegmentInfos.GetLastCommitGeneration(dir); dir.DeleteFile(IndexFileNames.SEGMENTS_GEN); int expectedCount = 0; rwReader.Dispose(); for (int i = 0; i < N + 1; i++) { try { IndexReader reader = DirectoryReader.Open(dir); // Work backwards in commits on what the expected // count should be. searcher_ = NewSearcher(reader); hits_ = searcher_.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(expectedCount, hits_.Length); if (expectedCount == 0) { expectedCount = 16; } else if (expectedCount == 16) { expectedCount = 17; } else if (expectedCount == 17) { expectedCount = 0; } reader.Dispose(); if (i == N) { Assert.Fail("should have failed on commits before last " + N); } } catch (IOException e) { if (i != N) { throw e; } } if (i < N) { dir.DeleteFile(IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen)); } gen--; } dir.Dispose(); } } private void AddDocWithID(IndexWriter writer, int id) { Document doc = new Document(); doc.Add(NewTextField("content", "aaa", Field.Store.NO)); doc.Add(NewStringField("id", "" + id, Field.Store.NO)); writer.AddDocument(doc); } private void AddDoc(IndexWriter writer) { Document doc = new Document(); doc.Add(NewTextField("content", "aaa", Field.Store.NO)); writer.AddDocument(doc); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Box.V2.Auth; using Box.V2.Config; using Box.V2.Converter; using Box.V2.Exceptions; using Box.V2.Managers; using Box.V2.Models; using Box.V2.Request; using Box.V2.Services; using NLog; using UITS.Box.Collaborations.BoxExtensions; using UITS.Box.Collaborations.IO; using UITS.Box.Collaborations.Model; namespace UITS.Box.Collaborations { public class BoxClient { private static Logger Log = LogManager.GetCurrentClassLogger(); private readonly string _outPath; private static BoxConfig _boxConfig; private static AuthRepository _authRepository; private static readonly List<string> CollabFields = new List<string>(){"item", "accessible_by", "created_by", "role"}; public BoxClient(string accessToken, string outPath) { _outPath = outPath; _boxConfig = new BoxConfig("key", "secret", new Uri("https://baz")); _authRepository = new AuthRepository(_boxConfig, new BoxService(new HttpRequestHandler()), new BoxJsonConverter(), new OAuthSession(accessToken, "refresh", 10, "bearer")); } public async Task RecordCollaborationsAsync(string outPath, List<string> logins, string[] domainWhitelist, string role) { // Record collaborations for up to 4 users in parallel. A few users will have absurdly deep Box accounts, so this prevents them from gumming up the works. // This value can be safely increased, but at some point Box will start throttling requests. const int maxDegreeOfParallelism = 4; var tasks = new List<Task>(); var throttler = new SemaphoreSlim(maxDegreeOfParallelism); var cts = new CancellationTokenSource(); var ct = cts.Token; foreach (var login in logins) { await throttler.WaitAsync(ct); tasks.Add(Task.Run(async () => { try { await RecordCollaborationsForUserAsync(outPath, login, domainWhitelist, role, ct); } catch { cts.Cancel(); } finally { throttler.Release(); } }, ct)); } await Task.WhenAll(tasks); } private static async Task RecordCollaborationsForUserAsync(string outPath, string login, string[] domainWhitelist, string role, CancellationToken ct) { try { // Fetch all the Box users associated with this username. This allows for the existence of duplicate accounts in your domain. List<BoxUser> users = await GetBoxUsersAsync(login); if (UserFoundForLogin(users, login)) { LogMultipleUsersForSingleLogin(users, login); foreach (BoxUser user in users) { // Record collaboration info for each Box user instance. Log.Info("Started reviewing {0} ({1})", user.Login, login); // Get the groups that this user belongs to. If a collaboration is with a group, and they're a member, we'll want to record that. var groupIds = await GroupIdsForUser(user); var collaborations = new List<Collaboration>(); await GatcherCollaborationsForBoxUserAsync(NewBoxFoldersManager(user), user, role, groupIds, collaborations); await ResultsWriter.WriteResultsAsync(outPath, collaborations, domainWhitelist); Log.Info("Finished reviewing {0} ({1})", user.Login, login); } } } catch (BoxException e) { if (e.StatusCode.Equals(HttpStatusCode.Unauthorized)) { Log.Error("Authorization has expired"); throw new AuthorizationExpiredException(); } Log.ErrorException(String.Format("Failed to find collaborations for '{0}' due to Box exception: {1}", login, e.Message), e); } catch (Exception e) { Log.ErrorException(String.Format("Failed to find collaborations for '{0}' due to generic exception: {1}", login, e.Message), e); } } private static async Task<List<string>> GroupIdsForUser(BoxUser user) { var boxGroupsManager = new BoxGroupsManager(_boxConfig, new OnBehalfOfUserService(new HttpRequestHandler(), user.Id), new BoxJsonConverter(), _authRepository); var groupMembershipsForUser = await boxGroupsManager.GetAllGroupMembershipsForUserAsync(user.Id); var groupIds = groupMembershipsForUser.Entries.Select(e => e.Id).ToList(); return groupIds; } private static BoxFoldersManager NewBoxFoldersManager(BoxUser user) { return new BoxFoldersManager(_boxConfig, new OnBehalfOfUserService(new HttpRequestHandler(), user.Id), new BoxJsonConverter(), _authRepository); } private static void LogMultipleUsersForSingleLogin(List<BoxUser> users, string login) { if (users.Count() > 1) { Log.Warn("Found {0} Box users for login {1}: {2}", users.Count(), login, String.Join(", ", users.Select(u => u.Login))); } } private static bool UserFoundForLogin(List<BoxUser> users, string login) { bool any = users.Any(); if (!any) { Log.Warn("No Box user found for login {0}", login); } return any; } private static async Task GatcherCollaborationsForBoxUserAsync(BoxFoldersManager folderManager, BoxUser user, string role, List<string> groupIds, List<Collaboration> result, string folderId = "0") { // Get all the subfolders of this current folder var subfolders = await GetAllSubfoldersAsync(folderManager, folderId); // Find all collaborations within this folder that meet our 'role' criteria var foldersWithCollaborations = subfolders.Where(f => f.HasCollaborations.GetValueOrDefault(false)).ToList(); await ReviewCollaborationsAsync(folderManager, foldersWithCollaborations, user, role, groupIds, result); // Recursively scan for collaborations in folders that *don't* already have collaborations. // Once we've determined that a folder has collaborations, we don't need to dive any deeper into it. foreach (var folder in subfolders.Except(foldersWithCollaborations, BoxFolderEqualityComparer.ById)) { await GatcherCollaborationsForBoxUserAsync(folderManager, user, role, groupIds, result, folder.Id); } } private async static Task ReviewCollaborationsAsync(BoxFoldersManager folderManager, IEnumerable<BoxFolder> collaborationFolders, BoxUser user, string role, List<string> groupIds, List<Collaboration> result) { switch (role) { case "owner": await ReviewOwnedCollaborationsAsync(folderManager, collaborationFolders, user, result); break; case "member": await ReviewMemberCollaborationsAsync(folderManager, collaborationFolders, user, groupIds, result); break; default: throw new ArgumentException("Must be 'owner' or 'member'", "role"); } } /// <summary> /// Record the folders, members, and roles of any collaborations owned by this user. /// </summary> private static async Task ReviewOwnedCollaborationsAsync(BoxFoldersManager folderManager, IEnumerable<BoxFolder> collaborationFolders, BoxUser user, List<Collaboration> result) { var ownedByThisUser = collaborationFolders.Where(c => c.OwnedBy.Id.Equals(user.Id)).ToList(); foreach (var folder in ownedByThisUser) { var collaborations = await folderManager.GetCollaborationsAsync(folder.Id, CollabFields); result.AddRange(collaborations.Entries.Select(c => new Collaboration(c, user))); } } /// <summary> /// Record folders, owners, and roles of any collaborations of which this user is a member. /// </summary> private static async Task ReviewMemberCollaborationsAsync(BoxFoldersManager folderManager, IEnumerable<BoxFolder> collaborationFolders, BoxUser user, List<string> groupIds, List<Collaboration> result) { foreach (var folder in collaborationFolders) { var collaborations = await folderManager.GetCollaborationsAsync(folder.Id, CollabFields); AddPersonalCollaborations(user, result, collaborations); AddGroupCollaborations(groupIds, result, collaborations); } } /// <summary> /// Determine collaborations where the member is this user specifically. /// </summary> private static void AddPersonalCollaborations(BoxUser user, List<Collaboration> result, BoxCollection<BoxCollaboration> collaborations) { var memberCollab = collaborations.Entries.SingleOrDefault(c => c.AccessibleBy.Id.Equals(user.Id)); if (memberCollab == null) return; result.Add(new Collaboration(memberCollab, memberCollab.CreatedBy)); } /// <summary> /// Determine collaborations where the member is a group that this user is in. /// </summary> private static void AddGroupCollaborations(List<string> groupIds, List<Collaboration> result, BoxCollection<BoxCollaboration> collaborations) { var groupCollabs = collaborations.Entries.Where(c => groupIds.Any(gid => c.AccessibleBy.Id.Equals(gid))).ToList(); result.AddRange(groupCollabs.Select(c => new Collaboration(c, c.CreatedBy))); } private static async Task<IList<BoxFolder>> GetAllSubfoldersAsync(BoxFoldersManager foldersManager, string folderId) { try { var items = new List<BoxItem>(); var itemsReceivedOnThisCall = 0; var itemsReceivedTotal = 0; var totalItemsCount = 0; var retry = true; do { var fields = new List<string> {BoxFolder.FieldName, BoxFolder.FieldHasCollaborations, BoxFolder.FieldOwnedBy}; BoxCollection<BoxItem> result = await foldersManager.GetFolderItemsAsync(folderId, 1000, itemsReceivedTotal, fields); items.AddRange(result.Entries); totalItemsCount = result.TotalCount; itemsReceivedOnThisCall = result.Entries.Count(); itemsReceivedTotal += itemsReceivedOnThisCall; if (itemsReceivedOnThisCall == 0 && totalItemsCount != 0) { if (retry) { retry = false; } else { Log.Warn("Received no folder items after retrying once. Bailing."); break; } } } while (itemsReceivedTotal < totalItemsCount); return items.Where(e => e.Type.Equals("folder")).Cast<BoxFolder>().ToList(); } catch (Exception e) { Log.Error("Failed to fetch folder with id '{0}': {1}", folderId, e.Message); } return new BoxFolder[0]; } // Get all Box users in this enterprise for which the username of the provided 'login' matches the left side of the '@' in the Box login. private static async Task<List<BoxUser>> GetBoxUsersAsync(string login) { var userManager = new BoxEnterpriseUsersManager(_boxConfig, new BoxService(new HttpRequestHandler()), new BoxJsonConverter(), _authRepository); var searchableLogin = login.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries).First().Trim(new[] { '@' }) + '@'; var boxUsers = await userManager.GetEnterpriseUsersAsync(searchableLogin); return boxUsers.Entries; } } internal class BoxFolderEqualityComparer : IEqualityComparer<BoxFolder> { public bool Equals(BoxFolder x, BoxFolder y) { return x != null && y!= null && !String.IsNullOrWhiteSpace(x.Id) && !String.IsNullOrWhiteSpace(y.Id) && x.Id.Equals(y.Id,StringComparison.InvariantCultureIgnoreCase); } public int GetHashCode(BoxFolder obj) { return obj == null ? 0 : String.IsNullOrWhiteSpace(obj.Id) ? 0 : obj.Id.GetHashCode(); } public static BoxFolderEqualityComparer ById { get { return new BoxFolderEqualityComparer(); } } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EvaluationContext : EvaluationContextBase { private const string TypeName = "<>x"; private const string MethodName = "<>m0"; internal const bool IsLocalScopeEndInclusive = false; internal readonly MethodContextReuseConstraints? MethodContextReuseConstraints; internal readonly CSharpCompilation Compilation; private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableSortedSet<int> _inScopeHoistedLocalSlots; private readonly MethodDebugInfo<TypeSymbol, LocalSymbol> _methodDebugInfo; private EvaluationContext( MethodContextReuseConstraints? methodContextReuseConstraints, CSharpCompilation compilation, MethodSymbol currentFrame, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { Debug.Assert(inScopeHoistedLocalSlots != null); Debug.Assert(methodDebugInfo != null); this.MethodContextReuseConstraints = methodContextReuseConstraints; this.Compilation = compilation; _currentFrame = currentFrame; _locals = locals; _inScopeHoistedLocalSlots = inScopeHoistedLocalSlots; _methodDebugInfo = methodDebugInfo; } /// <summary> /// Create a context for evaluating expressions at a type scope. /// </summary> /// <param name="previous">Previous context, if any, for possible re-use.</param> /// <param name="metadataBlocks">Module metadata</param> /// <param name="moduleVersionId">Module containing type</param> /// <param name="typeToken">Type metadata token</param> /// <returns>Evaluation context</returns> /// <remarks> /// No locals since locals are associated with methods, not types. /// </remarks> internal static EvaluationContext CreateTypeContext( CSharpMetadataContext previous, ImmutableArray<MetadataBlock> metadataBlocks, Guid moduleVersionId, int typeToken) { // Re-use the previous compilation if possible. var compilation = previous.Matches(metadataBlocks) ? previous.Compilation : metadataBlocks.ToCompilation(); return CreateTypeContext(compilation, moduleVersionId, typeToken); } internal static EvaluationContext CreateTypeContext( CSharpCompilation compilation, Guid moduleVersionId, int typeToken) { Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition); var currentType = compilation.GetType(moduleVersionId, typeToken); Debug.Assert((object)currentType != null); var currentFrame = new SynthesizedContextMethodSymbol(currentType); return new EvaluationContext( null, compilation, currentFrame, default(ImmutableArray<LocalSymbol>), ImmutableSortedSet<int>.Empty, MethodDebugInfo<TypeSymbol, LocalSymbol>.None); } /// <summary> /// Create a context for evaluating expressions within a method scope. /// </summary> /// <param name="previous">Previous context, if any, for possible re-use.</param> /// <param name="metadataBlocks">Module metadata</param> /// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param> /// <param name="moduleVersionId">Module containing method</param> /// <param name="methodToken">Method metadata token</param> /// <param name="methodVersion">Method version.</param> /// <param name="ilOffset">IL offset of instruction pointer in method</param> /// <param name="localSignatureToken">Method local signature token</param> /// <returns>Evaluation context</returns> internal static EvaluationContext CreateMethodContext( CSharpMetadataContext previous, ImmutableArray<MetadataBlock> metadataBlocks, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, uint ilOffset, int localSignatureToken) { var offset = NormalizeILOffset(ilOffset); // Re-use the previous compilation if possible. CSharpCompilation compilation; if (previous.Matches(metadataBlocks)) { // Re-use entire context if method scope has not changed. var previousContext = previous.EvaluationContext; if (previousContext != null && previousContext.MethodContextReuseConstraints.HasValue && previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset)) { return previousContext; } compilation = previous.Compilation; } else { compilation = metadataBlocks.ToCompilation(); } return CreateMethodContext( compilation, symReader, moduleVersionId, methodToken, methodVersion, offset, localSignatureToken); } internal static EvaluationContext CreateMethodContext( CSharpCompilation compilation, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, uint ilOffset, int localSignatureToken) { return CreateMethodContext( compilation, symReader, moduleVersionId, methodToken, methodVersion, NormalizeILOffset(ilOffset), localSignatureToken); } private static EvaluationContext CreateMethodContext( CSharpCompilation compilation, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset, int localSignatureToken) { var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var localSignatureHandle = (localSignatureToken != 0) ? (StandaloneSignatureHandle)MetadataTokens.Handle(localSignatureToken) : default(StandaloneSignatureHandle); var currentFrame = compilation.GetMethod(moduleVersionId, methodHandle); Debug.Assert((object)currentFrame != null); var symbolProvider = new CSharpEESymbolProvider(compilation.SourceAssembly, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var metadataDecoder = new MetadataDecoder((PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var localInfo = metadataDecoder.GetLocalInfo(localSignatureHandle); var typedSymReader = (ISymUnmanagedReader3)symReader; var debugInfo = MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo(typedSymReader, symbolProvider, methodToken, methodVersion, ilOffset, isVisualBasicMethod: false); var reuseSpan = debugInfo.ReuseSpan; var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); MethodDebugInfo<TypeSymbol, LocalSymbol>.GetLocals( localsBuilder, symbolProvider, debugInfo.LocalVariableNames, localInfo, debugInfo.DynamicLocalMap, debugInfo.TupleLocalMap); var inScopeHoistedLocals = debugInfo.GetInScopeHoistedLocalIndices(ilOffset, ref reuseSpan); localsBuilder.AddRange(debugInfo.LocalConstants); return new EvaluationContext( new MethodContextReuseConstraints(moduleVersionId, methodToken, methodVersion, reuseSpan), compilation, currentFrame, localsBuilder.ToImmutableAndFree(), inScopeHoistedLocals, debugInfo); } internal CompilationContext CreateCompilationContext() { return new CompilationContext( this.Compilation, _currentFrame, _locals, _inScopeHoistedLocalSlots, _methodDebugInfo); } /// <summary> /// Compile a collection of expressions at the same location. If all expressions /// compile successfully, a single assembly is returned along with the method /// tokens for the expression evaluation methods. If there are errors compiling /// any expression, null is returned along with the collection of error messages /// for all expressions. /// </summary> /// <remarks> /// Errors are returned as a single collection rather than grouped by expression /// since some errors (such as those detected during emit) are not easily /// attributed to a particular expression. /// </remarks> internal byte[] CompileExpressions( ImmutableArray<string> expressions, out ImmutableArray<int> methodTokens, out ImmutableArray<string> errorMessages) { var diagnostics = DiagnosticBag.GetInstance(); var syntaxNodes = expressions.SelectAsArray(expr => Parse(expr, treatAsExpression: true, diagnostics: diagnostics, formatSpecifiers: out var formatSpecifiers)); byte[] assembly = null; if (!diagnostics.HasAnyErrors()) { Debug.Assert(syntaxNodes.All(s => s != null)); var context = this.CreateCompilationContext(); var moduleBuilder = context.CompileExpressions(syntaxNodes, TypeName, MethodName, diagnostics); if (moduleBuilder != null) { using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, isDeterministic: false, cancellationToken: default(CancellationToken)); if (!diagnostics.HasAnyErrors()) { assembly = stream.ToArray(); } } } } if (assembly == null) { methodTokens = ImmutableArray<int>.Empty; errorMessages = ImmutableArray.CreateRange( diagnostics.AsEnumerable(). Where(d => d.Severity == DiagnosticSeverity.Error). Select(d => GetErrorMessage(d, CSharpDiagnosticFormatter.Instance, preferredUICulture: null))); } else { methodTokens = MetadataUtilities.GetSynthesizedMethods(assembly, MethodName); Debug.Assert(methodTokens.Length == expressions.Length); errorMessages = ImmutableArray<string>.Empty; } diagnostics.Free(); return assembly; } internal override CompileResult CompileExpression( string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out ResultProperties resultProperties, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData) { ReadOnlyCollection<string> formatSpecifiers; var syntax = Parse(expr, (compilationFlags & DkmEvaluationFlags.TreatAsExpression) != 0, diagnostics, out formatSpecifiers); if (syntax == null) { resultProperties = default(ResultProperties); return null; } var context = this.CreateCompilationContext(); var moduleBuilder = context.CompileExpression(syntax, TypeName, MethodName, aliases, testData, diagnostics, out var synthesizedMethod); if (moduleBuilder == null) { resultProperties = default(ResultProperties); return null; } using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, isDeterministic: false, cancellationToken: default(CancellationToken)); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } Debug.Assert(synthesizedMethod.ContainingType.MetadataName == TypeName); Debug.Assert(synthesizedMethod.MetadataName == MethodName); resultProperties = synthesizedMethod.ResultProperties; return new CSharpCompileResult( stream.ToArray(), synthesizedMethod, formatSpecifiers: formatSpecifiers); } } private static CSharpSyntaxNode Parse( string expr, bool treatAsExpression, DiagnosticBag diagnostics, out ReadOnlyCollection<string> formatSpecifiers) { if (!treatAsExpression) { // Try to parse as a statement. If that fails, parse as an expression. var statementDiagnostics = DiagnosticBag.GetInstance(); var statementSyntax = expr.ParseStatement(statementDiagnostics); Debug.Assert((statementSyntax == null) || !statementDiagnostics.HasAnyErrors()); statementDiagnostics.Free(); var isExpressionStatement = statementSyntax.IsKind(SyntaxKind.ExpressionStatement); if (statementSyntax != null && !isExpressionStatement) { formatSpecifiers = null; if (statementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement)) { return statementSyntax; } diagnostics.Add(ErrorCode.ERR_ExpressionOrDeclarationExpected, Location.None); return null; } } return expr.ParseExpression(diagnostics, allowFormatSpecifiers: true, formatSpecifiers: out formatSpecifiers); } internal override CompileResult CompileAssignment( string target, string expr, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out ResultProperties resultProperties, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData) { var assignment = target.ParseAssignment(expr, diagnostics); if (assignment == null) { resultProperties = default(ResultProperties); return null; } var context = this.CreateCompilationContext(); var moduleBuilder = context.CompileAssignment(assignment, TypeName, MethodName, aliases, testData, diagnostics, out var synthesizedMethod); if (moduleBuilder == null) { resultProperties = default(ResultProperties); return null; } using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, isDeterministic: false, cancellationToken: default(CancellationToken)); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } Debug.Assert(synthesizedMethod.ContainingType.MetadataName == TypeName); Debug.Assert(synthesizedMethod.MetadataName == MethodName); resultProperties = synthesizedMethod.ResultProperties; return new CSharpCompileResult( stream.ToArray(), synthesizedMethod, formatSpecifiers: null); } } private static readonly ReadOnlyCollection<byte> s_emptyBytes = new ReadOnlyCollection<byte>(Array.Empty<byte>()); internal override ReadOnlyCollection<byte> CompileGetLocals( ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out string typeName, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData) { var context = this.CreateCompilationContext(); var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, aliases, testData, diagnostics); ReadOnlyCollection<byte> assembly = null; if ((moduleBuilder != null) && (locals.Count > 0)) { using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, isDeterministic: false, cancellationToken: default(CancellationToken)); if (!diagnostics.HasAnyErrors()) { assembly = new ReadOnlyCollection<byte>(stream.ToArray()); } } } if (assembly == null) { locals.Clear(); assembly = s_emptyBytes; } typeName = TypeName; return assembly; } internal override bool HasDuplicateTypesOrAssemblies(Diagnostic diagnostic) { switch ((ErrorCode)diagnostic.Code) { case ErrorCode.ERR_DuplicateImport: case ErrorCode.ERR_DuplicateImportSimple: case ErrorCode.ERR_SameFullNameAggAgg: case ErrorCode.ERR_AmbigCall: return true; default: return false; } } internal override ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentities(Diagnostic diagnostic, AssemblyIdentity linqLibrary) { return GetMissingAssemblyIdentitiesHelper((ErrorCode)diagnostic.Code, diagnostic.Arguments, linqLibrary); } /// <remarks> /// Internal for testing. /// </remarks> internal static ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentitiesHelper(ErrorCode code, IReadOnlyList<object> arguments, AssemblyIdentity linqLibrary) { Debug.Assert(linqLibrary != null); switch (code) { case ErrorCode.ERR_NoTypeDef: case ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd: case ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd: case ErrorCode.ERR_SingleTypeNameNotFoundFwd: case ErrorCode.ERR_NameNotInContextPossibleMissingReference: // Probably can't happen. foreach (var argument in arguments) { var identity = (argument as AssemblyIdentity) ?? (argument as AssemblySymbol)?.Identity; if (identity != null && !identity.Equals(MissingCorLibrarySymbol.Instance.Identity)) { return ImmutableArray.Create(identity); } } break; case ErrorCode.ERR_DottedTypeNameNotFoundInNS: if (arguments.Count == 2) { var namespaceName = arguments[0] as string; var containingNamespace = arguments[1] as NamespaceSymbol; if (namespaceName != null && (object)containingNamespace != null && containingNamespace.ConstituentNamespaces.Any(n => n.ContainingAssembly.Identity.IsWindowsAssemblyIdentity())) { // This is just a heuristic, but it has the advantage of being portable, particularly // across different versions of (desktop) windows. var identity = new AssemblyIdentity($"{containingNamespace.ToDisplayString()}.{namespaceName}", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); return ImmutableArray.Create(identity); } } break; case ErrorCode.ERR_NoSuchMemberOrExtension: // Commonly, but not always, caused by absence of System.Core. case ErrorCode.ERR_DynamicAttributeMissing: case ErrorCode.ERR_DynamicRequiredTypesMissing: // MSDN says these might come from System.Dynamic.Runtime case ErrorCode.ERR_QueryNoProviderStandard: case ErrorCode.ERR_ExtensionAttrNotFound: // Probably can't happen. return ImmutableArray.Create(linqLibrary); case ErrorCode.ERR_BadAwaitArg_NeedSystem: Debug.Assert(false, "Roslyn no longer produces ERR_BadAwaitArg_NeedSystem"); break; } return default(ImmutableArray<AssemblyIdentity>); } } }
// 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt323() { var test = new VectorGetAndWithElement__GetAndWithElementUInt323(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt323 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector256<UInt32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]); bool succeeded = !expectedOutOfRangeException; try { UInt32 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { Vector256<UInt32> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector256<UInt32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt32)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<UInt32>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt32 result, UInt32[] values, [CallerMemberName] string method = "") { if (result != values[3]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<UInt32> result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt32[] result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 3) && (result[i] != values[i])) { succeeded = false; break; } } if (result[3] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Security.SecurityException.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Security { public partial class SecurityException : SystemException { #region Methods and constructors public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SecurityException(string message, Type type, string state) { } public SecurityException(string message, Exception inner) { } public SecurityException(string message) { } public SecurityException(string message, Type type) { } protected SecurityException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SecurityException() { } public SecurityException(string message, Object deny, Object permitOnly, System.Reflection.MethodInfo method, Object demanded, IPermission permThatFailed) { Contract.Ensures(0 <= string.Empty.Length); } public SecurityException(string message, System.Reflection.AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, System.Reflection.MethodInfo method, System.Security.Permissions.SecurityAction action, Object demanded, IPermission permThatFailed, System.Security.Policy.Evidence evidence) { Contract.Ensures(0 <= string.Empty.Length); } public override string ToString() { return default(string); } #endregion #region Properties and indexers public System.Security.Permissions.SecurityAction Action { get { return default(System.Security.Permissions.SecurityAction); } set { } } public Object Demanded { get { return default(Object); } set { } } public Object DenySetInstance { get { return default(Object); } set { } } public System.Reflection.AssemblyName FailedAssemblyInfo { get { return default(System.Reflection.AssemblyName); } set { } } public IPermission FirstPermissionThatFailed { get { return default(IPermission); } set { } } public string GrantedSet { get { return default(string); } set { } } public System.Reflection.MethodInfo Method { get { return default(System.Reflection.MethodInfo); } set { } } public string PermissionState { get { return default(string); } set { } } public Type PermissionType { get { return default(Type); } set { } } public Object PermitOnlySetInstance { get { return default(Object); } set { } } public string RefusedSet { get { return default(string); } set { } } public string Url { get { return default(string); } set { } } public SecurityZone Zone { get { return default(SecurityZone); } set { } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Net; using System.Net.Security; using System.Runtime; using System.Security.Authentication; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading.Tasks; namespace System.ServiceModel.Channels { class WindowsStreamSecurityUpgradeProvider : StreamSecurityUpgradeProvider { bool _extractGroupsForWindowsAccounts; EndpointIdentity _identity; IdentityVerifier _identityVerifier; ProtectionLevel _protectionLevel; SecurityTokenManager _securityTokenManager; NetworkCredential _serverCredential; string _scheme; bool _isClient; Uri _listenUri; public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement, BindingContext context, bool isClient) : base(context.Binding) { Contract.Assert(isClient, ".NET Core and .NET Native does not support server side"); _extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts; _protectionLevel = bindingElement.ProtectionLevel; _scheme = context.Binding.Scheme; _isClient = isClient; _listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress); SecurityCredentialsManager credentialProvider = context.BindingParameters.Find<SecurityCredentialsManager>(); if (credentialProvider == null) { credentialProvider = ClientCredentials.CreateDefaultCredentials(); } _securityTokenManager = credentialProvider.CreateSecurityTokenManager(); } public string Scheme { get { return _scheme; } } internal bool ExtractGroupsForWindowsAccounts { get { return _extractGroupsForWindowsAccounts; } } public override EndpointIdentity Identity { get { // If the server credential is null, then we have not been opened yet and have no identity to expose. if (_serverCredential != null) { if (_identity == null) { lock (ThisLock) { if (_identity == null) { _identity = SecurityUtils.CreateWindowsIdentity(_serverCredential); } } } } return _identity; } } internal IdentityVerifier IdentityVerifier { get { return _identityVerifier; } } public ProtectionLevel ProtectionLevel { get { return _protectionLevel; } } NetworkCredential ServerCredential { get { return _serverCredential; } } public override StreamUpgradeInitiator CreateUpgradeInitiator(EndpointAddress remoteAddress, Uri via) { ThrowIfDisposedOrNotOpen(); return new WindowsStreamSecurityUpgradeInitiator(this, remoteAddress, via); } protected override void OnAbort() { } protected override void OnClose(TimeSpan timeout) { } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndClose(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpen(TimeSpan timeout) { if (!_isClient) { SecurityTokenRequirement sspiTokenRequirement = TransportSecurityHelpers.CreateSspiTokenRequirement(Scheme, _listenUri); _serverCredential = TransportSecurityHelpers.GetSspiCredential(_securityTokenManager, sspiTokenRequirement, timeout, out _extractGroupsForWindowsAccounts); } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { OnOpen(timeout); return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpened() { base.OnOpened(); if (_identityVerifier == null) { _identityVerifier = IdentityVerifier.CreateDefault(); } if (_serverCredential == null) { _serverCredential = CredentialCache.DefaultNetworkCredentials; } } class WindowsStreamSecurityUpgradeInitiator : StreamSecurityUpgradeInitiatorBase { private WindowsStreamSecurityUpgradeProvider _parent; private IdentityVerifier _identityVerifier; private NetworkCredential _credential; private TokenImpersonationLevel _impersonationLevel; private SspiSecurityTokenProvider _clientTokenProvider; private bool _allowNtlm; public WindowsStreamSecurityUpgradeInitiator( WindowsStreamSecurityUpgradeProvider parent, EndpointAddress remoteAddress, Uri via) : base(FramingUpgradeString.Negotiate, remoteAddress, via) { _parent = parent; _clientTokenProvider = TransportSecurityHelpers.GetSspiTokenProvider( parent._securityTokenManager, remoteAddress, via, parent.Scheme, out _identityVerifier); } internal override async Task OpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Open(timeoutHelper.RemainingTime()); OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>(); OutWrapper<bool> allowNtlmWrapper = new OutWrapper<bool>(); SecurityUtils.OpenTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime()); _credential = await TransportSecurityHelpers.GetSspiCredentialAsync( _clientTokenProvider, impersonationLevelWrapper, allowNtlmWrapper, timeoutHelper.GetCancellationToken()); _impersonationLevel = impersonationLevelWrapper.Value; _allowNtlm = allowNtlmWrapper; return; } internal override void Open(TimeSpan timeout) { OpenAsync(timeout).GetAwaiter(); } internal override void Close(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Close(timeoutHelper.RemainingTime()); SecurityUtils.CloseTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime()); } #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream static SecurityMessageProperty CreateServerSecurity(NegotiateStream negotiateStream) { GenericIdentity remoteIdentity = (GenericIdentity)negotiateStream.RemoteIdentity; string principalName = remoteIdentity.Name; if ((principalName != null) && (principalName.Length > 0)) { ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(principalName); SecurityMessageProperty result = new SecurityMessageProperty(); result.TransportToken = new SecurityTokenSpecification(null, authorizationPolicies); result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return result; } else { return null; } } #endif // SUPPORTS_WINDOWSIDENTITY protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity) { OutWrapper<SecurityMessageProperty> remoteSecurityOut = new OutWrapper<SecurityMessageProperty>(); var retVal = OnInitiateUpgradeAsync(stream, remoteSecurityOut).GetAwaiter().GetResult(); remoteSecurity = remoteSecurityOut.Value; return retVal; } #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream protected override async Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity) { NegotiateStream negotiateStream; string targetName; EndpointIdentity identity; if (WcfEventSource.Instance.WindowsStreamSecurityOnInitiateUpgradeIsEnabled()) { WcfEventSource.Instance.WindowsStreamSecurityOnInitiateUpgrade(); } // prepare InitiateUpgradePrepare(stream, out negotiateStream, out targetName, out identity); // authenticate try { await negotiateStream.AuthenticateAsClientAsync(_credential, targetName, _parent.ProtectionLevel, _impersonationLevel); } catch (AuthenticationException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } remoteSecurity.Value = CreateServerSecurity(negotiateStream); ValidateMutualAuth(identity, negotiateStream, remoteSecurity.Value, _allowNtlm); return negotiateStream; } #else protected override Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity) { throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported); } #endif // SUPPORTS_WINDOWSIDENTITY #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream void InitiateUpgradePrepare( Stream stream, out NegotiateStream negotiateStream, out string targetName, out EndpointIdentity identity) { negotiateStream = new NegotiateStream(stream); targetName = string.Empty; identity = null; if (_parent.IdentityVerifier.TryGetIdentity(RemoteAddress, Via, out identity)) { targetName = SecurityUtils.GetSpnFromIdentity(identity, RemoteAddress); } else { targetName = SecurityUtils.GetSpnFromTarget(RemoteAddress); } } void ValidateMutualAuth(EndpointIdentity expectedIdentity, NegotiateStream negotiateStream, SecurityMessageProperty remoteSecurity, bool allowNtlm) { if (negotiateStream.IsMutuallyAuthenticated) { if (expectedIdentity != null) { if (!_parent.IdentityVerifier.CheckAccess(expectedIdentity, remoteSecurity.ServiceSecurityContext.AuthorizationContext)) { string primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(remoteSecurity.ServiceSecurityContext.AuthorizationContext); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format( SR.RemoteIdentityFailedVerification, primaryIdentity))); } } } else if (!allowNtlm) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.StreamMutualAuthNotSatisfied))); } } #endif // SUPPORTS_WINDOWSIDENTITY } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Parse.Abstractions.Infrastructure; using Parse.Infrastructure.Utilities; using static Parse.Resources; namespace Parse.Infrastructure { /// <summary> /// Implements `IStorageController` for PCL targets, based off of PCLStorage. /// </summary> public class CacheController : IDiskFileCacheController { class FileBackedCache : IDataCache<string, object> { public FileBackedCache(FileInfo file) => File = file; internal Task SaveAsync() => Lock(() => File.WriteContentAsync(JsonUtilities.Encode(Storage))); internal Task LoadAsync() => File.ReadAllTextAsync().ContinueWith(task => { lock (Mutex) { try { Storage = JsonUtilities.Parse(task.Result) as Dictionary<string, object>; } catch { Storage = new Dictionary<string, object> { }; } } }); // TODO: Check if the call to ToDictionary is necessary here considering contents is IDictionary<string object>. internal void Update(IDictionary<string, object> contents) => Lock(() => Storage = contents.ToDictionary(element => element.Key, element => element.Value)); public Task AddAsync(string key, object value) { lock (Mutex) { Storage[key] = value; return SaveAsync(); } } public Task RemoveAsync(string key) { lock (Mutex) { Storage.Remove(key); return SaveAsync(); } } public void Add(string key, object value) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); public bool Remove(string key) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); public void Add(KeyValuePair<string, object> item) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); public bool Remove(KeyValuePair<string, object> item) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); public bool ContainsKey(string key) => Lock(() => Storage.ContainsKey(key)); public bool TryGetValue(string key, out object value) { lock (Mutex) { return (Result: Storage.TryGetValue(key, out object found), value = found).Result; } } public void Clear() => Lock(() => Storage.Clear()); public bool Contains(KeyValuePair<string, object> item) => Lock(() => Elements.Contains(item)); public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) => Lock(() => Elements.CopyTo(array, arrayIndex)); public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => Storage.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => Storage.GetEnumerator(); public FileInfo File { get; set; } public object Mutex { get; set; } = new object { }; // ALTNAME: Operate TResult Lock<TResult>(Func<TResult> operation) { lock (Mutex) { return operation.Invoke(); } } void Lock(Action operation) { lock (Mutex) { operation.Invoke(); } } ICollection<KeyValuePair<string, object>> Elements => Storage as ICollection<KeyValuePair<string, object>>; Dictionary<string, object> Storage { get; set; } = new Dictionary<string, object> { }; public ICollection<string> Keys => Storage.Keys; public ICollection<object> Values => Storage.Values; public int Count => Storage.Count; public bool IsReadOnly => Elements.IsReadOnly; public object this[string key] { get => Storage[key]; set => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); } } FileInfo File { get; set; } FileBackedCache Cache { get; set; } TaskQueue Queue { get; } = new TaskQueue { }; /// <summary> /// Creates a Parse storage controller and attempts to extract a previously created settings storage file from the persistent storage location. /// </summary> public CacheController() { } /// <summary> /// Creates a Parse storage controller with the provided <paramref name="file"/> wrapper. /// </summary> /// <param name="file">The file wrapper that the storage controller instance should target</param> public CacheController(FileInfo file) => EnsureCacheExists(file); FileBackedCache EnsureCacheExists(FileInfo file = default) => Cache ??= new FileBackedCache(file ?? (File ??= PersistentCacheFile)); /// <summary> /// Loads a settings dictionary from the file wrapped by <see cref="File"/>. /// </summary> /// <returns>A storage dictionary containing the deserialized content of the storage file targeted by the <see cref="CacheController"/> instance</returns> public Task<IDataCache<string, object>> LoadAsync() { // Check if storage dictionary is already created from the controllers file (create if not) EnsureCacheExists(); // Load storage dictionary content async and return the resulting dictionary type return Queue.Enqueue(toAwait => toAwait.ContinueWith(_ => Cache.LoadAsync().OnSuccess(__ => Cache as IDataCache<string, object>)).Unwrap(), CancellationToken.None); } /// <summary> /// Saves the requested data. /// </summary> /// <param name="contents">The data to be saved.</param> /// <returns>A data cache containing the saved data.</returns> public Task<IDataCache<string, object>> SaveAsync(IDictionary<string, object> contents) => Queue.Enqueue(toAwait => toAwait.ContinueWith(_ => { EnsureCacheExists().Update(contents); return Cache.SaveAsync().OnSuccess(__ => Cache as IDataCache<string, object>); }).Unwrap()); /// <summary> /// <inheritdoc/> /// </summary> public void RefreshPaths() => Cache = new FileBackedCache(File = PersistentCacheFile); // TODO: Attach the following method to AppDomain.CurrentDomain.ProcessExit if that actually ever made sense for anything except randomly generated file names, otherwise attach the delegate when it is known the file name is a randomly generated string. /// <summary> /// Clears the data controlled by this class. /// </summary> public void Clear() { if (new FileInfo(FallbackRelativeCacheFilePath) is { Exists: true } file) { file.Delete(); } } /// <summary> /// <inheritdoc/> /// </summary> public string RelativeCacheFilePath { get; set; } /// <summary> /// <inheritdoc/> /// </summary> public string AbsoluteCacheFilePath { get => StoredAbsoluteCacheFilePath ?? Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), RelativeCacheFilePath ?? FallbackRelativeCacheFilePath)); set => StoredAbsoluteCacheFilePath = value; } string StoredAbsoluteCacheFilePath { get; set; } /// <summary> /// Gets the calculated persistent storage file fallback path for this app execution. /// </summary> public string FallbackRelativeCacheFilePath => StoredFallbackRelativeCacheFilePath ??= IdentifierBasedRelativeCacheLocationGenerator.Fallback.GetRelativeCacheFilePath(new MutableServiceHub { CacheController = this }); string StoredFallbackRelativeCacheFilePath { get; set; } /// <summary> /// Gets or creates the file pointed to by <see cref="AbsoluteCacheFilePath"/> and returns it's wrapper as a <see cref="FileInfo"/> instance. /// </summary> public FileInfo PersistentCacheFile { get { Directory.CreateDirectory(AbsoluteCacheFilePath.Substring(0, AbsoluteCacheFilePath.LastIndexOf(Path.DirectorySeparatorChar))); FileInfo file = new FileInfo(AbsoluteCacheFilePath); if (!file.Exists) using (file.Create()) ; // Hopefully the JIT doesn't no-op this. The behaviour of the "using" clause should dictate how the stream is closed, to make sure it happens properly. return file; } } /// <summary> /// Gets the file wrapper for the specified <paramref name="path"/>. /// </summary> /// <param name="path">The relative path to the target file</param> /// <returns>An instance of <see cref="FileInfo"/> wrapping the the <paramref name="path"/> value</returns> public FileInfo GetRelativeFile(string path) { Directory.CreateDirectory((path = Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), path))).Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar))); return new FileInfo(path); } // MoveAsync /// <summary> /// Transfers a file from <paramref name="originFilePath"/> to <paramref name="targetFilePath"/>. /// </summary> /// <param name="originFilePath"></param> /// <param name="targetFilePath"></param> /// <returns>A task that completes once the file move operation form <paramref name="originFilePath"/> to <paramref name="targetFilePath"/> completes.</returns> public async Task TransferAsync(string originFilePath, string targetFilePath) { if (!String.IsNullOrWhiteSpace(originFilePath) && !String.IsNullOrWhiteSpace(targetFilePath) && new FileInfo(originFilePath) is { Exists: true } originFile && new FileInfo(targetFilePath) is { } targetFile) { using StreamWriter writer = new StreamWriter(targetFile.OpenWrite(), Encoding.Unicode); using StreamReader reader = new StreamReader(originFile.OpenRead(), Encoding.Unicode); await writer.WriteAsync(await reader.ReadToEndAsync()); } } } }
using System; using System.Text.RegularExpressions; namespace QED.DataValidation { /// <summary> /// This class implements Jeffrey E.F. Friedl's rfc 822 compliant email validator routines. /// Implmented in C# by an unknown author. -ccarey 2003-06-12 /// </summary> public class EmailValidator { // static so that it's shared accross multiple instances. private static Regex oRegex; // Constants to combat backslashitis private const string Escape = @"\\"; private const string Period = @"\."; private const string Space = @"\040"; private const string Tab = @"\t"; private const string OpenBr = @"\["; private const string CloseBr = @"\]"; private const string OpenParen = @"\("; private const string CloseParen = @"\)"; private const string NonAscii = @"\x80-\xff"; private const string Ctrl = @"\000-\037"; private const string CRList = @"\n\015"; // Should only really be \015 private string sMailBox; private string sLocalPart; private string sDomain; private string sQuotedStr; private bool bIsValid = false; public string LocalPart { get { return sLocalPart; } } public string Domain { get { return sDomain; } } public string QuotedString { get { return sQuotedStr; } } public string Mailbox { get { return sMailBox; } } public bool IsValid { get { return bIsValid; } } public EmailValidator() { // initialise the regex... initRegex(); } public EmailValidator(string emailAddy) { // initialise the regex... initRegex(); Parse(emailAddy); } /// <summary> /// This is the actual implementation of the parse routine. /// </summary> /// <param name="email"></param> /// <returns></returns> public bool Parse(string email) { // Match against the regex... Match m = EmailValidator.oRegex.Match(email); this.bIsValid = m.Success; this.sDomain = m.Groups["domain"].ToString(); this.sLocalPart = m.Groups["localpart"].ToString(); this.sMailBox = m.Groups["mailbox"].ToString(); this.sQuotedStr = m.Groups["quotedstr"].ToString(); return this.bIsValid; } /// <summary> /// Init regex initialised the huge regex and compiles it so that it runs a little faster. /// </summary> private void initRegex() { // for within ""; string qtext = @"[^" + EmailValidator.Escape + EmailValidator.NonAscii + EmailValidator.CRList + "\"]"; string dtext = @"[^" + EmailValidator.Escape + EmailValidator.NonAscii + EmailValidator.CRList + EmailValidator.OpenBr + EmailValidator.CloseBr + "\"]"; string quoted_pair = " " + EmailValidator.Escape + " [^" + EmailValidator.NonAscii + "] "; // ********************************************* // comments. // Impossible to do properly with a regex, I make do by allowing at most // one level of nesting. string ctext = @" [^" + EmailValidator.Escape + EmailValidator.NonAscii + EmailValidator.CRList + "()] "; // Nested quoted Pairs string Cnested = ""; Cnested += EmailValidator.OpenParen; Cnested += ctext + "*"; Cnested += "(?:" + quoted_pair + " " + ctext + "*)*"; Cnested += EmailValidator.CloseParen; // A Comment Usually string comment = ""; comment += EmailValidator.OpenParen; comment += ctext + "*"; comment += "(?:"; comment += "(?: " + quoted_pair + " | " + Cnested + ")"; comment += ctext + "*"; comment += ")*"; comment += EmailValidator.CloseParen; // ********************************************* // X is optional whitespace/comments string X = ""; X += "[" + EmailValidator.Space + EmailValidator.Tab + "]*"; X += "(?: " + comment + " [" + EmailValidator.Space + EmailValidator.Tab + "]* )*"; // an email address atom... it's not nuclear ;) string atom_char = @"[^(" + EmailValidator.Space + ")<>\\@,;:\\\"." + EmailValidator.Escape + EmailValidator.OpenBr + EmailValidator.CloseBr + EmailValidator.Ctrl + EmailValidator.NonAscii + "]"; string atom = ""; atom += atom_char + "+"; atom += "(?!" + atom_char + ")"; // doublequoted string, unrolled. string quoted_str = "(?'quotedstr'"; quoted_str += "\\\""; quoted_str += qtext + " *"; quoted_str += "(?: " + quoted_pair + qtext + " * )*"; quoted_str += "\\\")"; // A word is an atom or quoted string string word = ""; word += "(?:"; word += atom; word += "|"; word += quoted_str; word += ")"; // A domain-ref is just an atom string domain_ref = atom; // A domain-literal is like a quoted string, but [...] instead of "..." string domain_lit = ""; domain_lit += EmailValidator.OpenBr; domain_lit += "(?: " + dtext + " | " + quoted_pair + " )*"; domain_lit += EmailValidator.CloseBr; // A sub-domain is a domain-ref or a domain-literal string sub_domain = ""; sub_domain += "(?:"; sub_domain += domain_ref; sub_domain += "|"; sub_domain += domain_lit; sub_domain += ")"; sub_domain += X; // a domain is a list of subdomains separated by dots string domain = "(?'domain'"; domain += sub_domain; domain += "(:?"; domain += EmailValidator.Period + " " + X + " " + sub_domain; domain += ")*)"; // a a route. A bunch of "@ domain" separated by commas, followed by a colon. string route = ""; route += "\\@ " + X + " " + domain; route += "(?: , " + X + " \\@ " + X + " " + domain + ")*"; route += ":"; route += X; // a local-part is a bunch of 'word' separated by periods string local_part = "(?'localpart'"; local_part += word + " " + X; local_part += "(?:"; local_part += EmailValidator.Period + " " + X + " " + word + " " + X; local_part += ")*)"; // an addr-spec is local@domain string addr_spec = local_part + " \\@ " + X + " " + domain; // a route-addr is <route? addr-spec> string route_addr = ""; route_addr += "< " + X; route_addr += "(?: " + route + " )?"; route_addr += addr_spec; route_addr += ">"; // a phrase........ string phrase_ctrl = @"\000-\010\012-\037"; // Like atom-char, but without listing space, and uses phrase_ctrl. // Since the class is negated, this matches the same as atom-char plus space and tab string phrase_char = "[^()<>\\@,;:\\\"." + EmailValidator.Escape + EmailValidator.OpenBr + EmailValidator.CloseBr + EmailValidator.NonAscii + phrase_ctrl + "]"; // We've worked it so that word, comment, and quoted_str to not consume trailing X // because we take care of it manually string phrase = ""; phrase += word; phrase += phrase_char; phrase += "(?:"; phrase += "(?: " + comment + " | " + quoted_str + " )"; phrase += phrase_char + " *"; phrase += ")*"; // A mailbox is an addr_spec or a phrase/route_addr string mailbox = ""; mailbox += X; mailbox += "(?'mailbox'"; mailbox += addr_spec; mailbox += "|"; mailbox += phrase + " " + route_addr; mailbox += ")"; // okay, now setup the object... We'll compile it since this is a rather large (euphemistically // speaking) regex... We also need to IgnorePatternWhitespace unless it's escaped. EmailValidator.oRegex = new Regex(mailbox,RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace); } public static string EmailToUser(string email){ EmailValidator ev = new EmailValidator(email); return ev.LocalPart; } } }
// 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.Collections.Generic; using System.Composition; using System.Composition.Hosting; using System.Composition.Hosting.Providers; using System.Linq; using Xunit; namespace System.Composition.UnitTests { public interface ISharedTestingClass { void Method(); } [Export(typeof(ISharedTestingClass))] public class NonSharedClass : ISharedTestingClass { [ImportingConstructor] public NonSharedClass() { } public void Method() { } } [Export(typeof(ISharedTestingClass))] [Shared] public class SharedClass : ISharedTestingClass { [ImportingConstructor] public SharedClass() { } public void Method() { } } [Export] [Shared] public class ClassWithExportFactoryShared { private readonly ExportFactory<ISharedTestingClass> _fact; [ImportingConstructor] public ClassWithExportFactoryShared(ExportFactory<ISharedTestingClass> factory) { _fact = factory; } public ISharedTestingClass Method() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] public class ClassWithExportFactoryNonShared { private readonly ExportFactory<ISharedTestingClass> _fact; [ImportingConstructor] public ClassWithExportFactoryNonShared(ExportFactory<ISharedTestingClass> factory) { _fact = factory; } public ISharedTestingClass Method() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] public class ClassWithExportFactoryAsAProperty { [Import] public ExportFactory<ISharedTestingClass> _fact { get; set; } public ClassWithExportFactoryAsAProperty() { } public ISharedTestingClass Method() { using (var b = _fact.CreateExport()) { return b.Value; } } } internal interface IX { } internal interface IY { } [Export] [Shared("Boundary")] public class A { public int SharedState { get; set; } } [Export] public class B { public A InstanceA { get; set; } public D InstanceD { get; set; } [ImportingConstructor] public B(A a, D d) { InstanceA = a; InstanceD = d; } } [Export] public class D { public A InstanceA; [ImportingConstructor] public D(A a) { InstanceA = a; } } [Export] public class C { private readonly ExportFactory<B> _fact; [ImportingConstructor] public C([SharingBoundary("Boundary")]ExportFactory<B> fact) { _fact = fact; } public B CreateInstance() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] public class CPrime { private readonly ExportFactory<B> _fact; [ImportingConstructor] public CPrime(ExportFactory<B> fact) { _fact = fact; } public B CreateInstance() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] [Shared("Boundary")] public class CirC { public CirA DepA { get; private set; } [ImportingConstructor] public CirC(CirA a) { DepA = a; } } [Export] [Shared] public class CirA { public int SharedState; private readonly ExportFactory<CirB> _fact; [ImportingConstructor] public CirA([SharingBoundary("Boundary")]ExportFactory<CirB> b) { _fact = b; } public CirB CreateInstance() { using (var ins = _fact.CreateExport()) { return ins.Value; } } } [Export] public class CirB { public CirC DepC { get; private set; } [ImportingConstructor] public CirB(CirC c) { DepC = c; } } public interface IProj { } [Export] public class SolA { private readonly IEnumerable<ExportFactory<IProj>> _fact; public List<IProj> Projects { get; private set; } [ImportingConstructor] public SolA([ImportMany][SharingBoundary("B1", "B2")] IEnumerable<ExportFactory<IProj>> c) { Projects = new List<IProj>(); _fact = c; } public void SetupProject() { foreach (var fact in _fact) { using (var instance = fact.CreateExport()) { Projects.Add(instance.Value); } } } } [Export(typeof(IProj))] public class ProjA : IProj { [ImportingConstructor] public ProjA(DocA docA, ColA colA) { } } [Export(typeof(IProj))] public class ProjB : IProj { [ImportingConstructor] public ProjB(DocB docA, ColB colA) { } } [Export] public class DocA { [ImportingConstructor] public DocA(ColA colA) { } } [Export] public class DocB { [ImportingConstructor] public DocB(ColB colB) { } } [Export] [Shared("B1")] public class ColA { public ColA() { } } [Export] [Shared("B2")] public class ColB { public ColB() { } } public interface ICol { } [Export(typeof(IX)), Export(typeof(IY)), Shared] public class XY : IX, IY { } public class SharingTest : ContainerTests { /// <summary> /// Two issues here One is that the message could be improved /// "The component (unknown) cannot be created outside the Boundary sharing boundary." /// Second is we don`t fail when we getExport for CPrime /// we fail only when we create instance of B.. is that correct. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void BoundaryExposedBoundaryButNoneImported() { try { var cc = CreateContainer(typeof(A), typeof(B), typeof(CPrime), typeof(D)); var cInstance = cc.GetExport<CPrime>(); var bIn1 = cInstance.CreateInstance(); } catch (Exception ex) { Assert.True(ex.Message.Contains("The component (unknown) cannot be created outside the Boundary sharing boundary")); } } /// <summary> /// Need a partcreationpolicy currently. /// Needs to be fixed so that specifying boundary would automatically create the shared /// </summary> [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/20656", TargetFrameworkMonikers.UapAot)] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void BoundarySharingTest() { var cc = CreateContainer(typeof(A), typeof(B), typeof(C), typeof(D)); var cInstance = cc.GetExport<C>(); var bIn1 = cInstance.CreateInstance(); var bIn2 = cInstance.CreateInstance(); bIn1.InstanceA.SharedState = 1; var val1 = bIn1.InstanceD.InstanceA; bIn2.InstanceA.SharedState = 5; var val2 = bIn2.InstanceD.InstanceA; Assert.True(val1.SharedState == 1); Assert.True(val2.SharedState == 5); } /// <summary> /// CirA root of the composition has to be shared explicitly. /// </summary> [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/20656", TargetFrameworkMonikers.UapAot)] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CircularBoundarySharingTest() { var cc = CreateContainer(typeof(CirA), typeof(CirB), typeof(CirC)); var cInstance = cc.GetExport<CirA>(); cInstance.SharedState = 1; var bInstance1 = cInstance.CreateInstance(); Assert.Equal(bInstance1.DepC.DepA.SharedState, 1); bInstance1.DepC.DepA.SharedState = 10; cInstance.CreateInstance(); Assert.Equal(bInstance1.DepC.DepA.SharedState, 10); } /// <summary> /// Something is badly busted here.. I am getting a null ref exception /// </summary> [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/20656", TargetFrameworkMonikers.UapAot)] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void MultipleBoundarySpecified() { var cc = CreateContainer(typeof(ProjA), typeof(ProjB), typeof(SolA), typeof(DocA), typeof(DocB), typeof(ColA), typeof(ColB)); var solInstance = cc.GetExport<SolA>(); solInstance.SetupProject(); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void SharedPartExportingMultipleContractsSharesAnInstance() { var cc = CreateContainer(typeof(XY)); var x = cc.GetExport<IX>(); var y = cc.GetExport<IY>(); Assert.Same(x, y); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void GetExportsCreatesInstancedObjectByDefault() { var cc = CreateContainer(typeof(NonSharedClass)); var val1 = cc.GetExport<ISharedTestingClass>(); var val2 = cc.GetExport<ISharedTestingClass>(); Assert.NotSame(val1, val2); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void GetExportsCreatesSharedObjectsWhenSpecified() { var cc = CreateContainer(typeof(SharedClass)); var val1 = cc.GetExport<ISharedTestingClass>(); var val2 = cc.GetExport<ISharedTestingClass>(); Assert.Same(val1, val2); } /// <summary> /// Class with export factory that, which is shared that has a part that is non shared /// verify that GetExport returns only one instance regardless of times it is called /// verify that On Method call different instances are returned. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ExportFactoryCreatesNewInstances() { var cc = CreateContainer(typeof(ClassWithExportFactoryShared), typeof(NonSharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryShared>(); var b2 = cc.GetExport<ClassWithExportFactoryShared>(); var inst1 = b1.Method(); var inst2 = b1.Method(); Assert.Same(b1, b2); Assert.NotSame(inst1, inst2); } /// <summary> /// ExportFactory should be importable as a property /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ClassWithExportFactoryAsAProperty() { var cc = CreateContainer(typeof(ClassWithExportFactoryAsAProperty), typeof(NonSharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryAsAProperty>(); var inst1 = b1.Method(); var inst2 = b1.Method(); Assert.NotNull(b1._fact); Assert.NotSame(inst1, inst2); } /// <summary> /// ExportFactory class is itself shared and /// will still respect the CreationPolicyAttribute on a part. If the export factory /// is creating a part which is shared, it will return back the same instance of the part. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ClassWithExportFactoryAndSharedExport() { var cc = CreateContainer(typeof(ClassWithExportFactoryShared), typeof(SharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryShared>(); var b2 = cc.GetExport<ClassWithExportFactoryShared>(); var inst1 = b1.Method(); var inst2 = b2.Method(); Assert.Same(b1, b2); Assert.Same(inst1, inst2); } /// <summary> /// Class which is nonShared has an exportFactory in it for a shared part. /// Two instances of the root class are created , the part created using export factory should not be shared /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ClassWithNonSharedExportFactoryCreatesSharedInstances() { var cc = CreateContainer(typeof(ClassWithExportFactoryNonShared), typeof(SharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryNonShared>(); var b2 = cc.GetExport<ClassWithExportFactoryNonShared>(); var inst1 = b1.Method(); var inst2 = b2.Method(); Assert.NotSame(b1, b2); Assert.Same(inst1, inst2); } [Shared, Export] public class ASharedPart { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ConsistentResultsAreReturneWhenResolvingLargeNumbersOfSharedParts() { var config = new ContainerConfiguration(); // Chosen to cause overflows in SmallSparseInitOnlyArray for (var i = 0; i < 1000; ++i) config.WithPart<ASharedPart>(); Assert.NotEqual(new ASharedPart(), new ASharedPart()); var container = config.CreateContainer(); var first = container.GetExports<ASharedPart>().ToList(); var second = container.GetExports<ASharedPart>().ToList(); Assert.Equal(first, second); } } }
// 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.Text; using System.Collections.Generic; using Xunit; using Microsoft.Xunit.Performance; namespace System.Runtime.Tests { public class Perf_String { public static IEnumerable<object[]> TestStringSizes() { yield return new object[] { 10 }; yield return new object[] { 100 }; yield return new object[] { 1000 }; } [Benchmark] [MemberData("TestStringSizes")] public void GetChars(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) { testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); testString.ToCharArray(); } } [Benchmark] [MemberData("TestStringSizes")] public void Concat_str_str(int size) { PerfUtils utils = new PerfUtils(); string testString1 = utils.CreateString(size); string testString2 = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) string.Concat(testString1, testString2); } [Benchmark] [MemberData("TestStringSizes")] public void Concat_str_str_str(int size) { PerfUtils utils = new PerfUtils(); string testString1 = utils.CreateString(size); string testString2 = utils.CreateString(size); string testString3 = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) string.Concat(testString1, testString2, testString3); } [Benchmark] [MemberData("TestStringSizes")] public void Concat_str_str_str_str(int size) { PerfUtils utils = new PerfUtils(); string testString1 = utils.CreateString(size); string testString2 = utils.CreateString(size); string testString3 = utils.CreateString(size); string testString4 = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) string.Concat(testString1, testString2, testString3, testString4); } [Benchmark] [MemberData("TestStringSizes")] public void Contains(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); string subString = testString.Substring(testString.Length / 2, testString.Length / 4); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Contains(subString); } [Benchmark] [MemberData("TestStringSizes")] public void Equals(int size) { PerfUtils utils = new PerfUtils(); string testString1 = utils.CreateString(size); string testString2 = new string(testString1.ToCharArray()); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString1.Equals(testString2); } [Benchmark] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(10)] [InlineData(100)] public void Format(int numberOfObjects) { PerfUtils utils = new PerfUtils(); // Setup the format string and the list of objects to format StringBuilder formatter = new StringBuilder(); List<string> objects = new List<string>(); for (int i = 0; i < numberOfObjects; i++) { formatter.Append("%s, "); objects.Add(utils.CreateString(10)); } string format = formatter.ToString(); string[] objectArr = objects.ToArray(); // Perform the actual formatting foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 5000; i++) string.Format(format, objectArr); } [Benchmark] [MemberData("TestStringSizes")] public void GetLength(int size) { PerfUtils utils = new PerfUtils(); int result; string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) { result = testString.Length; result = testString.Length; result = testString.Length; result = testString.Length; result = testString.Length; result = testString.Length; result = testString.Length; result = testString.Length; result = testString.Length; } } [Benchmark] [MemberData("TestStringSizes")] public void op_Equality(int size) { PerfUtils utils = new PerfUtils(); bool result; string testString1 = utils.CreateString(size); string testString2 = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) { result = testString1 == testString2; result = testString1 == testString2; result = testString1 == testString2; result = testString1 == testString2; result = testString1 == testString2; result = testString1 == testString2; } } [Benchmark] [MemberData("TestStringSizes")] public void Replace(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); string existingValue = testString.Substring(testString.Length / 2, 1); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Replace(existingValue, "1"); } [Benchmark] [MemberData("TestStringSizes")] public void Split(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); string existingValue = testString.Substring(testString.Length / 2, 1); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Split(existingValue); } [Benchmark] [MemberData("TestStringSizes")] public void StartsWith(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); string subString = testString.Substring(0, testString.Length / 4); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.StartsWith(subString); } [Benchmark] [MemberData("TestStringSizes")] public void Substring_int(int size) { PerfUtils utils = new PerfUtils(); int startIndex = size / 2; string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Substring(startIndex); } [Benchmark] [MemberData("TestStringSizes")] public void Substring_int_int(int size) { PerfUtils utils = new PerfUtils(); int startIndex = size / 2; int length = size / 4; string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Substring(startIndex, length); } [Benchmark] [MemberData("TestStringSizes")] public void ToLower(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.ToLower(); } [Benchmark] [MemberData("TestStringSizes")] public void ToUpper(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.ToUpper(); } [Benchmark] [MemberData("TestStringSizes")] public void Trim_WithWhitespace(int size) { PerfUtils utils = new PerfUtils(); string testString = " " + utils.CreateString(size) + " "; foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Trim(); } [Benchmark] [MemberData("TestStringSizes")] public void Trim_NothingToDo(int size) { PerfUtils utils = new PerfUtils(); string testString = utils.CreateString(size); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i < 10000; i++) testString.Trim(); } } }
// 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 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Internal.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for PolicyAssignmentsOperations. /// </summary> public static partial class PolicyAssignmentsOperationsExtensions { /// <summary> /// Deletes a policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// The scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// The name of the policy assignment to delete. /// </param> public static PolicyAssignment Delete(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).DeleteAsync(scope, policyAssignmentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// The scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// The name of the policy assignment to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PolicyAssignment> DeleteAsync(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, policyAssignmentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a policy assignment. /// </summary> /// Policy assignments are inherited by child resources. For example, when you /// apply a policy to a resource group that policy is assigned to all /// resources in the group. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// The scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// The name of the policy assignment. /// </param> /// <param name='parameters'> /// Parameters for the policy assignment. /// </param> public static PolicyAssignment Create(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, PolicyAssignment parameters) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).CreateAsync(scope, policyAssignmentName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a policy assignment. /// </summary> /// Policy assignments are inherited by child resources. For example, when you /// apply a policy to a resource group that policy is assigned to all /// resources in the group. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// The scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// The name of the policy assignment. /// </param> /// <param name='parameters'> /// Parameters for the policy assignment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PolicyAssignment> CreateAsync(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, PolicyAssignment parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(scope, policyAssignmentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// The scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// The name of the policy assignment to get. /// </param> public static PolicyAssignment Get(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).GetAsync(scope, policyAssignmentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// The scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// The name of the policy assignment to get. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PolicyAssignment> GetAsync(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(scope, policyAssignmentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments for the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains policy assignments. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> public static IPage<PolicyAssignment> ListForResourceGroup(this IPolicyAssignmentsOperations operations, string resourceGroupName, string filter = default(string)) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceGroupAsync(resourceGroupName, filter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments for the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains policy assignments. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PolicyAssignment>> ListForResourceGroupAsync(this IPolicyAssignmentsOperations operations, string resourceGroupName, string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments for a resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group containing the resource. The name is case /// insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='parentResourcePath'> /// The parent resource path. /// </param> /// <param name='resourceType'> /// The resource type. /// </param> /// <param name='resourceName'> /// The name of the resource with policy assignments. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<PolicyAssignment> ListForResource(this IPolicyAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<PolicyAssignment> odataQuery = default(ODataQuery<PolicyAssignment>)) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments for a resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group containing the resource. The name is case /// insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='parentResourcePath'> /// The parent resource path. /// </param> /// <param name='resourceType'> /// The resource type. /// </param> /// <param name='resourceName'> /// The name of the resource with policy assignments. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PolicyAssignment>> ListForResourceAsync(this IPolicyAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<PolicyAssignment> odataQuery = default(ODataQuery<PolicyAssignment>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListForResourceWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the policy assignments for a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<PolicyAssignment> List(this IPolicyAssignmentsOperations operations, ODataQuery<PolicyAssignment> odataQuery = default(ODataQuery<PolicyAssignment>)) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the policy assignments for a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PolicyAssignment>> ListAsync(this IPolicyAssignmentsOperations operations, ODataQuery<PolicyAssignment> odataQuery = default(ODataQuery<PolicyAssignment>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a policy assignment by ID. /// </summary> /// When providing a scope for the assigment, use /// '/subscriptions/{subscription-id}/' for subscriptions, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for resource groups, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' /// for resources. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// The ID of the policy assignment to delete. Use the format /// '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. /// </param> public static PolicyAssignment DeleteById(this IPolicyAssignmentsOperations operations, string policyAssignmentId) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).DeleteByIdAsync(policyAssignmentId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a policy assignment by ID. /// </summary> /// When providing a scope for the assigment, use /// '/subscriptions/{subscription-id}/' for subscriptions, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for resource groups, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' /// for resources. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// The ID of the policy assignment to delete. Use the format /// '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PolicyAssignment> DeleteByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteByIdWithHttpMessagesAsync(policyAssignmentId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a policy assignment by ID. /// </summary> /// Policy assignments are inherited by child resources. For example, when you /// apply a policy to a resource group that policy is assigned to all /// resources in the group. When providing a scope for the assigment, use /// '/subscriptions/{subscription-id}/' for subscriptions, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for resource groups, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' /// for resources. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// The ID of the policy assignment to create. Use the format /// '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. /// </param> /// <param name='parameters'> /// Parameters for policy assignment. /// </param> public static PolicyAssignment CreateById(this IPolicyAssignmentsOperations operations, string policyAssignmentId, PolicyAssignment parameters) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).CreateByIdAsync(policyAssignmentId, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a policy assignment by ID. /// </summary> /// Policy assignments are inherited by child resources. For example, when you /// apply a policy to a resource group that policy is assigned to all /// resources in the group. When providing a scope for the assigment, use /// '/subscriptions/{subscription-id}/' for subscriptions, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for resource groups, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' /// for resources. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// The ID of the policy assignment to create. Use the format /// '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. /// </param> /// <param name='parameters'> /// Parameters for policy assignment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PolicyAssignment> CreateByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, PolicyAssignment parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateByIdWithHttpMessagesAsync(policyAssignmentId, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a policy assignment by ID. /// </summary> /// When providing a scope for the assigment, use /// '/subscriptions/{subscription-id}/' for subscriptions, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for resource groups, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' /// for resources. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// The ID of the policy assignment to get. Use the format /// '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. /// </param> public static PolicyAssignment GetById(this IPolicyAssignmentsOperations operations, string policyAssignmentId) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).GetByIdAsync(policyAssignmentId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a policy assignment by ID. /// </summary> /// When providing a scope for the assigment, use /// '/subscriptions/{subscription-id}/' for subscriptions, /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' /// for resource groups, and /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' /// for resources. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// The ID of the policy assignment to get. Use the format /// '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PolicyAssignment> GetByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByIdWithHttpMessagesAsync(policyAssignmentId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments for the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<PolicyAssignment> ListForResourceGroupNext(this IPolicyAssignmentsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments for the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PolicyAssignment>> ListForResourceGroupNextAsync(this IPolicyAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments for a resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<PolicyAssignment> ListForResourceNext(this IPolicyAssignmentsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments for a resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PolicyAssignment>> ListForResourceNextAsync(this IPolicyAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListForResourceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the policy assignments for a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<PolicyAssignment> ListNext(this IPolicyAssignmentsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the policy assignments for a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PolicyAssignment>> ListNextAsync(this IPolicyAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2) #define SupportCustomYieldInstruction #endif using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using UniRx.InternalUtil; using UnityEngine; namespace UniRx { public sealed class MainThreadDispatcher : MonoBehaviour { public enum CullingMode { /// <summary> /// Won't remove any MainThreadDispatchers. /// </summary> Disabled, /// <summary> /// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself. /// </summary> Self, /// <summary> /// Search for excess MainThreadDispatchers and removes them all on Awake(). /// </summary> All } public static CullingMode cullingMode = CullingMode.Self; #if UNITY_EDITOR // In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update. // EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update. class EditorThreadDispatcher { static object gate = new object(); static EditorThreadDispatcher instance; public static EditorThreadDispatcher Instance { get { // Activate EditorThreadDispatcher is dangerous, completely Lazy. lock (gate) { if (instance == null) { instance = new EditorThreadDispatcher(); } return instance; } } } ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker(); EditorThreadDispatcher() { UnityEditor.EditorApplication.update += Update; } public void Enqueue(Action<object> action, object state) { editorQueueWorker.Enqueue(action, state); } public void UnsafeInvoke(Action action) { try { action(); } catch (Exception ex) { Debug.LogException(ex); } } public void UnsafeInvoke<T>(Action<T> action, T state) { try { action(state); } catch (Exception ex) { Debug.LogException(ex); } } public void PseudoStartCoroutine(IEnumerator routine) { editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); } void Update() { editorQueueWorker.ExecuteAll(x => Debug.LogException(x)); } void ConsumeEnumerator(IEnumerator routine) { if (routine.MoveNext()) { var current = routine.Current; if (current == null) { goto ENQUEUE; } var type = current.GetType(); if (type == typeof(WWW)) { var www = (WWW)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitWWW(www, routine)), null); return; } else if (type == typeof(AsyncOperation)) { var asyncOperation = (AsyncOperation)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine)), null); return; } else if (type == typeof(WaitForSeconds)) { var waitForSeconds = (WaitForSeconds)current; var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic); var second = (float)accessor.GetValue(waitForSeconds); editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine)), null); return; } else if (type == typeof(Coroutine)) { Debug.Log("Can't wait coroutine on UnityEditor"); goto ENQUEUE; } #if SupportCustomYieldInstruction else if (current is IEnumerator) { var enumerator = (IEnumerator)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapEnumerator(enumerator, routine)), null); return; } #endif ENQUEUE: editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); // next update } } IEnumerator UnwrapWaitWWW(WWW www, IEnumerator continuation) { while (!www.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation) { while (!asyncOperation.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation) { var startTime = DateTimeOffset.UtcNow; while (true) { yield return null; var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds; if (elapsed >= second) { break; } }; ConsumeEnumerator(continuation); } IEnumerator UnwrapEnumerator(IEnumerator enumerator, IEnumerator continuation) { while (enumerator.MoveNext()) { yield return null; } ConsumeEnumerator(continuation); } } #endif /// <summary>Dispatch Asyncrhonous action.</summary> public static void Post(Action<object> action, object state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; } #endif var dispatcher = Instance; if (!isQuitting && !object.ReferenceEquals(dispatcher, null)) { dispatcher.queueWorker.Enqueue(action, state); } } /// <summary>Dispatch Synchronous action if possible.</summary> public static void Send(Action<object> action, object state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; } #endif if (mainThreadToken != null) { try { action(state); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } else { Post(action, state); } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend(Action action) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; } #endif try { action(); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend<T>(Action<T> action, T state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; } #endif try { action(state); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>ThreadSafe StartCoroutine.</summary> public static void SendStartCoroutine(IEnumerator routine) { if (mainThreadToken != null) { StartCoroutine(routine); } else { #if UNITY_EDITOR // call from other thread if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (!isQuitting && !object.ReferenceEquals(dispatcher, null)) { dispatcher.queueWorker.Enqueue(_ => { var distpacher2 = Instance; if (distpacher2 != null) { distpacher2.StartCoroutine_Auto(routine); } }, null); } } } public static void StartUpdateMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.updateMicroCoroutine.AddCoroutine(routine); } } public static void StartFixedUpdateMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.fixedUpdateMicroCoroutine.AddCoroutine(routine); } } public static void StartEndOfFrameMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.endOfFrameMicroCoroutine.AddCoroutine(routine); } } new public static Coroutine StartCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; } #endif var dispatcher = Instance; if (dispatcher != null) { return dispatcher.StartCoroutine_Auto(routine); } else { return null; } } public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback) { if (exceptionCallback == null) { // do nothing Instance.unhandledExceptionCallback = Stubs<Exception>.Ignore; } else { Instance.unhandledExceptionCallback = exceptionCallback; } } ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker(); Action<Exception> unhandledExceptionCallback = ex => Debug.LogException(ex); // default MicroCoroutine updateMicroCoroutine = null; int updateCountForRefresh = 0; const int UpdateRefreshCycle = 79; MicroCoroutine fixedUpdateMicroCoroutine = null; int fixedUpdateCountForRefresh = 0; const int FixedUpdateRefreshCycle = 73; MicroCoroutine endOfFrameMicroCoroutine = null; int endOfFrameCountForRefresh = 0; const int EndOfFrameRefreshCycle = 71; static MainThreadDispatcher instance; static bool initialized; static bool isQuitting = false; public static string InstanceName { get { if (instance == null) { throw new NullReferenceException("MainThreadDispatcher is not initialized."); } return instance.name; } } public static bool IsInitialized { get { return initialized && instance != null; } } [ThreadStatic] static object mainThreadToken; static MainThreadDispatcher Instance { get { Initialize(); return instance; } } public static void Initialize() { if (!initialized) { #if UNITY_EDITOR // Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView. if (!ScenePlaybackDetector.IsPlaying) return; #endif MainThreadDispatcher dispatcher = null; try { dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); } catch { // Throw exception when calling from a worker thread. var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread."); UnityEngine.Debug.LogException(ex); throw ex; } if (isQuitting) { // don't create new instance after quitting // avoid "Some objects were not cleaned up when closing the scene find target" error. return; } if (dispatcher == null) { instance = new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>(); } else { instance = dispatcher; } DontDestroyOnLoad(instance); mainThreadToken = new object(); initialized = true; } } void Awake() { if (instance == null) { instance = this; mainThreadToken = new object(); initialized = true; StartCoroutine_Auto(RunUpdateMicroCoroutine()); StartCoroutine_Auto(RunFixedUpdateMicroCoroutine()); StartCoroutine_Auto(RunEndOfFrameMicroCoroutine()); // Added for consistency with Initialize() DontDestroyOnLoad(gameObject); } else { if (cullingMode == CullingMode.Self) { Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself..."); // Destroy this dispatcher if there's already one in the scene. DestroyDispatcher(this); } else if (cullingMode == CullingMode.All) { Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers..."); CullAllExcessDispatchers(); } else { Debug.LogWarning("There is already a MainThreadDispatcher in the scene."); } } } IEnumerator RunUpdateMicroCoroutine() { this.updateMicroCoroutine = new MicroCoroutine( () => { if (updateCountForRefresh > UpdateRefreshCycle) { updateCountForRefresh = 0; return true; } else { return false; } }, ex => unhandledExceptionCallback(ex)); while (true) { yield return null; updateCountForRefresh++; updateMicroCoroutine.Run(); } } IEnumerator RunFixedUpdateMicroCoroutine() { this.fixedUpdateMicroCoroutine = new MicroCoroutine( () => { if (fixedUpdateCountForRefresh > FixedUpdateRefreshCycle) { fixedUpdateCountForRefresh = 0; return true; } else { return false; } }, ex => unhandledExceptionCallback(ex)); while (true) { yield return YieldInstructionCache.WaitForFixedUpdate; fixedUpdateCountForRefresh++; fixedUpdateMicroCoroutine.Run(); } } IEnumerator RunEndOfFrameMicroCoroutine() { this.endOfFrameMicroCoroutine = new MicroCoroutine( () => { if (endOfFrameCountForRefresh > EndOfFrameRefreshCycle) { endOfFrameCountForRefresh = 0; return true; } else { return false; } }, ex => unhandledExceptionCallback(ex)); while (true) { yield return YieldInstructionCache.WaitForEndOfFrame; endOfFrameCountForRefresh++; endOfFrameMicroCoroutine.Run(); } } static void DestroyDispatcher(MainThreadDispatcher aDispatcher) { if (aDispatcher != instance) { // Try to remove game object if it's empty var components = aDispatcher.gameObject.GetComponents<Component>(); if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2) { if (components[0] is Transform && components[1] is MainThreadDispatcher) { Destroy(aDispatcher.gameObject); } } else { // Remove component MonoBehaviour.Destroy(aDispatcher); } } } public static void CullAllExcessDispatchers() { var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>(); for (int i = 0; i < dispatchers.Length; i++) { DestroyDispatcher(dispatchers[i]); } } void OnDestroy() { if (instance == this) { instance = GameObject.FindObjectOfType<MainThreadDispatcher>(); initialized = instance != null; /* // Although `this` still refers to a gameObject, it won't be found. var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); if (foundDispatcher != null) { // select another game object Debug.Log("new instance: " + foundDispatcher.name); instance = foundDispatcher; initialized = true; } */ } } void Update() { if (update != null) { try { update.OnNext(Unit.Default); } catch (Exception ex) { unhandledExceptionCallback(ex); } } queueWorker.ExecuteAll(unhandledExceptionCallback); } // for Lifecycle Management Subject<Unit> update; public static IObservable<Unit> UpdateAsObservable() { return Instance.update ?? (Instance.update = new Subject<Unit>()); } Subject<Unit> lateUpdate; void LateUpdate() { if (lateUpdate != null) lateUpdate.OnNext(Unit.Default); } public static IObservable<Unit> LateUpdateAsObservable() { return Instance.lateUpdate ?? (Instance.lateUpdate = new Subject<Unit>()); } Subject<bool> onApplicationFocus; void OnApplicationFocus(bool focus) { if (onApplicationFocus != null) onApplicationFocus.OnNext(focus); } public static IObservable<bool> OnApplicationFocusAsObservable() { return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>()); } Subject<bool> onApplicationPause; void OnApplicationPause(bool pause) { if (onApplicationPause != null) onApplicationPause.OnNext(pause); } public static IObservable<bool> OnApplicationPauseAsObservable() { return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>()); } Subject<Unit> onApplicationQuit; void OnApplicationQuit() { isQuitting = true; if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default); } public static IObservable<Unit> OnApplicationQuitAsObservable() { return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>()); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using RoslynIntellisense; using Microsoft.CodeAnalysis; using Intellisense.Common; //using csscript; // Shockingly there is no one truly transparent IPC solution for Win, Linux, Mac // - Named-pipes are not implemented on Linux // - Sockets seems to be a good portable approach but they claim port (no biggie though) // but on Windows opening socket server will require granting special permissions. Meaning a // "frightening" confirmation dialog that is not a good for UX. // - Unix domain socket plays the same role as named-pipes but with Socket interface: not portable // on Win and create file anyway. BTW the file that may be left on the system: // http://mono.1490590.n4.nabble.com/Unix-domain-sockets-on-mono-td1490601.html // - Unix-pipes then closest Win named-pipes equivalent are still OS specific and create a file as well. // --------------------- // Bottom line: the only a compromise solution, which is simple and portable is to use a plain socket. // - ultimately portable // - fast enough (particularly with request rate we need to meet - less than 1 request per 3 sec) // - requires no special permissions on Linux (even if it does on Win) // - full control of cleanup (as there is none) namespace Syntaxer { // Ports: // 18000 - Sublime Text 3 // 18001 - Notepad++ // 18002 - VSCode.CodeMap // 18003 - VSCode.CS-Script class Server { // -port:18003 -listen -timeout:60000 cscs_path:C:\Users\<user>\AppData\Roaming\Code\User\cs-script.user\syntaxer\1.2.2.0\cscs.exe static void Main(string[] args) { // Debug.Assert(false); DeployCSScriptIntegration(); var input = new Args(args); if (input.dr) DeployRoslyn(); // -listen -timeout:60000 -cscs_path:./cscs.exe if (Environment.OSVersion.Platform.ToString().StartsWith("Win")) { if (!input.dr) // not already deployed DeployRoslyn(); } else { LoadRoslyn(); } mono_root = Path.GetDirectoryName(typeof(string).Assembly.Location); Output.WriteLine(mono_root); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; TestIntellisenseCommon(); Run(input); } static string mono_root; static string local_dir; static string Local_dir { get { // must be assigned here as if it is assigned in the field declaration it triggers premature assembly loading. return local_dir = local_dir ?? Assembly.GetExecutingAssembly().Location.GetDirName(); } } private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return Probe(mono_root, args.Name) ?? Probe(mono_root.PathJoin("Fasades"), args.Name) ?? Probe(Local_dir, args.Name) ?? ProbeAlreadyLoaded(args.ShortName()); } static void Run(Args input) { if (input.cscs_path != null) { csscript.cscs_path = Path.GetFullPath(input.cscs_path); } if (csscript.cscs_path == null || !Directory.Exists(csscript.cscs_path)) { Console.WriteLine("Probing cscs.exe ..."); if (File.Exists(csscript.default_cscs_path)) { csscript.cscs_path = csscript.default_cscs_path; } else if (File.Exists(csscript.default_cscs_path2)) { csscript.cscs_path = csscript.default_cscs_path2; } else Console.WriteLine("Probing cscs.exe failed..."); } else Console.WriteLine("cscs.exe: " + csscript.cscs_path); if (input.test) { if (csscript.cscs_path == null) csscript.cscs_path = csscript.default_cscs_path; Test.All(); } else { if (input.listen) SocketServer.Listen(input); else Output.WriteLine(SyntaxProvider.ProcessRequest(input)); } } static void DeployRoslyn() { var dir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); ForEachRoslynAssembly((name, bytes) => { if (!File.Exists(Path.Combine(dir, name))) File.WriteAllBytes(Path.Combine(dir, name), bytes); }); } static void DeployCSScriptIntegration() { var dir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); ForEachCSScriptAssembly((name, bytes) => File.WriteAllBytes(Path.Combine(dir, name), bytes)); } static void LoadCSScriptIntegration() { ForEachCSScriptAssembly((name, bytes) => Assembly.Load(bytes)); } static void LoadRoslyn() { ForEachRoslynAssembly((name, bytes) => { Assembly.Load(bytes); }); } static void ForEachCSScriptAssembly(Action<string, byte[]> action) { Action<string, byte[]> _action = (name, bytes) => { try { action(name, bytes); } catch { } }; // _action("CSSRoslynProvider.dll", syntaxer.Properties.Resources.CSSRoslynProvider); _action("Intellisense.Common.dll", syntaxer.Properties.Resources.Intellisense_Common); _action("RoslynIntellisense.exe", syntaxer.Properties.Resources.RoslynIntellisense); } public static void TestIntellisenseCommon() { // the distro can be accidentally packed with the wrong assembly (older) version var assembly = typeof(ICompletionData).Assembly.GetName(); if (assembly.Version < new Version("1.0.1.0")) throw new Exception( $"Invalid {assembly.Name} version v{assembly.Version}\n" + $"Must be at least v1.0.1.0"); } static void ForEachRoslynAssembly(Action<string, byte[]> action) { Action<string, byte[]> _action = (name, bytes) => { try { action(name, bytes); } catch { } }; _action("csc.exe", syntaxer.Properties.Resources.csc_exe); _action("csc.exe.config", Encoding.UTF8.GetBytes(syntaxer.Properties.Resources.csc_exe_config)); _action("csc.rsp", syntaxer.Properties.Resources.csc_rsp); _action("csi.exe", syntaxer.Properties.Resources.csi_exe); _action("csi.rsp", syntaxer.Properties.Resources.csi_rsp); _action("csi.exe.config", Encoding.UTF8.GetBytes(syntaxer.Properties.Resources.csi_exe_config)); _action("Esent.Interop.dll", syntaxer.Properties.Resources.Esent_Interop); _action("Microsoft.Build.dll", syntaxer.Properties.Resources.Microsoft_Build); _action("Microsoft.Build.Framework.dll", syntaxer.Properties.Resources.Microsoft_Build_Framework); _action("Microsoft.Build.Tasks.CodeAnalysis.dll", syntaxer.Properties.Resources.Microsoft_Build_Tasks_CodeAnalysis); _action("Microsoft.Build.Tasks.Core.dll", syntaxer.Properties.Resources.Microsoft_Build_Tasks_Core); _action("Microsoft.Build.Utilities.Core.dll", syntaxer.Properties.Resources.Microsoft_Build_Utilities_Core); _action("Microsoft.CodeAnalysis.CSharp.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_CSharp); _action("Microsoft.CodeAnalysis.CSharp.Scripting.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_CSharp_Scripting); _action("Microsoft.CodeAnalysis.CSharp.Workspaces.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_CSharp_Workspaces); _action("Microsoft.CodeAnalysis.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis); _action("Microsoft.CodeAnalysis.Elfie.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_Elfie); _action("Microsoft.CodeAnalysis.Scripting.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_Scripting); _action("Microsoft.CodeAnalysis.VisualBasic.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_VisualBasic); _action("Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_VisualBasic_Workspaces); _action("Microsoft.CodeAnalysis.Workspaces.Desktop.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_Workspaces_Desktop); _action("Microsoft.CodeAnalysis.Workspaces.dll", syntaxer.Properties.Resources.Microsoft_CodeAnalysis_Workspaces); // Microsoft.CodeDom.Providers.DotNetCompilerPlatform included in CS-Script RoslynProvider _action("Microsoft.CSharp.Core.targets", syntaxer.Properties.Resources.Microsoft_CSharp_Core); _action("Microsoft.DiaSymReader.Native.amd64.dll", syntaxer.Properties.Resources.Microsoft_DiaSymReader_Native_amd64); _action("Microsoft.DiaSymReader.Native.x86.dll", syntaxer.Properties.Resources.Microsoft_DiaSymReader_Native_x86); _action("Microsoft.VisualBasic.Core.targets", syntaxer.Properties.Resources.Microsoft_VisualBasic_Core); _action("Microsoft.VisualStudio.RemoteControl.dll", syntaxer.Properties.Resources.Microsoft_VisualStudio_RemoteControl); _action("Microsoft.Win32.Primitives.dll", syntaxer.Properties.Resources.Microsoft_Win32_Primitives); _action("System.AppContext.dll", syntaxer.Properties.Resources.System_AppContext); _action("System.Collections.Immutable.dll", syntaxer.Properties.Resources.System_Collections_Immutable); _action("System.Composition.AttributedModel.dll", syntaxer.Properties.Resources.System_Composition_AttributedModel); _action("System.Composition.Convention.dll", syntaxer.Properties.Resources.System_Composition_Convention); _action("System.Composition.Hosting.dll", syntaxer.Properties.Resources.System_Composition_Hosting); _action("System.Composition.Runtime.dll", syntaxer.Properties.Resources.System_Composition_Runtime); _action("System.Composition.TypedParts.dll", syntaxer.Properties.Resources.System_Composition_TypedParts); _action("System.Console.dll", syntaxer.Properties.Resources.System_Console); _action("System.Diagnostics.FileVersionInfo.dll", syntaxer.Properties.Resources.System_Diagnostics_FileVersionInfo); _action("System.Diagnostics.Process.dll", syntaxer.Properties.Resources.System_Diagnostics_Process); _action("System.Diagnostics.StackTrace.dll", syntaxer.Properties.Resources.System_Diagnostics_StackTrace); _action("System.IO.Compression.dll", syntaxer.Properties.Resources.System_IO_Compression); _action("System.IO.FileSystem.dll", syntaxer.Properties.Resources.System_IO_FileSystem); _action("System.IO.FileSystem.DriveInfo.dll", syntaxer.Properties.Resources.System_IO_FileSystem_DriveInfo); _action("System.IO.FileSystem.Primitives.dll", syntaxer.Properties.Resources.System_IO_FileSystem_Primitives); _action("System.IO.Pipes.dll", syntaxer.Properties.Resources.System_IO_Pipes); _action("System.Reflection.Metadata.dll", syntaxer.Properties.Resources.System_Reflection_Metadata); _action("System.Runtime.InteropServices.RuntimeInformation.dll", syntaxer.Properties.Resources.System_Runtime_InteropServices_RuntimeInformation); _action("System.Security.AccessControl.dll", syntaxer.Properties.Resources.System_Security_AccessControl); _action("System.Security.Claims.dll", syntaxer.Properties.Resources.System_Security_Claims); _action("System.Security.Cryptography.Algorithms.dll", syntaxer.Properties.Resources.System_Security_Cryptography_Algorithms); _action("System.Security.Cryptography.Encoding.dll", syntaxer.Properties.Resources.System_Security_Cryptography_Encoding); _action("System.Security.Cryptography.Primitives.dll", syntaxer.Properties.Resources.System_Security_Cryptography_Primitives); _action("System.Security.Cryptography.X509Certificates.dll", syntaxer.Properties.Resources.System_Security_Cryptography_X509Certificates); _action("System.Security.Principal.Windows.dll", syntaxer.Properties.Resources.System_Security_Principal_Windows); _action("System.Text.Encoding.CodePages.dll", syntaxer.Properties.Resources.System_Text_Encoding_CodePages); _action("System.Threading.Tasks.Dataflow.dll", syntaxer.Properties.Resources.System_Threading_Tasks_Dataflow); _action("System.Threading.Thread.dll", syntaxer.Properties.Resources.System_Threading_Thread); _action("System.ValueTuple.dll", syntaxer.Properties.Resources.System_ValueTuple); _action("System.Xml.ReaderWriter.dll", syntaxer.Properties.Resources.System_Xml_ReaderWriter); _action("System.Xml.XmlDocument.dll", syntaxer.Properties.Resources.System_Xml_XmlDocument); _action("System.Xml.XPath.dll", syntaxer.Properties.Resources.System_Xml_XPath); _action("System.Xml.XPath.XDocument.dll", syntaxer.Properties.Resources.System_Xml_XPath_XDocument); _action("vbc.exe", syntaxer.Properties.Resources.vbc); _action("vbc.exe.config", Encoding.UTF8.GetBytes(syntaxer.Properties.Resources.vbc_exe)); _action("vbc.rsp", syntaxer.Properties.Resources.vbc1); _action("VBCSCompiler.exe", syntaxer.Properties.Resources.VBCSCompiler); _action("VBCSCompiler.exe.config", Encoding.UTF8.GetBytes(syntaxer.Properties.Resources.VBCSCompiler_exe)); } static Assembly Probe(string dir, string asmName) { var file = Path.Combine(dir, asmName.Split(',')[0] + ".dll"); if (File.Exists(file)) return Assembly.LoadFrom(file); else return null; } static Assembly ProbeAlreadyLoaded(string asmName) { return AppDomain.CurrentDomain.GetAssemblies().Where(x => x.GetName().Name == asmName).FirstOrDefault(); } } class SocketServer { static Dictionary<int, object> connections = new Dictionary<int, object>(); static void MonitorConnections(int connectionTimeout, Action requestShutdown) { do { Thread.Sleep(connectionTimeout); lock (connections) { foreach (int id in connections.Keys.ToArray()) if (!Utils.IsProcessRunning(id)) connections.Remove(id); } } while (connections.Any()); requestShutdown(); } public static void Listen(Args processArgs) { try { var serverSocket = new TcpListener(IPAddress.Loopback, processArgs.port); serverSocket.Start(); if (processArgs.client != 0) { connections[processArgs.client] = true; Output.WriteLine("Monitor client: " + processArgs.client); } Task.Run(() => MonitorConnections(processArgs.timeout, requestShutdown: serverSocket.Stop)); Output.WriteLine($" >> Server (v{Assembly.GetExecutingAssembly().GetName().Version}) Started (port={processArgs.port})"); new Engine().Preload(); Output.WriteLine($" >> Syntax engine loaded"); while (true) { Output.WriteLine(" >> Waiting for client request..."); TcpClient clientSocket = serverSocket.AcceptTcpClient(); Output.WriteLine(" >> Accepted client..."); lock (connections) { try { Output.WriteLine(" >> Reading request..."); string request = clientSocket.ReadAllText(); var args = new Args(request.GetLines()); if (args.exit) { clientSocket.WriteAllText("Bye"); break; } else { if (args.client != 0) { connections[args.client] = true; // Output.WriteLine("Monitor client: " + args.client); } } Output.WriteLine(" >> Processing client request"); string response = SyntaxProvider.ProcessRequest(args); if (response != null) clientSocket.WriteAllText(response); } catch (Exception e) { Output.WriteLine(e.Message); } } } serverSocket.Stop(); Output.WriteLine(" >> exit"); } catch (SocketException e) { if (e.ErrorCode == 10048) Output.WriteLine(">" + e.Message); else Output.WriteLine(e.Message); } catch (Exception e) { Output.WriteLine(e); } } } public static class TestServices { // "references" - request public static string FindRefreneces(string script, int offset, string context = null) => SyntaxProvider.FindRefreneces(script, offset, context); // "suggest_usings" - request public static string FindUsings(string script, string word) => SyntaxProvider.FindUsings(script, word, false); // "resolve" - request public static string Resolve(string script, int offset) => SyntaxProvider.Resolve(script, offset, false); // public static DomRegion Resolve(string script, int offset) => SyntaxProvider.ResolveRaw(script, offset); // "completion" - request public static string GetCompletion(string script, int offset) => SyntaxProvider.GetCompletion(script, offset); // public static IEnumerable<ICompletionData> GetCompletion(string script, int offset) => SyntaxProvider.GetCompletionRaw(script, offset); // "tooltip" - request public static string GetTooltip(string script, int offset, string hint, bool shortHintedTooltips) => SyntaxProvider.GetTooltip(script, offset, hint, shortHintedTooltips); // "signaturehelp" - request public static string GetSignatureHelp(string script, int offset) => SyntaxProvider.GetSignatureHelp(script, offset); // "project" - request public static Project GenerateProjectFor(string script) => CSScriptHelper.GenerateProjectFor(new SourceInfo(script)); // "codemap" - request public static string GetCodeMap(string script) => SyntaxProvider.CodeMap(script, false, false); // "format" - request public static string FormatCode(string script, ref int caretPos) => SyntaxProvider.FormatCode(script, ref caretPos); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NodaTime; using System.Linq; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Data.Market; using System.Collections.Generic; namespace QuantConnect.Algorithm { public partial class QCAlgorithm { /// <summary> /// Gets or sets the history provider for the algorithm /// </summary> public IHistoryProvider HistoryProvider { get; set; } /// <summary> /// Gets whether or not this algorithm is still warming up /// </summary> [DocumentationAttribute(HistoricalData)] public bool IsWarmingUp { get; private set; } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> [DocumentationAttribute(HistoricalData)] public void SetWarmup(TimeSpan timeSpan) { SetWarmUp(timeSpan, null); } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> [DocumentationAttribute(HistoricalData)] public void SetWarmUp(TimeSpan timeSpan) { SetWarmup(timeSpan); } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> /// <param name="resolution">The resolution to request</param> [DocumentationAttribute(HistoricalData)] public void SetWarmup(TimeSpan timeSpan, Resolution? resolution) { if (_locked) { throw new InvalidOperationException("QCAlgorithm.SetWarmup(): This method cannot be used after algorithm initialized"); } _warmupBarCount = null; _warmupTimeSpan = timeSpan; _warmupResolution = resolution; } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> /// <param name="resolution">The resolution to request</param> [DocumentationAttribute(HistoricalData)] public void SetWarmUp(TimeSpan timeSpan, Resolution? resolution) { SetWarmup(timeSpan, resolution); } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. The highest (smallest) resolution in the securities collection will be used. /// For example, if an algorithm has minute and daily data and 200 bars are requested, that would /// use 200 minute bars. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> [DocumentationAttribute(HistoricalData)] public void SetWarmup(int barCount) { SetWarmUp(barCount, null); } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. The highest (smallest) resolution in the securities collection will be used. /// For example, if an algorithm has minute and daily data and 200 bars are requested, that would /// use 200 minute bars. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> [DocumentationAttribute(HistoricalData)] public void SetWarmUp(int barCount) { SetWarmup(barCount); } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> /// <param name="resolution">The resolution to request</param> [DocumentationAttribute(HistoricalData)] public void SetWarmup(int barCount, Resolution? resolution) { if (_locked) { throw new InvalidOperationException("QCAlgorithm.SetWarmup(): This method cannot be used after algorithm initialized"); } _warmupTimeSpan = null; _warmupBarCount = barCount; _warmupResolution = resolution; } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> /// <param name="resolution">The resolution to request</param> [DocumentationAttribute(HistoricalData)] public void SetWarmUp(int barCount, Resolution? resolution) { SetWarmup(barCount, resolution); } /// <summary> /// Sets <see cref="IAlgorithm.IsWarmingUp"/> to false to indicate this algorithm has finished its warm up /// </summary> [DocumentationAttribute(HistoricalData)] public void SetFinishedWarmingUp() { IsWarmingUp = false; // notify the algorithm OnWarmupFinished(); } /// <summary> /// Message for exception that is thrown when the implicit conversion between symbol and string fails /// </summary> private readonly string _symbolEmptyErrorMessage = "Cannot create history for the given ticker. " + "Either explicitly use a symbol object to make the history request " + "or ensure the symbol has been added using the AddSecurity() method before making the history request."; /// <summary> /// Gets the history requests required for provide warm up data for the algorithm /// </summary> /// <returns></returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<HistoryRequest> GetWarmupHistoryRequests() { if (_warmupBarCount.HasValue) { return CreateBarCountHistoryRequests(Securities.Keys, _warmupBarCount.Value, _warmupResolution); } if (_warmupTimeSpan.HasValue) { var end = UtcTime.ConvertFromUtc(TimeZone); return CreateDateRangeHistoryRequests(Securities.Keys, end - _warmupTimeSpan.Value, end, _warmupResolution); } // if not warmup requested return nothing return Enumerable.Empty<HistoryRequest>(); } /// <summary> /// Get the history for all configured securities over the requested span. /// This will use the resolution and other subscription settings for each security. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="span">The span over which to request data. This is a calendar span, so take into consideration weekends and such</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(TimeSpan span, Resolution? resolution = null) { return History(Securities.Keys, Time - span, Time, resolution).Memoize(); } /// <summary> /// Get the history for all configured securities over the requested span. /// This will use the resolution and other subscription settings for each security. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(int periods, Resolution? resolution = null) { return History(Securities.Keys, periods, resolution).Memoize(); } /// <summary> /// Gets the historical data for all symbols of the requested type over the requested span. /// The symbol's configured values for resolution and fill forward behavior will be used /// The symbols must exist in the Securities collection. /// </summary> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<DataDictionary<T>> History<T>(TimeSpan span, Resolution? resolution = null) where T : IBaseData { return History<T>(Securities.Keys, span, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null) where T : IBaseData { return History<T>(symbols, Time - span, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols. The exact number of bars will be returned for /// each symbol. This may result in some data start earlier/later than others due to when various /// exchanges are open. The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) where T : IBaseData { var requests = symbols.Select(x => { var config = GetMatchingSubscription(x, typeof(T)); if (config == null) return null; var exchange = GetExchangeHours(x); var res = GetResolution(x, resolution); var start = _historyRequestFactory.GetStartTimeAlgoTz(x, periods, res, exchange, config.DataTimeZone); return _historyRequestFactory.CreateHistoryRequest(config, start, Time, exchange, res); }); return History(requests.Where(x => x != null)).Get<T>().Memoize(); } /// <summary> /// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null) where T : IBaseData { var requests = symbols.Select(x => { var config = GetMatchingSubscription(x, typeof(T)); if (config == null) return null; return _historyRequestFactory.CreateHistoryRequest(config, start, end, GetExchangeHours(x), resolution); }); return History(requests.Where(x => x != null)).Get<T>().Memoize(); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbol</typeparam> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<T> History<T>(Symbol symbol, TimeSpan span, Resolution? resolution = null) where T : IBaseData { return History<T>(symbol, Time - span, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbol. The exact number of bars will be returned. /// The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<TradeBar> History(Symbol symbol, int periods, Resolution? resolution = null) { if (symbol == null) throw new ArgumentException(_symbolEmptyErrorMessage); resolution = GetResolution(symbol, resolution); var marketHours = GetMarketHours(symbol); var start = _historyRequestFactory.GetStartTimeAlgoTz(symbol, periods, resolution.Value, marketHours.ExchangeHours, marketHours.DataTimeZone); return History(symbol, start, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbol. The exact number of bars will be returned. /// The symbol must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbol</typeparam> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<T> History<T>(Symbol symbol, int periods, Resolution? resolution = null) where T : IBaseData { if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick"); var config = GetHistoryRequestConfig(symbol, typeof(T), resolution); resolution = GetResolution(symbol, resolution); var start = _historyRequestFactory.GetStartTimeAlgoTz(symbol, periods, resolution.Value, GetExchangeHours(symbol), config.DataTimeZone); return History<T>(symbol, start, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbol between the specified dates. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<T> History<T>(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null) where T : IBaseData { var config = GetHistoryRequestConfig(symbol, typeof(T), resolution); var request = _historyRequestFactory.CreateHistoryRequest(config, start, end, GetExchangeHours(symbol), resolution); return History(request).Get<T>(symbol).Memoize(); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<TradeBar> History(Symbol symbol, TimeSpan span, Resolution? resolution = null) { return History(symbol, Time - span, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<TradeBar> History(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null) { var securityType = symbol.ID.SecurityType; if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd) { Error("Calling History<TradeBar> method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter."); } var resolutionToUse = resolution ?? GetResolution(symbol, resolution); if (resolutionToUse == Resolution.Tick) { throw new InvalidOperationException("Calling History<TradeBar> method with Resolution.Tick will return an empty result." + " Please use the generic version with Tick type parameter or provide a list of Symbols to use the Slice history request API."); } return History(new[] { symbol }, start, end, resolutionToUse).Get(symbol).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbol's configured values for resolution and fill forward behavior will be used /// The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null) { return History(symbols, Time - span, Time, resolution).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols. The exact number of bars will be returned for /// each symbol. This may result in some data start earlier/later than others due to when various /// exchanges are open. The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) { if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick"); return History(CreateBarCountHistoryRequests(symbols, periods, resolution)).Memoize(); } /// <summary> /// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <param name="fillForward">True to fill forward missing data, false otherwise</param> /// <param name="extendedMarket">True to include extended market hours data, false otherwise</param> /// <returns>An enumerable of slice containing the requested historical data</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null) { return History(CreateDateRangeHistoryRequests(symbols, start, end, resolution, fillForward, extendedMarket)).Memoize(); } /// <summary> /// Executes the specified history request /// </summary> /// <param name="request">the history request to execute</param> /// <returns>An enumerable of slice satisfying the specified history request</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(HistoryRequest request) { return History(new[] { request }).Memoize(); } /// <summary> /// Executes the specified history requests /// </summary> /// <param name="requests">the history requests to execute</param> /// <returns>An enumerable of slice satisfying the specified history request</returns> [DocumentationAttribute(HistoricalData)] public IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests) { return History(requests, TimeZone).Memoize(); } /// <summary> /// Yields data to warmup a security for all it's subscribed data types /// </summary> /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param> /// <returns>Securities historical data</returns> [DocumentationAttribute(AddingData)] [DocumentationAttribute(HistoricalData)] public IEnumerable<BaseData> GetLastKnownPrices(Security security) { return GetLastKnownPrices(security.Symbol); } /// <summary> /// Yields data to warmup a security for all it's subscribed data types /// </summary> /// <param name="symbol">The symbol we want to get seed data for</param> /// <returns>Securities historical data</returns> [DocumentationAttribute(AddingData)] [DocumentationAttribute(HistoricalData)] public IEnumerable<BaseData> GetLastKnownPrices(Symbol symbol) { if (!HistoryRequestValid(symbol) || HistoryProvider == null) { return Enumerable.Empty<BaseData>(); } var result = new Dictionary<TickType, BaseData>(); Resolution? resolution = null; Func<int, bool> requestData = period => { var historyRequests = CreateBarCountHistoryRequests(new[] { symbol }, period) .Select(request => { // For speed and memory usage, use Resolution.Minute as the minimum resolution request.Resolution = (Resolution)Math.Max((int)Resolution.Minute, (int)request.Resolution); // force no fill forward behavior request.FillForwardResolution = null; resolution = request.Resolution; return request; }) // request only those tick types we didn't get the data we wanted .Where(request => !result.ContainsKey(request.TickType)) .ToList(); foreach (var slice in History(historyRequests)) { for (var i = 0; i < historyRequests.Count; i++) { var historyRequest = historyRequests[i]; var data = slice.Get(historyRequest.DataType); if (data.ContainsKey(symbol)) { // keep the last data point per tick type result[historyRequest.TickType] = (BaseData)data[symbol]; } } } // true when all history requests tick types have a data point return historyRequests.All(request => result.ContainsKey(request.TickType)); }; if (!requestData(5)) { if (resolution.HasValue) { // If the first attempt to get the last know price returns null, it maybe the case of an illiquid security. // We increase the look-back period for this case accordingly to the resolution to cover 3 trading days var periods = resolution.Value == Resolution.Daily ? 3 : resolution.Value == Resolution.Hour ? 24 : 1440; requestData(periods); } else { // this shouldn't happen but just in case QuantConnect.Logging.Log.Error( $"QCAlgorithm.GetLastKnownPrices(): no history request was created for symbol {symbol} at {Time}"); } } // return the data ordered by time ascending return result.Values.OrderBy(data => data.Time); } /// <summary> /// Get the last known price using the history provider. /// Useful for seeding securities with the correct price /// </summary> /// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param> /// <returns>A single <see cref="BaseData"/> object with the last known price</returns> [Obsolete("This method is obsolete please use 'GetLastKnownPrices' which will return the last data point" + " for each type associated with the requested security")] [DocumentationAttribute(AddingData)] [DocumentationAttribute(HistoricalData)] public BaseData GetLastKnownPrice(Security security) { return GetLastKnownPrices(security.Symbol) // since we are returning a single data point let's respect order .OrderByDescending(data => GetTickTypeOrder(data.Symbol.SecurityType, LeanData.GetCommonTickTypeForCommonDataTypes(data.GetType(), data.Symbol.SecurityType))) .LastOrDefault(); } /// <summary> /// Centralized logic to get a configuration for a symbol, a data type and a resolution /// </summary> private SubscriptionDataConfig GetHistoryRequestConfig(Symbol symbol, Type requestedType, Resolution? resolution = null) { if (symbol == null) throw new ArgumentException(_symbolEmptyErrorMessage); // verify the types match var config = GetMatchingSubscription(symbol, requestedType, resolution); if (config == null) { var actualType = GetMatchingSubscription(symbol, typeof(BaseData)).Type; var message = $"The specified security is not of the requested type. Symbol: {symbol} Requested Type: {requestedType.Name} Actual Type: {actualType}"; if (resolution.HasValue) { message += $" Requested Resolution.{resolution.Value}"; } throw new ArgumentException(message); } return config; } [DocumentationAttribute(HistoricalData)] private IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests, DateTimeZone timeZone) { var sentMessage = false; // filter out any universe securities that may have made it this far var filteredRequests = requests.Where(hr => HistoryRequestValid(hr.Symbol)).ToList(); for (var i = 0; i < filteredRequests.Count; i++) { var request = filteredRequests[i]; // prevent future requests if (request.EndTimeUtc > UtcTime) { var endTimeUtc = UtcTime; var startTimeUtc = request.StartTimeUtc; if (request.StartTimeUtc > request.EndTimeUtc) { startTimeUtc = request.EndTimeUtc; } filteredRequests[i] = new HistoryRequest(startTimeUtc, endTimeUtc, request.DataType, request.Symbol, request.Resolution, request.ExchangeHours, request.DataTimeZone, request.FillForwardResolution, request.IncludeExtendedMarketHours, request.IsCustomData, request.DataNormalizationMode, request.TickType); if (!sentMessage) { sentMessage = true; Debug("Request for future history modified to end now."); } } } // filter out future data to prevent look ahead bias return ((IAlgorithm)this).HistoryProvider.GetHistory(filteredRequests, timeZone); } /// <summary> /// Helper method to create history requests from a date range /// </summary> private IEnumerable<HistoryRequest> CreateDateRangeHistoryRequests(IEnumerable<Symbol> symbols, DateTime startAlgoTz, DateTime endAlgoTz, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null) { return symbols.Where(HistoryRequestValid).SelectMany(x => { var requests = new List<HistoryRequest>(); foreach (var config in GetMatchingSubscriptions(x, typeof(BaseData), resolution)) { var request = _historyRequestFactory.CreateHistoryRequest(config, startAlgoTz, endAlgoTz, GetExchangeHours(x), resolution); // apply overrides var res = GetResolution(x, resolution); if (fillForward.HasValue) request.FillForwardResolution = fillForward.Value ? res : (Resolution?)null; if (extendedMarket.HasValue) request.IncludeExtendedMarketHours = extendedMarket.Value; requests.Add(request); } return requests; }); } /// <summary> /// Helper methods to create a history request for the specified symbols and bar count /// </summary> private IEnumerable<HistoryRequest> CreateBarCountHistoryRequests(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) { return symbols.Where(HistoryRequestValid).SelectMany(x => { var res = GetResolution(x, resolution); var exchange = GetExchangeHours(x); var configs = GetMatchingSubscriptions(x, typeof(BaseData), resolution).ToList(); if (!configs.Any()) { return Enumerable.Empty<HistoryRequest>(); } var start = _historyRequestFactory.GetStartTimeAlgoTz(x, periods, res, exchange, configs.First().DataTimeZone); var end = Time; return configs.Select(config => _historyRequestFactory.CreateHistoryRequest(config, start, end, exchange, res)); }); } private SubscriptionDataConfig GetMatchingSubscription(Symbol symbol, Type type, Resolution? resolution = null) { // find the first subscription matching the requested type with a higher resolution than requested return GetMatchingSubscriptions(symbol, type, resolution).FirstOrDefault(); } private int GetTickTypeOrder(SecurityType securityType, TickType tickType) { return SubscriptionManager.AvailableDataTypes[securityType].IndexOf(tickType); } private IEnumerable<SubscriptionDataConfig> GetMatchingSubscriptions(Symbol symbol, Type type, Resolution? resolution = null) { var matchingSubscriptions = SubscriptionManager.SubscriptionDataConfigService // we add internal subscription so that history requests are covered, this allows us to warm them up too .GetSubscriptionDataConfigs(symbol, includeInternalConfigs:true) // find all subscriptions matching the requested type with a higher resolution than requested .OrderByDescending(s => s.Resolution) // lets make sure to respect the order of the data types .ThenByDescending(config => GetTickTypeOrder(config.SecurityType, config.TickType)) .Where(s => SubscriptionDataConfigTypeFilter(type, s.Type)); var internalConfig = new List<SubscriptionDataConfig>(); var userConfig = new List<SubscriptionDataConfig>(); foreach (var config in matchingSubscriptions) { if (config.IsInternalFeed) { internalConfig.Add(config); } else { userConfig.Add(config); } } // if we have any user defined subscription configuration we use it, else we use internal ones if any List<SubscriptionDataConfig> configs = null; if(userConfig.Count != 0) { configs = userConfig; } else if (internalConfig.Count != 0) { configs = internalConfig; } // we use the subscription manager registered configurations here, we can not rely on the Securities collection // since this might be called when creating a security and warming it up if (configs != null && configs.Count != 0) { if (resolution.HasValue && (resolution == Resolution.Daily || resolution == Resolution.Hour) && symbol.SecurityType == SecurityType.Equity) { // for Daily and Hour resolution, for equities, we have to // filter out any existing subscriptions that could be of Quote type // This could happen if they were Resolution.Minute/Second/Tick return configs.Where(s => s.TickType != TickType.Quote); } return configs; } else { var entry = MarketHoursDatabase.GetEntry(symbol, new []{ type }); resolution = GetResolution(symbol, resolution); return SubscriptionManager .LookupSubscriptionConfigDataTypes(symbol.SecurityType, resolution.Value, symbol.IsCanonical()) .Where(tuple => SubscriptionDataConfigTypeFilter(type, tuple.Item1)) .Select(x => new SubscriptionDataConfig( x.Item1, symbol, resolution.Value, entry.DataTimeZone, entry.ExchangeHours.TimeZone, UniverseSettings.FillForward, UniverseSettings.ExtendedMarketHours, true, false, x.Item2, true, UniverseSettings.GetUniverseNormalizationModeOrDefault(symbol.SecurityType))); } } /// <summary> /// Helper method to determine if the provided config type passes the filter of the target type /// </summary> /// <remarks>If the target type is <see cref="BaseData"/>, <see cref="OpenInterest"/> config types will return false. /// This is useful to filter OpenInterest by default from history requests unless it's explicitly requested</remarks> private bool SubscriptionDataConfigTypeFilter(Type targetType, Type configType) { var targetIsGenericType = targetType == typeof(BaseData); return targetType.IsAssignableFrom(configType) && (!targetIsGenericType || configType != typeof(OpenInterest)); } private SecurityExchangeHours GetExchangeHours(Symbol symbol) { return GetMarketHours(symbol).ExchangeHours; } private MarketHoursDatabase.Entry GetMarketHours(Symbol symbol) { var hoursEntry = MarketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType); // user can override the exchange hours in algorithm, i.e. HistoryAlgorithm Security security; if (Securities.TryGetValue(symbol, out security)) { return new MarketHoursDatabase.Entry(hoursEntry.DataTimeZone, security.Exchange.Hours); } return hoursEntry; } private Resolution GetResolution(Symbol symbol, Resolution? resolution) { Security security; if (Securities.TryGetValue(symbol, out security)) { if (resolution != null) { return resolution.Value; } Resolution? result = null; var hasNonInternal = false; foreach (var config in SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol, includeInternalConfigs: true) // we process non internal configs first .OrderBy(config => config.IsInternalFeed ? 1 : 0)) { if (!config.IsInternalFeed || !hasNonInternal) { // once we find a non internal config we ignore internals hasNonInternal |= !config.IsInternalFeed; if (!result.HasValue || config.Resolution < result) { result = config.Resolution; } } } return result ?? UniverseSettings.Resolution; } else { return resolution ?? UniverseSettings.Resolution; } } /// <summary> /// Validate a symbol for a history request. /// Universe and canonical symbols are only valid for future security types /// </summary> private bool HistoryRequestValid(Symbol symbol) { return symbol.SecurityType == SecurityType.Future || !UniverseManager.ContainsKey(symbol) && !symbol.IsCanonical(); } } }
//--------------------------------------------------------------------- // File: ExecuteReceivePipelineStep.cs // // Summary: // //--------------------------------------------------------------------- // Copyright (c) 2004-2011, Kevin B. Smith. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. //--------------------------------------------------------------------- using System; using System.IO; using System.Collections.Generic; using Winterdom.BizTalk.PipelineTesting; using System.Collections.ObjectModel; using BizUnit.Common; using BizUnit.TestSteps.BizTalk.Common; using BizUnit.Xaml; namespace BizUnit.TestSteps.BizTalk.Pipeline { /// <summary> /// The ExecuteReceivePipelineStep can be used to execute a pipeline and test the output from it /// </summary> /// /// <remarks> /// The following shows an example of the Xml representation of this test step. The step /// can perform a pipeline and output that to an output file /// /// <list type="table"> /// <listheader> /// <term>Pipeline:assemblyPath</term> /// <description>The assembly containing the BizTalk pipeline to execute.</description> /// </listheader> /// <item> /// <term>Pipeline:typeName</term> /// <description>The typename of the BizTalk pipeline to execute</description> /// </item> /// <item> /// <term>DocSpecs:assembly</term> /// <description>The assembly containing the BizTalk docspec schema assembly path (multiple)</description> /// </item> /// <item> /// <term>DocSpecs:type</term> /// <description>The assembly containing the BizTalk docspec schema type name (multiple)</description> /// </item> /// <item> /// <term>Source</term> /// <description>The file path of the source input file to execute in the pipeline</description> /// </item> /// <item> /// <term>Source:Encoding</term> /// <description>The excoding type of the input file to execute in the pipeline</description> /// </item> /// <item> /// <term>DestinationDir</term> /// <description>The destination directory to write the pipeline output file(s)</description> /// </item> /// <item> /// <term>DestinationFileFormat</term> /// <description>The file format of the output file(s)</description> /// </item> /// <item> /// <term>ContextFileFormat</term> /// <description>The file format of the output message context file(s)</description> /// </item> /// </list> /// </remarks> public class ExecuteReceivePipelineStep : TestStepBase { private string _pipelineAssemblyPath; private string _pipelineTypeName; private Collection<DocSpecDefinition> _docSpecsRawList = new Collection<DocSpecDefinition>(); private Type[] _docSpecs; private string _instanceConfigFile; private string _source; private string _sourceEncoding; private string _destinationDir; private string _destinationFileFormat; private string _inputContextFile; private string _outputContextFileFormat; ///<summary> /// Gets and sets the assembly path for the .NET type of the pipeline to be executed ///</summary> public string PipelineAssemblyPath { get { return _pipelineAssemblyPath; } set { _pipelineAssemblyPath = value; } } ///<summary> /// Gets and sets the type name for the .NET type of the pipeline to be executed ///</summary> public string PipelineTypeName { get { return _pipelineTypeName; } set { _pipelineTypeName = value; } } ///<summary> /// Gets and sets the docspecs for the pipeline to be executed. Pairs of typeName, assemblyPath. ///</summary> public Collection<DocSpecDefinition> DocSpecs { get { return _docSpecsRawList; } private set { _docSpecsRawList = value; } } ///<summary> /// Gets and sets the pipeline instance configuration for the pipeline to be executed ///</summary> public string InstanceConfigFile { get { return _instanceConfigFile; } set { _instanceConfigFile = value; } } ///<summary> /// Gets and sets the source file path for the input file to the pipeline ///</summary> public string Source { get { return _source; } set { _source = value; } } ///<summary> /// Gets and sets the source encoding ///</summary> public string SourceEncoding { get { return _sourceEncoding; } set { _sourceEncoding = value; } } ///<summary> /// Gets and sets the destination of the pipeline output ///</summary> public string DestinationDir { get { return _destinationDir; } set { _destinationDir = value; } } ///<summary> /// Gets and sets the destination file format ///</summary> public string DestinationFileFormat { get { return _destinationFileFormat; } set { _destinationFileFormat = value; } } ///<summary> /// Gets and sets the message context for the input message ///</summary> public string InputContextFile { get { return _inputContextFile; } set { _inputContextFile = value; } } ///<summary> /// Gets and sets the message context file format for the output message ///</summary> public string OutputContextFileFormat { get { return _outputContextFileFormat; } set { _outputContextFileFormat = value; } } /// <summary> /// TestStepBase.Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { if (_docSpecsRawList.Count > 0) { var ds = new List<Type>(_docSpecsRawList.Count); foreach (var docSpec in _docSpecsRawList) { var ass = AssemblyHelper.LoadAssembly((string)docSpec.AssemblyPath); context.LogInfo("Loading DocumentSpec {0} from location {1}.", docSpec.TypeName, ass.Location); var type = ass.GetType(docSpec.TypeName); ds.Add(type); } _docSpecs = ds.ToArray(); } context.LogInfo("Loading pipeline {0} from location {1}.", _pipelineTypeName, _pipelineAssemblyPath); var pipelineType = ObjectCreator.GetType(_pipelineTypeName, _pipelineAssemblyPath); var pipelineWrapper = PipelineFactory.CreateReceivePipeline(pipelineType); if (!string.IsNullOrEmpty(_instanceConfigFile)) { pipelineWrapper.ApplyInstanceConfig(_instanceConfigFile); } if (null != _docSpecs) { foreach (Type docSpec in _docSpecs) { pipelineWrapper.AddDocSpec(docSpec); } } MessageCollection mc = null; using (Stream stream = new FileStream(_source, FileMode.Open, FileAccess.Read)) { var inputMessage = MessageHelper.CreateFromStream(stream); if (!string.IsNullOrEmpty(_sourceEncoding)) { inputMessage.BodyPart.Charset = _sourceEncoding; } // Load context file, add to message context. if (!string.IsNullOrEmpty(_inputContextFile) && new FileInfo(_inputContextFile).Exists) { var mi = MessageInfo.Deserialize(_inputContextFile); mi.MergeIntoMessage(inputMessage); } mc = pipelineWrapper.Execute(inputMessage); } for (var count = 0; count < mc.Count; count++) { string destination = null; if (!string.IsNullOrEmpty(_destinationFileFormat)) { destination = string.Format(_destinationFileFormat, count); if (!string.IsNullOrEmpty(_destinationDir)) { destination = Path.Combine(_destinationDir, destination); } PersistMessageHelper.PersistMessage(mc[count], destination); } if (!string.IsNullOrEmpty(_outputContextFileFormat)) { var contextDestination = string.Format(_outputContextFileFormat, count); if (!string.IsNullOrEmpty(_destinationDir)) { contextDestination = Path.Combine(_destinationDir, contextDestination); } var mi = BizTalkMessageInfoFactory.CreateMessageInfo(mc[count], destination); MessageInfo.Serialize(mi, contextDestination); } } } /// <summary> /// TestStepBase.Validate() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Validate(Context context) { ArgumentValidation.CheckForEmptyString(_pipelineTypeName, "pipelineTypeName"); // pipelineAssemblyPath - optional _source = context.SubstituteWildCards(_source); if (!new FileInfo(_source).Exists) { throw new ArgumentException("Source file does not exist.", _source); } // destinationDir - optional if (!string.IsNullOrEmpty(_destinationDir)) { _destinationDir = context.SubstituteWildCards(_destinationDir); } } } }
using System; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Agreement; using Org.BouncyCastle.Crypto.Agreement.Srp; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Tls { /// <summary> /// TLS 1.1 SRP key exchange. /// </summary> internal class TlsSrpKeyExchange : TlsKeyExchange { protected TlsClientContext context; protected KeyExchangeAlgorithm keyExchange; protected TlsSigner tlsSigner; protected byte[] identity; protected byte[] password; protected IAsymmetricKeyParameter serverPublicKey = null; protected byte[] s = null; protected IBigInteger B = null; protected Srp6Client srpClient = new Srp6Client(); internal TlsSrpKeyExchange(TlsClientContext context, KeyExchangeAlgorithm keyExchange, byte[] identity, byte[] password) { switch (keyExchange) { case KeyExchangeAlgorithm.SRP: this.tlsSigner = null; break; case KeyExchangeAlgorithm.SRP_RSA: this.tlsSigner = new TlsRsaSigner(); break; case KeyExchangeAlgorithm.SRP_DSS: this.tlsSigner = new TlsDssSigner(); break; default: throw new ArgumentException(@"unsupported key exchange algorithm", "keyExchange"); } this.context = context; this.keyExchange = keyExchange; this.identity = identity; this.password = password; } public virtual void SkipServerCertificate() { if (tlsSigner != null) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } } public virtual void ProcessServerCertificate(Certificate serverCertificate) { if (tlsSigner == null) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo; try { this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo); } // catch (RuntimeException) catch (Exception) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } if (!tlsSigner.IsValidPublicKey(this.serverPublicKey)) { throw new TlsFatalAlert(AlertDescription.certificate_unknown); } TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature); // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ } public virtual void SkipServerKeyExchange() { throw new TlsFatalAlert(AlertDescription.unexpected_message); } public virtual void ProcessServerKeyExchange(Stream input) { SecurityParameters securityParameters = context.SecurityParameters; Stream sigIn = input; ISigner signer = null; if (tlsSigner != null) { signer = InitSigner(tlsSigner, securityParameters); sigIn = new SignerStream(input, signer, null); } byte[] NBytes = TlsUtilities.ReadOpaque16(sigIn); byte[] gBytes = TlsUtilities.ReadOpaque16(sigIn); byte[] sBytes = TlsUtilities.ReadOpaque8(sigIn); byte[] BBytes = TlsUtilities.ReadOpaque16(sigIn); if (signer != null) { byte[] sigByte = TlsUtilities.ReadOpaque16(input); if (!signer.VerifySignature(sigByte)) { throw new TlsFatalAlert(AlertDescription.bad_certificate); } } IBigInteger N = new BigInteger(1, NBytes); IBigInteger g = new BigInteger(1, gBytes); // TODO Validate group parameters (see RFC 5054) //throw new TlsFatalAlert(AlertDescription.insufficient_security); this.s = sBytes; /* * RFC 5054 2.5.3: The client MUST abort the handshake with an "illegal_parameter" * alert if B % N = 0. */ try { this.B = Srp6Utilities.ValidatePublicValue(N, new BigInteger(1, BBytes)); } catch (CryptoException) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } this.srpClient.Init(N, g, new Sha1Digest(), context.SecureRandom); } public virtual void ValidateCertificateRequest(CertificateRequest certificateRequest) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } public virtual void SkipClientCredentials() { // OK } public virtual void ProcessClientCredentials(TlsCredentials clientCredentials) { throw new TlsFatalAlert(AlertDescription.internal_error); } public virtual void GenerateClientKeyExchange(Stream output) { byte[] keData = BigIntegers.AsUnsignedByteArray(srpClient.GenerateClientCredentials(s, this.identity, this.password)); TlsUtilities.WriteUint24(keData.Length + 2, output); TlsUtilities.WriteOpaque16(keData, output); } public virtual byte[] GeneratePremasterSecret() { try { // TODO Check if this needs to be a fixed size return BigIntegers.AsUnsignedByteArray(srpClient.CalculateSecret(B)); } catch (CryptoException) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } protected virtual ISigner InitSigner(TlsSigner tlsSigner, SecurityParameters securityParameters) { ISigner signer = tlsSigner.CreateVerifyer(this.serverPublicKey); signer.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length); signer.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length); return signer; } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Threading.Tasks; using Keen.Core; using Keen.EventCache; using Moq; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace Keen.Test { [TestFixture] public class BulkEventTest : TestBase { [Test] public void AddEvents_InvalidProject_Throws() { var settings = new ProjectSettingsProvider(projectId: "X", writeKey: SettingsEnv.WriteKey); var client = new KeenClient(settings); if (UseMocks) client.Event = new EventMock(settings, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { if ((p == settings) && (p.ProjectId == "X")) throw new KeenException(); else throw new Exception("Unexpected value"); })); Assert.Throws<KeenException>(() => client.AddEvents("AddEventTest", new[] { new { AProperty = "AValue" } })); } [Test] public void AddEvents_PartialFailure_Throws() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { var err = e.SelectToken("$.AddEventTest[2]") as JObject; if (null == err) throw new Exception("Unexpected error, test data not found"); return new List<CachedEvent>() { new CachedEvent("AddEventTest", e) }; })); object invalidEvent = new ExpandoObject(); ((IDictionary<string, object>)invalidEvent).Add("$" + new string('.', 260), "AValue"); var events = (from i in Enumerable.Range(1, 2) select new { AProperty = "AValue" + i }).ToList<object>(); events.Add(invalidEvent); Assert.Throws<KeenBulkException>(() => client.AddEvents("AddEventTest", events)); } [Test] public void AddEvents_NoCache_Success() { var client = new KeenClient(SettingsEnv); var done = false; if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { done = true; Assert.True(p == SettingsEnv, "Incorrect settings"); Assert.NotNull(e.Property("AddEventTest"), "Expected collection not found"); Assert.AreEqual(e.Property("AddEventTest").Value.AsEnumerable().Count(), 3, "Expected exactly 3 collection members"); foreach (dynamic q in ((dynamic)e).AddEventTest) Assert.NotNull(q.keen.timestamp, "keen.timestamp properties should exist"); return new List<CachedEvent>(); })); var events = from i in Enumerable.Range(1, 3) select new { AProperty = "AValue" + i }; Assert.DoesNotThrow(() => client.AddEvents("AddEventTest", events)); Assert.True((UseMocks && done) || !UseMocks, "AddEvent mock was not called"); } [Test] public void AddEvents_Cache_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { // Should not be called with caching enabled Assert.Fail(); return new List<CachedEvent>(); })); var events = from i in Enumerable.Range(1, 3) select new { AProperty = "AValue" + i }; Assert.DoesNotThrow(() => client.AddEvents("AddEventTest", events)); // reset the AddEvents mock if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { Assert.True(p == SettingsEnv, "Incorrect settings"); Assert.NotNull(e.Property("AddEventTest"), "Expected collection not found"); Assert.AreEqual(e.Property("AddEventTest").Value.AsEnumerable().Count(), 3, "Expected exactly 3 collection members"); foreach (dynamic q in ((dynamic)e).AddEventTest) Assert.NotNull(q.keen.timestamp, "keen.timestamp properties should exist"); return new List<CachedEvent>(); })); Assert.DoesNotThrow(() => client.SendCachedEvents()); } } [TestFixture] public class KeenClientTest : TestBase { [Test] public void Constructor_ProjectSettingsNull_Throws() { Assert.Throws<KeenException>(() => new KeenClient(null)); } [Test] public void Constructor_ProjectSettingsNoProjectID_Throws() { Assert.Throws<KeenException>(() => new ProjectSettingsProvider(projectId: "", masterKey: "X", writeKey: "X")); } [Test] public void Constructor_ProjectSettingsNoMasterOrWriteKeys_Throws() { Assert.Throws<KeenException>(() => new ProjectSettingsProvider(projectId: "X")); } [Test] public void GetCollectionSchema_NullProjectId_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.GetSchema(null)); } [Test] public void GetCollectionSchema_EmptyProjectId_Throws() { var settings = new ProjectSettingsProvider(projectId: "X", masterKey: SettingsEnv.MasterKey); var client = new KeenClient(settings); Assert.Throws<KeenException>(() => client.GetSchema("")); } [Test] public void GetCollectionSchemas_Success() { var client = new KeenClient(SettingsEnv); var expected = new JArray(); // todo: better mock return if (UseMocks) { var eventMock = new Mock<IEvent>(); eventMock.Setup(m => m.GetSchemas()) .Returns(Task.FromResult(expected)); client.Event = eventMock.Object; } var reply = client.GetSchemas(); Assert.NotNull(reply); } [Test] public void GetCollectionSchema_InvalidProjectId_Throws() { var settings = new ProjectSettingsProvider(projectId: "X", readKey: SettingsEnv.ReadKey); var client = new KeenClient(settings); if (UseMocks) client.EventCollection = new EventCollectionMock(settings, getSchema: new Func<string, IProjectSettings, JObject>((c, p) => { if ((p == settings) && (c == "X")) throw new KeenResourceNotFoundException(); else throw new Exception("Unexpected value"); })); Assert.Throws<KeenResourceNotFoundException>(() => client.GetSchema("X")); } [Test] public void GetCollectionSchema_ValidProjectIdInvalidSchema_Throws() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, getSchema: new Func<string, IProjectSettings, JObject>((c, p) => { if ((p == SettingsEnv) && (c == "DoesntExist")) throw new KeenResourceNotFoundException(); return new JObject(); })); Assert.Throws<KeenResourceNotFoundException>(() => client.GetSchema("DoesntExist")); } [Test] public void GetCollectionSchema_ValidProject_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, getSchema: new Func<string, IProjectSettings, JObject>((c, p) => { if ((p == SettingsEnv) && (c == "AddEventTest")) return JObject.Parse("{\"properties\":{\"AProperty\": \"string\"}}"); else throw new KeenResourceNotFoundException(c); })); Assert.DoesNotThrow(() => { dynamic response = client.GetSchema("AddEventTest"); Assert.NotNull(response["properties"]); Assert.NotNull(response["properties"]["AProperty"]); Assert.True((string)response["properties"]["AProperty"] == "string"); }); } [Test] public void AddEvent_InvalidProjectId_Throws() { var settings = new ProjectSettingsProvider(projectId: "X", writeKey: SettingsEnv.WriteKey); var client = new KeenClient(settings); if (UseMocks) client.EventCollection = new EventCollectionMock(settings, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == settings) && (c == "X") && (e["X"].Value<string>() == "X")) throw new KeenResourceNotFoundException(c); })); Assert.Throws<KeenResourceNotFoundException>(() => client.AddEvent("X", new { X = "X" })); } [Test] public void AddEvent_ValidProjectIdInvalidWriteKey_Throws() { var settings = new ProjectSettingsProvider(projectId: SettingsEnv.ProjectId, writeKey: "X"); var client = new KeenClient(settings); if (UseMocks) client.EventCollection = new EventCollectionMock(settings, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == settings) && (c == "X") && (e["X"].Value<string>() == "X")) throw new KeenInvalidApiKeyException(c); })); Assert.Throws<KeenInvalidApiKeyException>(() => client.AddEvent("X", new { X = "X" })); } [Test] public void AddEvent_InvalidCollectionNameBlank_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddEvent("", new { AProperty = "AValue" })); } [Test] public void AddEvent_InvalidCollectionNameNull_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddEvent(null, new { AProperty = "AValue" })); } [Test] public void AddEvent_InvalidCollectionNameDollarSign_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddEvent("$Invalid", new { AProperty = "AValue" })); } [Test] public void AddEvent_InvalidCollectionNameTooLong_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddEvent(new String('X', 257), new { AProperty = "AValue" })); } [Test] public void AddEvent_InvalidKeenNamespaceProperty_Throws() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "X") && (null != e.Property("keen")) && (e.Property("keen").Value.GetType() == typeof(JObject)) && (null != ((JObject)e.Property("keen").Value).Property("AProperty"))) throw new KeenInvalidKeenNamespacePropertyException(); else throw new Exception("Unexpected value"); })); Assert.Throws<KeenInvalidKeenNamespacePropertyException>(() => client.AddEvent("X", new { keen = new { AProperty = "AValue" } })); } [Test] public void AddEvent_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue")) return; else throw new Exception("Unexpected values"); })); Assert.DoesNotThrow(() => client.AddEvent("AddEventTest", new { AProperty = "AValue" })); } /* [Test] public void AddEvent_ScopedKeyWrite_Success() { var scope = "{\"timestamp\": \"2014-02-25T22:09:27.320082\", \"allowed_operations\": [\"write\"]}"; var scopedKey = ScopedKey.EncryptString(SettingsEnv.MasterKey, scope); var settings = new ProjectSettingsProvider(masterKey: SettingsEnv.MasterKey, projectId: SettingsEnv.ProjectId, writeKey: scopedKey); var client = new KeenClient(settings); if (UseMocks) client.EventCollection = new EventCollectionMock(settings, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { var key = JObject.Parse(ScopedKey.Decrypt(p.MasterKey, p.WriteKey)); if ((key["allowed_operations"].Values<string>().First() == "write") && (p == settings) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "CustomKey")) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => client.AddEvent("AddEventTest", new { AProperty = "CustomKey" })); } */ //[Test] //public void AddEvent_MultipleEventsInvalidCollection_Throws() //{ // var settings = new ProjectSettingsProviderEnv(); // var client = new KeenClient(settings); // var collection = new // { // AddEventTest = from i in Enumerable.Range(1, 10) // select new { AProperty = "AValue" + i }, // InvalidCollection = 2, // }; // Assert.Throws<KeenInternalServerErrorException>(() => client.AddEvents(collection)); //} //[Test] //public void AddEvent_MultipleEventsInvalidItem_Throws() //{ // var settings = new ProjectSettingsProviderEnv(); // var client = new KeenClient(settings); // var collection = new { AddEventTest = new List<dynamic>() }; // foreach( var k in new[]{ "ValidProperty", "Invalid.Property" }) // { // IDictionary<string, object> item = new ExpandoObject(); // item.Add(k, "AValue"); // collection.AddEventTest.Add(item); // } // Assert.DoesNotThrow(() => client.AddEvents(collection)); //} //[Test] //public void AddEvent_MultipleEventsAnonymous_Success() //{ // var settings = new ProjectSettingsProviderEnv(); // var client = new KeenClient(settings); // var collection = new // { // AddEventTest = from i in Enumerable.Range(1, 10) // select new { AProperty = "AValue" + i } // }; // Assert.DoesNotThrow(() => client.AddEvents(collection)); //} //[Test] //public void AddEvent_MultipleEventsExpando_Success() //{ // var settings = new ProjectSettingsProviderEnv(); // var client = new KeenClient(settings); // dynamic collection = new ExpandoObject(); // collection.AddEventTest = new List<dynamic>(); // foreach( var i in Enumerable.Range(1,10)) // { // dynamic anEvent = new ExpandoObject(); // anEvent.AProperty = "AValue" + i; // collection.AddEventTest.Add(anEvent); // } // Assert.DoesNotThrow(() => client.AddEvents(collection)); //} //private class TestCollection //{ // public class TestEvent // { // public string AProperty { get; set; } // } // public List<TestEvent> AddEventTest { get; set; } //} //[Test] //public void AddEvent_MultipleEvents_Success() //{ // var settings = new ProjectSettingsProviderEnv(); // var client = new KeenClient(settings); // var collection = new TestCollection() // { // AddEventTest = (from i in Enumerable.Range(1, 10) // select new TestCollection.TestEvent() { AProperty = "AValue"+i}).ToList() // }; // Assert.DoesNotThrow(() => client.AddEvents(collection)); //} [Test] public void DeleteCollection_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, deleteCollection: new Action<string, IProjectSettings>((c, p) => { if ((p == SettingsEnv) && (c == "DeleteColTest")) return; else throw new Exception("Unexpected value"); })); // Idempotent, does not matter if collection does not exist. Assert.DoesNotThrow(() => client.DeleteCollection("DeleteColTest")); } } [TestFixture] public class KeenClientGlobalPropertyTests : TestBase { [Test] public void AddGlobalProperty_SimpleValue_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"].Value<string>() == "AValue")) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => { client.AddGlobalProperty("AGlobal", "AValue"); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_InvalidValueNameDollar_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddGlobalProperty("$AGlobal", "AValue")); } [Test] public void AddGlobalProperty_InvalidValueNamePeriod_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddGlobalProperty("A.Global", "AValue")); } [Test] public void AddGlobalProperty_InvalidValueNameLength_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddGlobalProperty(new String('A', 256), "AValue")); } [Test] public void AddGlobalProperty_InvalidValueNameNull_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddGlobalProperty(null, "AValue")); } [Test] public void AddGlobalProperty_InvalidValueNameBlank_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddGlobalProperty("", "AValue")); } [Test] public void AddGlobalProperty_ObjectValue_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"]["AProperty"].Value<string>() == "AValue")) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => { client.AddGlobalProperty("AGlobal", new { AProperty = "AValue" }); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_CollectionValue_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"].Values<int>().All((x) => (x == 1) || (x == 2) || (x == 3)))) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => { client.AddGlobalProperty("AGlobal", new[] { 1, 2, 3, }); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_DelegateSimpleValue_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"] != null)) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => { client.AddGlobalProperty("AGlobal", new DynamicPropertyValue(() => DateTime.Now.Millisecond)); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_DelegateArrayValue_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"].Values<int>().All((x) => (x == 1) || (x == 2) || (x == 3)))) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => { client.AddGlobalProperty("AGlobal", new DynamicPropertyValue(() => new[] { 1, 2, 3 })); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_DelegateObjectValue_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"].Value<JObject>()["SubProp1"].Value<string>() == "Value")) return; else throw new Exception("Unexpected value"); })); Assert.DoesNotThrow(() => { client.AddGlobalProperty("AGlobal", new DynamicPropertyValue(() => new { SubProp1 = "Value", SubProp2 = "Value" })); client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_DelegateNullDynamicValue_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => { client.AddGlobalProperty("AGlobal", new DynamicPropertyValue(() => null)); }); } [Test] public void AddGlobalProperty_DelegateNullValueProvider_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => { client.AddGlobalProperty("AGlobal", null); }); } [Test] public void AddGlobalProperty_DelegateValueProviderNullReturn_Throws() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "AValue") && (e["AGlobal"].Value<string>() == "value")) return; else throw new Exception("Unexpected value"); })); var i = 0; // return valid for the first two tests, then null client.AddGlobalProperty("AGlobal", new DynamicPropertyValue(() => i++ > 1 ? null : "value")); // This is the second test (AddGlobalProperty runs the first) Assert.DoesNotThrow(() => client.AddEvent("AddEventTest", new { AProperty = "AValue" })); // Third test should fail. Assert.Throws<KeenException>(() => { client.AddEvent("AddEventTest", new { AProperty = "AValue" }); }); } [Test] public void AddGlobalProperty_DelegateValueProviderThrows_Throws() { var client = new KeenClient(SettingsEnv); Assert.Throws<KeenException>(() => client.AddGlobalProperty("AGlobal", new DynamicPropertyValue(() => { throw new Exception("test exception"); }))); } } [TestFixture] public class KeenClientCachingTest : TestBase { [Test] public void Caching_SendEmptyEvents_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); Assert.DoesNotThrow(() => client.SendCachedEvents()); } [Test] public void Caching_ClearEvents_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); Assert.DoesNotThrow(() => client.EventCache.ClearAsync()); } [Test] public void Caching_AddEvents_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); Assert.DoesNotThrow(() => client.AddEvent("CachedEventTest", new { AProperty = "AValue" })); Assert.DoesNotThrow(() => client.AddEvent("CachedEventTest", new { AProperty = "AValue" })); Assert.DoesNotThrow(() => client.AddEvent("CachedEventTest", new { AProperty = "AValue" })); } [Test] public async Task Caching_SendEvents_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { if ((p == SettingsEnv) && (null != e.Property("CachedEventTest")) && (e.Property("CachedEventTest").Value.Children().Count() == 3)) return new List<CachedEvent>(); else throw new Exception("Unexpected value"); })); client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); Assert.DoesNotThrow(() => client.SendCachedEvents()); Assert.Null(await client.EventCache.TryTakeAsync(), "Cache is empty"); } [Test] public async Task Caching_SendManyEvents_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); var total = 0; if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { if ((p == SettingsEnv) && (null != e.Property("CachedEventTest")) && ((e.Property("CachedEventTest").Value.Children().Count() == KeenConstants.BulkBatchSize))) { total += e.Property("CachedEventTest").Value.Children().Count(); return new List<CachedEvent>(); } else throw new Exception("Unexpected value"); })); for (int i = 0; i < KeenConstants.BulkBatchSize; i++) client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); Assert.DoesNotThrow(() => client.SendCachedEvents()); Assert.Null(await client.EventCache.TryTakeAsync(), "Cache is empty"); Assert.True(!UseMocks || (total == KeenConstants.BulkBatchSize)); } [Test] public void Caching_SendInvalidEvents_Throws() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { if (p == SettingsEnv) throw new KeenBulkException("Mock exception", new List<CachedEvent>() { new CachedEvent("CachedEventTest", e, new Exception()) }); else throw new Exception("Unexpected value"); })); var anEvent = new JObject(); anEvent.Add("AProperty", "AValue"); client.AddEvent("CachedEventTest", anEvent); anEvent.Add("keen", JObject.FromObject(new { invalidPropName = "value" })); client.AddEvent("CachedEventTest", anEvent); Assert.DoesNotThrow(() => { try { client.SendCachedEvents(); } catch (KeenBulkException ex) { if (ex.FailedEvents.Count() != 1) throw new Exception("Expected 1 failed event."); } }); } } [TestFixture] public class AsyncTests : TestBase { [Test] public async Task Async_DeleteCollection_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, deleteCollection: new Action<string, IProjectSettings>((c, p) => { if ((p == SettingsEnv) && (c == "DeleteColTest")) return; else throw new Exception("Unexpected value"); })); await client.DeleteCollectionAsync("DeleteColTest"); } [Test] public void Async_GetCollectionSchema_NullProjectId_Throws() { var client = new KeenClient(SettingsEnv); Assert.ThrowsAsync<KeenException>(() => client.GetSchemaAsync(null)); } [Test] public void Async_AddEvent_InvalidProjectId_Throws() { var settings = new ProjectSettingsProvider(projectId: "X", writeKey: SettingsEnv.WriteKey); var client = new KeenClient(settings); if (UseMocks) client.EventCollection = new EventCollectionMock(settings, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == settings) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "Value")) throw new KeenResourceNotFoundException(c); })); Assert.ThrowsAsync<KeenResourceNotFoundException>(() => client.AddEventAsync("AddEventTest", new { AProperty = "Value" })); } [Test] public void Async_AddEvent_ValidProjectIdInvalidWriteKey_Throws() { var settings = new ProjectSettingsProvider(projectId: SettingsEnv.ProjectId, writeKey: "X"); var client = new KeenClient(settings); if (UseMocks) client.EventCollection = new EventCollectionMock(settings, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == settings) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "Value")) throw new KeenInvalidApiKeyException(c); })); Assert.ThrowsAsync<KeenInvalidApiKeyException>(() => client.AddEventAsync("AddEventTest", new { AProperty = "Value" })); } [Test] public async Task Async_AddEvent_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.EventCollection = new EventCollectionMock(SettingsEnv, addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) => { if ((p == SettingsEnv) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "Value")) throw new KeenResourceNotFoundException(c); })); await client.AddEventAsync("AddEventTest", new { AProperty = "AValue" }); } [Test] public void Async_AddEvents_NullCollection_Throws() { var client = new KeenClient(SettingsEnv); Assert.ThrowsAsync<KeenException>(() => client.AddEventsAsync("AddEventTest", null)); } [Test] public async Task Async_AddEvents_Success() { var client = new KeenClient(SettingsEnv); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { Assert.AreEqual(p, SettingsEnv, "Unexpected settings object"); Assert.AreEqual(e.Property("AddEventTest").Value.AsEnumerable().Count(), 3, "Expected exactly 3 collection members"); return new List<CachedEvent>(); })); var events = from e in Enumerable.Range(1, 3) select new { AProperty = "Value" + e }; await client.AddEventsAsync("AddEventTest", events); } [Test] public async Task Async_Caching_SendEvents_Success() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { Assert.AreEqual(p, SettingsEnv, "Unexpected settings object"); Assert.AreEqual(e.Property("CachedEventTest").Value.AsEnumerable().Count(), 3, "Expected exactly 3 collection members"); return new List<CachedEvent>(); })); client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); client.AddEvent("CachedEventTest", new { AProperty = "AValue" }); await client.SendCachedEventsAsync(); Assert.Null(await client.EventCache.TryTakeAsync(), "Cache should be empty"); } [Test] public async Task Async_Caching_SendInvalidEvents_Throws() { var client = new KeenClient(SettingsEnv, new EventCacheMemory()); if (UseMocks) client.Event = new EventMock(SettingsEnv, addEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) => { var err = e.SelectToken("$.AddEventTest[2]") as JObject; if (null == err) throw new Exception("Unexpected error, test data not found"); return new List<CachedEvent>() { new CachedEvent("AddEventTest", e) }; })); object invalidEvent = new ExpandoObject(); ((IDictionary<string, object>)invalidEvent).Add("$" + new string('.', 260), "AValue"); var events = (from i in Enumerable.Range(1, 2) select new { AProperty = "AValue" + i }).ToList<object>(); events.Add(invalidEvent); await client.AddEventsAsync("AddEventTest", events); Assert.ThrowsAsync<KeenBulkException>(() => client.SendCachedEventsAsync()); } } }
// 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.Contracts; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace System.Runtime { public static class TaskHelpers { //This replaces the Wait<TException>(this Task task) method as we want to await and not Wait() public static async Task AsyncWait<TException>(this Task task) { try { await task; } catch { throw Fx.Exception.AsError<TException>(task.Exception); } } // Helper method when implementing an APM wrapper around a Task based async method which returns a result. // In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync: // return MethodAsync(params).ToApm(callback, state); // In the EndMethod, you would use ToApmEnd<TResult> to ensure the correct exception handling // This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided // state object public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback callback, object state) { // When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This // is so the callback can regain state. If the incoming task already holds the state object, there's no need // to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object. // This is a performance optimization for this special case. if (task.AsyncState == state) { if (callback != null) { task.ContinueWith((antecedent, obj) => { var callbackObj = obj as AsyncCallback; callbackObj(antecedent); }, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default); } return task; } // Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value. var tcs = new TaskCompletionSource<TResult>(state); var continuationState = Tuple.Create(tcs, callback); task.ContinueWith((antecedent, obj) => { var tuple = obj as Tuple<TaskCompletionSource<TResult>, AsyncCallback>; var tcsObj = tuple.Item1; var callbackObj = tuple.Item2; if (antecedent.IsFaulted) tcsObj.TrySetException(antecedent.Exception.InnerException); else if (antecedent.IsCanceled) tcsObj.TrySetCanceled(); else tcsObj.TrySetResult(antecedent.Result); if (callbackObj != null) { callbackObj(tcsObj.Task); } }, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default); return tcs.Task; } // Helper method when implementing an APM wrapper around a Task based async method which returns a result. // In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync: // return MethodAsync(params).ToApm(callback, state); // In the EndMethod, you would use ToApmEnd to ensure the correct exception handling // This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided // state object public static Task ToApm(this Task task, AsyncCallback callback, object state) { // When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This // is so the callback can regain state. If the incoming task already holds the state object, there's no need // to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object. // This is a performance optimization for this special case. if (task.AsyncState == state) { if (callback != null) { task.ContinueWith((antecedent, obj) => { var callbackObj = obj as AsyncCallback; callbackObj(antecedent); }, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default); } return task; } // Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value. // As we intend to create a task with no Result value, we don't care what result type the TCS holds as we // won't be using it. As Task<TResult> derives from Task, the returned Task is compatible. var tcs = new TaskCompletionSource<object>(state); var continuationState = Tuple.Create(tcs, callback); task.ContinueWith((antecedent, obj) => { var tuple = obj as Tuple<TaskCompletionSource<object>, AsyncCallback>; var tcsObj = tuple.Item1; var callbackObj = tuple.Item2; if (antecedent.IsFaulted) { tcsObj.TrySetException(antecedent.Exception.InnerException); } else if (antecedent.IsCanceled) { tcsObj.TrySetCanceled(); } else { tcsObj.TrySetResult(null); } if (callbackObj != null) { callbackObj(tcsObj.Task); } }, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default); return tcs.Task; } // Helper method to implement the End method of an APM method pair which is wrapping a Task based // async method when the Task returns a result. By using task.GetAwaiter.GetResult(), the exception // handling conventions are the same as when await'ing a task, i.e. this throws the first exception // and doesn't wrap it in an AggregateException. It also throws the right exception if the task was // cancelled. public static TResult ToApmEnd<TResult>(this IAsyncResult iar) { Task<TResult> task = iar as Task<TResult>; Contract.Assert(task != null, "IAsyncResult must be an instance of Task<TResult>"); return task.GetAwaiter().GetResult(); } // Helper method to implement the End method of an APM method pair which is wrapping a Task based // async method when the Task does not return result. public static void ToApmEnd(this IAsyncResult iar) { Task task = iar as Task; Contract.Assert(task != null, "IAsyncResult must be an instance of Task"); task.GetAwaiter().GetResult(); } // Awaitable helper to await a maximum amount of time for a task to complete. If the task doesn't // complete in the specified amount of time, returns false. This does not modify the state of the // passed in class, but instead is a mechanism to allow interrupting awaiting a task if a timeout // period passes. public static async Task<bool> AwaitWithTimeout(this Task task, TimeSpan timeout) { if (task.IsCompleted) { return true; } if (timeout == TimeSpan.MaxValue || timeout == Timeout.InfiniteTimeSpan) { await task; return true; } using (CancellationTokenSource cts = new CancellationTokenSource()) { var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token)); if (completedTask == task) { cts.Cancel(); return true; } else { return (task.IsCompleted); } } } // Task.GetAwaiter().GetResult() calls an internal variant of Wait() which doesn't wrap exceptions in // an AggregateException. public static void WaitForCompletion(this Task task) { task.GetAwaiter().GetResult(); } public static TResult WaitForCompletion<TResult>(this Task<TResult> task) { return task.GetAwaiter().GetResult(); } public static bool WaitWithTimeSpan(this Task task, TimeSpan timeout) { if (timeout >= TimeoutHelper.MaxWait) { task.Wait(); return true; } return task.Wait(timeout); } // Used by WebSocketTransportDuplexSessionChannel on the sync code path. // TODO: Try and switch as many code paths as possible which use this to async public static void Wait(this Task task, TimeSpan timeout, Action<Exception, TimeSpan, string> exceptionConverter, string operationType) { bool timedOut = false; try { if (timeout > TimeoutHelper.MaxWait) { task.Wait(); } else { timedOut = !task.Wait(timeout); } } catch (Exception ex) { if (Fx.IsFatal(ex) || exceptionConverter == null) { throw; } exceptionConverter(ex, timeout, operationType); } if (timedOut) { throw Fx.Exception.AsError(new TimeoutException(InternalSR.TaskTimedOutError(timeout))); } } public static Task CompletedTask() { return Task.FromResult(true); } public static DefaultTaskSchedulerAwaiter EnsureDefaultTaskScheduler() { return DefaultTaskSchedulerAwaiter.Singleton; } public static Action<object> OnAsyncCompletionCallback = OnAsyncCompletion; // Method to act as callback for asynchronous code which uses AsyncCompletionResult as the return type when used within // a Task based async method. These methods require a callback which is called in the case of the IO completing asynchronously. // This pattern still requires an allocation, whereas the purpose of using the AsyncCompletionResult enum is to avoid allocation. // In the future, this pattern should be replaced with a reusable awaitable object, potentially with a global pool. private static void OnAsyncCompletion(object state) { var tcs = state as TaskCompletionSource<bool>; Contract.Assert(state != null, "Async state should be of type TaskCompletionSource<bool>"); tcs.TrySetResult(true); } } // This awaiter causes an awaiting async method to continue on the same thread if using the // default task scheduler, otherwise it posts the continuation to the ThreadPool. While this // does a similar function to Task.ConfigureAwait, this code doesn't require a Task to function. // With Task.ConfigureAwait, you would need to call it on the first task on each potential code // path in a method. This could mean calling ConfigureAwait multiple times in a single method. // This awaiter can be awaited on at the beginning of a method a single time and isn't dependant // on running other awaitable code. public struct DefaultTaskSchedulerAwaiter : INotifyCompletion { public static DefaultTaskSchedulerAwaiter Singleton = new DefaultTaskSchedulerAwaiter(); // If the current TaskScheduler is the default, if we aren't currently running inside a task and // the default SynchronizationContext isn't current, when a Task starts, it will change the TaskScheduler // to one based off the current SynchronizationContext. Also, any async api's that WCF consumes will // post back to the same SynchronizationContext as they were started in which could cause WCF to deadlock // on our Sync code path. public bool IsCompleted { get { return (TaskScheduler.Current == TaskScheduler.Default) && (SynchronizationContext.Current == null || (SynchronizationContext.Current.GetType() == typeof(SynchronizationContext))); } } // Only called when IsCompleted returns false, otherwise the caller will call the continuation // directly causing it to stay on the same thread. public void OnCompleted(Action continuation) { Task.Run(continuation); } // Awaiter is only used to control where subsequent awaitable's run so GetResult needs no // implementation. Normally any exceptions would be thrown here, but we have nothing to throw // as we don't run anything, only control where other code runs. public void GetResult() { } public DefaultTaskSchedulerAwaiter GetAwaiter() { return this; } } // Async methods can't take an out (or ref) argument. This wrapper allows passing in place of an out argument // and can be used to return a value via a method argument. public class OutWrapper<T> { public OutWrapper() { Value = default(T); } public T Value { get; set; } public static implicit operator T(OutWrapper<T> wrapper) { return wrapper.Value; } } }
using System.Collections.Generic; using System; using System.IO; using Newtonsoft.Json; using RedditSharp; using System.Threading; using System.Linq; using System.Threading.Tasks; using System.Net; using Newtonsoft.Json.Linq; namespace MediaCrusher { static class Program { readonly static string[] SupportedContentTypes = new[] { "image/jpg", "image/jpeg", "image/png", "image/svg", "image/gif", "video/mp4", "video/ogv", "audio/mp3" }; public static Configuration Config { get; set; } public static Reddit Reddit { get; set; } public static Timer Timer { get; set; } public static int Main(string[] args) { Config = new Configuration(); if (File.Exists("config.json")) Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("config.json")); else { File.WriteAllText("config.json", JsonConvert.SerializeObject(Config, Formatting.Indented)); Console.WriteLine("Saved empty configuration in config.json, populate it and restart."); return 1; } Reddit = new Reddit(); Reddit.LogIn(Config.Username, Config.Password); Timer = new Timer(o => DoUpdate(), null, 0, 30000); Console.WriteLine("Press 'q' to exit."); ConsoleKeyInfo cki; do cki = Console.ReadKey(true); while (cki.KeyChar != 'q'); return 0; } public static void DoUpdate() { Console.WriteLine("Running update..."); try { var messages = Reddit.User.GetUnreadMessages(); foreach (var message in messages) { var comment = message as Comment; if (comment == null) { if (message is PrivateMessage) (message as PrivateMessage).SetAsRead(); continue; } comment.SetAsRead(); if (!comment.Body.Contains("/u/MediaCrusher")) continue; Console.WriteLine("Handling {0}", comment.FullName); var post = Reddit.GetThingByFullname("t3_" + comment.LinkId) as Post; if (post.Domain == "mediacru.sh") comment.Reply("This post is already on mediacru.sh, silly!"); else { var uri = new Uri(post.Url); if (uri.Host == "imgur.com" && !uri.LocalPath.StartsWith("/a/")) { // Swap out for i.imgur.com uri = new Uri("http://i.imgur.com/" + uri.LocalPath + ".png"); // Note: extension doesn't need to be correct } var task = Task.Factory.StartNew(() => { var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "HEAD"; var response = request.GetResponse() as HttpWebResponse; if (!SupportedContentTypes.Any(c => c == response.ContentType)) { comment.Reply("This post isn't a supported media type. :("); response.Close(); return; } else if (response.StatusCode != HttpStatusCode.OK) { comment.Reply("There was an error fetching this file. :("); response.Close(); return; } else { response.Close(); // Let's do this var client = new WebClient(); var file = client.DownloadData(uri); request = (HttpWebRequest)WebRequest.Create("https://mediacru.sh/upload/"); request.Method = "POST"; var builder = new MultipartFormBuilder(request); var ext = response.ContentType.Split('/')[1]; builder.AddFile("file", "foobar." + ext, file, response.ContentType); builder.Finish(); try { response = request.GetResponse() as HttpWebResponse; } catch (WebException e) { try { response = e.Response as HttpWebResponse; if (response.StatusCode != HttpStatusCode.Conflict) { comment.Reply("MediaCrush didn't like this for some reason. Sorry :("); return; } } catch { comment.Reply("MediaCrush didn't like this for some reason. Sorry :("); return; } } string hash; using (var stream = new StreamReader(response.GetResponseStream())) hash = stream.ReadToEnd(); while (true) { request = (HttpWebRequest)WebRequest.Create("https://mediacru.sh/upload/status/" + hash); request.Method = "GET"; response = request.GetResponse() as HttpWebResponse; string text; using (var stream = new StreamReader(response.GetResponseStream())) text = stream.ReadToEnd(); response.Close(); try { if (text == "done") { request = (HttpWebRequest)WebRequest.Create("https://mediacru.sh/" + hash + ".json"); request.Method = "GET"; response = request.GetResponse() as HttpWebResponse; var json = JObject.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd()); response.Close(); var compliment = GetCompliment(); var compression = (int)(json["compression"].Value<double>() * 100); if (compression >= 100) { comment.Reply(string.Format("Done! It loads **{0}% faster** now. https://mediacru.sh/{1}\n\n*{2}* " + "^^[faq](http://www.reddit.com/r/MediaCrush/wiki/mediacrusher) " + "^^- ^^[upload](https://mediacru.sh)", compression, hash, compliment)); } else { comment.Reply(string.Format("Done! https://mediacru.sh/{0}\n\n*{1}* " + "^^[faq](http://www.reddit.com/r/MediaCrush/wiki/mediacrusher) " + "^^- ^^[upload](https://mediacru.sh)", hash, compliment)); } Console.WriteLine("https://mediacru.sh/" + hash); return; } else if (text == "timeout") { comment.Reply("This took too long for us to process :("); return; } else if (text == "error") { comment.Reply("Something went wrong :("); return; } } catch (RateLimitException e) { Console.WriteLine("Rate limited - waiting {0} minutes", e.TimeToReset.TotalMinutes); Thread.Sleep(e.TimeToReset); } } } }); } } Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine("Exception occured during update:"); Console.WriteLine(e.ToString()); } Timer.Change(30000, Timeout.Infinite); } static Random Random = new Random(); public static string GetCompliment() { return Config.Compliments[Random.Next(Config.Compliments.Length)]; } } }
//@ outdir "built"; //@ using assembly "QRBuild"; using System; using System.Collections.Generic; using System.IO; using QRBuild.IO; using QRBuild.ProjectSystem; using QRBuild.Translations.ToolChain.Msvc; namespace Build { public sealed class Locations : ProjectLocations { static Locations() { dir = QRPath.GetAssemblyDirectory(typeof(Locations), 1); S = new Locations(); } public static readonly Locations S; private static readonly string dir; public readonly string Common = dir + @"\common.qr.cs"; public readonly string Bar = dir + @"\Libs\Bar\bar.qr.cs"; public readonly string Blah = dir + @"\Libs\Blah\blah.qr.cs"; } public static class Config { public static readonly string VcBinDir = @"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin"; public static readonly string PlatformSdkDir = @"C:\Program Files\Microsoft SDKs\Windows\v6.0A"; } public enum Architecture { x86, amd64, } public enum Configuration { debug, release, } public class MainVariant : BuildVariant { [VariantPart(100)] public Configuration Configuration; [VariantPart(200)] public Architecture Architecture; } public abstract class CppProject : Project { protected MainVariant MainVariant { get { return Variant as MainVariant; } } public virtual string ProjectDir { get { if (m_projectDir == null) { // Project DLL is always in a "built" sub-directory, so // the ProjectDir is 1 up from the AssemblyDirectory. m_projectDir = QRPath.GetAssemblyDirectory(GetType(), 1); } return m_projectDir; } } public string OutDir { get { if (m_outDir == null) { m_outDir = Path.Combine( ProjectDir, Path.Combine("built", FullVariantString) ); } return m_outDir; } } public MsvcToolChain ToolChain { get { if (m_msvcToolChain == null) { if (MainVariant.Architecture == Architecture.x86) { m_msvcToolChain = MsvcToolChain.ToolsX86TargetX86; } else if (MainVariant.Architecture == Architecture.amd64) { if (QRSystem.Is64BitOperatingSystem) { m_msvcToolChain = MsvcToolChain.ToolsAmd64TargetAmd64; } else { m_msvcToolChain = MsvcToolChain.ToolsX86TargetAmd64; } } else { throw new InvalidOperationException( String.Format("Unknown Architecture={0}.", MainVariant.Architecture) ); } } return m_msvcToolChain.Value; } } protected virtual void CompileOverride(MsvcCompileParams ccp) { } protected MsvcCompileParams CreateCompileParams( string sourceFile, Action<MsvcCompileParams> overrideParams) { string srcDir = Path.GetDirectoryName(sourceFile); string objDir = Path.Combine(OutDir, srcDir); var ccp = new MsvcCompileParams(); ccp.VcBinDir = Config.VcBinDir; ccp.CompileDir = Path.Combine(ProjectDir, srcDir); ccp.BuildFileDir = objDir; ccp.SourceFile = Path.GetFileName(sourceFile); ccp.ObjectPath = Path.Combine( objDir, ccp.SourceFile + ".obj"); ccp.Compile = true; ccp.ToolChain = ToolChain; ccp.CppExceptions = MsvcCppExceptions.Enabled; ccp.DebugInfoFormat = MsvcDebugInfoFormat.Normal; ccp.EnableMinimalRebuild = true; if (MainVariant.Configuration == Configuration.debug) { ccp.OptLevel = MsvcOptLevel.Disabled; } else { ccp.OptLevel = MsvcOptLevel.GlobalOptimizations; } // Allow derived class to override settings in bulk. CompileOverride(ccp); // Allow caller to override settings for just this file. if (overrideParams != null) { overrideParams(ccp); } return ccp; } /// Derived project classes can override this to set project-level /// defaults on compiler params. protected MsvcCompile Compile(string sourceFile) { return Compile(sourceFile, null); } protected MsvcCompile Compile( string sourceFile, Action<MsvcCompileParams> overrideParams) { var ccp = CreateCompileParams(sourceFile, overrideParams); var cc = new MsvcCompile(ProjectManager.BuildGraph, ccp); cc.ModuleName = ModuleName + ".Compile"; m_compiles.Add(cc); return cc; } /// Derived project classes can override this to set project-level /// defaults on linker params. protected virtual void LinkerOverride(MsvcLinkerParams lp) { } protected MsvcLinkerParams CreateLinkerParams( string outputName, Action<MsvcLinkerParams> overrideParams) { var lp = new MsvcLinkerParams(); lp.VcBinDir = Config.VcBinDir; lp.ToolChain = ToolChain; lp.CompileDir = ProjectDir; lp.BuildFileDir = OutDir; lp.Inputs.Add(Config.PlatformSdkDir + @"\lib\kernel32.lib"); lp.Inputs.Add(Config.PlatformSdkDir + @"\lib\user32.lib"); foreach (MsvcCompile cc in m_compiles) { lp.Inputs.Add(cc.Params.ObjectPath); } lp.OutputFilePath = Path.Combine(OutDir, outputName); lp.Incremental = true; LinkerOverride(lp); if (overrideParams != null) { overrideParams(lp); } return lp; } protected MsvcLink Link(string outputName) { return Link(outputName, null); } protected virtual MsvcLink Link( string outputName, Action<MsvcLinkerParams> overrideParams) { var lp = CreateLinkerParams(outputName, overrideParams); var link = new MsvcLink(ProjectManager.BuildGraph, lp); link.ModuleName = ModuleName + ".Link"; return link; } /// Derived project classes can override this to set project-level /// defaults on lib params. protected virtual void LibOverride(MsvcLibParams lp) { } protected MsvcLibParams CreateLibParams( string outputName, Action<MsvcLibParams> overrideParams) { var lp = new MsvcLibParams(); lp.VcBinDir = Config.VcBinDir; lp.ToolChain = ToolChain; lp.CompileDir = ProjectDir; lp.BuildFileDir = OutDir; foreach (MsvcCompile cc in m_compiles) { lp.Inputs.Add(cc.Params.ObjectPath); } lp.OutputFilePath = Path.Combine(OutDir, outputName); LibOverride(lp); if (overrideParams != null) { overrideParams(lp); } return lp; } protected MsvcLib Lib(string outputName) { return Lib(outputName, null); } protected virtual MsvcLib Lib( string outputName, Action<MsvcLibParams> overrideParams) { var lp = CreateLibParams(outputName, overrideParams); var lib = new MsvcLib(ProjectManager.BuildGraph, lp); lib.ModuleName = ModuleName + ".Lib"; return lib; } private string m_projectDir; private string m_outDir; private MsvcToolChain? m_msvcToolChain; private List<MsvcCompile> m_compiles = new List<MsvcCompile>(); } }
// 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.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AbsUInt32() { var test = new SimpleUnaryOpTest__AbsUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.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 (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 SimpleUnaryOpTest__AbsUInt32 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__AbsUInt32 testClass) { var result = AdvSimd.Abs(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__AbsUInt32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((Int32*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar1; private Vector64<Int32> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__AbsUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public SimpleUnaryOpTest__AbsUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Abs( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Abs( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector64<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Abs( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((Int32*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var result = AdvSimd.Abs(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Abs(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__AbsUInt32(); var result = AdvSimd.Abs(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__AbsUInt32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((Int32*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Abs(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) { var result = AdvSimd.Abs( AdvSimd.LoadVector64((Int32*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Abs(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Abs( AdvSimd.LoadVector64((Int32*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _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(Vector64<Int32> op1, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (uint)Math.Abs(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (uint)Math.Abs(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<UInt32>(Vector64<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Pocket; using Serilog.Sinks.RollingFileAlternate; using LoggerConfiguration = Serilog.LoggerConfiguration; #region UsefulUsings using static Pocket.Logger<Demo.Examples>; #endregion namespace Demo { public class Examples { static Examples() { } public static void HelloPocketLogger() { #region HelloPocketLogger Log.Info("Hello!"); Log.Event("LoudNoise"); Log.Warning("That's strange..."); Log.Error("Oh no! Run!"); #endregion } public static void LogInfo() { #region LogInfo var x = "world"; var y = DateTime.Now; Log.Info("Hello", x, y); #endregion } public static void LogInfoWithNamedTemplateParams() { #region LogInfoWithNamedTemplateParams var x = "world"; var y = DateTime.Now; Log.Info("Hello {x}! The time is {y}!", x, y); #endregion } public static void LogEvent() { #region LogEvent Log.Event("LoudNoise", ("loudness", 9000), ("nearness", 1.5)); #endregion } public static void LogWarning() { #region LogWarning Log.Warning("That's strange...", new DataMisalignedException()); #endregion } public static void LogError() { #region LogError Log.Error("Oh no! Run!", new BarrierPostPhaseException()); #endregion } public static void LogOnExit() { #region LogOnExit using (var _ = Log.OnExit()) { } #endregion } public static void LogOnEnterAndExit() { #region LogOnEnterAndExit using (var _ = Log.OnEnterAndExit()) { } #endregion } public static void LogConfirmOnExit() { #region LogConfirmOnExit using (var operation = Log.ConfirmOnExit()) { } #endregion } public static void LogConfirmOnExitSucceed() { #region LogConfirmOnExitSucceed using (var operation = Log.ConfirmOnExit()) { operation.Succeed(); } #endregion } public static void LogConfirmOnExitFail() { #region LogConfirmOnExitFail using (var operation = Log.ConfirmOnExit()) { operation.Fail(); } #endregion } public static void LogOnEnterAndConfirmOnExit() { #region LogOnEnterAndConfirmOnExit using (var operation = Log.OnEnterAndConfirmOnExit()) { operation.Succeed(); } #endregion } public static async Task Checkpoints() { #region Checkpoints using (var operation = Log.OnEnterAndConfirmOnExit()) { var apiResult = await CallSomeApiAsync(); operation.Event("CalledSomeApi", ("ResultCode", apiResult)); operation.Succeed("We did it!"); } #endregion } public static void ExitArgs() { #region ExitArgs var myVariable = "initial value"; using (var operation = Log.OnEnterAndConfirmOnExit( exitArgs: () => new[] { (nameof(myVariable), (object) myVariable) })) { operation.Info("", (nameof(myVariable), myVariable)); myVariable = "new value"; operation.Succeed("Yes!"); } #endregion } #region ChildOperations public static async Task Method1() { using var operation = Log.OnEnterAndConfirmOnExit(); await Method2(operation); operation.Succeed(); } private static async Task Method2(ConfirmationLogger operation) { using var childOperation = operation.OnEnterAndConfirmOnExit(); childOperation.Succeed(); } #endregion public static void SubscribeAndSendToConsole() { Program.ConsoleSubscription.Dispose(); #region SubscribeAndSendToConsole Log.Info("Before subscribing."); var subscription = LogEvents.Subscribe(e => Console.WriteLine(e.ToLogString())); Log.Info("After subscribing."); subscription.Dispose(); Log.Info("After disposing the subscription."); #endregion } public static void LogEventStructure() { Program.ConsoleSubscription.Dispose(); #region LogEventStructure using var subscription = LogEvents.Subscribe(e => { Console.WriteLine(e.ToLogString()); Console.WriteLine($" {nameof(e.TimestampUtc)}: {e.TimestampUtc}"); Console.WriteLine($" {nameof(e.Operation.Id)}: {e.Operation.Id}"); Console.WriteLine($" {nameof(e.Category)}: {e.Category}"); Console.WriteLine($" {nameof(e.OperationName)}: {e.OperationName}"); Console.WriteLine($" {nameof(e.LogLevel)}: {e.LogLevel}"); Console.WriteLine($" {nameof(e.Operation.IsStart)}: {e.Operation.IsStart}"); Console.WriteLine($" {nameof(e.Operation.IsEnd)}: {e.Operation.IsEnd}"); Console.WriteLine($" {nameof(e.Operation.Duration)}: {e.Operation.Duration}"); Console.WriteLine($" {nameof(e.Operation.IsSuccessful)}: {e.Operation.IsSuccessful}"); }); Log.Info("INFO"); using var operation = Log.OnEnterAndConfirmOnExit(); operation.Event("EVENT"); operation.Succeed(); #endregion } public static void Evaluate() { Program.ConsoleSubscription.Dispose(); #region Evaluate using var subscription = LogEvents.Subscribe(e => { var evaluated = e.Evaluate(); Console.WriteLine(evaluated.Message); foreach (var property in evaluated.Properties) { Console.WriteLine($" {property.Name}: {property.Value}"); } }); Log.Event("EventWithProperties", ("a number", 1), ("a date", DateTime.Now)); Log.Event("EventWithMetrics", ("one", 1d), ("pi, more or less", 3.14)); #endregion } public static void SubscribeAndSendToSerilog() { Program.ConsoleSubscription.Dispose(); #region SubscribeAndSendToSerilog using var serilogLogger = new LoggerConfiguration() .WriteTo .RollingFileAlternate(".", outputTemplate: "{Message}{NewLine}") .CreateLogger(); using (var subscription = LogEvents.Subscribe( e => serilogLogger.Information(e.ToLogString()))) { Log.Info("After subscribing."); } var logFile = new DirectoryInfo(".") .GetFiles() .OrderBy(f => f.LastWriteTime) .Last(); Console.WriteLine(File.ReadAllText(logFile.FullName)); #endregion } public static void Enrich() { #region Enrich LogEvents.Enrich(add => { add(("app_version", Assembly.GetExecutingAssembly().GetName().Version)); add(("machine_name", Environment.MachineName)); }); Log.Info("Hello!"); #endregion } private static async Task<int> CallSomeApiAsync() { await Task.Delay(100); return 42; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class CredentialOperationsExtensions { /// <summary> /// Create a credential. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// credential operation. /// </param> /// <returns> /// The response model for the create or update credential operation. /// </returns> public static CredentialCreateOrUpdateResponse CreateOrUpdate(this ICredentialOperations operations, string resourceGroupName, string automationAccount, CredentialCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ICredentialOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a credential. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// credential operation. /// </param> /// <returns> /// The response model for the create or update credential operation. /// </returns> public static Task<CredentialCreateOrUpdateResponse> CreateOrUpdateAsync(this ICredentialOperations operations, string resourceGroupName, string automationAccount, CredentialCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the credential. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='credentialName'> /// Required. The name of credential. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this ICredentialOperations operations, string resourceGroupName, string automationAccount, string credentialName) { return Task.Factory.StartNew((object s) => { return ((ICredentialOperations)s).DeleteAsync(resourceGroupName, automationAccount, credentialName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the credential. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='credentialName'> /// Required. The name of credential. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this ICredentialOperations operations, string resourceGroupName, string automationAccount, string credentialName) { return operations.DeleteAsync(resourceGroupName, automationAccount, credentialName, CancellationToken.None); } /// <summary> /// Retrieve the credential identified by credential name. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='credentialName'> /// Required. The name of credential. /// </param> /// <returns> /// The response model for the get credential operation. /// </returns> public static CredentialGetResponse Get(this ICredentialOperations operations, string resourceGroupName, string automationAccount, string credentialName) { return Task.Factory.StartNew((object s) => { return ((ICredentialOperations)s).GetAsync(resourceGroupName, automationAccount, credentialName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the credential identified by credential name. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='credentialName'> /// Required. The name of credential. /// </param> /// <returns> /// The response model for the get credential operation. /// </returns> public static Task<CredentialGetResponse> GetAsync(this ICredentialOperations operations, string resourceGroupName, string automationAccount, string credentialName) { return operations.GetAsync(resourceGroupName, automationAccount, credentialName, CancellationToken.None); } /// <summary> /// Retrieve a list of credentials. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list credential operation. /// </returns> public static CredentialListResponse List(this ICredentialOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((ICredentialOperations)s).ListAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of credentials. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list credential operation. /// </returns> public static Task<CredentialListResponse> ListAsync(this ICredentialOperations operations, string resourceGroupName, string automationAccount) { return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of credentials. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list credential operation. /// </returns> public static CredentialListResponse ListNext(this ICredentialOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((ICredentialOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of credentials. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list credential operation. /// </returns> public static Task<CredentialListResponse> ListNextAsync(this ICredentialOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Update a credential. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the patch credential operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Patch(this ICredentialOperations operations, string resourceGroupName, string automationAccount, CredentialPatchParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ICredentialOperations)s).PatchAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update a credential. (see /// http://aka.ms/azureautomationsdk/credentialoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.ICredentialOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the patch credential operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> PatchAsync(this ICredentialOperations operations, string resourceGroupName, string automationAccount, CredentialPatchParameters parameters) { return operations.PatchAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } } }
using System; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Linq; using Marten.Schema.Identity; using Marten.Services; using Marten.Services.Deletes; using Marten.Util; using Npgsql; using NpgsqlTypes; namespace Marten.Schema { public class Resolver<T> : IResolver<T>, IDocumentStorage, IDocumentUpsert where T : class { private readonly string _deleteSql; private readonly Func<T, object> _identity; private readonly string _loadArraySql; private readonly string _loaderSql; private readonly ISerializer _serializer; private readonly DocumentMapping _mapping; private readonly bool _useCharBufferPooling; private readonly FunctionName _upsertName; private readonly Action<SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> _sprocWriter; public Resolver(ISerializer serializer, DocumentMapping mapping, bool useCharBufferPooling) { _serializer = serializer; _mapping = mapping; _useCharBufferPooling = useCharBufferPooling; IdType = TypeMappings.ToDbType(mapping.IdMember.GetMemberType()); _loaderSql = $"select {_mapping.SelectFields().Join(", ")} from {_mapping.Table.QualifiedName} as d where id = :id"; _deleteSql = $"delete from {_mapping.Table.QualifiedName} where id = :id"; _loadArraySql = $"select {_mapping.SelectFields().Join(", ")} from {_mapping.Table.QualifiedName} as d where id = ANY(:ids)"; _identity = LambdaBuilder.Getter<T, object>(mapping.IdMember); _sprocWriter = buildSprocWriter(mapping); _upsertName = mapping.UpsertFunction; if (mapping.DeleteStyle == DeleteStyle.Remove) { DeleteByIdSql = $"delete from {_mapping.Table.QualifiedName} where id = ?"; DeleteByWhereSql = $"delete from {_mapping.Table.QualifiedName} as d where ?"; } else { DeleteByIdSql = $"update {_mapping.Table.QualifiedName} set {DocumentMapping.DeletedColumn} = True, {DocumentMapping.DeletedAtColumn} = now() where id = ?"; DeleteByWhereSql = $"update {_mapping.Table.QualifiedName} as d set {DocumentMapping.DeletedColumn} = True, {DocumentMapping.DeletedAtColumn} = now() where ?"; } } public string DeleteByWhereSql { get; } public string DeleteByIdSql { get; } private Action<SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> buildSprocWriter(DocumentMapping mapping) { var call = Expression.Parameter(typeof(SprocCall), "call"); var doc = Expression.Parameter(typeof(T), "doc"); var batch = Expression.Parameter(typeof(UpdateBatch), "batch"); var mappingParam = Expression.Parameter(typeof(DocumentMapping), "mapping"); var currentVersion = Expression.Parameter(typeof(Guid?), "currentVersion"); var newVersion = Expression.Parameter(typeof(Guid), "newVersion"); var arguments = new UpsertFunction(mapping).OrderedArguments().Select(x => { return x.CompileUpdateExpression(_serializer.EnumStorage, call, doc, batch, mappingParam, currentVersion, newVersion, _useCharBufferPooling); }); var block = Expression.Block(arguments); var lambda = Expression.Lambda<Action<SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid>>(block, new ParameterExpression[] { call, doc, batch, mappingParam, currentVersion, newVersion }); return lambda.Compile(); } public Type DocumentType => _mapping.DocumentType; public NpgsqlDbType IdType { get; } public virtual T Resolve(int startingIndex, DbDataReader reader, IIdentityMap map) { if (reader.IsDBNull(startingIndex)) return null; var json = reader.GetString(startingIndex); var id = reader[startingIndex + 1]; var version = reader.GetFieldValue<Guid>(startingIndex + 2); return map.Get<T>(id, json, version); } public virtual async Task<T> ResolveAsync(int startingIndex, DbDataReader reader, IIdentityMap map, CancellationToken token) { if (await reader.IsDBNullAsync(startingIndex, token).ConfigureAwait(false)) return null; var json = await reader.GetFieldValueAsync<string>(startingIndex, token).ConfigureAwait(false); var id = await reader.GetFieldValueAsync<object>(startingIndex + 1, token).ConfigureAwait(false); var version = await reader.GetFieldValueAsync<Guid>(startingIndex + 2, token).ConfigureAwait(false); return map.Get<T>(id, json, version); } public T Resolve(IIdentityMap map, ILoader loader, object id) { return map.Get(id, () => loader.LoadDocument<T>(id)); } public Task<T> ResolveAsync(IIdentityMap map, ILoader loader, CancellationToken token, object id) { return map.GetAsync(id, async tk => await loader.LoadDocumentAsync<T>(id, tk).ConfigureAwait(false), token); } public virtual FetchResult<T> Fetch(DbDataReader reader, ISerializer serializer) { var found = reader.Read(); if (!found) return null; var json = reader.GetString(0); var doc = serializer.FromJson<T>(json); var version = reader.GetFieldValue<Guid>(2); return new FetchResult<T>(doc, json, version); } public virtual async Task<FetchResult<T>> FetchAsync(DbDataReader reader, ISerializer serializer, CancellationToken token) { var found = await reader.ReadAsync(token).ConfigureAwait(false); if (!found) return null; var json = await reader.GetFieldValueAsync<string>(0, token).ConfigureAwait(false); var doc = serializer.FromJson<T>(json); var version = await reader.GetFieldValueAsync<Guid>(2, token).ConfigureAwait(false); return new FetchResult<T>(doc, json, version); } public NpgsqlCommand LoaderCommand(object id) { return new NpgsqlCommand(_loaderSql).With("id", id); } public NpgsqlCommand DeleteCommandForId(object id) { return new NpgsqlCommand(_deleteSql).With("id", id); } public NpgsqlCommand DeleteCommandForEntity(object entity) { return DeleteCommandForId(_identity((T) entity)); } public NpgsqlCommand LoadByArrayCommand<TKey>(TKey[] ids) { return new NpgsqlCommand(_loadArraySql).With("ids", ids); } public object Identity(object document) { return _identity((T) document); } public void RegisterUpdate(UpdateBatch batch, object entity) { var json = batch.Serializer.ToJson(entity); RegisterUpdate(batch, entity, json); } public void RegisterUpdate(UpdateBatch batch, object entity, string json) { var newVersion = CombGuidIdGeneration.NewGuid(); var currentVersion = batch.Versions.Version<T>(Identity(entity)); ICallback callback = null; if (_mapping.UseOptimisticConcurrency) { callback = new OptimisticConcurrencyCallback<T>(Identity(entity), batch.Versions, newVersion, currentVersion); } var call = batch.Sproc(_upsertName, callback); _sprocWriter(call, (T) entity, batch, _mapping, currentVersion, newVersion); } public void Remove(IIdentityMap map, object entity) { var id = Identity(entity); map.Remove<T>(id); } public void Delete(IIdentityMap map, object id) { map.Remove<T>(id); } public void Store(IIdentityMap map, object id, object entity) { map.Store<T>(id, (T) entity); } public IStorageOperation DeletionForId(object id) { return new DeleteById(DeleteByIdSql, this, id); } public IStorageOperation DeletionForEntity(object entity) { return new DeleteById(DeleteByIdSql, this, Identity(entity), entity); } public IStorageOperation DeletionForWhere(IWhereFragment @where) { return new DeleteWhere(typeof(T), DeleteByWhereSql, @where); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography { /// <summary> /// AES wrapper around the CAPI implementation. /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class AesCryptoServiceProvider : Aes { private static volatile KeySizes[] s_supportedKeySizes; private static volatile int s_defaultKeySize; [SecurityCritical] private SafeCspHandle m_cspHandle; // Note that keys are stored in CAPI rather than directly in the KeyValue property, which should not // be used to retrieve the key value directly. [SecurityCritical] private SafeCapiKeyHandle m_key; [System.Security.SecurityCritical] public AesCryptoServiceProvider () { Contract.Ensures(m_cspHandle != null && !m_cspHandle.IsInvalid && !m_cspHandle.IsClosed); // On Windows XP the AES CSP has the prototype name, but on newer operating systems it has the // standard name string providerName = CapiNative.ProviderNames.MicrosoftEnhancedRsaAes; if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 1) { providerName = CapiNative.ProviderNames.MicrosoftEnhancedRsaAesPrototype; } m_cspHandle = CapiNative.AcquireCsp(null, providerName, CapiNative.ProviderType.RsaAes, CapiNative.CryptAcquireContextFlags.VerifyContext, true); // CAPI will not allow feedback sizes greater than 64 bits FeedbackSizeValue = 8; // Get the different AES key sizes supported by this platform, raising an error if there are no // supported key sizes. int defaultKeySize = 0; KeySizes[] keySizes = FindSupportedKeySizes(m_cspHandle, out defaultKeySize); if (keySizes.Length != 0) { Debug.Assert(defaultKeySize > 0, "defaultKeySize > 0"); KeySizeValue = defaultKeySize; } else { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } } /// <summary> /// Value of the symmetric key used for encryption / decryption /// </summary> public override byte[] Key { [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] get { Contract.Ensures(m_key != null && !m_key.IsInvalid && !m_key.IsClosed); Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length == KeySizeValue / 8); if (m_key == null || m_key.IsInvalid || m_key.IsClosed) { GenerateKey(); } // We don't hold onto a key value directly, so we need to export it from CAPI when the user // wants a byte array representation. byte[] keyValue = CapiNative.ExportSymmetricKey(m_key); return keyValue; } [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] set { Contract.Ensures(m_key != null && !m_key.IsInvalid && !m_key.IsClosed); if (value == null) { throw new ArgumentNullException("value"); } byte[] keyValue = (byte[])value.Clone(); if (!ValidKeySize(keyValue.Length * 8)) { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidKeySize)); } // Import the key, then close any current key and replace with the new one. We need to make // sure the import is successful before closing the current key to avoid having an algorithm // with no valid keys. SafeCapiKeyHandle importedKey = CapiNative.ImportSymmetricKey(m_cspHandle, GetAlgorithmId(keyValue.Length * 8), keyValue); if (m_key != null) { m_key.Dispose(); } m_key = importedKey; KeySizeValue = keyValue.Length * 8; } } /// <summary> /// Size, in bits, of the key /// </summary> public override int KeySize { get { return base.KeySize; } [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] set { base.KeySize = value; // Since the key size is being reset, we need to reset the key itself as well if (m_key != null) { m_key.Dispose(); } } } /// <summary> /// Create an object to perform AES decryption with the current key and IV /// </summary> /// <returns></returns> [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public override ICryptoTransform CreateDecryptor() { Contract.Ensures(Contract.Result<ICryptoTransform>() != null); if (m_key == null || m_key.IsInvalid || m_key.IsClosed) { throw new CryptographicException(SR.GetString(SR.Cryptography_DecryptWithNoKey)); } return CreateDecryptor(m_key, IVValue); } /// <summary> /// Create an object to perform AES decryption with the given key and IV /// </summary> [System.Security.SecurityCritical] public override ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) { Contract.Ensures(Contract.Result<ICryptoTransform>() != null); if (key == null) { throw new ArgumentNullException("key"); } if (!ValidKeySize(key.Length * 8)) { throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidKeySize), "key"); } if (iv != null && iv.Length * 8 != BlockSizeValue) { throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidIVSize), "iv"); } byte[] keyCopy = (byte[])key.Clone(); byte[] ivCopy = null; if (iv != null) { ivCopy = (byte[])iv.Clone(); } using (SafeCapiKeyHandle importedKey = CapiNative.ImportSymmetricKey(m_cspHandle, GetAlgorithmId(keyCopy.Length * 8), keyCopy)) { return CreateDecryptor(importedKey, ivCopy); } } /// <summary> /// Create an object to perform AES decryption /// </summary> [System.Security.SecurityCritical] private ICryptoTransform CreateDecryptor(SafeCapiKeyHandle key, byte[] iv) { Contract.Requires(key != null); Contract.Ensures(Contract.Result<ICryptoTransform>() != null); return new CapiSymmetricAlgorithm(BlockSizeValue, FeedbackSizeValue, m_cspHandle, key, iv, Mode, PaddingValue, EncryptionMode.Decrypt); } /// <summary> /// Create an object to do AES encryption with the current key and IV /// </summary> [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public override ICryptoTransform CreateEncryptor() { Contract.Ensures(Contract.Result<ICryptoTransform>() != null); if (m_key == null || m_key.IsInvalid || m_key.IsClosed) { GenerateKey(); } // ECB is the only mode which does not require an IV -- generate one here if we don't have one yet. if (Mode != CipherMode.ECB && IVValue == null) { GenerateIV(); } return CreateEncryptor(m_key, IVValue); } /// <summary> /// Create an object to do AES encryption with the given key and IV /// </summary> [System.Security.SecurityCritical] public override ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) { Contract.Ensures(Contract.Result<ICryptoTransform>() != null); if (key == null) { throw new ArgumentNullException("key"); } if (!ValidKeySize(key.Length * 8)) { throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidKeySize), "key"); } if (iv != null && iv.Length * 8 != BlockSizeValue) { throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidIVSize), "iv"); } byte[] keyCopy = (byte[])key.Clone(); byte[] ivCopy = null; if (iv != null) { ivCopy = (byte[])iv.Clone(); } using (SafeCapiKeyHandle importedKey = CapiNative.ImportSymmetricKey(m_cspHandle, GetAlgorithmId(keyCopy.Length * 8), keyCopy)) { return CreateEncryptor(importedKey, ivCopy); } } /// <summary> /// Create an object to perform AES encryption /// </summary> [System.Security.SecurityCritical] private ICryptoTransform CreateEncryptor(SafeCapiKeyHandle key, byte[] iv) { Contract.Requires(key != null); Contract.Ensures(Contract.Result<ICryptoTransform>() != null); return new CapiSymmetricAlgorithm(BlockSizeValue, FeedbackSizeValue, m_cspHandle, key, iv, Mode, PaddingValue, EncryptionMode.Encrypt); } /// <summary> /// Release any CAPI handles we're holding onto /// </summary> [System.Security.SecurityCritical] protected override void Dispose(bool disposing) { Contract.Ensures(!disposing || m_key == null || m_key.IsClosed); Contract.Ensures(!disposing || m_cspHandle == null || m_cspHandle.IsClosed); try { if (disposing) { if (m_key != null) { m_key.Dispose(); } if (m_cspHandle != null) { m_cspHandle.Dispose(); } } } finally { base.Dispose(disposing); } } /// <summary> /// Get the size of AES keys supported by the given CSP, and which size should be used by default. /// /// We assume that the same CSP will always be used by all instances of the AesCryptoServiceProvider /// in the current AppDomain. If we add the ability for users to choose which CSP to use on a /// per-instance basis, we need to update the code to account for the CSP when checking the cached /// key size values. /// </summary> [System.Security.SecurityCritical] private static KeySizes[] FindSupportedKeySizes(SafeCspHandle csp, out int defaultKeySize) { Contract.Requires(csp != null); Contract.Ensures(Contract.Result<KeySizes[]>() != null); // If this platform has any supported algorithm sizes, then the default key size should be set to a // reasonable value. Contract.Ensures(Contract.Result<KeySizes[]>().Length == 0 || (Contract.ValueAtReturn<int>(out defaultKeySize) > 0 && Contract.ValueAtReturn<int>(out defaultKeySize) % 8 == 0)); if (s_supportedKeySizes == null) { List<KeySizes> keySizes = new List<KeySizes>(); int maxKeySize = 0; // // Enumerate the CSP's supported algorithms to see what key sizes it supports for AES // CapiNative.PROV_ENUMALGS algorithm = CapiNative.GetProviderParameterStruct<CapiNative.PROV_ENUMALGS>(csp, CapiNative.ProviderParameter.EnumerateAlgorithms, CapiNative.ProviderParameterFlags.RestartEnumeration); // Translate between CAPI AES algorithm IDs and supported key sizes while (algorithm.aiAlgId != CapiNative.AlgorithmId.None) { switch (algorithm.aiAlgId) { case CapiNative.AlgorithmId.Aes128: keySizes.Add(new KeySizes(128, 128, 0)); if (128 > maxKeySize) { maxKeySize = 128; } break; case CapiNative.AlgorithmId.Aes192: keySizes.Add(new KeySizes(192, 192, 0)); if (192 > maxKeySize) { maxKeySize = 192; } break; case CapiNative.AlgorithmId.Aes256: keySizes.Add(new KeySizes(256, 256, 0)); if (256 > maxKeySize) { maxKeySize = 256; } break; default: break; } algorithm = CapiNative.GetProviderParameterStruct<CapiNative.PROV_ENUMALGS>(csp, CapiNative.ProviderParameter.EnumerateAlgorithms, CapiNative.ProviderParameterFlags.None); } s_supportedKeySizes = keySizes.ToArray(); s_defaultKeySize = maxKeySize; } defaultKeySize = s_defaultKeySize; return s_supportedKeySizes; } /// <summary> /// Generate a new random key /// </summary> [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public override void GenerateKey() { Contract.Ensures(m_key != null && !m_key.IsInvalid & !m_key.IsClosed); Contract.Assert(m_cspHandle != null); SafeCapiKeyHandle key = null; RuntimeHelpers.PrepareConstrainedRegions(); try { if (!CapiNative.UnsafeNativeMethods.CryptGenKey(m_cspHandle, GetAlgorithmId(KeySizeValue), CapiNative.KeyFlags.Exportable, out key)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } finally { if (key != null && !key.IsInvalid) { key.SetParentCsp(m_cspHandle); } } if (m_key != null) { m_key.Dispose(); } m_key = key; } /// <summary> /// Generate a random initialization vector /// </summary> [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public override void GenerateIV() { Contract.Ensures(IVValue != null && IVValue.Length == BlockSizeValue / 8); Contract.Assert(m_cspHandle != null); Contract.Assert(BlockSizeValue % 8 == 0); byte[] iv = new byte[BlockSizeValue / 8]; if (!CapiNative.UnsafeNativeMethods.CryptGenRandom(m_cspHandle, iv.Length, iv)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } IVValue = iv; } /// <summary> /// Map an AES key size to the corresponding CAPI algorithm ID /// </summary> private static CapiNative.AlgorithmId GetAlgorithmId(int keySize) { // We should always return either a data encryption algorithm ID or None if we don't recognize the key size Contract.Ensures( ((((int)Contract.Result<CapiNative.AlgorithmId>()) & (int)CapiNative.AlgorithmClass.DataEncryption) == (int)CapiNative.AlgorithmClass.DataEncryption) || Contract.Result<CapiNative.AlgorithmId>() == CapiNative.AlgorithmId.None); switch (keySize) { case 128: return CapiNative.AlgorithmId.Aes128; case 192: return CapiNative.AlgorithmId.Aes192; case 256: return CapiNative.AlgorithmId.Aes256; default: return CapiNative.AlgorithmId.None; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEngine; using Debug = UnityEngine.Debug; using Object = UnityEngine.Object; namespace UnityTest { [Serializable] public class AssertionComponent : MonoBehaviour, IAssertionComponentConfigurator { [SerializeField] public float checkAfterTime = 1f; [SerializeField] public bool repeatCheckTime = true; [SerializeField] public float repeatEveryTime = 1f; [SerializeField] public int checkAfterFrames = 1; [SerializeField] public bool repeatCheckFrame = true; [SerializeField] public int repeatEveryFrame = 1; [SerializeField] public bool hasFailed; [SerializeField] public CheckMethod checkMethods = CheckMethod.Start; [SerializeField] private ActionBase m_ActionBase; [SerializeField] public int checksPerformed = 0; private int m_CheckOnFrame; private string m_CreatedInFilePath = ""; private int m_CreatedInFileLine = -1; public ActionBase Action { get { return m_ActionBase; } set { m_ActionBase = value; m_ActionBase.go = gameObject; } } public Object GetFailureReferenceObject() { #if UNITY_EDITOR if (!string.IsNullOrEmpty(m_CreatedInFilePath)) { return UnityEditor.AssetDatabase.LoadAssetAtPath(m_CreatedInFilePath, typeof(Object)); } #endif return this; } public string GetCreationLocation() { if (!string.IsNullOrEmpty(m_CreatedInFilePath)) { var idx = m_CreatedInFilePath.LastIndexOf("\\") + 1; return string.Format("{0}, line {1} ({2})", m_CreatedInFilePath.Substring(idx), m_CreatedInFileLine, m_CreatedInFilePath); } return ""; } public void Awake() { if (!Debug.isDebugBuild) Destroy(this); OnComponentCopy(); } public void OnValidate() { if (Application.isEditor) OnComponentCopy(); } private void OnComponentCopy() { if (m_ActionBase == null) return; var oldActionList = Resources.FindObjectsOfTypeAll(typeof(AssertionComponent)).Where(o => ((AssertionComponent)o).m_ActionBase == m_ActionBase && o != this); // if it's not a copy but a new component don't do anything if (!oldActionList.Any()) return; if (oldActionList.Count() > 1) Debug.LogWarning("More than one refence to comparer found. This shouldn't happen"); var oldAction = oldActionList.First() as AssertionComponent; m_ActionBase = oldAction.m_ActionBase.CreateCopy(oldAction.gameObject, gameObject); } public void Start() { CheckAssertionFor(CheckMethod.Start); if (IsCheckMethodSelected(CheckMethod.AfterPeriodOfTime)) { StartCoroutine("CheckPeriodically"); } if (IsCheckMethodSelected(CheckMethod.Update)) { m_CheckOnFrame = Time.frameCount + checkAfterFrames; } } public IEnumerator CheckPeriodically() { yield return new WaitForSeconds(checkAfterTime); CheckAssertionFor(CheckMethod.AfterPeriodOfTime); while (repeatCheckTime) { yield return new WaitForSeconds(repeatEveryTime); CheckAssertionFor(CheckMethod.AfterPeriodOfTime); } } public bool ShouldCheckOnFrame() { if (Time.frameCount > m_CheckOnFrame) { if (repeatCheckFrame) m_CheckOnFrame += repeatEveryFrame; else m_CheckOnFrame = Int32.MaxValue; return true; } return false; } public void OnDisable() { CheckAssertionFor(CheckMethod.OnDisable); } public void OnEnable() { CheckAssertionFor(CheckMethod.OnEnable); } public void OnDestroy() { CheckAssertionFor(CheckMethod.OnDestroy); } public void Update() { if (IsCheckMethodSelected(CheckMethod.Update) && ShouldCheckOnFrame()) { CheckAssertionFor(CheckMethod.Update); } } public void FixedUpdate() { CheckAssertionFor(CheckMethod.FixedUpdate); } public void LateUpdate() { CheckAssertionFor(CheckMethod.LateUpdate); } public void OnControllerColliderHit() { CheckAssertionFor(CheckMethod.OnControllerColliderHit); } public void OnParticleCollision() { CheckAssertionFor(CheckMethod.OnParticleCollision); } public void OnJointBreak() { CheckAssertionFor(CheckMethod.OnJointBreak); } public void OnBecameInvisible() { CheckAssertionFor(CheckMethod.OnBecameInvisible); } public void OnBecameVisible() { CheckAssertionFor(CheckMethod.OnBecameVisible); } public void OnTriggerEnter() { CheckAssertionFor(CheckMethod.OnTriggerEnter); } public void OnTriggerExit() { CheckAssertionFor(CheckMethod.OnTriggerExit); } public void OnTriggerStay() { CheckAssertionFor(CheckMethod.OnTriggerStay); } public void OnCollisionEnter() { CheckAssertionFor(CheckMethod.OnCollisionEnter); } public void OnCollisionExit() { CheckAssertionFor(CheckMethod.OnCollisionExit); } public void OnCollisionStay() { CheckAssertionFor(CheckMethod.OnCollisionStay); } public void OnTriggerEnter2D() { CheckAssertionFor(CheckMethod.OnTriggerEnter2D); } public void OnTriggerExit2D() { CheckAssertionFor(CheckMethod.OnTriggerExit2D); } public void OnTriggerStay2D() { CheckAssertionFor(CheckMethod.OnTriggerStay2D); } public void OnCollisionEnter2D() { CheckAssertionFor(CheckMethod.OnCollisionEnter2D); } public void OnCollisionExit2D() { CheckAssertionFor(CheckMethod.OnCollisionExit2D); } public void OnCollisionStay2D() { CheckAssertionFor(CheckMethod.OnCollisionStay2D); } private void CheckAssertionFor(CheckMethod checkMethod) { if (IsCheckMethodSelected(checkMethod)) { Assertions.CheckAssertions(this); } } public bool IsCheckMethodSelected(CheckMethod method) { return method == (checkMethods & method); } #region Assertion Component create methods public static T Create<T>(CheckMethod checkOnMethods, GameObject gameObject, string propertyPath) where T : ActionBase { IAssertionComponentConfigurator configurator; return Create<T>(out configurator, checkOnMethods, gameObject, propertyPath); } public static T Create<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath) where T : ActionBase { return CreateAssertionComponent<T>(out configurator, checkOnMethods, gameObject, propertyPath); } public static T Create<T>(CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, GameObject gameObject2, string propertyPath2) where T : ComparerBase { IAssertionComponentConfigurator configurator; return Create<T>(out configurator, checkOnMethods, gameObject, propertyPath, gameObject2, propertyPath2); } public static T Create<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, GameObject gameObject2, string propertyPath2) where T : ComparerBase { var comparer = CreateAssertionComponent<T>(out configurator, checkOnMethods, gameObject, propertyPath); comparer.compareToType = ComparerBase.CompareToType.CompareToObject; comparer.other = gameObject2; comparer.otherPropertyPath = propertyPath2; return comparer; } public static T Create<T>(CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, object constValue) where T : ComparerBase { IAssertionComponentConfigurator configurator; return Create<T>(out configurator, checkOnMethods, gameObject, propertyPath, constValue); } public static T Create<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath, object constValue) where T : ComparerBase { var comparer = CreateAssertionComponent<T>(out configurator, checkOnMethods, gameObject, propertyPath); if (constValue == null) { comparer.compareToType = ComparerBase.CompareToType.CompareToNull; return comparer; } comparer.compareToType = ComparerBase.CompareToType.CompareToConstantValue; comparer.ConstValue = constValue; return comparer; } private static T CreateAssertionComponent<T>(out IAssertionComponentConfigurator configurator, CheckMethod checkOnMethods, GameObject gameObject, string propertyPath) where T : ActionBase { var ac = gameObject.AddComponent<AssertionComponent>(); ac.checkMethods = checkOnMethods; var comparer = ScriptableObject.CreateInstance<T>(); ac.Action = comparer; ac.Action.go = gameObject; ac.Action.thisPropertyPath = propertyPath; configurator = ac; #if !UNITY_METRO var stackTrace = new StackTrace(true); var thisFileName = stackTrace.GetFrame(0).GetFileName(); for (int i = 1; i < stackTrace.FrameCount; i++) { var stackFrame = stackTrace.GetFrame(i); if (stackFrame.GetFileName() != thisFileName) { string filePath = stackFrame.GetFileName().Substring(Application.dataPath.Length - "Assets".Length); ac.m_CreatedInFilePath = filePath; ac.m_CreatedInFileLine = stackFrame.GetFileLineNumber(); break; } } #endif // if !UNITY_METRO return comparer; } #endregion #region AssertionComponentConfigurator public int UpdateCheckStartOnFrame { set { checkAfterFrames = value; } } public int UpdateCheckRepeatFrequency { set { repeatEveryFrame = value; } } public bool UpdateCheckRepeat { set { repeatCheckFrame = value; } } public float TimeCheckStartAfter { set { checkAfterTime = value; } } public float TimeCheckRepeatFrequency { set { repeatEveryTime = value; } } public bool TimeCheckRepeat { set { repeatCheckTime = value; } } public AssertionComponent Component { get { return this; } } #endregion } public interface IAssertionComponentConfigurator { /// <summary> /// If the assertion is evaluated in Update, after how many frame should the evaluation start. Deafult is 1 (first frame) /// </summary> int UpdateCheckStartOnFrame { set; } /// <summary> /// If the assertion is evaluated in Update and UpdateCheckRepeat is true, how many frame should pass between evaluations /// </summary> int UpdateCheckRepeatFrequency { set; } /// <summary> /// If the assertion is evaluated in Update, should the evaluation be repeated after UpdateCheckRepeatFrequency frames /// </summary> bool UpdateCheckRepeat { set; } /// <summary> /// If the assertion is evaluated after a period of time, after how many seconds the first evaluation should be done /// </summary> float TimeCheckStartAfter { set; } /// <summary> /// If the assertion is evaluated after a period of time and TimeCheckRepeat is true, after how many seconds should the next evaluation happen /// </summary> float TimeCheckRepeatFrequency { set; } /// <summary> /// If the assertion is evaluated after a period, should the evaluation happen again after TimeCheckRepeatFrequency seconds /// </summary> bool TimeCheckRepeat { set; } AssertionComponent Component { get; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WebApiAngularJsUploader.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.ComponentModel.Composition; using Prism.Logging; using Prism.Modularity; using ModuleTracking; namespace ModularityWithMef.Desktop { /// <summary> /// Provides tracking of modules for the quickstart. /// </summary> /// <remarks> /// This class is for demonstration purposes for the quickstart and not expected to be used in a real world application. /// This class exports the interface for modules and the concrete type for the shell. /// </remarks> [Export(typeof(IModuleTracker))] public class ModuleTracker : IModuleTracker { private readonly ModuleTrackingState moduleATrackingState; private readonly ModuleTrackingState moduleBTrackingState; private readonly ModuleTrackingState moduleCTrackingState; private readonly ModuleTrackingState moduleDTrackingState; private readonly ModuleTrackingState moduleETrackingState; private readonly ModuleTrackingState moduleFTrackingState; #pragma warning disable 649 // MEF will import [Import] private ILoggerFacade logger; #pragma warning restore 649 /// <summary> /// Initializes a new instance of the <see cref="ModuleTracker"/> class. /// </summary> public ModuleTracker() { // These states are defined specifically for the desktop version of the quickstart. this.moduleATrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleA, ExpectedDiscoveryMethod = DiscoveryMethod.ApplicationReference, ExpectedInitializationMode = InitializationMode.WhenAvailable, ExpectedDownloadTiming = DownloadTiming.WithApplication, ConfiguredDependencies = WellKnownModuleNames.ModuleD, }; this.moduleBTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleB, ExpectedDiscoveryMethod = DiscoveryMethod.DirectorySweep, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, }; this.moduleCTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleC, ExpectedDiscoveryMethod = DiscoveryMethod.ApplicationReference, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.WithApplication, }; this.moduleDTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleD, ExpectedDiscoveryMethod = DiscoveryMethod.DirectorySweep, ExpectedInitializationMode = InitializationMode.WhenAvailable, ExpectedDownloadTiming = DownloadTiming.InBackground, }; this.moduleETrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleE, ExpectedDiscoveryMethod = DiscoveryMethod.ConfigurationManifest, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, }; this.moduleFTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleF, ExpectedDiscoveryMethod = DiscoveryMethod.ConfigurationManifest, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, ConfiguredDependencies = WellKnownModuleNames.ModuleE, }; } /// <summary> /// Gets the tracking state of module A. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleATrackingState { get { return this.moduleATrackingState; } } /// <summary> /// Gets the tracking state of module B. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleBTrackingState { get { return this.moduleBTrackingState; } } /// <summary> /// Gets the tracking state of module C. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleCTrackingState { get { return this.moduleCTrackingState; } } /// <summary> /// Gets the tracking state of module D. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleDTrackingState { get { return this.moduleDTrackingState; } } /// <summary> /// Gets the tracking state of module E. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleETrackingState { get { return this.moduleETrackingState; } } /// <summary> /// Gets the tracking state of module F. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleFTrackingState { get { return this.moduleFTrackingState; } } /// <summary> /// Records the module is loading. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> /// <param name="bytesReceived">The number of bytes downloaded.</param> /// <param name="totalBytesToReceive">The total number of bytes expected.</param> public void RecordModuleDownloading(string moduleName, long bytesReceived, long totalBytesToReceive) { ModuleTrackingState moduleTrackingState = this.GetModuleTrackingState(moduleName); if (moduleTrackingState != null) { moduleTrackingState.BytesReceived = bytesReceived; moduleTrackingState.TotalBytesToReceive = totalBytesToReceive; if (bytesReceived < totalBytesToReceive) { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Downloading; } else { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Downloaded; } } this.logger.Log( string.Format("'{0}' module is loading {1}/{2} bytes.", moduleName, bytesReceived, totalBytesToReceive), Category.Debug, Priority.Low); } /// <summary> /// Records the module has been constructed. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> public void RecordModuleConstructed(string moduleName) { ModuleTrackingState moduleTrackingState = this.GetModuleTrackingState(moduleName); if (moduleTrackingState != null) { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Constructed; } this.logger.Log(string.Format("'{0}' module constructed.", moduleName), Category.Debug, Priority.Low); } /// <summary> /// Records the module has been initialized. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> public void RecordModuleInitialized(string moduleName) { ModuleTrackingState moduleTrackingState = this.GetModuleTrackingState(moduleName); if (moduleTrackingState != null) { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Initialized; } this.logger.Log(string.Format("{0} module initialized.", moduleName), Category.Debug, Priority.Low); } /// <summary> /// Records the module is loaded. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> public void RecordModuleLoaded(string moduleName) { this.logger.Log(string.Format("'{0}' module loaded.", moduleName), Category.Debug, Priority.Low); } // A helper to make updating specific property instances by name easier. private ModuleTrackingState GetModuleTrackingState(string moduleName) { switch (moduleName) { case WellKnownModuleNames.ModuleA: return this.ModuleATrackingState; case WellKnownModuleNames.ModuleB: return this.ModuleBTrackingState; case WellKnownModuleNames.ModuleC: return this.ModuleCTrackingState; case WellKnownModuleNames.ModuleD: return this.ModuleDTrackingState; case WellKnownModuleNames.ModuleE: return this.ModuleETrackingState; case WellKnownModuleNames.ModuleF: return this.ModuleFTrackingState; default: return null; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.Security; using System.Xml; using System.Xml.Linq; using Examine; using umbraco.businesslogic; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.web; using umbraco.cms.helpers; using umbraco.cms.presentation.Trees; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Publishing; using Umbraco.Core.Services; using umbraco.NodeFactory; using umbraco.presentation.masterpages; using uWebshop.API; using uWebshop.Umbraco; using uWebshop.Umbraco.Services; using umbraco; using umbraco.BasePages; using umbraco.BusinessLogic; using uWebshop.Common; using uWebshop.Common.Interfaces; using uWebshop.DataAccess; using uWebshop.Domain; using uWebshop.Domain.Helpers; using uWebshop.Domain.Interfaces; using uWebshop.Domain.Services; using uWebshop.Umbraco.Businesslogic; using Catalog = uWebshop.Domain.Catalog; using Log = uWebshop.Domain.Log; using Settings = uWebshop.Domain.Settings; using Store = uWebshop.Domain.Store; using DeleteEventArgs = umbraco.cms.businesslogic.DeleteEventArgs; namespace uWebshop.Umbraco6 { public class ApplicationEventHandler : ApplicationStartupHandler { static ApplicationEventHandler() { try { Domain.Core.Initialize.ContinueInitialization(); Log.Instance.LogDebug("uWebshop initialized"); } catch (Exception ex) { umbraco.BusinessLogic.Log.Add(LogTypes.Error, 0, "Error while initializing uWebshop, most likely due to wrong umbraco.config, please republish the site " + ex.Message); } } #region constructors public ApplicationEventHandler() { ContentService.Created += ContentService_Created; ContentService.Published += ContentService_Published; Document.BeforePublish += DocumentBeforePublish; Document.AfterPublish += DocumentAfterPublish; Document.BeforeSave += DocumentBeforeSave; Document.AfterSave += DocumentAfterSave; Document.AfterMoveToTrash += DocumentAfterMoveToTrash; Document.AfterUnPublish += DocumentOnAfterUnPublish; Document.AfterDelete += DocumentOnAfterDelete; DocumentType.AfterSave += DocumentTypeOnAfterSave; Document.AfterCopy += DocumentAfterCopy; BaseTree.BeforeNodeRender += BaseContentTree_BeforeNodeRender; umbracoPage.Load += UmbracoPageLoad; content.AfterUpdateDocumentCache += ContentOnAfterUpdateDocumentCache; OrderInfo.BeforeStatusChanged += OrderBeforeStatusChanged; OrderInfo.AfterStatusChanged += OrderEvents.OrderStatusChanged; //OrderInfo.OrderLoaded += OrderInfoOrderLoaded; example UmbracoDefault.BeforeRequestInit += UmbracoDefaultBeforeRequestInit; UmbracoDefault.AfterRequestInit += UmbracoDefaultAfterRequestInit; var indexer = ExamineManager.Instance.IndexProviderCollection[UwebshopConfiguration.Current.ExamineIndexer]; indexer.GatheringNodeData += GatheringNodeDataHandler; } protected void GatheringNodeDataHandler(object sender, IndexingNodeDataEventArgs e) { try { foreach (var xElement in e.Node.Elements().Where(element => element.Name.LocalName.StartsWith("description"))) { if (xElement != null) e.Fields.Add("RTEItem" + xElement.Name.LocalName, xElement.Value); } } catch { } foreach (var field in defaultPriceValues()) { try { //grab the current data from the Fields collection string value; if (e.Fields == null || !e.Fields.TryGetValue(field, out value)) continue; var currencyFieldValue = e.Fields[field]; var currencyValueAsInt = int.Parse(currencyFieldValue); //prefix with leading zero's currencyFieldValue = currencyValueAsInt.ToString("D8"); //now put it back into the Fields so we can pretend nothing happened! ;) e.Fields[field] = currencyFieldValue; } catch (Exception ex) { Domain.Log.Instance.LogError("GatheringNodeDataHandler defaultPriceValues Examine: " + ex); } } foreach (var field in DefaultCsvValues()) { try { string value; if (e.Fields == null || !e.Fields.TryGetValue(field, out value)) continue; var csvFieldValue = e.Fields[field]; //Log.Instance.LogDebug( "examine MNTP before: " + mntp); //let's get rid of those commas! csvFieldValue = csvFieldValue.Replace(",", " "); //Log.Instance.LogDebug( "examine MNTP after: " + mntp); //now put it back into the Fields so we can pretend nothing happened! e.Fields[field] = csvFieldValue; } catch (Exception ex) { Domain.Log.Instance.LogError("GatheringNodeDataHandler DefaultCsvValues Examine: " + ex); } } } public List<string> defaultPriceValues() { return new List<string> { "price" }; } public List<string> DefaultCsvValues() { return new List<string> {"categories", //"metaTags", metatags can't be stripped of comma "images", "files"}; } private void DocumentAfterCopy(Document sender, CopyEventArgs e) { if (sender.Level > 2 && sender.ContentType.Alias == Order.NodeAlias) { Guid currentGuid; var orderGuid = sender.getProperty("orderGuid").Value.ToString(); Guid.TryParse(orderGuid, out currentGuid); var order = OrderHelper.GetOrder(currentGuid); var newOrder = OrderHelper.CreateNewOrderFromExisting(order); IO.Container.Resolve<IOrderNumberService>().GenerateAndPersistOrderNumber(order); order.OrderNodeId = e.NewDocument.Id; order.Save(); e.NewDocument.Text = order.OrderNumber; e.NewDocument.SetProperty("orderGuid", newOrder.UniqueOrderId.ToString()); e.NewDocument.SetProperty("orderStatusPicker", newOrder.Status.ToString()); e.NewDocument.Save(); BasePage.Current.ClientTools.SyncTree(e.NewDocument.Parent.Path, false); BasePage.Current.ClientTools.ChangeContentFrameUrl(string.Concat("editContent.aspx?id=", e.NewDocument.Id)); } } private void DocumentOnAfterDelete(Document sender, DeleteEventArgs e) { ClearCaches(sender); } //public void OrderInfoOrderLoaded(OrderInfo orderInfo) //{ // example // const int productLimit = 10; // orderInfo.RegisterCustomOrderValidation( // order => order.OrderLines.All(line => line.ProductInfo.ItemCount.GetValueOrDefault(1) <= productLimit), // order => "TheUniqueKeyThatWillShowInTheError"); //} private void DocumentTypeOnAfterSave(DocumentType sender, SaveEventArgs saveEventArgs) { //if (UwebshopConfiguration.Current.RebuildExamineIndex && ExamineManager.Instance != null) //{ // var externalIndex = ExamineManager.Instance.IndexProviderCollection["ExternalIndexer"]; // if (externalIndex != null) externalIndex.RebuildIndex(); //} // todo: clear full cache after some time } private void ResetAll(int id, string nodeTypeAlias) { IO.Container.Resolve<IApplicationCacheManagingService>().ReloadEntityWithGlobalId(id, nodeTypeAlias); //UmbracoStaticCachedEntityRepository.ResetStaticCache(); } private void ContentOnAfterUpdateDocumentCache(Document sender, DocumentCacheEventArgs documentCacheEventArgs) { //if (sender.ContentType.Alias.StartsWith("uwbs") && sender.ContentType.Alias != Order.NodeAlias) //todo: work with aliasses from config var alias = sender.ContentType.Alias; // todo: make a nice way for this block if (Product.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (ProductVariant.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (Category.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (PaymentProvider.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (PaymentProviderMethod.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (DiscountProduct.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (DiscountOrder.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (ShippingProvider.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (ShippingProviderMethod.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (Store.IsAlias(alias)) { ResetAll(sender.Id, alias); } else if (alias.StartsWith("uwbs") && alias != Order.NodeAlias) { ResetAll(sender.Id, alias); } var storePickerProperty = sender.getProperty(Constants.StorePickerAlias); if (storePickerProperty != null) { int storeId; if (storePickerProperty.Value != null && int.TryParse(storePickerProperty.Value.ToString(), out storeId)) { var storeService = StoreHelper.StoreService; var storeById = storeService.GetById(storeId, null); if (storeById != null) { storeService.TriggerStoreChangedEvent(storeById); } } } if (alias.StartsWith(Settings.NodeAlias)) { IO.Container.Resolve<ISettingsService>().TriggerSettingsChangedEvent(SettingsLoader.GetSettings()); } if (alias.StartsWith(Store.NodeAlias)) { //todo: naar nieuwe v6+ API omzetten var storeService = StoreHelper.StoreService; storeService.TriggerStoreChangedEvent(storeService.GetById(sender.Id, null)); var node = new Node(sender.Id); if (!sender.Text.Equals(node.Name)) { StoreHelper.RenameStore(node.Name, sender.Text); } } } private void DocumentOnAfterUnPublish(Document sender, UnPublishEventArgs unPublishEventArgs) { // todo: check whether this event is thrown when node is automatically unpublished by umbraco (after certain datetime) ClearCaches(sender); } private static void ClearCaches(Document sender) { //todo: work with aliasses from config //if (sender.ContentType.Alias.StartsWith("uwbs") && sender.ContentType.Alias != Order.NodeAlias) if (sender.ContentType.Alias != Order.NodeAlias) { IO.Container.Resolve<IApplicationCacheManagingService>().UnloadEntityWithGlobalId(sender.Id, sender.ContentType.Alias); //UmbracoStaticCachedEntityRepository.ResetStaticCache(); } } private static void DocumentBeforeSave(Document sender, SaveEventArgs e) { if (sender.ContentType.Alias.StartsWith(Store.NodeAlias)) { var reg = new Regex(@"\s*"); var storeAlias = reg.Replace(sender.Text, ""); sender.Text = storeAlias; return; } var parentId = sender.ParentId; if (parentId < 0) { return; } var parentDoc = new Document(sender.ParentId); if (parentDoc.ContentType != null && (Category.IsAlias(sender.ContentType.Alias) && parentDoc.ContentType.Alias == Catalog.CategoryRepositoryNodeAlias)) { var docs = GlobalSettings.HideTopLevelNodeFromPath ? Document.GetRootDocuments().SelectMany(d => d.Children).ToArray() : Document.GetRootDocuments(); FixRootCategoryUrlName(sender, docs, "url"); foreach (var store in StoreHelper.GetAllStores()) { string multiStorePropertyName; if (GetMultiStorePropertyName(sender, store, out multiStorePropertyName)) continue; FixRootCategoryUrlName(sender, docs, multiStorePropertyName); } } } private static bool GetMultiStorePropertyName(Document sender, Store store, out string propertyName) { propertyName = "url_" + store.Alias.ToLower(); if (sender.getProperty(propertyName) != null) return false; propertyName = "url_" + store.Alias.ToUpper(); if (sender.getProperty(propertyName) != null) return false; propertyName = "url_" + store.Alias; return sender.getProperty(propertyName) == null; } private static void FixRootCategoryUrlName(Document sender, Document[] docs, string propertyName) { var urlName = sender.getProperty(propertyName).Value.ToString(); if (docs.Any(x => urlName == x.Text)) { int count = 1; var existingRenames = docs.Where(x => x.Text.StartsWith(urlName)).Select(x => x.Text).Select(x => Regex.Match(x, urlName + @" [(](\d)[)]").Groups[1].Value).Select(x => { int i; int.TryParse(x, out i); return i; }); if (existingRenames.Any()) { count = existingRenames.Max() + 1; } sender.SetProperty(propertyName, urlName + " (" + count + ")"); } } private static void UmbracoPageLoad(object sender, EventArgs e) { } private static void DocumentAfterMoveToTrash(Document sender, MoveToTrashEventArgs e) { if (sender.ContentType.Alias.StartsWith(Store.NodeAlias)) { var reg = new Regex(@"\s*"); var storeAlias = reg.Replace(sender.Text, ""); StoreHelper.UnInstallStore(storeAlias); } ClearCaches(sender); } protected void UmbracoDefaultBeforeRequestInit(object sender, RequestInitEventArgs e) { try { //Domain.Core.Initialize.Init(); } catch (Exception) { //throw; } try { var currentNode = Node.GetCurrent(); if (ProductVariant.IsAlias(currentNode.NodeTypeAlias)) { var product = DomainHelper.GetProductById(currentNode.Parent.Id); if (product != null) HttpContext.Current.Response.RedirectPermanent(product.NiceUrl(), true); } else if (Product.IsAlias(currentNode.NodeTypeAlias)) { var product = DomainHelper.GetProductById(currentNode.Id); if (product != null) HttpContext.Current.Response.RedirectPermanent(product.NiceUrl(), true); } else if (Category.IsAlias(currentNode.NodeTypeAlias)) { var category = DomainHelper.GetCategoryById(currentNode.Id); if (category != null) HttpContext.Current.Response.RedirectPermanent( /* todo nicer */RazorExtensions.ExtensionMethods.NiceUrl(category), true); } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { // intentionally left empty, because Umbraco will serve a 404 } } private static void UmbracoDefaultAfterRequestInit(object sender, RequestInitEventArgs e) { var currentMember = Membership.GetUser(); var currentorder = UwebshopRequest.Current.OrderInfo ?? OrderHelper.GetOrder(); var orderRepository = IO.Container.Resolve<IOrderRepository>(); if (currentorder != null && (currentMember != null && currentorder.CustomerInfo.LoginName != currentMember.UserName)) { orderRepository.SetCustomer(currentorder.UniqueOrderId, currentMember.UserName); currentorder.CustomerInfo.LoginName = currentMember.UserName; if (currentMember.ProviderUserKey != null) { orderRepository.SetCustomerId(currentorder.UniqueOrderId, (int)currentMember.ProviderUserKey); currentorder.CustomerInfo.CustomerId = (int) currentMember.ProviderUserKey; } currentorder.ResetDiscounts(); currentorder.Save(); } if (currentorder != null && currentMember == null && !string.IsNullOrEmpty(currentorder.CustomerInfo.LoginName)) { orderRepository.SetCustomer(currentorder.UniqueOrderId, string.Empty); currentorder.CustomerInfo.LoginName = string.Empty; orderRepository.SetCustomerId(currentorder.UniqueOrderId, 0); currentorder.CustomerInfo.CustomerId = 0; currentorder.ResetDiscounts(); currentorder.Save(); } var cookie = HttpContext.Current.Request.Cookies["StoreInfo"]; if (cookie != null) { if (currentMember != null && !string.IsNullOrEmpty(cookie["Wishlist"])) { var wishlistId = cookie["Wishlist"]; Guid wishGuid; Guid.TryParse(wishlistId, out wishGuid); if (wishGuid != default(Guid) || wishGuid != Guid.Empty) { var wishlist = OrderHelper.GetOrder(wishGuid); wishlist.CustomerInfo.LoginName = currentMember.UserName; var userKey = 0; if (currentMember.ProviderUserKey != null) { int.TryParse(currentMember.ProviderUserKey.ToString(), out userKey); if (userKey != 0) { wishlist.CustomerInfo.CustomerId = userKey; } } var wishlistName = "Wishlist"; var wishlistCount = Customers.GetWishlists(currentMember.UserName).Count() + 1; wishlist.Name = string.Format("{0}{1}", wishlistName, wishlistCount); wishlist.Save(); cookie.Values.Remove("Wishlist"); } } } var paymentProvider = UwebshopRequest.Current.PaymentProvider; if (paymentProvider != null) { new PaymentRequestHandler().HandleuWebshopPaymentRequest(paymentProvider); Log.Instance.LogDebug("UmbracoDefaultAfterRequestInit paymentProvider: " + paymentProvider.Name); var paymentProviderTemplate = paymentProvider.Node.template; ((UmbracoDefault)sender).MasterPageFile = template.GetMasterPageName(paymentProviderTemplate); return; } // todo: ombouwen naar UwebshopRequest.Current.Category, UwebshopRequest.Current lostrekken (ivm speed) var currentCategoryId = HttpContext.Current.Request["resolvedCategoryId"]; var currentProductId = HttpContext.Current.Request["resolvedProductId"]; if (!string.IsNullOrEmpty(currentCategoryId)) //string.IsNullOrEmpty(currentProductUrl)) { int categoryId; if (!int.TryParse(currentCategoryId, out categoryId)) return; var categoryFromUrl = DomainHelper.GetCategoryById(categoryId); if (categoryFromUrl == null) return; if (categoryFromUrl.Disabled) { HttpContext.Current.Response.StatusCode = 404; HttpContext.Current.Response.Redirect(library.NiceUrl(int.Parse(GetCurrentNotFoundPageId())), true); return; } if (Access.HasAccess(categoryFromUrl.Id, categoryFromUrl.GetUmbracoPath(), Membership.GetUser())) { if (categoryFromUrl.Template != 0) { //umbraco.cms.businesslogic.template.Template.GetTemplate(currentCategory.Template).TemplateFilePath ((UmbracoDefault) sender).MasterPageFile = template.GetMasterPageName(categoryFromUrl.Template); //// get the template //var t = template.GetMasterPageName(currentCategory.Template); //// you did this and it works pre-4.10, right? //page.MasterPageFile = t; //// now this should work starting with 4.10 //e.Page.Template = t; } var altTemplate = HttpContext.Current.Request["altTemplate"]; if (!string.IsNullOrEmpty(altTemplate)) { var altTemplateId = umbraco.cms.businesslogic.template.Template.GetTemplateIdFromAlias(altTemplate); if (altTemplateId != 0) { ((UmbracoDefault) sender).MasterPageFile = template.GetMasterPageName(altTemplateId); } } } else { if (HttpContext.Current.User.Identity.IsAuthenticated) { HttpContext.Current.Response.Redirect(library.NiceUrl(Access.GetErrorPage(categoryFromUrl.GetUmbracoPath())), true); } HttpContext.Current.Response.Redirect(library.NiceUrl(Access.GetLoginPage(categoryFromUrl.GetUmbracoPath())), true); } } else if (!string.IsNullOrEmpty(currentProductId)) // else { int productId; if (!int.TryParse(currentProductId, out productId)) return; var productFromUrl = DomainHelper.GetProductById(productId); if (productFromUrl == null) return; if (Access.HasAccess(productFromUrl.Id, productFromUrl.Path(), Membership.GetUser())) { if (productFromUrl.Template != 0) { ((UmbracoDefault) sender).MasterPageFile = template.GetMasterPageName(productFromUrl.Template); } var altTemplate = HttpContext.Current.Request["altTemplate"]; if (!string.IsNullOrEmpty(altTemplate)) { var altTemplateId = umbraco.cms.businesslogic.template.Template.GetTemplateIdFromAlias(altTemplate); if (altTemplateId != 0) { ((UmbracoDefault) sender).MasterPageFile = template.GetMasterPageName(altTemplateId); } } } else { if (HttpContext.Current.User.Identity.IsAuthenticated) { HttpContext.Current.Response.Redirect(library.NiceUrl(Access.GetErrorPage(productFromUrl.Path())), true); } HttpContext.Current.Response.Redirect(library.NiceUrl(Access.GetLoginPage(productFromUrl.Path())), true); } } } internal static string GetCurrentNotFoundPageId() { library.GetCurrentDomains(1); var error404 = ""; var error404Node = UmbracoSettings.GetKeyAsNode("/settings/content/errors/error404"); if (error404Node.ChildNodes.Count > 0 && error404Node.ChildNodes[0].HasChildNodes) { // try to get the 404 based on current culture (via domain) XmlNode cultureErrorNode; if (umbraco.cms.businesslogic.web.Domain.Exists(HttpContext.Current.Request.ServerVariables["SERVER_NAME"])) { var d = umbraco.cms.businesslogic.web.Domain.GetDomain(HttpContext.Current.Request.ServerVariables["SERVER_NAME"]); // test if a 404 page exists with current culture cultureErrorNode = error404Node.SelectSingleNode(string.Format("errorPage [@culture = '{0}']", d.Language.CultureAlias)); if (cultureErrorNode != null && cultureErrorNode.FirstChild != null) error404 = cultureErrorNode.FirstChild.Value; } else if (error404Node.SelectSingleNode(string.Format("errorPage [@culture = '{0}']", System.Threading.Thread.CurrentThread.CurrentUICulture.Name)) != null) { cultureErrorNode = error404Node.SelectSingleNode(string.Format("errorPage [@culture = '{0}']", System.Threading.Thread.CurrentThread.CurrentUICulture.Name)); if (cultureErrorNode.FirstChild != null) error404 = cultureErrorNode.FirstChild.Value; } else { cultureErrorNode = error404Node.SelectSingleNode("errorPage [@culture = 'default']"); if (cultureErrorNode != null && cultureErrorNode.FirstChild != null) error404 = cultureErrorNode.FirstChild.Value; } } else error404 = UmbracoSettings.GetKey("/settings/content/errors/error404"); return error404; } protected void OrderBeforeStatusChanged(OrderInfo orderInfo, BeforeOrderStatusChangedEventArgs e) { } #endregion public static SortedDictionary<string, string> GetCountryList() { //create a new Generic list to hold the country names returned var cultureList = new SortedDictionary<string, string>(); //create an array of CultureInfo to hold all the cultures found, these include the users local cluture, and all the //cultures installed with the .Net Framework var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures); //loop through all the cultures found foreach (var culture in cultures) { try { //pass the current culture's Locale ID (http://msdn.microsoft.com/en-us/library/0h88fahh.aspx) //to the RegionInfo contructor to gain access to the information for that culture var region = new RegionInfo(culture.LCID); //make sure out generic list doesnt already //contain this country if (!cultureList.ContainsKey(region.EnglishName)) //not there so add the EnglishName (http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo.englishname.aspx) //value to our generic list cultureList.Add(region.EnglishName, region.TwoLetterISORegionName); } catch { } } return cultureList; } public static void DocumentAfterSave(Document sender, SaveEventArgs e) { } protected void DocumentAfterPublish(Document sender, PublishEventArgs e) { // when thinking about adding something here, consider ContentOnAfterUpdateDocumentCache! if (sender.Level > 2) { if (sender.ContentType.Alias == Order.NodeAlias || sender.Parent != null && (OrderedProduct.IsAlias(sender.ContentType.Alias) || sender.Parent.Parent != null && OrderedProductVariant.IsAlias(sender.ContentType.Alias))) { var orderDoc = sender.ContentType.Alias == Order.NodeAlias ? sender : (OrderedProduct.IsAlias(sender.ContentType.Alias) && !OrderedProductVariant.IsAlias(sender.ContentType.Alias) ? new Document(sender.Parent.Id) : new Document(sender.Parent.Parent.Id)); if (orderDoc.ContentType.Alias != Order.NodeAlias) throw new Exception("There was an error in the structure of the order documents"); // load existing orderInfo (why..? => possibly to preserve information not represented in the umbraco documents) if (string.IsNullOrEmpty(orderDoc.getProperty("orderGuid").Value.ToString())) { Store store = null; var storeDoc = sender.GetAncestorDocuments().FirstOrDefault(x => x.ContentType.Alias == OrderStoreFolder.NodeAlias); if (storeDoc != null) { store = StoreHelper.GetAllStores().FirstOrDefault(x => x.Name == storeDoc.Text); } if (store == null) { store = StoreHelper.GetAllStores().FirstOrDefault(); } var orderInfo = OrderHelper.CreateOrder(store); IO.Container.Resolve<IOrderNumberService>().GenerateAndPersistOrderNumber(orderInfo); orderInfo.Status = OrderStatus.Confirmed; orderInfo.Save(); sender.SetProperty("orderGuid", orderInfo.UniqueOrderId.ToString()); sender.Save(); } else { var orderGuid = Guid.Parse(orderDoc.getProperty("orderGuid").Value.ToString()); var orderInfo = OrderHelper.GetOrderInfo(orderGuid); var order = new Order(orderDoc.Id); orderInfo.CustomerEmail = order.CustomerEmail; orderInfo.CustomerFirstName = order.CustomerFirstName; orderInfo.CustomerLastName = order.CustomerLastName; var dictionaryCustomer = orderDoc.GenericProperties.Where(x => x.PropertyType.Alias.StartsWith("customer")).ToDictionary(customerProperty => customerProperty.PropertyType.Alias, customerProperty => customerProperty.Value.ToString()); orderInfo.AddCustomerFields(dictionaryCustomer, CustomerDatatypes.Customer); var dictionaryShipping = orderDoc.GenericProperties.Where(x => x.PropertyType.Alias.StartsWith("shipping")).ToDictionary(property => property.PropertyType.Alias, property => property.Value.ToString()); orderInfo.AddCustomerFields(dictionaryShipping, CustomerDatatypes.Shipping); var dictionarExtra = orderDoc.GenericProperties.Where(x => x.PropertyType.Alias.StartsWith("extra")).ToDictionary(property => property.PropertyType.Alias, property => property.Value.ToString()); orderInfo.AddCustomerFields(dictionarExtra, CustomerDatatypes.Extra); //orderInfo.SetVATNumber(order.CustomerVATNumber); happens in AddCustomerFields var orderPaidProperty = order.Document.getProperty("orderPaid"); if (orderPaidProperty != null && orderPaidProperty.Value != null) orderInfo.Paid = orderPaidProperty.Value == "1"; // load data recursively from umbraco documents into order tree orderInfo.OrderLines = orderDoc.Children.Select(d => { var fields = d.GenericProperties.Where(x => !OrderedProduct.DefaultProperties.Contains(x.PropertyType.Alias)).ToDictionary(s => s.PropertyType.Alias, s => d.GetProperty<string>(s.PropertyType.Alias)); var xDoc = new XDocument(new XElement("Fields")); OrderUpdatingService.AddFieldsToXDocumentBasedOnCMSDocumentType(xDoc, fields, d.ContentType.Alias); var orderedProduct = new OrderedProduct(d.Id); var productInfo = new ProductInfo(orderedProduct, orderInfo); productInfo.ProductVariants = d.Children.Select(cd => new ProductVariantInfo(new OrderedProductVariant(cd.Id), productInfo, productInfo.Vat)).ToList(); return new OrderLine(productInfo, orderInfo) {_customData = xDoc}; }).ToList(); // store order IO.Container.Resolve<IOrderRepository>().SaveOrderInfo(orderInfo); } // cancel does give a warning message balloon in Umbraco. //e.Cancel = true; //if (sender.ContentType.Alias != Order.NodeAlias) //{ // orderDoc.Publish(new User(0)); //} //if (orderDoc.ParentId != 0) //{ BasePage.Current.ClientTools.SyncTree(sender.Parent.Path, false); BasePage.Current.ClientTools.ChangeContentFrameUrl(string.Concat("editContent.aspx?id=", sender.Id)); //} //orderDoc.delete(); BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.success, "Order Updated!", "This order has been updated!"); } } } protected void BaseContentTree_BeforeNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e) { } // UNPUBLISH & REMOVE Incomplete Orders AFTER EXPIREDATE HAS BEEN PASSED protected void DocumentBeforePublish(Document sender, PublishEventArgs e) { if (Category.IsAlias(sender.ContentType.Alias)) { SetAliasedPropertiesIfEnabled(sender, "categoryUrl"); } if (Product.IsAlias(sender.ContentType.Alias)) { SetAliasedPropertiesIfEnabled(sender, "productUrl"); } if (sender.ContentType.Alias == Order.NodeAlias) { // order => todo: delete node, update SQL } } private static void SetAliasedPropertiesIfEnabled(Document sender, string propertyName) { var property = sender.getProperty(propertyName); if (property == null) return; property.Value = url.FormatUrl(property.Value.ToString()); foreach (var shopAlias in StoreHelper.GetAllStores()) { var aliasedEnabled = sender.getProperty("enable_" + shopAlias.Alias.ToUpper()); if (aliasedEnabled == null || aliasedEnabled.Value.ToString() != "1") continue; var aliasedproperty = sender.getProperty(propertyName + "_" + shopAlias.Alias.ToUpper()); // test == test --> overerf van global // test == "" --> overef van global if (aliasedproperty != null && aliasedproperty.Value == property.Value || aliasedproperty != null && string.IsNullOrEmpty(aliasedproperty.Value.ToString())) { aliasedproperty.Value = url.FormatUrl(property.Value.ToString()); } // test == bla --> niets doen else if (aliasedproperty != null && !string.IsNullOrEmpty(aliasedproperty.Value.ToString())) { aliasedproperty.Value = url.FormatUrl(aliasedproperty.Value.ToString()); } } } private static void ContentService_Created(IContentService sender, global::Umbraco.Core.Events.NewEventArgs<IContent> e) { if (e.Entity.Id != 0) { if (e.Entity.ContentType.Alias.StartsWith(Store.NodeAlias)) { var reg = new Regex(@"\s*"); var storeAlias = reg.Replace(e.Entity.Name, ""); Umbraco.Helpers.InstallStore(storeAlias, new Document(e.Entity.Id)); e.Entity.Name = storeAlias; sender.Save(e.Entity); } } } private static void ContentService_Published(IPublishingStrategy sender, PublishEventArgs<IContent> e) { var contents = e.PublishedEntities.Where(c => c.ContentType.Alias.StartsWith(Order.NodeAlias)); sender.UnPublish(contents, 0); } } }
using System; using NUnit.Framework; using System.Drawing; using OpenQA.Selenium.Environment; using System.Collections.ObjectModel; namespace OpenQA.Selenium { [TestFixture] public class VisibilityTest : DriverTestFixture { [Test] [Category("Javascript")] public void ShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot() { driver.Url = javascriptPage; Assert.IsTrue(driver.FindElement(By.Id("displayed")).Displayed); Assert.IsFalse(driver.FindElement(By.Id("none")).Displayed); Assert.IsFalse(driver.FindElement(By.Id("suppressedParagraph")).Displayed); Assert.IsFalse(driver.FindElement(By.Id("hidden")).Displayed); } [Test] [Category("Javascript")] public void VisibilityShouldTakeIntoAccountParentVisibility() { driver.Url = javascriptPage; IWebElement childDiv = driver.FindElement(By.Id("hiddenchild")); IWebElement hiddenLink = driver.FindElement(By.Id("hiddenlink")); Assert.IsFalse(childDiv.Displayed); Assert.IsFalse(hiddenLink.Displayed); } [Test] [Category("Javascript")] public void ShouldCountElementsAsVisibleIfStylePropertyHasBeenSet() { driver.Url = javascriptPage; IWebElement shown = driver.FindElement(By.Id("visibleSubElement")); Assert.IsTrue(shown.Displayed); } [Test] [Category("Javascript")] public void ShouldModifyTheVisibilityOfAnElementDynamically() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("hideMe")); Assert.IsTrue(element.Displayed); element.Click(); Assert.IsFalse(element.Displayed); } [Test] [Category("Javascript")] public void HiddenInputElementsAreNeverVisible() { driver.Url = javascriptPage; IWebElement shown = driver.FindElement(By.Name("hidden")); Assert.IsFalse(shown.Displayed); } [Test] [Category("Javascript")] public void ShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("unclickable")); Assert.Throws<ElementNotVisibleException>(() => element.Click()); } [Test] [Category("Javascript")] public void ShouldNotBeAbleToTypeAnElementThatIsNotDisplayed() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("unclickable")); Assert.Throws<ElementNotVisibleException>(() => element.SendKeys("You don't see me")); Assert.AreNotEqual(element.GetAttribute("value"), "You don't see me"); } [Test] [Category("Javascript")] public void ShouldNotBeAbleToSelectAnElementThatIsNotDisplayed() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("untogglable")); Assert.Throws<ElementNotVisibleException>(() => element.Click()); } [Test] [Category("Javascript")] public void ZeroSizedDivIsShownIfDescendantHasSize() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("zero")); Size size = element.Size; Assert.AreEqual(0, size.Width, "Should have 0 width"); Assert.AreEqual(0, size.Height, "Should have 0 height"); Assert.IsTrue(element.Displayed); } [Test] public void ParentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIsHidden() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("visibility-css.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("suggest")); Assert.IsTrue(element.Displayed); } [Test] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.PhantomJS)] [IgnoreBrowser(Browser.Safari)] public void ElementHiddenByOverflowXIsNotVisible() { string[] pages = new string[]{ "overflow/x_hidden_y_hidden.html", "overflow/x_hidden_y_scroll.html", "overflow/x_hidden_y_auto.html", }; foreach (string page in pages) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page); IWebElement right = driver.FindElement(By.Id("right")); Assert.IsFalse(right.Displayed, "Failed for " + page); IWebElement bottomRight = driver.FindElement(By.Id("bottom-right")); Assert.IsFalse(bottomRight.Displayed, "Failed for " + page); } } [Test] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.PhantomJS)] public void ElementHiddenByOverflowYIsNotVisible() { string[] pages = new string[]{ "overflow/x_hidden_y_hidden.html", "overflow/x_scroll_y_hidden.html", "overflow/x_auto_y_hidden.html", }; foreach (string page in pages) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page); IWebElement bottom = driver.FindElement(By.Id("bottom")); Assert.IsFalse(bottom.Displayed, "Failed for " + page); IWebElement bottomRight = driver.FindElement(By.Id("bottom-right")); Assert.IsFalse(bottomRight.Displayed, "Failed for " + page); } } [Test] public void ElementScrollableByOverflowXIsVisible() { string[] pages = new string[]{ "overflow/x_scroll_y_hidden.html", "overflow/x_scroll_y_scroll.html", "overflow/x_scroll_y_auto.html", "overflow/x_auto_y_hidden.html", "overflow/x_auto_y_scroll.html", "overflow/x_auto_y_auto.html", }; foreach (string page in pages) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page); IWebElement right = driver.FindElement(By.Id("right")); Assert.IsTrue(right.Displayed, "Failed for " + page); } } [Test] [IgnoreBrowser(Browser.Safari)] public void ElementScrollableByOverflowYIsVisible() { string[] pages = new string[]{ "overflow/x_hidden_y_scroll.html", "overflow/x_scroll_y_scroll.html", "overflow/x_auto_y_scroll.html", "overflow/x_hidden_y_auto.html", "overflow/x_scroll_y_auto.html", "overflow/x_auto_y_auto.html", }; foreach (string page in pages) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page); IWebElement bottom = driver.FindElement(By.Id("bottom")); Assert.IsTrue(bottom.Displayed, "Failed for " + page); } } [Test] public void ElementScrollableByOverflowXAndYIsVisible() { string[] pages = new string[]{ "overflow/x_scroll_y_scroll.html", "overflow/x_scroll_y_auto.html", "overflow/x_auto_y_scroll.html", "overflow/x_auto_y_auto.html", }; foreach (string page in pages) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page); IWebElement bottomRight = driver.FindElement(By.Id("bottom-right")); Assert.IsTrue(bottomRight.Displayed, "Failed for " + page); } } [Test] [IgnoreBrowser(Browser.Android)] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Opera)] public void tooSmallAWindowWithOverflowHiddenIsNotAProblem() { IWindow window = driver.Manage().Window; Size originalSize = window.Size; try { // Short in the Y dimension window.Size = new Size(1024, 500); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("overflow-body.html"); IWebElement element = driver.FindElement(By.Name("resultsFrame")); Assert.IsTrue(element.Displayed); } finally { window.Size = originalSize; } } [Test] [IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldShowElementNotVisibleWithHiddenAttribute() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("singleHidden")); Assert.IsFalse(element.Displayed); } [Test] [IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("child")); Assert.IsFalse(element.Displayed); } [Test] public void ShouldBeAbleToClickOnElementsWithOpacityZero() { if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = clickJackerPage; IWebElement element = driver.FindElement(By.Id("clickJacker")); Assert.AreEqual("0", element.GetCssValue("opacity"), "Precondition failed: clickJacker should be transparent"); element.Click(); Assert.AreEqual("1", element.GetCssValue("opacity")); } [Test] [Category("JavaScript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Opera)] public void ShouldBeAbleToSelectOptionsFromAnInvisibleSelect() { driver.Url = formsPage; IWebElement select = driver.FindElement(By.Id("invisi_select")); ReadOnlyCollection<IWebElement> options = select.FindElements(By.TagName("option")); IWebElement apples = options[0]; IWebElement oranges = options[1]; Assert.IsTrue(apples.Selected, "Apples should be selected"); Assert.IsFalse(oranges.Selected, "Oranges shoudl be selected"); oranges.Click(); Assert.IsFalse(apples.Selected, "Apples should not be selected"); Assert.IsTrue(oranges.Selected, "Oranges should be selected"); } [Test] [Category("Javascript")] public void CorrectlyDetectMapElementsAreShown() { driver.Url = mapVisibilityPage; IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0")); bool isShown = area.Displayed; Assert.IsTrue(isShown, "The element and the enclosing map should be considered shown."); } [Test] public void ElementsWithOpacityZeroShouldNotBeVisible() { driver.Url = clickJackerPage; IWebElement element = driver.FindElement(By.Id("clickJacker")); Assert.IsFalse(element.Displayed); } } }
/* DrawEvents.cs This is a NovaVR script created for the CMS Collaboration CMS.VR project http://novavrllc.com Version 0.5 Copyright (c) 2017 NovaVR LLC. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Creates the event pieces using UnityEngine; using System; using JsonFx.Json; using System.Collections.Generic; using TubeRender; namespace CMSdraw { public static class CMSvar { // scales public const float min_track_radius = 0.002f; // for rendering as tapering tubes public const float max_track_radius = 0.02f; // for rendering as tapering tubes public const float min_electron_radius = 0.003f; // for rendering as tapering tubes public const float max_electron_radius = 0.024f; // for rendering as tapering tubes public const float min_jet_radius = 0.03f; // for rendering as tapering tubes public const float max_jet_radius = 0.03f; // for rendering as tapering tubes public const float min_MET_radius = 0.03f; // for rendering as tapering tubes public const float max_MET_radius = 0.03f; // for rendering as tapering tubes public const float min_muon_radius = 0.03f; // for rendering as tapering tubes public const float max_muon_radius = 0.24f; // for rendering as tapering tubes public const float jetRescale = 0.1f; // rescale length of rendered jets // Define a rotation by 90 degrees around the y-axis: public static Quaternion rt = Quaternion.Euler(0, 0, 90f); // Number of segments in your Bezier curves: public const int nsegments = 24; // transparency public const float track_transparency = 0.5f; public const float electron_transparency = 1.0f; public const float muon_transparency = 0.5f; public const float jet_transparency = 0.5f; public const float MET_transparency = 0.5f; // color public static Color track_color = Color.green; public static Color electron_color = Color.black; public static Color muon_color = Color.yellow; public static Color jet_color = new Color(0.548f,0.7f,0.95f); public static Color MET_color = Color.magenta; // You might want to apply some cuts: public const float Tracks_V2_pt_min = 0.0f; public const float GsfElectrons_V1_pt_min = 5.0f; public const float PFJets_V1_pt_min = 20.0f; public const float PFMETs_V1_pt_min = 5.0f; public const float GlobalMuons_V1_pt_min = 5.0f; // Where various info is stored in the CMS JSON format: public const int Event_V2_run_index = 0; public const int Event_V2_event_index = 1; public const int Event_V2_ls_index = 2; public const int Event_V2_orbit_index = 3; public const int Event_V2_bx_index = 4; public const int Event_V2_time_index = 5; public const int Event_V2_localtime_index = 6; public const int PFJets_V1_et_index = 0; public const int PFJets_V1_eta_index = 1; public const int PFJets_V1_theta_index = 2; public const int PFJets_V1_phi_index = 3; public const int PFMETs_V1_phi_index = 0; public const int PFMETs_V1_pt_index = 1; public const int PFMETs_V1_px_index = 2; public const int PFMETs_V1_py_index = 3; public const int PFMETs_V1_pz_index = 4; public const int Vertices_V1_isValid_index = 0; public const int Vertices_V1_isFake_index = 1; public const int Vertices_V1_pos_index = 2; public const int Vertices_V1_xError_index = 3; public const int Vertices_V1_yError_index = 4; public const int Vertices_V1_zError_index = 5; public const int Vertices_V1_chi2_index = 6; public const int Vertices_V1_ndof_index = 7; public const int TriggerPaths_V1_Name_index = 0; public const int TriggerPaths_V1_Index_index = 1; public const int TriggerPaths_V1_WasRun_index = 2; public const int TriggerPaths_V1_Accept_index = 3; public const int TriggerPaths_V1_Error_index = 4; public const int TriggerPaths_V1_Objects_index = 0; public const int Photons_V1_energy_index = 0; public const int Photons_V1_et_index = 1; public const int Photons_V1_eta_index = 2; public const int Photons_V1_phi_index = 3; public const int Photons_V1_pos_index = 4; public const int Photons_V1_hadronicOverEm_index = 5; public const int Photons_V1_hadronicDepth1OverEcal_index = 6; public const int Photons_V1_hadronicOverDepth2Ecal_index = 7; public const int Tracks_V2_pos_index = 0; public const int Tracks_V2_dir_index = 1; public const int Tracks_V2_pt_index = 2; public const int Tracks_V2_phi_index = 3; public const int Tracks_V2_eta_index = 4; public const int Tracks_V2_charge_index = 5; public const int GsfElectrons_V1_pos_index = 4; public const int GsfElectrons_V1_dir_index = 5; public const int GsfElectrons_V1_pt_index = 0; public const int GsfElectrons_V1_eta_index = 1; public const int GsfElectrons_V1_phi_index = 2; public const int GsfElectrons_V1_charge_index = 3; public const int GlobalMuons_V1_pt_index = 0; public const int GlobalMuons_V1_charge_index = 1; public const int GlobalMuons_V1_rp_index = 2; public const int GlobalMuons_V1_phi_index = 3; public const int GlobalMuons_V1_eta_index = 4; public const int GlobalMuons_V1_calo_energy_index = 5; public const int HBrecHits_V2_energy_index = 0; public const int HBrecHits_V2_eta_index = 1; public const int HBrecHits_V2_phi_index = 2; public const int HBrecHits_V2_time_index = 3; public const int HBrecHits_V2_detid_index = 4; public const int HBrecHits_V2_front_1_index = 5; public const int HBrecHits_V2_front_2_index = 6; public const int HBrecHits_V2_front_3_index = 7; public const int HBrecHits_V2_front_4_index = 8; public const int HBrecHits_V2_back_1_index = 9; public const int HBrecHits_V2_back_2_index = 10; public const int HBrecHits_V2_back_3_index = 11; public const int HBrecHits_V2_back_4_index = 12; public const int HErecHits_V2_energy_index = 0; public const int HErecHits_V2_eta_index = 1; public const int HErecHits_V2_phi_index = 2; public const int HErecHits_V2_time_index = 3; public const int HErecHits_V2_detid_index = 4; public const int HErecHits_V2_front_1_index = 5; public const int HErecHits_V2_front_2_index = 6; public const int HErecHits_V2_front_3_index = 7; public const int HErecHits_V2_front_4_index = 8; public const int HErecHits_V2_back_1_index = 9; public const int HErecHits_V2_back_2_index = 10; public const int HErecHits_V2_back_3_index = 11; public const int HErecHits_V2_back_4_index = 12; public const int EBrecHits_V2_energy_index = 0; public const int EBrecHits_V2_eta_index = 1; public const int EBrecHits_V2_phi_index = 2; public const int EBrecHits_V2_time_index = 3; public const int EBrecHits_V2_detid_index = 4; public const int EBrecHits_V2_front_1_index = 5; public const int EBrecHits_V2_front_2_index = 6; public const int EBrecHits_V2_front_3_index = 7; public const int EBrecHits_V2_front_4_index = 8; public const int EBrecHits_V2_back_1_index = 9; public const int EBrecHits_V2_back_2_index = 10; public const int EBrecHits_V2_back_3_index = 11; public const int EBrecHits_V2_back_4_index = 12; public const int EErecHits_V2_energy_index = 0; public const int EErecHits_V2_eta_index = 1; public const int EErecHits_V2_phi_index = 2; public const int EErecHits_V2_time_index = 3; public const int EErecHits_V2_detid_index = 4; public const int EErecHits_V2_front_1_index = 5; public const int EErecHits_V2_front_2_index = 6; public const int EErecHits_V2_front_3_index = 7; public const int EErecHits_V2_front_4_index = 8; public const int EErecHits_V2_back_1_index = 9; public const int EErecHits_V2_back_2_index = 10; public const int EErecHits_V2_back_3_index = 11; public const int EErecHits_V2_back_4_index = 12; } public class Track : MonoBehaviour { public float track_pt, track_eta, track_phi, track_charge; public string track_name; public Track(string name, float pt, float eta, float phi, float charge) { this.track_name = name; this.track_pt = pt; this.track_eta = eta; this.track_phi = phi; this.track_charge = charge; } } public class Jet : MonoBehaviour { public float jet_pt, jet_eta, jet_theta, jet_phi; public string jet_name; public Jet(string name, float pt, float eta, float theta, float phi) { this.jet_name = name; this.jet_pt = pt; this.jet_eta = eta; this.jet_theta = theta; this.jet_phi = phi; } } public class MET : MonoBehaviour { public float MET_pt, MET_phi; public string MET_name; public MET(string name, float pt, float phi) { this.MET_name = name; this.MET_pt = pt; this.MET_phi = phi; } } public class Muon : MonoBehaviour { public float muon_pt, muon_eta, muon_phi, muon_charge; public string muon_name; public Muon(string name, float pt, float eta, float phi, float charge) { this.muon_name = name; this.muon_pt = pt; this.muon_eta = eta; this.muon_phi = phi; this.muon_charge = charge; } } public class Rechit : MonoBehaviour { public float rechit_energy, rechit_eta, rechit_phi, rechit_time; public long rechit_detid; public string rechit_name; public Rechit(string name, float pt, float eta, float phi, float time, long detid) { this.rechit_name = name; this.rechit_energy = pt; this.rechit_eta = eta; this.rechit_phi = phi; this.rechit_time = time; this.rechit_detid = detid; } } public class DrawEvents { private int ti, ei, mi, pi; private float track_pt, track_eta, track_phi, track_charge; private float electron_pt, electron_eta, electron_phi, electron_charge; private float jet_pt, jet_eta, jet_theta, jet_phi; private Vector3 jet_ptvec; private float MET_pt, MET_phi; private Vector3 MET_ptvec; private Vector3 p1, p2, p3, p4; private double[] p1v, p2v; private Vector3 v1, v2; private double[] v1v, v2v; private float dp1p2; private float scale0, scale1; private float t; private float tube_min_radius, tube_max_radius; private Color tube_base_color; private float tube_alpha; private Material tube_material; private int front_1_index, front_2_index, front_3_index, front_4_index; private int back_1_index, back_2_index, back_3_index, back_4_index; private int POINT_COUNT; private Vector3[] controlPoints, bezierPoints, muonPoints; private CubicBezierCurve curve; private void RenderTubes(int POINT_COUNT, Vector3[] points, TubeRender.TubeRenderer tube) { // optimise for realtime manipulation //tube.MarkDynamic(); // define uv mapping for the end caps //tube.uvRectCap = new Rect( 0, 0, 4/12f, 4/12f ); tube.edgeCount = 24; tube.caps = TubeRenderer.CapMode.Both; // define points and radiuses tube.points = new Vector3[ POINT_COUNT ]; tube.radiuses = new float[ POINT_COUNT ]; // for tapered tubes //tube.radius = 0.02f; // for tubes of fixed radius for( int p = 0; p < POINT_COUNT; p++ ){ t = p / (float)POINT_COUNT; tube.points[p] = points[p]; tube.radiuses[p] = tube_min_radius + t * tube_max_radius; } // make the tube look nice: Renderer r = tube.GetComponent<Renderer>(); if (tube_material != null) r.material = tube_material; else { r.material = new Material (Shader.Find ("Transparent/Diffuse")); r.material.EnableKeyword ("_EMISSION"); r.material.EnableKeyword ("_ALPHAPREMULTIPLY_ON"); r.material.SetColor ("_Color", tube_base_color); Color col = r.material.color; col.a = tube_alpha; r.material.color = col; r.material.SetColor ("_EmissionColor", Color.yellow); } } // RenderTubes public int DrawTracks(object[][] tracks, object[][] extras, object[] assocs, int pt_index, int eta_index, int phi_index, int charge_index, float min_pt, string label, int trackcount, GameObject GB) { trackcount = 0; if (tracks == null) return 0; // if JSON collection was empty, return immediately // assign rendering attributes according to the label if (label == "track") { tube_min_radius = CMSvar.min_track_radius; tube_max_radius = CMSvar.max_track_radius; tube_base_color = CMSvar.track_color; tube_alpha = CMSvar.track_transparency; } else if (label == "electron") { tube_min_radius = CMSvar.min_electron_radius; tube_max_radius = CMSvar.max_electron_radius; tube_base_color = CMSvar.electron_color; tube_alpha = CMSvar.electron_transparency; } else Debug.Log ("Bad label: " + label); // extract the data for each track in the JSON event foreach (int[][] asc in assocs) { ti = asc [0][1]; ei = asc [1][1]; track_pt = (float)(double)tracks[ti][pt_index]; track_eta = (float)(double)tracks[ti][eta_index]; track_phi = (float)(double)tracks[ti][phi_index]; track_charge = (float)(int)tracks[ti][charge_index]; if (track_pt > min_pt) { // render the track trackcount++; p1v = (double[])extras[ei][0]; p1.x = (float)p1v[0]; p1.y = (float)p1v[1]; p1.z = (float)p1v[2]; v1v = (double[])extras[ei][1]; v1.x = (float)v1v[0]; v1.y = (float)v1v[1]; v1.z = (float)v1v[2]; p2v = (double[])extras[ei][2]; p2.x = (float)p2v[0]; p2.y = (float)p2v[1]; p2.z = (float)p2v[2]; v2v = (double[])extras[ei][3]; v2.x = (float)v2v[0]; v2.y = (float)v2v[1]; v2.z = (float)v2v[2]; p1 = CMSvar.rt * p1; v1 = CMSvar.rt * v1; p2 = CMSvar.rt * p2; v2 = CMSvar.rt * v2; v1.Normalize(); v2.Normalize(); dp1p2 = Vector3.Distance(p1, p2); scale0 = 0.25f * dp1p2; scale1 = 0.25f * dp1p2; p3.x = p1.x + scale0 * v1.x; p3.y = p1.y + scale0 * v1.y; p3.z = p1.z + scale0 * v1.z; p4.x = p2.x + scale1 * v2.x; p4.y = p2.y + scale1 * v2.y; p4.z = p2.z + scale1 * v2.z; // now we have the 4 Vector3's that define the Bezier curve controlPoints = new Vector3[4] {p1,p2,p3,p4}; POINT_COUNT = CMSvar.nsegments; curve = new CubicBezierCurve(controlPoints); // this is the curve // the curve will be rendered as <POINT_COUNT> straight segments bezierPoints = new Vector3[POINT_COUNT]; for (int i = 0; i < POINT_COUNT; i++) { t = i / (float)POINT_COUNT; bezierPoints[i] = curve.GetPoint(t); } // create game object and add TubeRenderer component TubeRender.TubeRenderer tube = new GameObject( label + trackcount ).AddComponent<TubeRenderer>(); // add Track component Track track = tube.gameObject.AddComponent<Track>() as Track; track.track_pt = track_pt; track.track_eta = track_eta; track.track_phi = track_phi; track.track_charge = track_charge; track.track_name = label + trackcount; // make tube a child of the game object tube.transform.parent = GB.transform; RenderTubes(POINT_COUNT, bezierPoints, tube); } // if (track_pt > 0) } // foreach return trackcount; } // DrawTracks public int DrawJets(object[] jets, int pt_index, int eta_index, int theta_index, int phi_index, float min_pt, string label, int jetcount, GameObject GC) { jetcount = 0; if (jets == null) return 0; // if JSON collection was empty, return immediately // assign rendering attributes according to the label if (label == "jet") { tube_min_radius = CMSvar.min_jet_radius; tube_max_radius = CMSvar.max_jet_radius; tube_base_color = CMSvar.jet_color; tube_alpha = CMSvar.jet_transparency; } else if (label == "MET") { tube_min_radius = CMSvar.min_MET_radius; tube_max_radius = CMSvar.max_MET_radius; tube_base_color = CMSvar.MET_color; tube_alpha = CMSvar.MET_transparency; } else Debug.LogError ("Bad label: " + label); // extract the data for each track in the JSON event foreach (object jet2 in jets) { if (label == "jet") { // not sure why we have to do the casting this way double[] jetvec = (double[])jet2; float[] jet = new float[jetvec.Length]; for (int i = 0; i < jetvec.Length; i++) jet [i] = (float)jetvec [i]; jet_pt = (float)(double)jet [pt_index]; jet_eta = (float)(double)jet [eta_index]; jet_theta = (float)(double)jet [theta_index]; jet_phi = (float)(double)jet [phi_index]; jet_ptvec.x = jet_pt * Mathf.Cos (jet_phi); jet_ptvec.y = jet_pt * Mathf.Sin (jet_phi); jet_ptvec.z = jet_pt * (float)Math.Sinh (jet_eta); } else Debug.LogError ("Bad label: " + label); if (jet_pt > min_pt) { // render the jet jetcount++; jet_ptvec = CMSvar.rt * jet_ptvec; // the jet is rendered as a straight tube but use Bezier anyway p1 = Vector3.zero; p2 = jet_ptvec * CMSvar.jetRescale; p3 = p1; p4 = p2; // now we have the 4 Vector3's that define the Bezier curve controlPoints = new Vector3[4] {p1,p2,p3,p4}; POINT_COUNT = CMSvar.nsegments; curve = new CubicBezierCurve(controlPoints); // this is the curve // the curve will be rendered as <POINT_COUNT> straight segments bezierPoints = new Vector3[POINT_COUNT]; for (int i = 0; i < POINT_COUNT; i++) { t = i / (float)POINT_COUNT; bezierPoints[i] = curve.GetPoint(t); } // create game object and add TubeRenderer component TubeRender.TubeRenderer tube = new GameObject( "jet" + jetcount ).AddComponent<TubeRenderer>(); // add Jet component Jet jet = tube.gameObject.AddComponent<Jet>() as Jet; jet.jet_pt = jet_pt; jet.jet_eta = jet_eta; jet.jet_theta = jet_theta; jet.jet_phi = jet_phi; jet.jet_name = label + jetcount; // make tube a child of the game object tube.transform.parent = GC.transform; //tube_material = Resources.Load("Materials/Emissive_white", typeof(Material)) as Material; RenderTubes(POINT_COUNT, bezierPoints, tube); } // if (jet_pt > min_pt) } // foreach return jetcount; } // DrawJets public int DrawMET(object[][] METs, int pt_index, int phi_index, float min_pt, string label, int METcount, GameObject GD) { METcount = 0; if (METs == null) return 0; // if JSON collection was empty, return immediately tube_min_radius = CMSvar.min_MET_radius; tube_max_radius = CMSvar.max_MET_radius; tube_base_color = CMSvar.MET_color; tube_alpha = CMSvar.MET_transparency; // extract the data for each MET object in the JSON event foreach (object[] MET2 in METs) { float[] MET = new float[MET2.Length]; for (int i = 0; i < MET2.Length; i++) MET[i] = Single.Parse(MET2[i].ToString()); MET_pt = (float)(double)MET [pt_index]; MET_phi = (float)(double)MET [phi_index]; MET_ptvec.x = MET_pt * Mathf.Cos (MET_phi); MET_ptvec.y = MET_pt * Mathf.Sin (MET_phi); MET_ptvec.z = 0f; if (MET_pt > min_pt) { // render the MET METcount++; MET_ptvec = CMSvar.rt * MET_ptvec; // the MET is rendered as a straight tube but use Bezier anyway p1 = Vector3.zero; p2 = MET_ptvec * CMSvar.jetRescale; p3 = p1; p4 = p2; // now we have the 4 Vector3's that define the Bezier curve controlPoints = new Vector3[4] {p1,p2,p3,p4}; POINT_COUNT = CMSvar.nsegments; curve = new CubicBezierCurve(controlPoints); // this is the curve // the curve will be rendered as <POINT_COUNT> straight segments bezierPoints = new Vector3[POINT_COUNT]; for (int i = 0; i < POINT_COUNT; i++) { t = i / (float)POINT_COUNT; bezierPoints[i] = curve.GetPoint(t); } // create game object and add TubeRenderer component TubeRender.TubeRenderer tube = new GameObject( "MET" ).AddComponent<TubeRenderer>(); // add MET component MET met = tube.gameObject.AddComponent<MET>() as MET; met.MET_pt = MET_pt; met.MET_phi = MET_phi; met.MET_name = label; // make tube a child of the game object tube.transform.parent = GD.transform; tube_material = Resources.Load("Materials/Emissive_magenta", typeof(Material)) as Material; tube_material = null; RenderTubes(POINT_COUNT, bezierPoints, tube); } // if (MET_pt > min_pt) } // foreach return METcount; } // DrawMET public int DrawMuons(object[] muons, object[] points, object[] assocs, int pt_index, int eta_index, int phi_index, int charge_index, float min_pt, string label, int muoncount, GameObject GE) { muoncount = 0; if (muons == null) return 0; // if JSON collection was empty, return immediately // assign rendering attributes according to the label tube_min_radius = CMSvar.min_muon_radius; tube_max_radius = CMSvar.max_muon_radius; tube_base_color = CMSvar.muon_color; tube_alpha = CMSvar.muon_transparency; int nrawmuons = 0; // can accommodate up to 12 muons: float[] m_pt = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f}; float[] m_eta = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f}; float[] m_phi = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f}; float[] m_charge = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f}; List<Vector3>[] muonPoints = new List<Vector3>[12]; for (int im = 0; im < 12; im++) muonPoints[im] = new List<Vector3>(); // recast all the points as an array of Vector3's int i = 0; int npoints = points.Length; Vector3[] pointsf = new Vector3[npoints]; foreach (double[][] pointsd in points) { pointsf[i].x = (float)pointsd[0][0]; pointsf[i].y = (float)pointsd[0][1]; pointsf[i].z = (float)pointsd[0][2]; i++; } // extract the kinematic data for each muon in the JSON event nrawmuons = muons.Length; mi = 0; foreach (object[] mu in muons) { m_pt [mi] = (float)(double)mu[pt_index]; m_eta [mi] = (float)(double)mu[eta_index]; m_phi [mi] = (float)(double)mu[phi_index]; m_charge [mi] = (float)(int)mu[charge_index]; mi++; } // extract the point data for each muon in the JSON event foreach (int[][] asc in assocs) { mi = asc [0] [1]; // labels which muon it is pi = asc [1] [1]; // labels a point on the muon track // For a particular muon we don't want all the muon points, only the ones // labeled by the pi's. muonPoints[mi].Add(CMSvar.rt * pointsf[pi]); } // foreach // Now go back through the muons and render the ones that pass the pt cut: for (int im = 0; im < nrawmuons; im++) { if (m_pt[im] > min_pt) { // render the muon muoncount++; // we have all the points that define the muon track Vector3[] mpoints = muonPoints[im].ToArray(); POINT_COUNT = mpoints.Length; // create game object and add TubeRenderer component TubeRender.TubeRenderer tube = new GameObject ("muon" + muoncount).AddComponent<TubeRenderer> (); // add Muon component Muon muon = tube.gameObject.AddComponent<Muon>() as Muon; muon.muon_pt = m_pt[im]; muon.muon_eta = m_eta[im]; muon.muon_phi = m_phi[im]; muon.muon_charge = m_charge[im]; muon.muon_name = label + muoncount; // make tube a child of the game object tube.transform.parent = GE.transform; tube_material = Resources.Load("Materials/Emissive_red", typeof(Material)) as Material; RenderTubes (POINT_COUNT, mpoints, tube); } } // for return muoncount; } // DrawMuons public int DrawRechits(object[] rechits, int energy_index, int eta_index, int phi_index, int time_index, int detid_index, float min_energy, float energy_scale, string label, int rechitcount, GameObject GF) { rechitcount = 0; if (rechits == null) return 0; // if JSON collection was empty, return immediately // assign rendering attributes according to the label if (label == "HBrechit") { energy_index = CMSvar.HBrecHits_V2_energy_index; eta_index = CMSvar.HBrecHits_V2_eta_index; phi_index = CMSvar.HBrecHits_V2_phi_index; time_index = CMSvar.HBrecHits_V2_time_index; detid_index = CMSvar.HBrecHits_V2_detid_index; front_1_index = CMSvar.HBrecHits_V2_front_1_index; front_2_index = CMSvar.HBrecHits_V2_front_2_index; front_3_index = CMSvar.HBrecHits_V2_front_3_index; front_4_index = CMSvar.HBrecHits_V2_front_4_index; back_1_index = CMSvar.HBrecHits_V2_back_1_index; back_2_index = CMSvar.HBrecHits_V2_back_2_index; back_3_index = CMSvar.HBrecHits_V2_back_3_index; back_4_index = CMSvar.HBrecHits_V2_back_4_index; } else if (label == "HErechit") { energy_index = CMSvar.HErecHits_V2_energy_index; eta_index = CMSvar.HErecHits_V2_eta_index; phi_index = CMSvar.HErecHits_V2_phi_index; time_index = CMSvar.HErecHits_V2_time_index; detid_index = CMSvar.HErecHits_V2_detid_index; front_1_index = CMSvar.HErecHits_V2_front_1_index; front_2_index = CMSvar.HErecHits_V2_front_2_index; front_3_index = CMSvar.HErecHits_V2_front_3_index; front_4_index = CMSvar.HErecHits_V2_front_4_index; back_1_index = CMSvar.HErecHits_V2_back_1_index; back_2_index = CMSvar.HErecHits_V2_back_2_index; back_3_index = CMSvar.HErecHits_V2_back_3_index; back_4_index = CMSvar.HErecHits_V2_back_4_index; } else if (label == "EBrechit") { energy_index = CMSvar.EBrecHits_V2_energy_index; eta_index = CMSvar.EBrecHits_V2_eta_index; phi_index = CMSvar.EBrecHits_V2_phi_index; time_index = CMSvar.EBrecHits_V2_time_index; detid_index = CMSvar.EBrecHits_V2_detid_index; front_1_index = CMSvar.EBrecHits_V2_front_1_index; front_2_index = CMSvar.EBrecHits_V2_front_2_index; front_3_index = CMSvar.EBrecHits_V2_front_3_index; front_4_index = CMSvar.EBrecHits_V2_front_4_index; back_1_index = CMSvar.EBrecHits_V2_back_1_index; back_2_index = CMSvar.EBrecHits_V2_back_2_index; back_3_index = CMSvar.EBrecHits_V2_back_3_index; back_4_index = CMSvar.EBrecHits_V2_back_4_index; } else if (label == "EErechit") { energy_index = CMSvar.EErecHits_V2_energy_index; eta_index = CMSvar.EErecHits_V2_eta_index; phi_index = CMSvar.EErecHits_V2_phi_index; time_index = CMSvar.EErecHits_V2_time_index; detid_index = CMSvar.EErecHits_V2_detid_index; front_1_index = CMSvar.EErecHits_V2_front_1_index; front_2_index = CMSvar.EErecHits_V2_front_2_index; front_3_index = CMSvar.EErecHits_V2_front_3_index; front_4_index = CMSvar.EErecHits_V2_front_4_index; back_1_index = CMSvar.EErecHits_V2_back_1_index; back_2_index = CMSvar.EErecHits_V2_back_2_index; back_3_index = CMSvar.EErecHits_V2_back_3_index; back_4_index = CMSvar.EErecHits_V2_back_4_index; } else Debug.LogError ("Bad label: " + label); // extract the data for each rechit in the JSON event foreach (object[] rh in rechits) { // be careful of cases where the double is really an int: float rh_energy = (rh[energy_index].GetType() == typeof(System.Double)) ? (float)(double)rh[energy_index] : (float)(int)rh[energy_index]; float rh_eta = (rh[eta_index].GetType() == typeof(System.Double)) ? (float)(double)rh[eta_index] : (float)(int)rh[eta_index]; float rh_phi = (rh[phi_index].GetType() == typeof(System.Double)) ? (float)(double)rh[phi_index] : (float)(int)rh[phi_index]; float rh_time = (rh[time_index].GetType() == typeof(System.Double)) ? (float)(double)rh[time_index] : (float)(int)rh[time_index]; long rh_detid = (long)(int)rh[detid_index]; if (rh_energy > min_energy) { // render the rechit rechitcount++; // a cube or parallelpiped is defined by its 8 vertices double[] p; p = (double[])rh[front_1_index]; Vector3 f1 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[front_2_index]; Vector3 f2 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[front_3_index]; Vector3 f3 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[front_4_index]; Vector3 f4 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[back_1_index]; Vector3 b1 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[back_2_index]; Vector3 b2 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[back_3_index]; Vector3 b3 = new Vector3((float)p[0],(float)p[1],(float)p[2]); p = (double[])rh[back_4_index]; Vector3 b4 = new Vector3((float)p[0],(float)p[1],(float)p[2]); Vector3 diff1 = b1 - f1; Vector3 diff2 = b2 - f2; Vector3 diff3 = b3 - f3; Vector3 diff4 = b4 - f4; diff1.Normalize(); diff2.Normalize(); diff3.Normalize(); diff4.Normalize(); Vector3 scale = new Vector3(energy_scale, energy_scale, energy_scale); diff1 = Vector3.Scale (diff1, scale); diff2 = Vector3.Scale (diff2, scale); diff3 = Vector3.Scale (diff3, scale); diff4 = Vector3.Scale (diff4, scale); Vector3 f1d = f1 + diff1; Vector3 f2d = f2 + diff2; Vector3 f3d = f3 + diff3; Vector3 f4d = f4 + diff4; f1 = CMSvar.rt * f1; f2 = CMSvar.rt * f2; f3 = CMSvar.rt * f3; f4 = CMSvar.rt * f4; f1d = CMSvar.rt * f1d; f2d = CMSvar.rt * f2d; f3d = CMSvar.rt * f3d; f4d = CMSvar.rt * f4d; Vector3[] vertices = {f1, f2, f3, f4, f1d, f2d, f3d, f4d}; int[] triangles = { 0, 2, 1, //face front 0, 3, 2, 2, 3, 4, //face top 2, 4, 5, 1, 2, 5, //face right 1, 5, 6, 0, 7, 4, //face left 0, 4, 3, 5, 4, 7, //face back 5, 7, 6, 0, 6, 7, //face bottom 0, 1, 6 }; GameObject rechit = new GameObject(label + rechitcount); // make tube a child of the game object rechit.transform.parent = GF.transform; MeshFilter meshFilter = rechit.AddComponent<MeshFilter>(); MeshRenderer meshRenderer = rechit.AddComponent<MeshRenderer>(); Material Emissive_yellow = Resources.Load("Materials/Emissive_yellow", typeof(Material)) as Material; meshRenderer.material = Emissive_yellow; Mesh mesh = rechit.GetComponent<MeshFilter>().mesh; mesh.Clear (); mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals (); // add Rechit component Rechit re = rechit.AddComponent<Rechit>() as Rechit; re.rechit_energy = rh_energy; re.rechit_eta = rh_eta; re.rechit_phi = rh_phi; re.rechit_time = rh_time; re.rechit_detid = rh_detid; re.rechit_name = label + rechitcount; } // if (rh_energy > min_energy) } // foreach return rechitcount; } // DrawRechits } // DrawEvents } // CMSdraw
namespace Humidifier.KinesisAnalyticsV2 { using System.Collections.Generic; using ApplicationTypes; public class Application : Humidifier.Resource { public override string AWSTypeName { get { return @"AWS::KinesisAnalyticsV2::Application"; } } /// <summary> /// ApplicationName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationname /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic ApplicationName { get; set; } /// <summary> /// RuntimeEnvironment /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-runtimeenvironment /// Required: True /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic RuntimeEnvironment { get; set; } /// <summary> /// ApplicationConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationconfiguration /// Required: False /// UpdateType: Mutable /// Type: ApplicationConfiguration /// </summary> public ApplicationConfiguration ApplicationConfiguration { get; set; } /// <summary> /// ApplicationDescription /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationdescription /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ApplicationDescription { get; set; } /// <summary> /// ServiceExecutionRole /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-serviceexecutionrole /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ServiceExecutionRole { get; set; } } namespace ApplicationTypes { public class S3ContentLocation { /// <summary> /// BucketARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-s3contentlocation.html#cfn-kinesisanalyticsv2-application-s3contentlocation-bucketarn /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic BucketARN { get; set; } /// <summary> /// FileKey /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-s3contentlocation.html#cfn-kinesisanalyticsv2-application-s3contentlocation-filekey /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic FileKey { get; set; } /// <summary> /// ObjectVersion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-s3contentlocation.html#cfn-kinesisanalyticsv2-application-s3contentlocation-objectversion /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ObjectVersion { get; set; } } public class PropertyGroup { /// <summary> /// PropertyMap /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-propertygroup.html#cfn-kinesisanalyticsv2-application-propertygroup-propertymap /// Required: False /// UpdateType: Mutable /// PrimitiveType: Json /// </summary> public dynamic PropertyMap { get; set; } /// <summary> /// PropertyGroupId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-propertygroup.html#cfn-kinesisanalyticsv2-application-propertygroup-propertygroupid /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic PropertyGroupId { get; set; } } public class KinesisStreamsInput { /// <summary> /// ResourceARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-kinesisstreamsinput.html#cfn-kinesisanalyticsv2-application-kinesisstreamsinput-resourcearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ResourceARN { get; set; } } public class MappingParameters { /// <summary> /// JSONMappingParameters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-mappingparameters.html#cfn-kinesisanalyticsv2-application-mappingparameters-jsonmappingparameters /// Required: False /// UpdateType: Mutable /// Type: JSONMappingParameters /// </summary> public JSONMappingParameters JSONMappingParameters { get; set; } /// <summary> /// CSVMappingParameters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-mappingparameters.html#cfn-kinesisanalyticsv2-application-mappingparameters-csvmappingparameters /// Required: False /// UpdateType: Mutable /// Type: CSVMappingParameters /// </summary> public CSVMappingParameters CSVMappingParameters { get; set; } } public class CheckpointConfiguration { /// <summary> /// ConfigurationType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-checkpointconfiguration.html#cfn-kinesisanalyticsv2-application-checkpointconfiguration-configurationtype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ConfigurationType { get; set; } /// <summary> /// CheckpointInterval /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-checkpointconfiguration.html#cfn-kinesisanalyticsv2-application-checkpointconfiguration-checkpointinterval /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic CheckpointInterval { get; set; } /// <summary> /// MinPauseBetweenCheckpoints /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-checkpointconfiguration.html#cfn-kinesisanalyticsv2-application-checkpointconfiguration-minpausebetweencheckpoints /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic MinPauseBetweenCheckpoints { get; set; } /// <summary> /// CheckpointingEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-checkpointconfiguration.html#cfn-kinesisanalyticsv2-application-checkpointconfiguration-checkpointingenabled /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic CheckpointingEnabled { get; set; } } public class InputParallelism { /// <summary> /// Count /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputparallelism.html#cfn-kinesisanalyticsv2-application-inputparallelism-count /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic Count { get; set; } } public class InputLambdaProcessor { /// <summary> /// ResourceARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputlambdaprocessor.html#cfn-kinesisanalyticsv2-application-inputlambdaprocessor-resourcearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ResourceARN { get; set; } } public class FlinkApplicationConfiguration { /// <summary> /// CheckpointConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-flinkapplicationconfiguration.html#cfn-kinesisanalyticsv2-application-flinkapplicationconfiguration-checkpointconfiguration /// Required: False /// UpdateType: Mutable /// Type: CheckpointConfiguration /// </summary> public CheckpointConfiguration CheckpointConfiguration { get; set; } /// <summary> /// ParallelismConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-flinkapplicationconfiguration.html#cfn-kinesisanalyticsv2-application-flinkapplicationconfiguration-parallelismconfiguration /// Required: False /// UpdateType: Mutable /// Type: ParallelismConfiguration /// </summary> public ParallelismConfiguration ParallelismConfiguration { get; set; } /// <summary> /// MonitoringConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-flinkapplicationconfiguration.html#cfn-kinesisanalyticsv2-application-flinkapplicationconfiguration-monitoringconfiguration /// Required: False /// UpdateType: Mutable /// Type: MonitoringConfiguration /// </summary> public MonitoringConfiguration MonitoringConfiguration { get; set; } } public class Input { /// <summary> /// NamePrefix /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-input.html#cfn-kinesisanalyticsv2-application-input-nameprefix /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic NamePrefix { get; set; } /// <summary> /// InputSchema /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-input.html#cfn-kinesisanalyticsv2-application-input-inputschema /// Required: True /// UpdateType: Mutable /// Type: InputSchema /// </summary> public InputSchema InputSchema { get; set; } /// <summary> /// KinesisStreamsInput /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-input.html#cfn-kinesisanalyticsv2-application-input-kinesisstreamsinput /// Required: False /// UpdateType: Mutable /// Type: KinesisStreamsInput /// </summary> public KinesisStreamsInput KinesisStreamsInput { get; set; } /// <summary> /// KinesisFirehoseInput /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-input.html#cfn-kinesisanalyticsv2-application-input-kinesisfirehoseinput /// Required: False /// UpdateType: Mutable /// Type: KinesisFirehoseInput /// </summary> public KinesisFirehoseInput KinesisFirehoseInput { get; set; } /// <summary> /// InputProcessingConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-input.html#cfn-kinesisanalyticsv2-application-input-inputprocessingconfiguration /// Required: False /// UpdateType: Mutable /// Type: InputProcessingConfiguration /// </summary> public InputProcessingConfiguration InputProcessingConfiguration { get; set; } /// <summary> /// InputParallelism /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-input.html#cfn-kinesisanalyticsv2-application-input-inputparallelism /// Required: False /// UpdateType: Mutable /// Type: InputParallelism /// </summary> public InputParallelism InputParallelism { get; set; } } public class ApplicationSnapshotConfiguration { /// <summary> /// SnapshotsEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationsnapshotconfiguration.html#cfn-kinesisanalyticsv2-application-applicationsnapshotconfiguration-snapshotsenabled /// Required: True /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic SnapshotsEnabled { get; set; } } public class KinesisFirehoseInput { /// <summary> /// ResourceARN /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-kinesisfirehoseinput.html#cfn-kinesisanalyticsv2-application-kinesisfirehoseinput-resourcearn /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ResourceARN { get; set; } } public class InputSchema { /// <summary> /// RecordEncoding /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html#cfn-kinesisanalyticsv2-application-inputschema-recordencoding /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RecordEncoding { get; set; } /// <summary> /// RecordColumns /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html#cfn-kinesisanalyticsv2-application-inputschema-recordcolumns /// Required: True /// UpdateType: Mutable /// Type: List /// ItemType: RecordColumn /// </summary> public List<RecordColumn> RecordColumns { get; set; } /// <summary> /// RecordFormat /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html#cfn-kinesisanalyticsv2-application-inputschema-recordformat /// Required: True /// UpdateType: Mutable /// Type: RecordFormat /// </summary> public RecordFormat RecordFormat { get; set; } } public class RecordColumn { /// <summary> /// Mapping /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html#cfn-kinesisanalyticsv2-application-recordcolumn-mapping /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Mapping { get; set; } /// <summary> /// SqlType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html#cfn-kinesisanalyticsv2-application-recordcolumn-sqltype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SqlType { get; set; } /// <summary> /// Name /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html#cfn-kinesisanalyticsv2-application-recordcolumn-name /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Name { get; set; } } public class ParallelismConfiguration { /// <summary> /// ConfigurationType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-configurationtype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ConfigurationType { get; set; } /// <summary> /// ParallelismPerKPU /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-parallelismperkpu /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic ParallelismPerKPU { get; set; } /// <summary> /// AutoScalingEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-autoscalingenabled /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic AutoScalingEnabled { get; set; } /// <summary> /// Parallelism /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-parallelism /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic Parallelism { get; set; } } public class CSVMappingParameters { /// <summary> /// RecordRowDelimiter /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-csvmappingparameters.html#cfn-kinesisanalyticsv2-application-csvmappingparameters-recordrowdelimiter /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RecordRowDelimiter { get; set; } /// <summary> /// RecordColumnDelimiter /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-csvmappingparameters.html#cfn-kinesisanalyticsv2-application-csvmappingparameters-recordcolumndelimiter /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RecordColumnDelimiter { get; set; } } public class MonitoringConfiguration { /// <summary> /// ConfigurationType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-monitoringconfiguration.html#cfn-kinesisanalyticsv2-application-monitoringconfiguration-configurationtype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ConfigurationType { get; set; } /// <summary> /// MetricsLevel /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-monitoringconfiguration.html#cfn-kinesisanalyticsv2-application-monitoringconfiguration-metricslevel /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic MetricsLevel { get; set; } /// <summary> /// LogLevel /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-monitoringconfiguration.html#cfn-kinesisanalyticsv2-application-monitoringconfiguration-loglevel /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic LogLevel { get; set; } } public class RecordFormat { /// <summary> /// MappingParameters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordformat.html#cfn-kinesisanalyticsv2-application-recordformat-mappingparameters /// Required: False /// UpdateType: Mutable /// Type: MappingParameters /// </summary> public MappingParameters MappingParameters { get; set; } /// <summary> /// RecordFormatType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordformat.html#cfn-kinesisanalyticsv2-application-recordformat-recordformattype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RecordFormatType { get; set; } } public class JSONMappingParameters { /// <summary> /// RecordRowPath /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-jsonmappingparameters.html#cfn-kinesisanalyticsv2-application-jsonmappingparameters-recordrowpath /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic RecordRowPath { get; set; } } public class CodeContent { /// <summary> /// ZipFileContent /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-codecontent.html#cfn-kinesisanalyticsv2-application-codecontent-zipfilecontent /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ZipFileContent { get; set; } /// <summary> /// S3ContentLocation /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-codecontent.html#cfn-kinesisanalyticsv2-application-codecontent-s3contentlocation /// Required: False /// UpdateType: Mutable /// Type: S3ContentLocation /// </summary> public S3ContentLocation S3ContentLocation { get; set; } /// <summary> /// TextContent /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-codecontent.html#cfn-kinesisanalyticsv2-application-codecontent-textcontent /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic TextContent { get; set; } } public class SqlApplicationConfiguration { /// <summary> /// Inputs /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-sqlapplicationconfiguration.html#cfn-kinesisanalyticsv2-application-sqlapplicationconfiguration-inputs /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Input /// </summary> public List<Input> Inputs { get; set; } } public class InputProcessingConfiguration { /// <summary> /// InputLambdaProcessor /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputprocessingconfiguration.html#cfn-kinesisanalyticsv2-application-inputprocessingconfiguration-inputlambdaprocessor /// Required: False /// UpdateType: Mutable /// Type: InputLambdaProcessor /// </summary> public InputLambdaProcessor InputLambdaProcessor { get; set; } } public class ApplicationConfiguration { /// <summary> /// ApplicationCodeConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-applicationcodeconfiguration /// Required: False /// UpdateType: Mutable /// Type: ApplicationCodeConfiguration /// </summary> public ApplicationCodeConfiguration ApplicationCodeConfiguration { get; set; } /// <summary> /// EnvironmentProperties /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-environmentproperties /// Required: False /// UpdateType: Mutable /// Type: EnvironmentProperties /// </summary> public EnvironmentProperties EnvironmentProperties { get; set; } /// <summary> /// FlinkApplicationConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-flinkapplicationconfiguration /// Required: False /// UpdateType: Mutable /// Type: FlinkApplicationConfiguration /// </summary> public FlinkApplicationConfiguration FlinkApplicationConfiguration { get; set; } /// <summary> /// SqlApplicationConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-sqlapplicationconfiguration /// Required: False /// UpdateType: Mutable /// Type: SqlApplicationConfiguration /// </summary> public SqlApplicationConfiguration SqlApplicationConfiguration { get; set; } /// <summary> /// ApplicationSnapshotConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationconfiguration.html#cfn-kinesisanalyticsv2-application-applicationconfiguration-applicationsnapshotconfiguration /// Required: False /// UpdateType: Mutable /// Type: ApplicationSnapshotConfiguration /// </summary> public ApplicationSnapshotConfiguration ApplicationSnapshotConfiguration { get; set; } } public class ApplicationCodeConfiguration { /// <summary> /// CodeContentType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationcodeconfiguration.html#cfn-kinesisanalyticsv2-application-applicationcodeconfiguration-codecontenttype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic CodeContentType { get; set; } /// <summary> /// CodeContent /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-applicationcodeconfiguration.html#cfn-kinesisanalyticsv2-application-applicationcodeconfiguration-codecontent /// Required: True /// UpdateType: Mutable /// Type: CodeContent /// </summary> public CodeContent CodeContent { get; set; } } public class EnvironmentProperties { /// <summary> /// PropertyGroups /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-environmentproperties.html#cfn-kinesisanalyticsv2-application-environmentproperties-propertygroups /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: PropertyGroup /// </summary> public List<PropertyGroup> PropertyGroups { get; set; } } } }
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Description: TranslationDictionariesWriter & TranslationDictionariesReader class // //--------------------------------------------------------------------------- using System; using System.IO; using System.Resources; using System.Collections; using System.Globalization; using System.Windows; using System.Diagnostics; using System.ComponentModel; using System.Windows.Markup.Localizer; namespace BamlLocalization { /// <summary> /// Writer to write out localizable values into CSV or tab-separated txt files. /// </summary> internal static class TranslationDictionariesWriter { /// <summary> /// Write the localizable key-value pairs /// </summary> /// <param name="options"></param> internal static void Write(LocBamlOptions options) { Stream output = new FileStream(options.Output, FileMode.Create); InputBamlStreamList bamlStreamList = new InputBamlStreamList(options); using (ResourceTextWriter writer = new ResourceTextWriter(options.TranslationFileType, output)) { options.WriteLine(StringLoader.Get("WriteBamlValues")); for (int i = 0; i < bamlStreamList.Count; i++) { options.Write(" "); options.Write(StringLoader.Get("ProcessingBaml", bamlStreamList[i].Name)); // Search for comment file in the same directory. The comment file has the extension to be // "loc". string commentFile = Path.ChangeExtension(bamlStreamList[i].Name, "loc"); TextReader commentStream = null; try { if (File.Exists(commentFile)) { commentStream = new StreamReader(commentFile); } // create the baml localizer BamlLocalizer mgr = new BamlLocalizer( bamlStreamList[i].Stream, new BamlLocalizabilityByReflection(options.Assemblies), commentStream ); // extract localizable resource from the baml stream BamlLocalizationDictionary dict = mgr.ExtractResources(); // write out each resource foreach (DictionaryEntry entry in dict) { // column 1: baml stream name writer.WriteColumn(bamlStreamList[i].Name); BamlLocalizableResourceKey key = (BamlLocalizableResourceKey)entry.Key; BamlLocalizableResource resource = (BamlLocalizableResource)entry.Value; // column 2: localizable resource key writer.WriteColumn(LocBamlConst.ResourceKeyToString(key)); // column 3: localizable resource's category writer.WriteColumn(resource.Category.ToString()); // column 4: localizable resource's readability writer.WriteColumn(resource.Readable.ToString()); // column 5: localizable resource's modifiability writer.WriteColumn(resource.Modifiable.ToString()); // column 6: localizable resource's localization comments writer.WriteColumn(resource.Comments); // column 7: localizable resource's content writer.WriteColumn(resource.Content); // Done. finishing the line writer.EndLine(); } options.WriteLine(StringLoader.Get("Done")); } finally { if (commentStream != null) commentStream.Close(); } } // close all the baml input streams, output stream is closed by writer. bamlStreamList.Close(); } } } /// <summary> /// Reader to read the translations from CSV or tab-separated txt file /// </summary> internal class TranslationDictionariesReader { /// <summary> /// Constructor /// </summary> /// <param name="reader">resoure text reader that reads CSV or a tab-separated txt file</param> internal TranslationDictionariesReader(ResourceTextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); // hash key is case insensitive strings _table = new Hashtable(); // we read each Row int rowNumber = 0; while (reader.ReadRow()) { rowNumber++; // field #1 is the baml name. string bamlName = reader.GetColumn(0); // it can't be null if (bamlName == null) throw new ApplicationException(StringLoader.Get("EmptyRowEncountered")); if (string.IsNullOrEmpty(bamlName)) { // allow for comment lines in csv file. // each comment line starts with ",". It will make the first entry as String.Empty. // and we will skip the whole line. continue; // if the first column is empty, take it as a comment line } // field #2: key to the localizable resource string key = reader.GetColumn(1); if (key == null) throw new ApplicationException(StringLoader.Get("NullBamlKeyNameInRow")); BamlLocalizableResourceKey resourceKey = LocBamlConst.StringToResourceKey(key); // get the dictionary BamlLocalizationDictionary dictionary = this[bamlName]; if (dictionary == null) { // we create one if it is not there yet. dictionary = new BamlLocalizationDictionary(); this[bamlName] = dictionary; } BamlLocalizableResource resource; // the rest of the fields are either all null, // or all non-null. If all null, it means the resource entry is deleted. // get the string category string categoryString = reader.GetColumn(2); if (categoryString == null) { // it means all the following fields are null starting from column #3. resource = null; } else { // the rest must all be non-null. // the last cell can be null if there is no content for (int i = 3; i < 6; i++) { if (reader.GetColumn(i) == null) throw new Exception(StringLoader.Get("InvalidRow")); } // now we know all are non-null. let's try to create a resource resource = new BamlLocalizableResource(); // field #3: Category resource.Category = (LocalizationCategory)StringCatConverter.ConvertFrom(categoryString); // field #4: Readable resource.Readable = (bool)BoolTypeConverter.ConvertFrom(reader.GetColumn(3)); // field #5: Modifiable resource.Modifiable = (bool)BoolTypeConverter.ConvertFrom(reader.GetColumn(4)); // field #6: Comments resource.Comments = reader.GetColumn(5); // field #7: Content resource.Content = reader.GetColumn(6); // in case content being the last column, consider null as empty. if (resource.Content == null) resource.Content = string.Empty; // field > #7: Ignored. } // at this point, we are good. // add to the dictionary. dictionary.Add(resourceKey, resource); } } internal BamlLocalizationDictionary this[string key] { get { return (BamlLocalizationDictionary)_table[key.ToLowerInvariant()]; } set { _table[key.ToLowerInvariant()] = value; } } // hashtable that maps from baml name to its ResourceDictionary private Hashtable _table; private static TypeConverter BoolTypeConverter = TypeDescriptor.GetConverter(true); private static TypeConverter StringCatConverter = TypeDescriptor.GetConverter(LocalizationCategory.Text); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; using Shouldly; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.LoadBalancer { public class LeastConnectionTests { private ServiceHostAndPort _hostAndPort; private Response<ServiceHostAndPort> _result; private LeastConnection _leastConnection; private List<Service> _services; private Random _random; private DownstreamContext _context; public LeastConnectionTests() { _context = new DownstreamContext(new DefaultHttpContext()); _random = new Random(); } [Fact] public void should_be_able_to_lease_and_release_concurrently() { var serviceName = "products"; var availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), }; _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); var tasks = new Task[100]; for(var i = 0; i < tasks.Length; i++) { tasks[i] = LeaseDelayAndRelease(); } Task.WaitAll(tasks); } [Fact] public void should_handle_service_returning_to_available() { var serviceName = "products"; var availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), }; _leastConnection = new LeastConnection(() => Task.FromResult(availableServices), serviceName); var hostAndPortOne = _leastConnection.Lease(_context).Result; hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); var hostAndPortTwo = _leastConnection.Lease(_context).Result; hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), }; hostAndPortOne = _leastConnection.Lease(_context).Result; hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); hostAndPortTwo = _leastConnection.Lease(_context).Result; hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.1"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), }; hostAndPortOne = _leastConnection.Lease(_context).Result; hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); hostAndPortTwo = _leastConnection.Lease(_context).Result; hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); } private async Task LeaseDelayAndRelease() { var hostAndPort = await _leastConnection.Lease(_context); await Task.Delay(_random.Next(1, 100)); _leastConnection.Release(hostAndPort.Data); } [Fact] public void should_get_next_url() { var serviceName = "products"; var hostAndPort = new ServiceHostAndPort("localhost", 80); var availableServices = new List<Service> { new Service(serviceName, hostAndPort, string.Empty, string.Empty, new string[0]) }; this.Given(x => x.GivenAHostAndPort(hostAndPort)) .And(x => x.GivenTheLoadBalancerStarts(availableServices, serviceName)) .When(x => x.WhenIGetTheNextHostAndPort()) .Then(x => x.ThenTheNextHostAndPortIsReturned()) .BDDfy(); } [Fact] public void should_serve_from_service_with_least_connections() { var serviceName = "products"; var availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.3", 80), string.Empty, string.Empty, new string[0]) }; _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); var response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[2].HostAndPort.DownstreamHost); } [Fact] public void should_build_connections_per_service() { var serviceName = "products"; var availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), }; _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); var response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); } [Fact] public void should_release_connection() { var serviceName = "products"; var availableServices = new List<Service> { new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), }; _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); var response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); //release this so 2 should have 1 connection and we should get 2 back as our next host and port _leastConnection.Release(availableServices[1].HostAndPort); response = _leastConnection.Lease(_context).Result; response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); } [Fact] public void should_return_error_if_services_are_null() { var serviceName = "products"; var hostAndPort = new ServiceHostAndPort("localhost", 80); this.Given(x => x.GivenAHostAndPort(hostAndPort)) .And(x => x.GivenTheLoadBalancerStarts(null, serviceName)) .When(x => x.WhenIGetTheNextHostAndPort()) .Then(x => x.ThenServiceAreNullErrorIsReturned()) .BDDfy(); } [Fact] public void should_return_error_if_services_are_empty() { var serviceName = "products"; var hostAndPort = new ServiceHostAndPort("localhost", 80); this.Given(x => x.GivenAHostAndPort(hostAndPort)) .And(x => x.GivenTheLoadBalancerStarts(new List<Service>(), serviceName)) .When(x => x.WhenIGetTheNextHostAndPort()) .Then(x => x.ThenServiceAreEmptyErrorIsReturned()) .BDDfy(); } private void ThenServiceAreNullErrorIsReturned() { _result.IsError.ShouldBeTrue(); _result.Errors[0].ShouldBeOfType<ServicesAreNullError>(); } private void ThenServiceAreEmptyErrorIsReturned() { _result.IsError.ShouldBeTrue(); _result.Errors[0].ShouldBeOfType<ServicesAreEmptyError>(); } private void GivenTheLoadBalancerStarts(List<Service> services, string serviceName) { _services = services; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); } private void WhenTheLoadBalancerStarts(List<Service> services, string serviceName) { GivenTheLoadBalancerStarts(services, serviceName); } private void GivenAHostAndPort(ServiceHostAndPort hostAndPort) { _hostAndPort = hostAndPort; } private void WhenIGetTheNextHostAndPort() { _result = _leastConnection.Lease(_context).Result; } private void ThenTheNextHostAndPortIsReturned() { _result.Data.DownstreamHost.ShouldBe(_hostAndPort.DownstreamHost); _result.Data.DownstreamPort.ShouldBe(_hostAndPort.DownstreamPort); } } }
using System.Net; using FluentAssertions; using JetBrains.Annotations; using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Updating.Relationships; public sealed class RemoveFromToManyRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>> { private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext; private readonly ReadWriteFakers _fakers = new(); public RemoveFromToManyRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext) { _testContext = testContext; testContext.UseController<WorkItemsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddSingleton<IResourceDefinition<WorkItem, int>, RemoveExtraFromWorkItemDefinition>(); }); var workItemDefinition = (RemoveExtraFromWorkItemDefinition)testContext.Factory.Services.GetRequiredService<IResourceDefinition<WorkItem, int>>(); workItemDefinition.Reset(); } [Fact] public async Task Cannot_remove_from_ManyToOne_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Assignee = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingWorkItem.Assignee.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("Failed to deserialize request body: Only to-many relationships can be targeted through this endpoint."); error.Detail.Should().Be("Relationship 'assignee' is not a to-many relationship."); error.Source.Should().BeNull(); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Can_remove_from_OneToMany_relationship_with_unassigned_existing_resource() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet(); UserAccount existingSubscriber = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<UserAccount>(); dbContext.AddInRange(existingWorkItem, existingSubscriber); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingSubscriber.StringId }, new { type = "userAccounts", id = existingWorkItem.Subscribers.ElementAt(0).StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Subscribers.ShouldHaveCount(1); workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(1).Id); List<UserAccount> userAccountsInDatabase = await dbContext.UserAccounts.ToListAsync(); userAccountsInDatabase.ShouldHaveCount(3); }); } [Fact] public async Task Can_remove_from_OneToMany_relationship_with_extra_removals_from_resource_definition() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(3).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<UserAccount>(); dbContext.AddInRange(existingWorkItem); await dbContext.SaveChangesAsync(); }); var workItemDefinition = (RemoveExtraFromWorkItemDefinition)_testContext.Factory.Services.GetRequiredService<IResourceDefinition<WorkItem, int>>(); workItemDefinition.ExtraSubscribersIdsToRemove.Add(existingWorkItem.Subscribers.ElementAt(2).Id); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingWorkItem.Subscribers.ElementAt(0).StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); workItemDefinition.PreloadedSubscribers.ShouldHaveCount(1); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Subscribers.ShouldHaveCount(1); workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(1).Id); List<UserAccount> userAccountsInDatabase = await dbContext.UserAccounts.ToListAsync(); userAccountsInDatabase.ShouldHaveCount(3); }); } [Fact] public async Task Can_remove_from_ManyToMany_relationship_with_unassigned_existing_resource() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Tags = _fakers.WorkTag.Generate(2).ToHashSet(); WorkTag existingTag = _fakers.WorkTag.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WorkTag>(); dbContext.AddInRange(existingWorkItem, existingTag); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "workTags", id = existingWorkItem.Tags.ElementAt(1).StringId }, new { type = "workTags", id = existingTag.StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/tags"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Tags).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Tags.ShouldHaveCount(1); workItemInDatabase.Tags.Single().Id.Should().Be(existingWorkItem.Tags.ElementAt(0).Id); List<WorkTag> tagsInDatabase = await dbContext.WorkTags.ToListAsync(); tagsInDatabase.ShouldHaveCount(3); }); } [Fact] public async Task Can_remove_from_ManyToMany_relationship_with_extra_removals_from_resource_definition() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Tags = _fakers.WorkTag.Generate(3).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WorkTag>(); dbContext.AddInRange(existingWorkItem); await dbContext.SaveChangesAsync(); }); var workItemDefinition = (RemoveExtraFromWorkItemDefinition)_testContext.Factory.Services.GetRequiredService<IResourceDefinition<WorkItem, int>>(); workItemDefinition.ExtraTagIdsToRemove.Add(existingWorkItem.Tags.ElementAt(2).Id); var requestBody = new { data = new[] { new { type = "workTags", id = existingWorkItem.Tags.ElementAt(1).StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/tags"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); workItemDefinition.PreloadedTags.ShouldHaveCount(1); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Tags).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Tags.ShouldHaveCount(1); workItemInDatabase.Tags.Single().Id.Should().Be(existingWorkItem.Tags.ElementAt(0).Id); List<WorkTag> tagsInDatabase = await dbContext.WorkTags.ToListAsync(); tagsInDatabase.ShouldHaveCount(3); }); } [Fact] public async Task Cannot_remove_for_missing_request_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string requestBody = string.Empty; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Failed to deserialize request body: Missing request body."); error.Detail.Should().BeNull(); error.Source.Should().BeNull(); error.Meta.Should().NotContainKey("requestBody"); } [Fact] public async Task Cannot_remove_for_null_request_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); const string requestBody = "null"; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected an object, instead of 'null'."); error.Detail.Should().BeNull(); error.Source.Should().BeNull(); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_remove_for_missing_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { id = existingWorkItem.Subscribers.ElementAt(0).StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data[0]"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_remove_for_unknown_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = Unknown.ResourceType, id = Unknown.StringId.For<UserAccount, long>() } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found."); error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data[0]/type"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_remove_for_missing_ID() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts" } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'id' element is required."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data[0]"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_remove_unknown_IDs_from_OneToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string userAccountId1 = Unknown.StringId.For<UserAccount, long>(); string userAccountId2 = Unknown.StringId.AltFor<UserAccount, long>(); var requestBody = new { data = new[] { new { type = "userAccounts", id = userAccountId1 }, new { type = "userAccounts", id = userAccountId2 } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.ShouldHaveCount(2); ErrorObject error1 = responseDocument.Errors[0]; error1.StatusCode.Should().Be(HttpStatusCode.NotFound); error1.Title.Should().Be("A related resource does not exist."); error1.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId1}' in relationship 'subscribers' does not exist."); error1.Meta.Should().NotContainKey("requestBody"); ErrorObject error2 = responseDocument.Errors[1]; error2.StatusCode.Should().Be(HttpStatusCode.NotFound); error2.Title.Should().Be("A related resource does not exist."); error2.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId2}' in relationship 'subscribers' does not exist."); error2.Meta.Should().NotContainKey("requestBody"); } [Fact] public async Task Cannot_remove_unknown_IDs_from_ManyToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string tagId1 = Unknown.StringId.For<WorkTag, int>(); string tagId2 = Unknown.StringId.AltFor<WorkTag, int>(); var requestBody = new { data = new[] { new { type = "workTags", id = tagId1 }, new { type = "workTags", id = tagId2 } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/tags"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.ShouldHaveCount(2); ErrorObject error1 = responseDocument.Errors[0]; error1.StatusCode.Should().Be(HttpStatusCode.NotFound); error1.Title.Should().Be("A related resource does not exist."); error1.Detail.Should().Be($"Related resource of type 'workTags' with ID '{tagId1}' in relationship 'tags' does not exist."); error1.Meta.Should().NotContainKey("requestBody"); ErrorObject error2 = responseDocument.Errors[1]; error2.StatusCode.Should().Be(HttpStatusCode.NotFound); error2.Title.Should().Be("A related resource does not exist."); error2.Detail.Should().Be($"Related resource of type 'workTags' with ID '{tagId2}' in relationship 'tags' does not exist."); error2.Meta.Should().NotContainKey("requestBody"); } [Fact] public async Task Cannot_remove_from_unknown_resource_type_in_url() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingWorkItem.Subscribers.ElementAt(0).StringId } } }; string route = $"/{Unknown.ResourceType}/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Should().BeEmpty(); } [Fact] public async Task Cannot_remove_from_unknown_resource_ID_in_url() { // Arrange UserAccount existingSubscriber = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingSubscriber); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingSubscriber.StringId } } }; string workItemId = Unknown.StringId.For<WorkItem, int>(); string route = $"/workItems/{workItemId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist."); error.Source.Should().BeNull(); error.Meta.Should().NotContainKey("requestBody"); } [Fact] public async Task Cannot_remove_from_unknown_relationship_in_url() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = Unknown.StringId.For<UserAccount, long>() } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/{Unknown.Relationship}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested relationship does not exist."); error.Detail.Should().Be($"Resource of type 'workItems' does not contain a relationship named '{Unknown.Relationship}'."); error.Source.Should().BeNull(); error.Meta.Should().NotContainKey("requestBody"); } [Fact] public async Task Cannot_remove_for_relationship_mismatch_between_url_and_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingWorkItem.Subscribers.ElementAt(0).StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/tags"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Conflict); error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found."); error.Detail.Should().Be("Type 'userAccounts' is incompatible with type 'workTags' of relationship 'tags'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data[0]/type"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Can_remove_with_duplicates() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "userAccounts", id = existingWorkItem.Subscribers.ElementAt(0).StringId }, new { type = "userAccounts", id = existingWorkItem.Subscribers.ElementAt(0).StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Subscribers.ShouldHaveCount(1); workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(1).Id); }); } [Fact] public async Task Can_remove_with_empty_list() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = Array.Empty<object>() }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Subscribers.ShouldHaveCount(1); workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(0).Id); }); } [Fact] public async Task Cannot_remove_with_missing_data_in_OneToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/subscribers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required."); error.Detail.Should().BeNull(); error.Source.Should().BeNull(); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_remove_with_null_data_in_ManyToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object?)null }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/tags"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of 'null'."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_remove_with_object_data_in_ManyToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/tags"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of an object."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Can_remove_self_from_cyclic_OneToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Children = _fakers.WorkItem.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); existingWorkItem.Children.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "workItems", id = existingWorkItem.StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/children"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Children).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Children.ShouldHaveCount(1); workItemInDatabase.Children[0].Id.Should().Be(existingWorkItem.Children[0].Id); }); } [Fact] public async Task Can_remove_self_from_cyclic_ManyToMany_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.RelatedFrom = _fakers.WorkItem.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); existingWorkItem.RelatedFrom.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "workItems", id = existingWorkItem.StringId } } }; string route = $"/workItems/{existingWorkItem.StringId}/relationships/relatedFrom"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true WorkItem workItemInDatabase = await dbContext.WorkItems .Include(workItem => workItem.RelatedFrom) .Include(workItem => workItem.RelatedTo) .FirstWithIdAsync(existingWorkItem.Id); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore workItemInDatabase.RelatedFrom.ShouldHaveCount(1); workItemInDatabase.RelatedFrom[0].Id.Should().Be(existingWorkItem.RelatedFrom[0].Id); workItemInDatabase.RelatedTo.Should().BeEmpty(); }); } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class RemoveExtraFromWorkItemDefinition : JsonApiResourceDefinition<WorkItem, int> { // Enables to verify that not the full relationship was loaded upfront. public ISet<UserAccount> PreloadedSubscribers { get; } = new HashSet<UserAccount>(IdentifiableComparer.Instance); public ISet<WorkTag> PreloadedTags { get; } = new HashSet<WorkTag>(IdentifiableComparer.Instance); // Enables to verify that adding extra IDs for removal from ResourceDefinition works correctly. public ISet<long> ExtraSubscribersIdsToRemove { get; } = new HashSet<long>(); public ISet<int> ExtraTagIdsToRemove { get; } = new HashSet<int>(); public RemoveExtraFromWorkItemDefinition(IResourceGraph resourceGraph) : base(resourceGraph) { } public void Reset() { PreloadedSubscribers.Clear(); PreloadedTags.Clear(); ExtraSubscribersIdsToRemove.Clear(); ExtraTagIdsToRemove.Clear(); } public override Task OnRemoveFromRelationshipAsync(WorkItem workItem, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { if (hasManyRelationship.Property.Name == nameof(WorkItem.Subscribers)) { RemoveFromSubscribers(workItem, rightResourceIds); } else if (hasManyRelationship.Property.Name == nameof(WorkItem.Tags)) { RemoveFromTags(workItem, rightResourceIds); } return Task.CompletedTask; } private void RemoveFromSubscribers(WorkItem workItem, ISet<IIdentifiable> rightResourceIds) { if (!workItem.Subscribers.IsNullOrEmpty()) { PreloadedSubscribers.AddRange(workItem.Subscribers); } foreach (long subscriberId in ExtraSubscribersIdsToRemove) { rightResourceIds.Add(new UserAccount { Id = subscriberId }); } } private void RemoveFromTags(WorkItem workItem, ISet<IIdentifiable> rightResourceIds) { if (!workItem.Tags.IsNullOrEmpty()) { PreloadedTags.AddRange(workItem.Tags); } foreach (int tagId in ExtraTagIdsToRemove) { rightResourceIds.Add(new WorkTag { Id = tagId }); } } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /** * standard vector test for SHA-384 from FIPS Draft 180-2. * * Note, the first two vectors are _not_ from the draft, the last three are. */ [TestFixture] public class Sha384DigestTest : ITest { // static private string testVec1 = ""; static private string resVec1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"; static private string testVec2 = "61"; static private string resVec2 = "54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31"; static private string testVec3 = "616263"; static private string resVec3 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"; static private string testVec4 = "61626364656667686263646566676869636465666768696a6465666768696a6b65666768696a6b6c666768696a6b6c6d6768696a6b6c6d6e68696a6b6c6d6e6f696a6b6c6d6e6f706a6b6c6d6e6f70716b6c6d6e6f7071726c6d6e6f707172736d6e6f70717273746e6f707172737475"; static private string resVec4 = "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039"; // 1 million 'a' static private string testVec5 = "61616161616161616161"; static private string resVec5 = "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"; public string Name { get { return "SHA384"; } } public ITestResult Perform() { IDigest digest = new Sha384Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; string resStr; // // test 1 // digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec1.Equals(resStr)) { return new SimpleTestResult(false, "SHA-384 failing standard vector test 1" + SimpleTest.NewLine + " expected: " + resVec1 + SimpleTest.NewLine + " got : " + resStr); } // // test 2 // byte[] bytes = Hex.Decode(testVec2); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec2.Equals(resStr)) { return new SimpleTestResult(false, "SHA-384 failing standard vector test 2" + SimpleTest.NewLine + " expected: " + resVec2 + SimpleTest.NewLine + " got : " + resStr); } // // test 3 // bytes = Hex.Decode(testVec3); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec3.Equals(resStr)) { return new SimpleTestResult(false, "SHA-384 failing standard vector test 3" + SimpleTest.NewLine + " expected: " + resVec3 + SimpleTest.NewLine + " got : " + resStr); } // // test 4 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "SHA-384 failing standard vector test 4" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } // // test 5 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length/2); // clone the IDigest IDigest d = new Sha384Digest((Sha384Digest)digest); digest.BlockUpdate(bytes, bytes.Length/2, bytes.Length - bytes.Length/2); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "SHA384 failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } d.BlockUpdate(bytes, bytes.Length/2, bytes.Length - bytes.Length/2); d.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "SHA384 failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } // test 6 bytes = Hex.Decode(testVec5); for ( int i = 0; i < 100000; i++ ) { digest.BlockUpdate(bytes, 0, bytes.Length); } digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec5.Equals(resStr)) { return new SimpleTestResult(false, "SHA-384 failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec5 + SimpleTest.NewLine + " got : " + resStr); } return new SimpleTestResult(true, Name + ": Okay"); } public static void Main( string[] args) { ITest test = new Sha384DigestTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using Prism.Properties; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Prism.Modularity { /// <summary> /// Represents a group of <see cref="ModuleInfo"/> instances that are usually deployed together. <see cref="ModuleInfoGroup"/>s /// are also used by the <see cref="ModuleCatalog"/> to prevent common deployment problems such as having a module that's required /// at startup that depends on modules that will only be downloaded on demand. /// /// The group also forwards <see cref="Ref"/> and <see cref="InitializationMode"/> values to the <see cref="ModuleInfo"/>s that it /// contains. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class ModuleInfoGroup : IModuleCatalogItem, IList<ModuleInfo>, IList // IList must be supported in Silverlight 2 to be able to add items from XAML { private readonly Collection<ModuleInfo> modules = new Collection<ModuleInfo>(); /// <summary> /// Gets or sets the <see cref="ModuleInfo.InitializationMode"/> for the whole group. Any <see cref="ModuleInfo"/> classes that are /// added after setting this value will also get this <see cref="InitializationMode"/>. /// </summary> /// <see cref="ModuleInfo.InitializationMode"/> /// <value>The initialization mode.</value> public InitializationMode InitializationMode { get; set; } /// <summary> /// Gets or sets the <see cref="ModuleInfo.Ref"/> value for the whole group. Any <see cref="ModuleInfo"/> classes that are /// added after setting this value will also get this <see cref="Ref"/>. /// /// The ref value will also be used by the <see cref="IModuleManager"/> to determine which <see cref="IModuleTypeLoader"/> to use. /// For example, using an "file://" prefix with a valid URL will cause the FileModuleTypeLoader to be used /// (Only available in the desktop version of CAL). /// </summary> /// <see cref="ModuleInfo.Ref"/> /// <value>The ref value that will be used.</value> public string Ref { get; set; } /// <summary> /// Adds an <see cref="ModuleInfo"/> moduleInfo to the <see cref="ModuleInfoGroup"/>. /// </summary> /// <param name="item">The <see cref="ModuleInfo"/> to the <see cref="ModuleInfoGroup"/>.</param> public void Add(ModuleInfo item) { this.ForwardValues(item); this.modules.Add(item); } /// <summary> /// Forwards <see cref="InitializationMode"/> and <see cref="Ref"/> properties from this <see cref="ModuleInfoGroup"/> /// to <paramref name="moduleInfo"/>. /// </summary> /// <param name="moduleInfo">The module info to forward values to.</param> /// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="moduleInfo"/> is <see langword="null"/>.</exception> protected void ForwardValues(ModuleInfo moduleInfo) { if (moduleInfo == null) throw new ArgumentNullException(nameof(moduleInfo)); if (moduleInfo.Ref == null) { moduleInfo.Ref = this.Ref; } if (moduleInfo.InitializationMode == InitializationMode.WhenAvailable && this.InitializationMode != InitializationMode.WhenAvailable) { moduleInfo.InitializationMode = this.InitializationMode; } } /// <summary> /// Removes all <see cref="ModuleInfo"/>s from the <see cref="ModuleInfoGroup"/>. /// </summary> public void Clear() { this.modules.Clear(); } /// <summary> /// Determines whether the <see cref="ModuleInfoGroup"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ModuleInfoGroup"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ModuleInfoGroup"/>; otherwise, false. /// </returns> public bool Contains(ModuleInfo item) { return this.modules.Contains(item); } /// <summary> /// Copies the elements of the <see cref="ModuleInfoGroup"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="ModuleInfoGroup"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="arrayIndex"/> is less than 0. /// </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional. /// -or- /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="ModuleInfoGroup"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>. /// </exception> public void CopyTo(ModuleInfo[] array, int arrayIndex) { this.modules.CopyTo(array, arrayIndex); } /// <summary> /// Gets the number of elements contained in the <see cref="ModuleInfoGroup"/>. /// </summary> /// <value></value> /// <returns> /// The number of elements contained in the <see cref="ModuleInfoGroup"/>. /// </returns> public int Count { get { return this.modules.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="ModuleInfoGroup"/> is read-only. /// </summary> /// <value></value> /// <returns>false, because the <see cref="ModuleInfoGroup"/> is not Read-Only. /// </returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ModuleInfoGroup"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="ModuleInfoGroup"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ModuleInfoGroup"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ModuleInfoGroup"/>. /// </returns> public bool Remove(ModuleInfo item) { return this.modules.Remove(item); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<ModuleInfo> GetEnumerator() { return this.modules.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Adds an item to the <see cref="ModuleInfoGroup"/>. /// </summary> /// <param name="value"> /// The <see cref="T:System.Object"/> to add to the <see cref="ModuleInfoGroup"/>. /// Must be of type <see cref="ModuleInfo"/> /// </param> /// <returns> /// The position into which the new element was inserted. /// </returns> int IList.Add(object value) { this.Add((ModuleInfo)value); return 1; } /// <summary> /// Determines whether the <see cref="ModuleInfoGroup"/> contains a specific value. /// </summary> /// <param name="value"> /// The <see cref="T:System.Object"/> to locate in the <see cref="ModuleInfoGroup"/>. /// Must be of type <see cref="ModuleInfo"/> /// </param> /// <returns> /// true if the <see cref="T:System.Object"/> is found in the <see cref="ModuleInfoGroup"/>; otherwise, false. /// </returns> bool IList.Contains(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); ModuleInfo moduleInfo = value as ModuleInfo; if (moduleInfo == null) throw new ArgumentException(Resources.ValueMustBeOfTypeModuleInfo, nameof(value)); return this.Contains(moduleInfo); } /// <summary> /// Determines the index of a specific item in the <see cref="ModuleInfoGroup"/>. /// </summary> /// <param name="value"> /// The <see cref="T:System.Object"/> to locate in the <see cref="ModuleInfoGroup"/>. /// Must be of type <see cref="ModuleInfo"/> /// </param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> public int IndexOf(object value) { return this.modules.IndexOf((ModuleInfo)value); } /// <summary> /// Inserts an item to the <see cref="ModuleInfoGroup"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value"> /// The <see cref="T:System.Object"/> to insert into the <see cref="ModuleInfoGroup"/>. /// Must be of type <see cref="ModuleInfo"/> /// </param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="ModuleInfoGroup"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="value"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="value"/> is not of type <see cref="ModuleInfo"/> /// </exception> public void Insert(int index, object value) { if (value == null) throw new ArgumentNullException(nameof(value)); ModuleInfo moduleInfo = value as ModuleInfo; if (moduleInfo == null) throw new ArgumentException(Resources.ValueMustBeOfTypeModuleInfo, nameof(value)); this.modules.Insert(index, moduleInfo); } /// <summary> /// Gets a value indicating whether the <see cref="ModuleInfoGroup"/> has a fixed size. /// </summary> /// <returns>false, because the <see cref="ModuleInfoGroup"/> does not have a fixed length. /// </returns> public bool IsFixedSize { get { return false; } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ModuleInfoGroup"/>. /// </summary> /// <param name="value"> /// The <see cref="T:System.Object"/> to remove from the <see cref="ModuleInfoGroup"/>. /// Must be of type <see cref="ModuleInfo"/> /// </param> void IList.Remove(object value) { this.Remove((ModuleInfo)value); } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public void RemoveAt(int index) { this.modules.RemoveAt(index); } /// <summary> /// Gets or sets the <see cref="System.Object"/> at the specified index. /// </summary> /// <value></value> object IList.this[int index] { get { return this[index]; } set { this[index] = (ModuleInfo)value; } } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than zero. /// </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional. /// -or- /// <paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { ((ICollection)this.modules).CopyTo(array, index); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe). /// </summary> /// <value></value> /// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false. /// </returns> public bool IsSynchronized { get { return ((ICollection)this.modules).IsSynchronized; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <value></value> /// <returns> /// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </returns> public object SyncRoot { get { return ((ICollection)this.modules).SyncRoot; } } /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> public int IndexOf(ModuleInfo item) { return this.modules.IndexOf(item); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception> public void Insert(int index, ModuleInfo item) { this.modules.Insert(index, item); } /// <summary> /// Gets or sets the <see cref="ModuleInfo"/> at the specified index. /// </summary> /// <value>The <see cref="ModuleInfo"/> at the specified index </value> public ModuleInfo this[int index] { get { return this.modules[index]; } set { this.modules[index] = value; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ServicoDeBooking.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using Boo.Lang.Compiler.TypeSystem; namespace Boo.Lang.Compiler.Steps { using Boo.Lang.Compiler.Ast; //TODO: constant propagation (which allows precise unreachable branch detection) public class ConstantFolding : AbstractTransformerCompilerStep { public const string FoldedExpression = "foldedExpression"; override public void Run() { if (Errors.Count > 0) return; Visit(CompileUnit); } override public void OnModule(Module node) { Visit(node.Members); } object GetLiteralValue(Expression node) { switch (node.NodeType) { case NodeType.CastExpression: return GetLiteralValue(((CastExpression) node).Target); case NodeType.BoolLiteralExpression: return ((BoolLiteralExpression) node).Value; case NodeType.IntegerLiteralExpression: return ((IntegerLiteralExpression) node).Value; case NodeType.DoubleLiteralExpression: return ((DoubleLiteralExpression) node).Value; case NodeType.MemberReferenceExpression: { IField field = node.Entity as IField; if (null != field && field.IsLiteral) { if (field.Type.IsEnum) { object o = field.StaticValue; if (null != o && o != Error.Default) return o; } else { Expression e = field.StaticValue as Expression; return (null != e) ? GetLiteralValue(e) : field.StaticValue; } } break; } } return null; } override public void LeaveEnumMember(EnumMember node) { if (node.Initializer.NodeType == NodeType.IntegerLiteralExpression) return; IType type = node.Initializer.ExpressionType; if (null != type && (TypeSystemServices.IsIntegerNumber(type) || type.IsEnum)) { object val = GetLiteralValue(node.Initializer); if (null != val && val != Error.Default) node.Initializer = new IntegerLiteralExpression(Convert.ToInt64(val)); } return; } override public void LeaveBinaryExpression(BinaryExpression node) { if (AstUtil.GetBinaryOperatorKind(node.Operator) == BinaryOperatorKind.Assignment || node.Operator == BinaryOperatorType.ReferenceEquality || node.Operator == BinaryOperatorType.ReferenceInequality) return; if (null == node.Left.ExpressionType || null == node.Right.ExpressionType) return; object lhs = GetLiteralValue(node.Left); object rhs = GetLiteralValue(node.Right); if (null == lhs || null == rhs) return; Expression folded = null; IType lhsType = GetExpressionType(node.Left); IType rhsType = GetExpressionType(node.Right); if (TypeSystemServices.BoolType == lhsType && TypeSystemServices.BoolType == rhsType) { folded = GetFoldedBoolLiteral(node.Operator, Convert.ToBoolean(lhs), Convert.ToBoolean(rhs)); } else if (TypeSystemServices.DoubleType == lhsType || TypeSystemServices.SingleType == lhsType || TypeSystemServices.DoubleType == rhsType || TypeSystemServices.SingleType == rhsType) { folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(lhs), Convert.ToDouble(rhs)); } else if (TypeSystemServices.IsIntegerNumber(lhsType) || lhsType.IsEnum) { bool lhsSigned = TypeSystemServices.IsSignedNumber(lhsType); bool rhsSigned = TypeSystemServices.IsSignedNumber(rhsType); if (lhsSigned == rhsSigned) //mixed signed/unsigned not supported for folding { folded = lhsSigned ? GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(lhs), Convert.ToInt64(rhs)) : GetFoldedIntegerLiteral(node.Operator, Convert.ToUInt64(lhs), Convert.ToUInt64(rhs)); } } if (null != folded) { folded.LexicalInfo = node.LexicalInfo; folded.ExpressionType = GetExpressionType(node); folded.Annotate(FoldedExpression, node); ReplaceCurrentNode(folded); } } override public void LeaveUnaryExpression(UnaryExpression node) { if (node.Operator == UnaryOperatorType.Explode || node.Operator == UnaryOperatorType.AddressOf || node.Operator == UnaryOperatorType.Indirection || node.Operator == UnaryOperatorType.LogicalNot) return; if (null == node.Operand.ExpressionType) return; object operand = GetLiteralValue(node.Operand); if (null == operand) return; Expression folded = null; IType operandType = GetExpressionType(node.Operand); if (TypeSystemServices.DoubleType == operandType || TypeSystemServices.SingleType == operandType) { folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(operand)); } else if (TypeSystemServices.IsIntegerNumber(operandType) || operandType.IsEnum) { folded = GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(operand)); } if (null != folded) { folded.LexicalInfo = node.LexicalInfo; folded.ExpressionType = GetExpressionType(node); ReplaceCurrentNode(folded); } } static BoolLiteralExpression GetFoldedBoolLiteral(BinaryOperatorType @operator, bool lhs, bool rhs) { bool result; switch (@operator) { //comparison case BinaryOperatorType.Equality: result = (lhs == rhs); break; case BinaryOperatorType.Inequality: result = (lhs != rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; //logical case BinaryOperatorType.And: result = lhs && rhs; break; case BinaryOperatorType.Or: result = lhs || rhs; break; default: return null; //not supported } return new BoolLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, long lhs, long rhs) { long result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = (long) Math.Pow(lhs, rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; case BinaryOperatorType.ShiftLeft: result = lhs << (int) rhs; break; case BinaryOperatorType.ShiftRight: result = lhs >> (int) rhs; break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new IntegerLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, ulong lhs, ulong rhs) { ulong result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = (ulong) Math.Pow(lhs, rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; case BinaryOperatorType.ShiftLeft: result = lhs << (int) rhs; break; case BinaryOperatorType.ShiftRight: result = lhs >> (int) rhs; break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new IntegerLiteralExpression((long) result); } static LiteralExpression GetFoldedDoubleLiteral(BinaryOperatorType @operator, double lhs, double rhs) { double result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = Math.Pow(lhs, rhs); break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new DoubleLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(UnaryOperatorType @operator, long operand) { long result; switch (@operator) { case UnaryOperatorType.UnaryNegation: result = -operand; break; case UnaryOperatorType.OnesComplement: result = ~operand; break; default: return null; //not supported } return new IntegerLiteralExpression(result); } static LiteralExpression GetFoldedDoubleLiteral(UnaryOperatorType @operator, double operand) { double result; switch (@operator) { case UnaryOperatorType.UnaryNegation: result = -operand; break; default: return null; //not supported } return new DoubleLiteralExpression(result); } } }
/* * Copyright (c) 2013 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace MiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WORD_BREAK = "{}[],:\""; public static bool IsWordBreak(char c) { return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; } enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new char[4]; for (int i=0; i< 4; i++) { hex[i] = NextChar; } s.Append((char) Convert.ToInt32(new string(hex), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (Char.IsWhiteSpace(PeekChar)) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (!IsWordBreak(PeekChar)) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } switch (PeekChar) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } switch (NextWord) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append((bool) value ? "true" : "false"); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(new string((char) value, 1)); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u"); builder.Append(codepoint.ToString("x4")); } break; } } builder.Append('\"'); } void SerializeOther(object value) { // NOTE: decimals lose precision during serialization. // They always have, I'm just letting you know. // Previously floats and doubles lost precision too. if (value is float) { builder.Append(((float) value).ToString("R")); } else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) { builder.Append(value); } else if (value is double || value is decimal) { builder.Append(Convert.ToDouble(value).ToString("R")); } else { SerializeString(value.ToString()); } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure { /// <summary> /// The Service Management API provides programmatic access to much of the /// functionality available through the Management Portal. The Service /// Management API is a REST API. All API operations are performed over /// SSL, and are mutually authenticated using X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public static partial class VirtualMachineOSImageOperationsExtensions { /// <summary> /// Share an already replicated OS image. This operation is only for /// publishers. You have to be registered as image publisher with /// Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to share. /// </param> /// <param name='permission'> /// Required. The sharing permission: public, msdn, or private. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse BeginSharing(this IVirtualMachineOSImageOperations operations, string imageName, string permission) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).BeginSharingAsync(imageName, permission); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Share an already replicated OS image. This operation is only for /// publishers. You have to be registered as image publisher with /// Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to share. /// </param> /// <param name='permission'> /// Required. The sharing permission: public, msdn, or private. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> BeginSharingAsync(this IVirtualMachineOSImageOperations operations, string imageName, string permission) { return operations.BeginSharingAsync(imageName, permission, CancellationToken.None); } /// <summary> /// Unreplicate an OS image to multiple target locations. This /// operation is only for publishers. You have to be registered as /// image publisher with Windows Azure to be able to call this. Note: /// The operation removes the published copies of the user OS Image. /// It does not remove the actual user OS Image. To remove the actual /// user OS Image, the publisher will have to call Delete OS Image. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to replicate. Note: /// The OS Image Name should be the user OS Image, not the published /// name of the OS Image. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse BeginUnreplicating(this IVirtualMachineOSImageOperations operations, string imageName) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).BeginUnreplicatingAsync(imageName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unreplicate an OS image to multiple target locations. This /// operation is only for publishers. You have to be registered as /// image publisher with Windows Azure to be able to call this. Note: /// The operation removes the published copies of the user OS Image. /// It does not remove the actual user OS Image. To remove the actual /// user OS Image, the publisher will have to call Delete OS Image. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to replicate. Note: /// The OS Image Name should be the user OS Image, not the published /// name of the OS Image. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> BeginUnreplicatingAsync(this IVirtualMachineOSImageOperations operations, string imageName) { return operations.BeginUnreplicatingAsync(imageName, CancellationToken.None); } /// <summary> /// The Create OS Image operation adds an operating system image that /// is stored in a storage account and is available from the image /// repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Virtual Machine Image /// operation. /// </param> /// <returns> /// Parameters returned from the Create Virtual Machine Image operation. /// </returns> public static VirtualMachineOSImageCreateResponse Create(this IVirtualMachineOSImageOperations operations, VirtualMachineOSImageCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).CreateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Create OS Image operation adds an operating system image that /// is stored in a storage account and is available from the image /// repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Virtual Machine Image /// operation. /// </param> /// <returns> /// Parameters returned from the Create Virtual Machine Image operation. /// </returns> public static Task<VirtualMachineOSImageCreateResponse> CreateAsync(this IVirtualMachineOSImageOperations operations, VirtualMachineOSImageCreateParameters parameters) { return operations.CreateAsync(parameters, CancellationToken.None); } /// <summary> /// The Delete OS Image operation deletes the specified OS image from /// your image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the image to delete. /// </param> /// <param name='deleteFromStorage'> /// Required. Specifies that the source blob for the image should also /// be deleted from storage. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IVirtualMachineOSImageOperations operations, string imageName, bool deleteFromStorage) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).DeleteAsync(imageName, deleteFromStorage); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete OS Image operation deletes the specified OS image from /// your image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the image to delete. /// </param> /// <param name='deleteFromStorage'> /// Required. Specifies that the source blob for the image should also /// be deleted from storage. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IVirtualMachineOSImageOperations operations, string imageName, bool deleteFromStorage) { return operations.DeleteAsync(imageName, deleteFromStorage, CancellationToken.None); } /// <summary> /// The Get OS Image operation retrieves the details for an operating /// system image from the image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the OS image to retrieve. /// </param> /// <returns> /// A virtual machine image associated with your subscription. /// </returns> public static VirtualMachineOSImageGetResponse Get(this IVirtualMachineOSImageOperations operations, string imageName) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).GetAsync(imageName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get OS Image operation retrieves the details for an operating /// system image from the image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the OS image to retrieve. /// </param> /// <returns> /// A virtual machine image associated with your subscription. /// </returns> public static Task<VirtualMachineOSImageGetResponse> GetAsync(this IVirtualMachineOSImageOperations operations, string imageName) { return operations.GetAsync(imageName, CancellationToken.None); } /// <summary> /// Gets OS Image's properties and its replication details. This /// operation is only for publishers. You have to be registered as /// image publisher with Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to replicate. /// </param> /// <returns> /// The Get Details OS Images operation response. /// </returns> public static VirtualMachineOSImageGetDetailsResponse GetDetails(this IVirtualMachineOSImageOperations operations, string imageName) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).GetDetailsAsync(imageName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets OS Image's properties and its replication details. This /// operation is only for publishers. You have to be registered as /// image publisher with Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to replicate. /// </param> /// <returns> /// The Get Details OS Images operation response. /// </returns> public static Task<VirtualMachineOSImageGetDetailsResponse> GetDetailsAsync(this IVirtualMachineOSImageOperations operations, string imageName) { return operations.GetDetailsAsync(imageName, CancellationToken.None); } /// <summary> /// The List OS Images operation retrieves a list of the operating /// system images from the image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <returns> /// The List OS Images operation response. /// </returns> public static VirtualMachineOSImageListResponse List(this IVirtualMachineOSImageOperations operations) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List OS Images operation retrieves a list of the operating /// system images from the image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <returns> /// The List OS Images operation response. /// </returns> public static Task<VirtualMachineOSImageListResponse> ListAsync(this IVirtualMachineOSImageOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Replicate an OS image to multiple target locations. This operation /// is only for publishers. You have to be registered as image /// publisher with Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine OS image to replicate. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Replicate Virtual Machine /// Image operation. /// </param> /// <returns> /// The response body contains the published name of the image. /// </returns> public static VirtualMachineOSImageReplicateResponse Replicate(this IVirtualMachineOSImageOperations operations, string imageName, VirtualMachineOSImageReplicateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).ReplicateAsync(imageName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Replicate an OS image to multiple target locations. This operation /// is only for publishers. You have to be registered as image /// publisher with Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine OS image to replicate. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Replicate Virtual Machine /// Image operation. /// </param> /// <returns> /// The response body contains the published name of the image. /// </returns> public static Task<VirtualMachineOSImageReplicateResponse> ReplicateAsync(this IVirtualMachineOSImageOperations operations, string imageName, VirtualMachineOSImageReplicateParameters parameters) { return operations.ReplicateAsync(imageName, parameters, CancellationToken.None); } /// <summary> /// Share an already replicated OS image. This operation is only for /// publishers. You have to be registered as image publisher with /// Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to share. /// </param> /// <param name='permission'> /// Required. The sharing permission: public, msdn, or private. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static OperationStatusResponse Share(this IVirtualMachineOSImageOperations operations, string imageName, string permission) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).ShareAsync(imageName, permission); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Share an already replicated OS image. This operation is only for /// publishers. You have to be registered as image publisher with /// Windows Azure to be able to call this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to share. /// </param> /// <param name='permission'> /// Required. The sharing permission: public, msdn, or private. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<OperationStatusResponse> ShareAsync(this IVirtualMachineOSImageOperations operations, string imageName, string permission) { return operations.ShareAsync(imageName, permission, CancellationToken.None); } /// <summary> /// Unreplicate an OS image to multiple target locations. This /// operation is only for publishers. You have to be registered as /// image publisher with Windows Azure to be able to call this. Note: /// The operation removes the published copies of the user OS Image. /// It does not remove the actual user OS Image. To remove the actual /// user OS Image, the publisher will have to call Delete OS Image. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to replicate. Note: /// The OS Image Name should be the user OS Image, not the published /// name of the OS Image. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static OperationStatusResponse Unreplicate(this IVirtualMachineOSImageOperations operations, string imageName) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).UnreplicateAsync(imageName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unreplicate an OS image to multiple target locations. This /// operation is only for publishers. You have to be registered as /// image publisher with Windows Azure to be able to call this. Note: /// The operation removes the published copies of the user OS Image. /// It does not remove the actual user OS Image. To remove the actual /// user OS Image, the publisher will have to call Delete OS Image. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to replicate. Note: /// The OS Image Name should be the user OS Image, not the published /// name of the OS Image. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<OperationStatusResponse> UnreplicateAsync(this IVirtualMachineOSImageOperations operations, string imageName) { return operations.UnreplicateAsync(imageName, CancellationToken.None); } /// <summary> /// The Update OS Image operation updates an OS image that in your /// image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to be updated. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Virtual Machine Image /// operation. /// </param> /// <returns> /// Parameters returned from the Create Virtual Machine Image operation. /// </returns> public static VirtualMachineOSImageUpdateResponse Update(this IVirtualMachineOSImageOperations operations, string imageName, VirtualMachineOSImageUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IVirtualMachineOSImageOperations)s).UpdateAsync(imageName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Update OS Image operation updates an OS image that in your /// image repository. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOSImageOperations. /// </param> /// <param name='imageName'> /// Required. The name of the virtual machine image to be updated. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Virtual Machine Image /// operation. /// </param> /// <returns> /// Parameters returned from the Create Virtual Machine Image operation. /// </returns> public static Task<VirtualMachineOSImageUpdateResponse> UpdateAsync(this IVirtualMachineOSImageOperations operations, string imageName, VirtualMachineOSImageUpdateParameters parameters) { return operations.UpdateAsync(imageName, parameters, CancellationToken.None); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NPOI.HPSF { using System; using System.IO; using System.Collections; /// <summary> /// Provides various static utility methods. /// @author Rainer Klute (klute@rainer-klute.de) /// @since 2002-02-09 /// </summary> internal class Util { /// <summary> /// Copies a part of a byte array into another byte array. /// </summary> /// <param name="src">The source byte array.</param> /// <param name="srcOffSet">OffSet in the source byte array.</param> /// <param name="Length">The number of bytes To Copy.</param> /// <param name="dst">The destination byte array.</param> /// <param name="dstOffSet">OffSet in the destination byte array.</param> public static void Copy(byte[] src, int srcOffSet, int Length, byte[] dst, int dstOffSet) { for (int i = 0; i < Length; i++) dst[dstOffSet + i] = src[srcOffSet + i]; } /// <summary> /// Concatenates the contents of several byte arrays into a /// single one. /// </summary> /// <param name="byteArrays">The byte arrays To be conCatened.</param> /// <returns>A new byte array containing the conCatenated byte arrays.</returns> public static byte[] Cat(byte[][] byteArrays) { int capacity = 0; for (int i = 0; i < byteArrays.Length; i++) capacity += byteArrays[i].Length; byte[] result = new byte[capacity]; int r = 0; for (int i = 0; i < byteArrays.Length; i++) for (int j = 0; j < byteArrays[i].Length; j++) result[r++] = byteArrays[i][j]; return result; } /// <summary> /// Copies bytes from a source byte array into a new byte /// array. /// </summary> /// <param name="src">Copy from this byte array.</param> /// <param name="offset">Start Copying here.</param> /// <param name="Length">Copy this many bytes.</param> /// <returns>The new byte array. Its Length is number of copied bytes.</returns> public static byte[] Copy(byte[] src, int offset, int Length) { byte[] result = new byte[Length]; Copy(src, offset, Length, result, 0); return result; } /** * The difference between the Windows epoch (1601-01-01 * 00:00:00) and the Unix epoch (1970-01-01 00:00:00) in * milliseconds: 11644473600000L. (Use your favorite spReadsheet * program To verify the correctness of this value. By the way, * did you notice that you can tell from the epochs which * operating system is the modern one? :-)) */ public static long EPOCH_DIFF = new DateTime(1970, 1, 1).Ticks; //11644473600000L; /// <summary> /// Converts a Windows FILETIME into a {@link DateTime}. The Windows /// FILETIME structure holds a DateTime and time associated with a /// file. The structure identifies a 64-bit integer specifying the /// number of 100-nanosecond intervals which have passed since /// January 1, 1601. This 64-bit value is split into the two double /// words stored in the structure. /// </summary> /// <param name="high">The higher double word of the FILETIME structure.</param> /// <param name="low">The lower double word of the FILETIME structure.</param> /// <returns>The Windows FILETIME as a {@link DateTime}.</returns> public static DateTime FiletimeToDate(int high, int low) { long filetime = ((long)high << 32) | ((long)low & 0xffffffffL); return FiletimeToDate(filetime); } /// <summary> /// Converts a Windows FILETIME into a {@link DateTime}. The Windows /// FILETIME structure holds a DateTime and time associated with a /// file. The structure identifies a 64-bit integer specifying the /// number of 100-nanosecond intervals which have passed since /// January 1, 1601. /// </summary> /// <param name="filetime">The filetime To Convert.</param> /// <returns>The Windows FILETIME as a {@link DateTime}.</returns> public static DateTime FiletimeToDate(long filetime) { return DateTime.FromFileTime(filetime); //long ms_since_16010101 = filetime / (1000 * 10); //long ms_since_19700101 = ms_since_16010101 -EPOCH_DIFF; //return new DateTime(ms_since_19700101); } /// <summary> /// Converts a {@link DateTime} into a filetime. /// </summary> /// <param name="dateTime">The DateTime To be Converted</param> /// <returns>The filetime</returns> public static long DateToFileTime(DateTime dateTime) { //long ms_since_19700101 = DateTime.Ticks; //long ms_since_16010101 = ms_since_19700101 + EPOCH_DIFF; //return ms_since_16010101 * (1000 * 10); return dateTime.ToFileTime(); } /// <summary> /// Compares To object arrays with regarding the objects' order. For /// example, [1, 2, 3] and [2, 1, 3] are equal. /// </summary> /// <param name="c1">The first object array.</param> /// <param name="c2">The second object array.</param> /// <returns><c>true</c> /// if the object arrays are equal, /// <c>false</c> /// if they are not.</returns> public static bool AreEqual(IList c1, IList c2) { return internalEquals(c1, c2); } /// <summary> /// Internals the equals. /// </summary> /// <param name="c1">The c1.</param> /// <param name="c2">The c2.</param> /// <returns></returns> private static bool internalEquals(IList c1, IList c2) { IEnumerator o1 = c1.GetEnumerator(); while( o1.MoveNext()) { Object obj1 = o1.Current; bool matchFound = false; IEnumerator o2 = c2.GetEnumerator(); while( !matchFound && o2.MoveNext()) { Object obj2 = o2.Current; if (obj1.Equals(obj2)) { matchFound = true; //o2[i2] = null; } } if (!matchFound) return false; } return true; } /// <summary> /// Pads a byte array with 0x00 bytes so that its Length is a multiple of /// 4. /// </summary> /// <param name="ba">The byte array To pad.</param> /// <returns>The padded byte array.</returns> public static byte[] Pad4(byte[] ba) { int PAD = 4; byte[] result; int l = ba.Length % PAD; if (l == 0) result = ba; else { l = PAD - l; result = new byte[ba.Length+l ]; Array.Copy(ba,result, ba.Length); } return result; } /// <summary> /// Pads a character array with 0x0000 characters so that its Length is a /// multiple of 4. /// </summary> /// <param name="ca">The character array To pad.</param> /// <returns>The padded character array.</returns> public static char[] Pad4(char[] ca) { int PAD = 4; char[] result; int l = ca.Length % PAD; if (l == 0) result = ca; else { l = PAD - l; result = new char[ca.Length+l]; Array.Copy(ca, result, ca.Length); } return result; } /// <summary> /// Pads a string with 0x0000 characters so that its Length is a /// multiple of 4. /// </summary> /// <param name="s">The string To pad.</param> /// <returns> The padded string as a character array.</returns> public static char[] Pad4(String s) { return Pad4(s.ToCharArray()); } } }
//------------------------------------------------------------------------------ // radar.cs // A fully clientside radar that displays objects relative to your own player // position and indicates whether or not they are above, below or on-altitude // with you as well as hostile status. // Copyright (c) 2016 Robert MacGregor //============================================================================== // Update rate in milliseconds. This controls the rotational aspect of the // radar. $Radar::UpdateTime = 34; // Marker update rate in milliseconds. This controls the marker position updates // relative to your player object. $Radar::MarkerUpdateTime = 32; // The effective distance in meters. $Radar::Distance = 300; // How much distance each individual pixel should represent in meters. $Radar::PixelDistance = 2.3; // Whether or not the radar should consider player rotation when operating. $Radar::Rotates = true; // An angle in radians representing where forward is relative to your screen. By // default this is 3.14159 / 2 so that up = forward. $Radar::Facing = 3.14159 / 2; // The threshold at which we consider things to be on the same height as us on // radar so that < threshold is below, > threshold is above and in between is on // on altitude. $Radar::HeightThreshold = 10; // The types of objects to search for. This is a constant as none of the other types are really applicanble. $Radar::SearchTypes = $TypeMasks::PlayerObjectType | $TypeMasks::VehicleObjectType; exec("libs/types/array.cs"); function apply_SIPatch() { memPatch("58B26D", "cc9c"); memPatch("4376B7", "9090"); memPatch("43745D", "9090"); memPatch("42E938", "9090"); memPatch("5E2EEC", "9090"); memPatch("602AF3", "9090"); memPatch("58C24C", "9090"); memPatch("6B40D0", "9090"); memPatch("5E34B6", "9090909090909090909090909090909090909090909090909090"); // Clientside Radius Checks memPatch("58b142","cc9c9e"); memPatch("58b162","cc9c9e"); memPatch("58b162","cc9c9e"); memPatch("58b182","cc9c9e"); memPatch("58b1a2","cc9c9e"); memPatch("58b26D","cc9c9e"); } //------------------------------------------------------------------------------ // Description: Primary update function for the clientside radar. This is called // once per $Radar::UpdateTime ms via its own schedule thread once called. If // a thread already exists, it is reset while the update function is called // normally. //============================================================================== function Radar::update(%this) { if (isEventPending(%this.updateHandle)) cancel(%this.updateHandle); %this.targets.clear(); %controlled = ServerConnection.getControlObject(); %position = %controlled.getPosition(); // Grab a list of potential objects in ServerConnection InitContainerRadiusSearch(%position, $Radar::Distance, $Radar::SearchTypes); while (isObject(%object = ContainerSearchNext())) if (%object.getState() $= "Move") %this.targets.add(%object); %this.paintTargets(); %this.updateHandle = %this.schedule($Radar::UpdateTime, "update"); } //------------------------------------------------------------------------------ // Description: Update function for the individual markers on radar. This is // called once per $Radar::MarkerUpdateTime ms via its own schedule thread // once called. If a thread already exists, it is reset while the update // function is called normally. When in operation, this function controls the // marker positions relative to your own player facing. //============================================================================== function Radar::updateMarkers(%this) { if (isEventPending(%this.markerUpdateHandle)) cancel(%this.markerUpdateHandle); if (!$Radar::Rotates) { %this.markerUpdateHandle = %this.schedule($Radar::MarkerUpdateTime, "updateMarkers"); return; } %controlled = ServerConnection.getControlObject(); %direction = getWords(%controlled.getForwardVector(), 0, 1); %directionX = getWord(%direction, 0); %directionY = getWord(%direction, 1); %angle = 0; if ($Radar::Rotates) %angle = mATan(%directionY, %directionX); %angle += $Radar::Facing; %center = %this.centerX SPC %this.centerY; // Loop for each marker that's visible for (%iteration = 0; %iteration < %this.markers.length; %iteration++) { %marker = %this.markers.element[%iteration]; if (%marker.isUsed) { %marker.setVisible(true); %relative = vectorSub(%center, %marker.realPosition); %relativeNorm = vectorNormalize(%relative); %magnitude = vectorLen(%relative); %relativeNormX = getWord(%relativeNorm, 0); %relativeNormY = getWord(%relativeNorm, 1); %relativeNorm = (%relativeNormX * mCos(%angle) - %relativeNormY * mSin(%angle)) SPC (%relativeNormX * mSin(%angle) + %relativeNormY * mCos(%angle)); %relative = vectorScale(%relativeNorm, %magnitude); %marker.setPosition(getWord(%relative, 0) + %this.centerX, getWord(%relative, 1) + %this.centerY); } } %this.markerUpdateHandle = %this.schedule($Radar::MarkerUpdateTime, "updateMarkers"); } //------------------------------------------------------------------------------ // Description: Populates the radar with marker objects to use as well as // centering the radar somewhere on your game screen. // Parameter %centerX: The X coordinate on screen to center upon. // Parameter %centerY: THe Y coordinate on screen to center upon. //============================================================================== function Radar::addMarkers(%this, %centerX, %centerY) { %this.markers.clear(); %this.centerX = %centerX; %this.centerY = %centerY; %this.centerMarker = new GuiBitmapCtrl() { bitmap = "radar"; }; PlayGUI.add(%this.centerMarker); %this.centerMarker.setExtent(300, 300); %halfExtent = vectorScale(%this.centerMarker.getExtent(), 0.5); %centerX = %centerX - getWord(%halfExtent, 0); %centerY = %centerY - getWord(%halfExtent, 1); %this.centerMarker.setPosition(%centerX, %centerY); for (%iteration = 0; %iteration < 10; %iteration++) { %marker = new GuiBitmapCtrl() { profile = HostileProfile; bitmap = "hostile_up"; }; PlayGUI.add(%marker); %marker.setVisible(false); %marker.setExtent(20, 20); %this.markers.add(%marker); } } //------------------------------------------------------------------------------ // Description: Locates targets that are within $Radar::Distance meters of // the player and paints them onto the radar by selecting unused markers. //============================================================================== function Radar::paintTargets(%this) { %controlled = ServerConnection.getControlObject(); %position = %controlled.getPosition(); // Set all markers to be unused by default, which controls visible status for (%iteration = 0; %iteration < %this.markers.length; %iteration++) %this.markers.element[%iteration].isUsed = false; for (%iteration = 0; %iteration < %this.targets.length; %iteration++) { %object = %this.targets.element[%iteration]; // Figure out where they are relative to us %relative = vectorSub(%position, %object.getPosition()); %relativeDist = vectorLen(%relative); %relativeNorm = vectorNormalize(%relative); // Translate their distance into pixel values %magnitude = %relativeDist / $Radar::PixelDistance; // Rotate the relative normal by our facing %relativeNormX = getWord(%relativeNorm, 0); %relativeNormY = getWord(%relativeNorm, 1); // TODO: Perform a sanity check to ensure that these dots are actually on radar // This can happen if our pixel distance doesn't divide evenly into our on-screen // radar dimensions %extent = %this.centerMarker.getExtent(); if (%magnitude > getWord(%extent, 0) || %magnitude > getWord(%extent, 1)) continue; // We project this entity onto the screen as a position relative to our radar center %radarPosition = vectorScale(%relativeNorm, %magnitude); if (%iteration < %this.markers.length) { %marker = %this.markers.element[%iteration]; %marker.isUsed = true; %radarPositionX = -getWord(%radarPosition, 0); %radarPositionY = getWord(%radarPosition, 1); %realPosition = (%radarPositionX + %this.centerX) SPC (%radarPositionY + %this.centerY); // Center it %realPosition = vectorSub(%realPosition, vectorScale(%marker.getExtent(), 0.5)); %marker.realPosition = %realPosition; //%marker.setPosition(getWord(%realPosition, 0), getWord(%realPosition, 1)); %marker.setProfile(NeutralProfile); %relation = 1; %heightDifference = getWord(%object.getPosition(), 2) - getWord(%position, 2); %direction = "level"; if (%heightDifference > $Radar::HeightThreshold) %direction = "up"; else if (%heightDifference < -$Radar::HeightThreshold) %direction = "down"; switch(%relation) { case 0: // Neutral %marker.setBitmap("neutral_" @ %direction); case 1: // Friendly %marker.setBitmap("friendly_" @ %direction); case -1: // Hostile %marker.setBitmap("hostile_" @ %direction); } } } for (%iteration = 0; %iteration < %this.markers.length; %iteration++) if (!%this.markers.element[%iteration].isUsed) %this.markers.element[%iteration].setVisible(false); } if (!isObject(Radar)) new ScriptObject(Radar) { class = "Radar"; targets = Array.create(); markers = Array.create(); };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddSByte() { var test = new SimpleBinaryOpTest__AddSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.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 (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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__AddSByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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 Vector64<SByte> _fld1; public Vector64<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddSByte testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector64<SByte> _clsVar1; private static Vector64<SByte> _clsVar2; private Vector64<SByte> _fld1; private Vector64<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleBinaryOpTest__AddSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_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 = AdvSimd.Add( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_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(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) fixed (Vector64<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((SByte*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(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<Vector64<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddSByte(); var result = AdvSimd.Add(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__AddSByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(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 = AdvSimd.Add(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 = AdvSimd.Add( AdvSimd.LoadVector64((SByte*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&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(Vector64<SByte> op1, Vector64<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((sbyte)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((sbyte)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<SByte>(Vector64<SByte>, Vector64<SByte>): {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; } } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Linq; using NetGore.IO; using NetGore.World; using SFML.Graphics; namespace NetGore.Graphics { /// <summary> /// Creates a grid of uniform size that can be drawn to the screen. /// </summary> public class ScreenGrid : IPersistable { Color _color = new Color(255, 255, 255, 75); Vector2 _size = new Vector2(32); /// <summary> /// Gets or sets the color of the grid lines. /// </summary> [SyncValue] public Color Color { get { return _color; } set { _color = value; } } /// <summary> /// Gets or sets the height of the grid in pixels. Must be greater than zero. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than /// or equal to zero.</exception> [Browsable(false)] public float Height { get { return Size.Y; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value", "Height must be greater than 0."); _size.Y = value; } } /// <summary> /// Gets or sets the size of the <see cref="ScreenGrid"/>. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Either the X or Y on the <paramref name="value"/> is less than /// or equal to zero.</exception> [SyncValue] public Vector2 Size { get { return _size; } set { if (value.X <= 0 || value.Y <= 0) throw new ArgumentOutOfRangeException("value", "Size's X and Y both must be greater than 0."); _size = value; } } /// <summary> /// Gets or sets the width of the grid in pixels. Must be greater than zero. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than /// or equal to zero.</exception> [Browsable(false)] public float Width { get { return Size.X; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value", "Width must be greater than 0."); _size.X = value; } } /// <summary> /// Aligns an object's position to the grid. /// </summary> /// <param name="entity">The <see cref="Entity"/> to edit.</param> public void Align(Entity entity) { if (entity == null) { Debug.Fail("entity is null."); return; } var x = (float)(Math.Round(entity.Position.X / Width)) * Width; var y = (float)(Math.Round(entity.Position.Y / Height)) * Height; entity.Position = new Vector2(x, y); } /// <summary> /// Aligns a position to the grid, forcing rounding down. /// </summary> /// <param name="pos">Vector position to align to the grid.</param> /// <returns>Vector aligned to the grid.</returns> public Vector2 AlignDown(Vector2 pos) { var x = (float)(Math.Floor(pos.X / Width) * Width); var y = (float)(Math.Floor(pos.Y / Height) * Height); return new Vector2(x, y); } /// <summary> /// Draws the grid. /// </summary> /// <param name="sb">The <see cref="ISpriteBatch"/> to draw to.</param> /// <param name="camera">The <see cref="Camera2D"/> describing the view.</param> public void Draw(ISpriteBatch sb, ICamera2D camera) { if (sb == null) { Debug.Fail("sb is null."); return; } if (sb.IsDisposed) { Debug.Fail("sb is disposed."); return; } if (camera == null) { Debug.Fail("camera is null."); return; } var p1 = new Vector2(); var p2 = new Vector2(); var min = camera.Min; var max = camera.Max; var size = camera.Size; min -= new Vector2(min.X % Size.X, min.Y % Size.Y); // Vertical lines p1.Y = (float)Math.Round(min.Y); p2.Y = (float)Math.Round(p1.Y + size.Y + 32); for (var x = min.X; x < max.X; x += Size.X) { p1.X = (float)Math.Round(x); p2.X = (float)Math.Round(x); RenderLine.Draw(sb, p1, p2, Color); } // Horizontal lines p1.X = (float)Math.Round(camera.Min.X); p2.X = (float)Math.Round(p1.X + size.X + 32); for (var y = min.Y; y < max.Y; y += Size.Y) { p1.Y = (float)Math.Round(y); p2.Y = (float)Math.Round(y); RenderLine.Draw(sb, p1, p2, Color); } } /// <summary> /// Snaps an <see cref="Entity"/>'s position to the grid. Intended for when moving an <see cref="Entity"/>. /// </summary> /// <param name="entity"><see cref="Entity"/> to snap to the grid.</param> public void SnapToGridPosition(Entity entity) { if (entity == null) { Debug.Fail("entity is null."); return; } var newPos = (entity.Position / Size).Round() * Size; entity.Position = newPos; } /// <summary> /// Snaps an <see cref="Entity"/>'s size to the grid. Intended for when resizing an <see cref="Entity"/>. /// </summary> /// <param name="entity"><see cref="Entity"/> to snap to the grid.</param> public void SnapToGridSize(Entity entity) { if (entity == null) { Debug.Fail("entity is null."); return; } var newSize = (entity.Size / Size).Round() * Size; if (newSize.X < Size.X) newSize.X = Size.X; if (newSize.Y < Size.Y) newSize.Y = Size.Y; entity.Size = newSize; } #region IPersistable Members /// <summary> /// Reads the state of the object from an <see cref="IValueReader"/>. Values should be read in the exact /// same order as they were written. /// </summary> /// <param name="reader">The <see cref="IValueReader"/> to read the values from.</param> public void ReadState(IValueReader reader) { PersistableHelper.Read(this, reader); } /// <summary> /// Writes the state of the object to an <see cref="IValueWriter"/>. /// </summary> /// <param name="writer">The <see cref="IValueWriter"/> to write the values to.</param> public void WriteState(IValueWriter writer) { PersistableHelper.Write(this, writer); } #endregion } }
--- /dev/null 2016-03-11 14:48:39.000000000 -0500 +++ src/System.Diagnostics.Process/src/SR.cs 2016-03-11 14:48:59.917099000 -0500 @@ -0,0 +1,534 @@ +using System; +using System.Resources; + +namespace FxResources.System.Diagnostics.Process +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.Diagnostics.Process.SR"; + + internal static String PriorityClassNotSupported + { + get + { + return SR.GetResourceString("PriorityClassNotSupported", null); + } + } + + internal static String NoAssociatedProcess + { + get + { + return SR.GetResourceString("NoAssociatedProcess", null); + } + } + + internal static String ProcessIdRequired + { + get + { + return SR.GetResourceString("ProcessIdRequired", null); + } + } + + internal static String NotSupportedRemote + { + get + { + return SR.GetResourceString("NotSupportedRemote", null); + } + } + + internal static String NoProcessInfo + { + get + { + return SR.GetResourceString("NoProcessInfo", null); + } + } + + internal static String WaitTillExit + { + get + { + return SR.GetResourceString("WaitTillExit", null); + } + } + + internal static String NoProcessHandle + { + get + { + return SR.GetResourceString("NoProcessHandle", null); + } + } + + internal static String MissingProccess + { + get + { + return SR.GetResourceString("MissingProccess", null); + } + } + + internal static String BadMinWorkset + { + get + { + return SR.GetResourceString("BadMinWorkset", null); + } + } + + internal static String BadMaxWorkset + { + get + { + return SR.GetResourceString("BadMaxWorkset", null); + } + } + + internal static String ProcessHasExited + { + get + { + return SR.GetResourceString("ProcessHasExited", null); + } + } + + internal static String ProcessHasExitedNoId + { + get + { + return SR.GetResourceString("ProcessHasExitedNoId", null); + } + } + + internal static String ThreadExited + { + get + { + return SR.GetResourceString("ThreadExited", null); + } + } + + internal static String ProcessNotFound + { + get + { + return SR.GetResourceString("ProcessNotFound", null); + } + } + + internal static String CantGetProcessId + { + get + { + return SR.GetResourceString("CantGetProcessId", null); + } + } + + internal static String ProcessDisabled + { + get + { + return SR.GetResourceString("ProcessDisabled", null); + } + } + + internal static String WaitReasonUnavailable + { + get + { + return SR.GetResourceString("WaitReasonUnavailable", null); + } + } + + internal static String NotSupportedRemoteThread + { + get + { + return SR.GetResourceString("NotSupportedRemoteThread", null); + } + } + + internal static String CouldntConnectToRemoteMachine + { + get + { + return SR.GetResourceString("CouldntConnectToRemoteMachine", null); + } + } + + internal static String CouldntGetProcessInfos + { + get + { + return SR.GetResourceString("CouldntGetProcessInfos", null); + } + } + + internal static String InputIdleUnkownError + { + get + { + return SR.GetResourceString("InputIdleUnkownError", null); + } + } + + internal static String FileNameMissing + { + get + { + return SR.GetResourceString("FileNameMissing", null); + } + } + + internal static String EnumProcessModuleFailed + { + get + { + return SR.GetResourceString("EnumProcessModuleFailed", null); + } + } + + internal static String EnumProcessModuleFailedDueToWow + { + get + { + return SR.GetResourceString("EnumProcessModuleFailedDueToWow", null); + } + } + + internal static String NoAsyncOperation + { + get + { + return SR.GetResourceString("NoAsyncOperation", null); + } + } + + internal static String InvalidApplication + { + get + { + return SR.GetResourceString("InvalidApplication", null); + } + } + + internal static String StandardOutputEncodingNotAllowed + { + get + { + return SR.GetResourceString("StandardOutputEncodingNotAllowed", null); + } + } + + internal static String StandardErrorEncodingNotAllowed + { + get + { + return SR.GetResourceString("StandardErrorEncodingNotAllowed", null); + } + } + + internal static String CantGetStandardOut + { + get + { + return SR.GetResourceString("CantGetStandardOut", null); + } + } + + internal static String CantGetStandardIn + { + get + { + return SR.GetResourceString("CantGetStandardIn", null); + } + } + + internal static String CantGetStandardError + { + get + { + return SR.GetResourceString("CantGetStandardError", null); + } + } + + internal static String CantMixSyncAsyncOperation + { + get + { + return SR.GetResourceString("CantMixSyncAsyncOperation", null); + } + } + + internal static String CantRedirectStreams + { + get + { + return SR.GetResourceString("CantRedirectStreams", null); + } + } + + internal static String CantUseEnvVars + { + get + { + return SR.GetResourceString("CantUseEnvVars", null); + } + } + + internal static String EnvironmentBlockTooLong + { + get + { + return SR.GetResourceString("EnvironmentBlockTooLong", null); + } + } + + internal static String PendingAsyncOperation + { + get + { + return SR.GetResourceString("PendingAsyncOperation", null); + } + } + + internal static String UseShellExecute + { + get + { + return SR.GetResourceString("UseShellExecute", null); + } + } + + internal static String InvalidParameter + { + get + { + return SR.GetResourceString("InvalidParameter", null); + } + } + + internal static String InvalidEnumArgument + { + get + { + return SR.GetResourceString("InvalidEnumArgument", null); + } + } + + internal static String CategoryHelpCorrupt + { + get + { + return SR.GetResourceString("CategoryHelpCorrupt", null); + } + } + + internal static String CounterNameCorrupt + { + get + { + return SR.GetResourceString("CounterNameCorrupt", null); + } + } + + internal static String CounterDataCorrupt + { + get + { + return SR.GetResourceString("CounterDataCorrupt", null); + } + } + + internal static String CantGetProcessStartInfo + { + get + { + return SR.GetResourceString("CantGetProcessStartInfo", null); + } + } + + internal static String CantSetProcessStartInfo + { + get + { + return SR.GetResourceString("CantSetProcessStartInfo", null); + } + } + + internal static String CantGetAllPids + { + get + { + return SR.GetResourceString("CantGetAllPids", null); + } + } + + internal static String CantFindProcessExecutablePath + { + get + { + return SR.GetResourceString("CantFindProcessExecutablePath", null); + } + } + + internal static String NegativePidNotSupported + { + get + { + return SR.GetResourceString("NegativePidNotSupported", null); + } + } + + internal static String ProcessorAffinityNotSupported + { + get + { + return SR.GetResourceString("ProcessorAffinityNotSupported", null); + } + } + + internal static String ResourceLimitQueryFailure + { + get + { + return SR.GetResourceString("ResourceLimitQueryFailure", null); + } + } + + internal static String RUsageFailure + { + get + { + return SR.GetResourceString("RUsageFailure", null); + } + } + + internal static String MinimumWorkingSetNotSupported + { + get + { + return SR.GetResourceString("MinimumWorkingSetNotSupported", null); + } + } + + internal static String OsxExternalProcessWorkingSetNotSupported + { + get + { + return SR.GetResourceString("OsxExternalProcessWorkingSetNotSupported", null); + } + } + + internal static String ProcessInformationUnavailable + { + get + { + return SR.GetResourceString("ProcessInformationUnavailable", null); + } + } + + internal static String RemoteMachinesNotSupported + { + get + { + return SR.GetResourceString("RemoteMachinesNotSupported", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Diagnostics.Process.SR); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2, p3); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing API Operation Policy. /// </summary> internal partial class ApiOperationPolicyOperations : IServiceOperations<ApiManagementClient>, IApiOperationPolicyOperations { /// <summary> /// Initializes a new instance of the ApiOperationPolicyOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ApiOperationPolicyOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Deletes specific API operation policy of the Api Management service /// instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='aid'> /// Required. Identifier of the API. /// </param> /// <param name='oid'> /// Required. Identifier of the API operation. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string aid, string oid, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (aid == null) { throw new ArgumentNullException("aid"); } if (oid == null) { throw new ArgumentNullException("oid"); } if (etag == null) { throw new ArgumentNullException("etag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("aid", aid); tracingParameters.Add("oid", oid); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/apis/"; url = url + Uri.EscapeDataString(aid); url = url + "/operations/"; url = url + Uri.EscapeDataString(oid); url = url + "/policy"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets specific API operation policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='aid'> /// Required. Identifier of the API. /// </param> /// <param name='oid'> /// Required. Identifier of the API operation. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get policy output operation. /// </returns> public async Task<PolicyGetResponse> GetAsync(string resourceGroupName, string serviceName, string aid, string oid, string format, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (aid == null) { throw new ArgumentNullException("aid"); } if (oid == null) { throw new ArgumentNullException("oid"); } if (format == null) { throw new ArgumentNullException("format"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("aid", aid); tracingParameters.Add("oid", oid); tracingParameters.Add("format", format); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/apis/"; url = url + Uri.EscapeDataString(aid); url = url + "/operations/"; url = url + Uri.EscapeDataString(oid); url = url + "/policy"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", format); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PolicyGetResponse(); result.PolicyBytes = Encoding.UTF8.GetBytes(responseContent); } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Sets policy for API operation. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='aid'> /// Required. Identifier of the API. /// </param> /// <param name='oid'> /// Required. Identifier of the API operation. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <param name='policyStream'> /// Required. Policy stream. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> SetAsync(string resourceGroupName, string serviceName, string aid, string oid, string format, Stream policyStream, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (aid == null) { throw new ArgumentNullException("aid"); } if (oid == null) { throw new ArgumentNullException("oid"); } if (format == null) { throw new ArgumentNullException("format"); } if (policyStream == null) { throw new ArgumentNullException("policyStream"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("aid", aid); tracingParameters.Add("oid", oid); tracingParameters.Add("format", format); tracingParameters.Add("policyStream", policyStream); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "SetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/apis/"; url = url + Uri.EscapeDataString(aid); url = url + "/operations/"; url = url + Uri.EscapeDataString(oid); url = url + "/policy"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request Stream requestContent = policyStream; httpRequest.Content = new StreamContent(requestContent); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(format); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.AspNetCore.Mvc.Rendering { /// <summary> /// Form-related extensions for <see cref="IHtmlHelper"/>. /// </summary> public static class HtmlHelperFormExtensions { /// <summary> /// Renders a &lt;form&gt; start tag to the response. The &lt;form&gt;'s <c>action</c> attribute value will /// match the current request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm(this IHtmlHelper htmlHelper) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } // Generates <form action="{current url}" method="post">. return htmlHelper.BeginForm( actionName: null, controllerName: null, routeValues: null, method: FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The &lt;form&gt;'s <c>action</c> attribute value will /// match the current request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="antiforgery"> /// If <c>true</c>, &lt;form&gt; elements will include an antiforgery token. /// If <c>false</c>, suppresses the generation an &lt;input&gt; of type "hidden" with an antiforgery token. /// If <c>null</c>, &lt;form&gt; elements will include an antiforgery token. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm(this IHtmlHelper htmlHelper, bool? antiforgery) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } // Generates <form action="{current url}" method="post">. return htmlHelper.BeginForm( actionName: null, controllerName: null, routeValues: null, method: FormMethod.Post, antiforgery: antiforgery, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the /// current action will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm(this IHtmlHelper htmlHelper, FormMethod method) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName: null, controllerName: null, routeValues: null, method: method, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the /// current action will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML /// attributes. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, FormMethod method, object htmlAttributes) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName: null, controllerName: null, routeValues: null, method: method, antiforgery: null, htmlAttributes: htmlAttributes); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the /// current action will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="antiforgery"> /// If <c>true</c>, &lt;form&gt; elements will include an antiforgery token. /// If <c>false</c>, suppresses the generation an &lt;input&gt; of type "hidden" with an antiforgery token. /// If <c>null</c>, &lt;form&gt; elements will include an antiforgery token only if /// <paramref name="method"/> is not <see cref="FormMethod.Get"/>. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML /// attributes. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, FormMethod method, bool? antiforgery, object htmlAttributes) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName: null, controllerName: null, routeValues: null, method: method, antiforgery: antiforgery, htmlAttributes: htmlAttributes); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the /// current action will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm(this IHtmlHelper htmlHelper, object routeValues) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName: null, controllerName: null, routeValues: routeValues, method: FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the action with name /// <paramref name="actionName"/> will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, string actionName, string controllerName) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName, controllerName, routeValues: null, method: FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the action with name /// <paramref name="actionName"/> will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, string actionName, string controllerName, object routeValues) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName, controllerName, routeValues, FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the action with name /// <paramref name="actionName"/> will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName, controllerName, routeValues: null, method: method, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the action with name /// <paramref name="actionName"/> will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName, controllerName, routeValues, method, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. When the user submits the form, the action with name /// <paramref name="actionName"/> will process the request. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML /// attributes. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginForm( this IHtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginForm( actionName, controllerName, routeValues: null, method: method, antiforgery: null, htmlAttributes: htmlAttributes); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The first route that can provide a URL with the /// specified <paramref name="routeValues"/> generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, object routeValues) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName: null, routeValues: routeValues, method: FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The first route that can provide a URL with the /// specified <paramref name="routeValues"/> generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <param name="antiforgery"> /// If <c>true</c>, &lt;form&gt; elements will include an antiforgery token. /// If <c>false</c>, suppresses the generation an &lt;input&gt; of type "hidden" with an antiforgery token. /// If <c>null</c>, &lt;form&gt; elements will include an antiforgery token. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, object routeValues, bool? antiforgery) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName: null, routeValues: routeValues, method: FormMethod.Post, antiforgery: antiforgery, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The route with name <paramref name="routeName"/> /// generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeName">The name of the route.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, string routeName) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName, routeValues: null, method: FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The route with name <paramref name="routeName"/> /// generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeName">The name of the route.</param> /// <param name="antiforgery"> /// If <c>true</c>, &lt;form&gt; elements will include an antiforgery token. /// If <c>false</c>, suppresses the generation an &lt;input&gt; of type "hidden" with an antiforgery token. /// If <c>null</c>, &lt;form&gt; elements will include an antiforgery token. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, string routeName, bool? antiforgery) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName, routeValues: null, method: FormMethod.Post, antiforgery: antiforgery, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The route with name <paramref name="routeName"/> /// generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm( this IHtmlHelper htmlHelper, string routeName, object routeValues) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName, routeValues, FormMethod.Post, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The route with name <paramref name="routeName"/> /// generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeName">The name of the route.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm( this IHtmlHelper htmlHelper, string routeName, FormMethod method) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName, routeValues: null, method: method, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The route with name <paramref name="routeName"/> /// generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the route /// parameters. /// </param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm( this IHtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName, routeValues, method, antiforgery: null, htmlAttributes: null); } /// <summary> /// Renders a &lt;form&gt; start tag to the response. The route with name <paramref name="routeName"/> /// generates the &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param> /// <param name="routeName">The name of the route.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML /// attributes. /// </param> /// <returns> /// An <see cref="MvcForm"/> instance which renders the &lt;/form&gt; end tag when disposed. /// </returns> /// <remarks> /// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>. /// </remarks> public static MvcForm BeginRouteForm( this IHtmlHelper htmlHelper, string routeName, FormMethod method, object htmlAttributes) { if (htmlHelper == null) { throw new ArgumentNullException(nameof(htmlHelper)); } return htmlHelper.BeginRouteForm( routeName, routeValues: null, method: method, antiforgery: null, htmlAttributes: htmlAttributes); } } }
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using BenchmarkDotNet.Attributes; namespace FastExpressionCompiler.Benchmarks { public class ManuallyComposedLambdaBenchmark { private static Expression<Func<B, X>> ComposeManualExprWithParams(Expression aConstExpr) { var bParamExpr = Expression.Parameter(typeof(B), "b"); return Expression.Lambda<Func<B, X>>( Expression.New(typeof(X).GetTypeInfo().DeclaredConstructors.First(), aConstExpr, bParamExpr), bParamExpr); } private static LightExpression.Expression<Func<B, X>> ComposeManualExprWithParams(LightExpression.Expression aConstExpr) { var bParamExpr = LightExpression.Expression.Parameter(typeof(B), "b"); return LightExpression.Expression.Lambda<Func<B, X>>( LightExpression.Expression.New(typeof(X).GetTypeInfo().DeclaredConstructors.First(), aConstExpr, bParamExpr), bParamExpr); } public class A { } public class B { } public class X { public A A { get; } public B B { get; } public X(A a, B b) { A = a; B = b; } } private static readonly A _a = new A(); private static readonly ConstantExpression _aConstExpr = Expression.Constant(_a, typeof(A)); private static readonly Expression<Func<B, X>> _expr = ComposeManualExprWithParams(_aConstExpr); private static readonly LightExpression.ConstantExpression _aConstLEExpr = LightExpression.Expression.Constant(_a, typeof(A)); private static readonly FastExpressionCompiler.LightExpression.Expression<Func<B, X>> _leExpr = ComposeManualExprWithParams(_aConstLEExpr); [MemoryDiagnoser] public class Create_and_Compile { /* ## v3-preview-03 | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |----------------------- |-----------:|----------:|----------:|------:|--------:|-------:|-------:|-------:|----------:| | SystemExpr_Compile | 171.098 us | 1.9611 us | 1.8344 us | 30.22 | 0.85 | 1.2207 | 0.4883 | - | 5.11 KB | | SystemExpr_CompileFast | 7.314 us | 0.1273 us | 0.1191 us | 1.29 | 0.05 | 0.4883 | 0.2441 | 0.0305 | 2.03 KB | | LightExpr_CompileFast | 5.647 us | 0.0813 us | 0.1217 us | 1.00 | 0.00 | 0.3815 | 0.1907 | 0.0305 | 1.59 KB | ## v3-preview-05 BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.630 (2004/?/20H1) Intel Core i7-8565U CPU 1.80GHz (Whiskey Lake), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=5.0.100 [Host] : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |----------------------- |-----------:|----------:|----------:|------:|--------:|-------:|-------:|-------:|----------:| | SystemExpr_Compile | 165.654 us | 1.7359 us | 1.4496 us | 26.72 | 0.80 | 1.2207 | 0.4883 | - | 5.31 KB | | SystemExpr_CompileFast | 6.680 us | 0.1275 us | 0.1192 us | 1.07 | 0.04 | 0.4959 | 0.2441 | 0.0305 | 2.04 KB | | LightExpr_CompileFast | 6.160 us | 0.1209 us | 0.1773 us | 1.00 | 0.00 | 0.3815 | 0.1907 | 0.0305 | 1.59 KB | */ [Benchmark] public Func<B, X> SystemExpr_Compile() => ComposeManualExprWithParams(Expression.Constant(_a, typeof(A))).Compile(); [Benchmark] public Func<B, X> SystemExpr_CompileFast() => ComposeManualExprWithParams(Expression.Constant(_a, typeof(A))).CompileFast(true); [Benchmark(Baseline = true)] public Func<B, X> LightExpr_CompileFast() => LightExpression.ExpressionCompiler.CompileFast<Func<B, X>>(ComposeManualExprWithParams(LightExpression.Expression.Constant(_a, typeof(A))), true); } [MemoryDiagnoser] public class Compilation { /* ## 26.01.2019: V2 Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | ------------------------------------------------ |-----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:| Compile | 176.107 us | 1.3451 us | 1.2582 us | 36.05 | 0.75 | 0.9766 | 0.4883 | - | 4.7 KB | CompileFast | 7.257 us | 0.0648 us | 0.0606 us | 1.49 | 0.03 | 0.4349 | 0.2136 | 0.0305 | 1.99 KB | CompileFastWithPreCreatedClosure | 5.186 us | 0.0896 us | 0.0795 us | 1.06 | 0.02 | 0.3281 | 0.1602 | 0.0305 | 1.5 KB | CompileFastWithPreCreatedClosureLightExpression | 4.892 us | 0.0965 us | 0.0948 us | 1.00 | 0.00 | 0.3281 | 0.1602 | 0.0305 | 1.5 KB | ## v3-preview-02 | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |---------------------------- |-----------:|----------:|----------:|------:|--------:|-------:|-------:|-------:|----------:| | Compile | 153.405 us | 3.0500 us | 5.8762 us | 32.77 | 2.25 | 0.9766 | 0.4883 | - | 4.59 KB | | CompileFast | 4.716 us | 0.0925 us | 0.0820 us | 1.02 | 0.03 | 0.3510 | 0.1755 | 0.0305 | 1.46 KB | | CompileFast_LightExpression | 4.611 us | 0.0898 us | 0.0840 us | 1.00 | 0.00 | 0.3433 | 0.1678 | 0.0305 | 1.42 KB | ## v3-preview-03 | Method | Mean | Error | StdDev | Median | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |---------------------------- |-----------:|----------:|----------:|-----------:|------:|--------:|-------:|-------:|-------:|----------:| | Compile | 154.112 us | 1.7660 us | 1.4747 us | 154.045 us | 32.73 | 1.11 | 0.9766 | 0.4883 | - | 4.59 KB | | CompileFast | 4.828 us | 0.0950 us | 0.1984 us | 4.750 us | 1.04 | 0.05 | 0.3510 | 0.1755 | 0.0305 | 1.46 KB | | CompileFast_LightExpression | 4.704 us | 0.0940 us | 0.1188 us | 4.708 us | 1.00 | 0.00 | 0.3433 | 0.1678 | 0.0305 | 1.42 KB | ## v3-preview-05 BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.630 (2004/?/20H1) Intel Core i7-8565U CPU 1.80GHz (Whiskey Lake), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=5.0.100 [Host] : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |---------------------------- |-----------:|----------:|----------:|------:|--------:|-------:|-------:|-------:|----------:| | Compile | 148.633 us | 1.4863 us | 1.2411 us | 33.20 | 1.05 | 0.9766 | 0.4883 | - | 4.78 KB | | CompileFast | 4.498 us | 0.0887 us | 0.1022 us | 1.02 | 0.04 | 0.3510 | 0.1755 | 0.0305 | 1.46 KB | | CompileFast_LightExpression | 4.365 us | 0.0860 us | 0.1364 us | 1.00 | 0.00 | 0.3433 | 0.1678 | 0.0305 | 1.42 KB | */ [Benchmark] public Func<B, X> Compile() => _expr.Compile(); [Benchmark] public Func<B, X> CompileFast() => _expr.CompileFast(true); [Benchmark(Baseline = true)] public Func<B, X> CompileFast_LightExpression() => LightExpression.ExpressionCompiler.CompileFast<Func<B, X>>(_leExpr, true); // [Benchmark] public Func<B, X> CompileFastWithPreCreatedClosure() => _expr.TryCompileWithPreCreatedClosure<Func<B, X>>(_aConstExpr) ?? _expr.Compile(); // [Benchmark] public Func<B, X> CompileFastWithPreCreatedClosureLightExpression() => LightExpression.ExpressionCompiler.TryCompileWithPreCreatedClosure<Func<B, X>>( _leExpr, _aConstLEExpr) ?? LightExpression.ExpressionCompiler.CompileSys(_leExpr); } [MemoryDiagnoser] public class Invocation { /* ## 26.01.2019: V2 Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | ------------------------------------------ |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:| FastCompiledLambdaWithPreCreatedClosureLE | 10.64 ns | 0.0404 ns | 0.0358 ns | 1.00 | 0.0068 | - | - | 32 B | DirectLambdaCall | 10.65 ns | 0.0601 ns | 0.0533 ns | 1.00 | 0.0068 | - | - | 32 B | FastCompiledLambda | 10.98 ns | 0.0434 ns | 0.0406 ns | 1.03 | 0.0068 | - | - | 32 B | FastCompiledLambdaWithPreCreatedClosure | 11.10 ns | 0.0369 ns | 0.0345 ns | 1.04 | 0.0068 | - | - | 32 B | CompiledLambda | 11.13 ns | 0.0620 ns | 0.0518 ns | 1.05 | 0.0068 | - | - | 32 B | ## V3 baseline Method | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated | ------------------------------------------ |---------:|----------:|----------:|------:|-------:|------:|------:|----------:| DirectLambdaCall | 11.35 ns | 0.0491 ns | 0.0460 ns | 1.01 | 0.0068 | - | - | 32 B | CompiledLambda | 11.68 ns | 0.0409 ns | 0.0342 ns | 1.04 | 0.0068 | - | - | 32 B | FastCompiledLambda | 11.73 ns | 0.0905 ns | 0.0802 ns | 1.04 | 0.0068 | - | - | 32 B | FastCompiledLambdaWithPreCreatedClosure | 11.26 ns | 0.0414 ns | 0.0387 ns | 1.00 | 0.0068 | - | - | 32 B | FastCompiledLambdaWithPreCreatedClosureLE | 11.27 ns | 0.0594 ns | 0.0556 ns | 1.00 | 0.0068 | - | - | 32 B | ## V3-preview-02 | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated | |----------------------------------- |---------:|---------:|---------:|------:|--------:|-------:|------:|------:|----------:| | DirectLambdaCall | 11.07 ns | 0.183 ns | 0.171 ns | 1.02 | 0.02 | 0.0076 | - | - | 32 B | | CompiledLambda | 12.31 ns | 0.101 ns | 0.090 ns | 1.13 | 0.01 | 0.0076 | - | - | 32 B | | FastCompiledLambda | 10.80 ns | 0.146 ns | 0.137 ns | 1.00 | 0.01 | 0.0076 | - | - | 32 B | | FastCompiledLambda_LightExpression | 10.86 ns | 0.109 ns | 0.096 ns | 1.00 | 0.00 | 0.0076 | - | - | 32 B | ## V3-preview-05 BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.630 (2004/?/20H1) Intel Core i7-8565U CPU 1.80GHz (Whiskey Lake), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=5.0.100 [Host] : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT | Method | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated | |----------------------------------- |---------:|---------:|---------:|------:|-------:|------:|------:|----------:| | DirectLambdaCall | 11.86 ns | 0.140 ns | 0.131 ns | 1.00 | 0.0076 | - | - | 32 B | | CompiledLambda | 13.44 ns | 0.115 ns | 0.096 ns | 1.13 | 0.0076 | - | - | 32 B | | FastCompiledLambda | 12.43 ns | 0.173 ns | 0.154 ns | 1.05 | 0.0076 | - | - | 32 B | | FastCompiledLambda_LightExpression | 11.87 ns | 0.121 ns | 0.101 ns | 1.00 | 0.0076 | - | - | 32 B | */ private static readonly Func<B, X> _lambdaCompiled = _expr.Compile(); private static readonly Func<B, X> _lambdaCompiledFast = _expr.CompileFast(true); private static readonly Func<B, X> _lambdaCompiledFast_LightExpession = _expr.CompileFast<Func<B, X>>(true); private static readonly Func<B, X> _lambdaCompiledFastWithClosure = _expr.TryCompileWithPreCreatedClosure<Func<B, X>>(_aConstExpr); private static readonly Func<B, X> _lambdaCompiledFastWithClosureLE = LightExpression.ExpressionCompiler.TryCompileWithPreCreatedClosure<Func<B, X>>( _leExpr, _aConstLEExpr); private static readonly A _aa = new A(); private static readonly B _bb = new B(); private static readonly Func<B, X> _lambda = b => new X(_aa, b); [Benchmark] public X DirectLambdaCall() => _lambda(_bb); [Benchmark] public X CompiledLambda() => _lambdaCompiled(_bb); [Benchmark] public X FastCompiledLambda() => _lambdaCompiledFast(_bb); [Benchmark(Baseline = true)] public X FastCompiledLambda_LightExpression() => _lambdaCompiledFast_LightExpession(_bb); // [Benchmark] public X FastCompiledLambdaWithPreCreatedClosure() => _lambdaCompiledFastWithClosure(_bb); // [Benchmark] public X FastCompiledLambdaWithPreCreatedClosureLE() => _lambdaCompiledFastWithClosureLE(_bb); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Bookshelf.Areas.HelpPage.ModelDescriptions; using Bookshelf.Areas.HelpPage.Models; namespace Bookshelf.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: CultureInfo-specific collection of resources. ** ** ===========================================================*/ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Private; namespace System.Resources { // A RuntimeResourceSet stores all the resources defined in one // particular CultureInfo, with some loading optimizations. // // It is expected that nearly all the runtime's users will be satisfied with the // default resource file format, and it will be more efficient than most simple // implementations. Users who would consider creating their own ResourceSets and/or // ResourceReaders and ResourceWriters are people who have to interop with a // legacy resource file format, are creating their own resource file format // (using XML, for instance), or require doing resource lookups at runtime over // the network. This group will hopefully be small, but all the infrastructure // should be in place to let these users write & plug in their own tools. // // The Default Resource File Format // // The fundamental problems addressed by the resource file format are: // // * Versioning - A ResourceReader could in theory support many different // file format revisions. // * Storing intrinsic datatypes (ie, ints, Strings, DateTimes, etc) in a compact // format // * Support for user-defined classes - Accomplished using Serialization // * Resource lookups should not require loading an entire resource file - If you // look up a resource, we only load the value for that resource, minimizing working set. // // // There are four sections to the default file format. The first // is the Resource Manager header, which consists of a magic number // that identifies this as a Resource file, and a ResourceSet class name. // The class name is written here to allow users to provide their own // implementation of a ResourceSet (and a matching ResourceReader) to // control policy. If objects greater than a certain size or matching a // certain naming scheme shouldn't be stored in memory, users can tweak that // with their own subclass of ResourceSet. // // The second section in the system default file format is the // RuntimeResourceSet specific header. This contains a version number for // the .resources file, the number of resources in this file, the number of // different types contained in the file, followed by a list of fully // qualified type names. After this, we include an array of hash values for // each resource name, then an array of virtual offsets into the name section // of the file. The hashes allow us to do a binary search on an array of // integers to find a resource name very quickly without doing many string // compares (except for once we find the real type, of course). If a hash // matches, the index into the array of hash values is used as the index // into the name position array to find the name of the resource. The type // table allows us to read multiple different classes from the same file, // including user-defined types, in a more efficient way than using // Serialization, at least when your .resources file contains a reasonable // proportion of base data types such as Strings or ints. We use // Serialization for all the non-instrinsic types. // // The third section of the file is the name section. It contains a // series of resource names, written out as byte-length prefixed little // endian Unicode strings (UTF-16). After each name is a four byte virtual // offset into the data section of the file, pointing to the relevant // string or serialized blob for this resource name. // // The fourth section in the file is the data section, which consists // of a type and a blob of bytes for each item in the file. The type is // an integer index into the type table. The data is specific to that type, // but may be a number written in binary format, a String, or a serialized // Object. // // The system default file format (V1) is as follows: // // What Type of Data // ==================================================== =========== // // Resource Manager header // Magic Number (0xBEEFCACE) Int32 // Resource Manager header version Int32 // Num bytes to skip from here to get past this header Int32 // Class name of IResourceReader to parse this file String // Class name of ResourceSet to parse this file String // // RuntimeResourceReader header // ResourceReader version number Int32 // [Only in debug V2 builds - "***DEBUG***"] String // Number of resources in the file Int32 // Number of types in the type table Int32 // Name of each type Set of Strings // Padding bytes for 8-byte alignment (use PAD) Bytes (0-7) // Hash values for each resource name Int32 array, sorted // Virtual offset of each resource name Int32 array, coupled with hash values // Absolute location of Data section Int32 // // RuntimeResourceReader Name Section // Name & virtual offset of each resource Set of (UTF-16 String, Int32) pairs // // RuntimeResourceReader Data Section // Type and Value of each resource Set of (Int32, blob of bytes) pairs // // This implementation, when used with the default ResourceReader class, // loads only the strings that you look up for. It can do string comparisons // without having to create a new String instance due to some memory mapped // file optimizations in the ResourceReader and FastResourceComparer // classes. This keeps the memory we touch to a minimum when loading // resources. // // If you use a different IResourceReader class to read a file, or if you // do case-insensitive lookups (and the case-sensitive lookup fails) then // we will load all the names of each resource and each resource value. // This could probably use some optimization. // // In addition, this supports object serialization in a similar fashion. // We build an array of class types contained in this file, and write it // to RuntimeResourceReader header section of the file. Every resource // will contain its type (as an index into the array of classes) with the data // for that resource. We will use the Runtime's serialization support for this. // // All strings in the file format are written with BinaryReader and // BinaryWriter, which writes out the length of the String in bytes as an // Int32 then the contents as Unicode chars encoded in UTF-8. In the name // table though, each resource name is written in UTF-16 so we can do a // string compare byte by byte against the contents of the file, without // allocating objects. Ideally we'd have a way of comparing UTF-8 bytes // directly against a String object, but that may be a lot of work. // // The offsets of each resource string are relative to the beginning // of the Data section of the file. This way, if a tool decided to add // one resource to a file, it would only need to increment the number of // resources, add the hash &amp; location of last byte in the name section // to the array of resource hashes and resource name positions (carefully // keeping these arrays sorted), add the name to the end of the name &amp; // offset list, possibly add the type list of types types (and increase // the number of items in the type table), and add the resource value at // the end of the file. The other offsets wouldn't need to be updated to // reflect the longer header section. // // Resource files are currently limited to 2 gigabytes due to these // design parameters. A future version may raise the limit to 4 gigabytes // by using unsigned integers, or may use negative numbers to load items // out of an assembly manifest. Also, we may try sectioning the resource names // into smaller chunks, each of size sqrt(n), would be substantially better for // resource files containing thousands of resources. // #if CORERT public // On CoreRT, this must be public because of need to whitelist past the ReflectionBlock. #else internal #endif sealed class RuntimeResourceSet : ResourceSet, IEnumerable { internal const int Version = 2; // File format version number // Cache for resources. Key is the resource name, which can be cached // for arbitrarily long times, since the object is usually a string // literal that will live for the lifetime of the appdomain. The // value is a ResourceLocator instance, which might cache the object. private Dictionary<String, ResourceLocator> _resCache; // For our special load-on-demand reader, cache the cast. The // RuntimeResourceSet's implementation knows how to treat this reader specially. private ResourceReader _defaultReader; // This is a lookup table for case-insensitive lookups, and may be null. // Consider always using a case-insensitive resource cache, as we don't // want to fill this out if we can avoid it. The problem is resource // fallback will somewhat regularly cause us to look up resources that // don't exist. private Dictionary<String, ResourceLocator> _caseInsensitiveTable; // If we're not using our custom reader, then enumerate through all // the resources once, adding them into the table. private bool _haveReadFromReader; internal RuntimeResourceSet(String fileName) : base(false) { _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; } internal RuntimeResourceSet(Stream stream) : base(false) { _resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; } protected override void Dispose(bool disposing) { if (Reader == null) return; if (disposing) { lock (Reader) { _resCache = null; if (_defaultReader != null) { _defaultReader.Close(); _defaultReader = null; } _caseInsensitiveTable = null; // Set Reader to null to avoid a race in GetObject. base.Dispose(disposing); } } else { // Just to make sure we always clear these fields in the future... _resCache = null; _caseInsensitiveTable = null; _defaultReader = null; base.Dispose(disposing); } } public override IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { IResourceReader copyOfReader = Reader; if (copyOfReader == null || _resCache == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfReader.GetEnumerator(); } public override String GetString(String key) { Object o = GetObject(key, false, true); return (String)o; } public override String GetString(String key, bool ignoreCase) { Object o = GetObject(key, ignoreCase, true); return (String)o; } public override Object GetObject(String key) { return GetObject(key, false, false); } public override Object GetObject(String key, bool ignoreCase) { return GetObject(key, ignoreCase, false); } private Object GetObject(String key, bool ignoreCase, bool isString) { if (key == null) throw new ArgumentNullException(nameof(key)); if (Reader == null || _resCache == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); Object value = null; ResourceLocator resLocation; lock (Reader) { if (Reader == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); if (_defaultReader != null) { // Find the offset within the data section int dataPos = -1; if (_resCache.TryGetValue(key, out resLocation)) { value = resLocation.Value; dataPos = resLocation.DataPosition; } if (dataPos == -1 && value == null) { dataPos = _defaultReader.FindPosForResource(key); } if (dataPos != -1 && value == null) { Debug.Assert(dataPos >= 0, "data section offset cannot be negative!"); // Normally calling LoadString or LoadObject requires // taking a lock. Note that in this case, we took a // lock on the entire RuntimeResourceSet, which is // sufficient since we never pass this ResourceReader // to anyone else. ResourceTypeCode typeCode; if (isString) { value = _defaultReader.LoadString(dataPos); typeCode = ResourceTypeCode.String; } else { value = _defaultReader.LoadObject(dataPos, out typeCode); } resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null); lock (_resCache) { _resCache[key] = resLocation; } } if (value != null || !ignoreCase) { return value; // may be null } } // if (_defaultReader != null) // At this point, we either don't have our default resource reader // or we haven't found the particular resource we're looking for // and may have to search for it in a case-insensitive way. if (!_haveReadFromReader) { // If necessary, init our case insensitive hash table. if (ignoreCase && _caseInsensitiveTable == null) { _caseInsensitiveTable = new Dictionary<String, ResourceLocator>(StringComparer.OrdinalIgnoreCase); } if (_defaultReader == null) { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { DictionaryEntry entry = en.Entry; String readKey = (String)entry.Key; ResourceLocator resLoc = new ResourceLocator(-1, entry.Value); _resCache.Add(readKey, resLoc); if (ignoreCase) _caseInsensitiveTable.Add(readKey, resLoc); } // Only close the reader if it is NOT our default one, // since we need it around to resolve ResourceLocators. if (!ignoreCase) Reader.Close(); } else { Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups"); ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal(); while (en.MoveNext()) { // Note: Always ask for the resource key before the data position. String currentKey = (String)en.Key; int dataPos = en.DataPosition; ResourceLocator resLoc = new ResourceLocator(dataPos, null); _caseInsensitiveTable.Add(currentKey, resLoc); } } _haveReadFromReader = true; } Object obj = null; bool found = false; bool keyInWrongCase = false; if (_defaultReader != null) { if (_resCache.TryGetValue(key, out resLocation)) { found = true; obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase); } } if (!found && ignoreCase) { if (_caseInsensitiveTable.TryGetValue(key, out resLocation)) { found = true; keyInWrongCase = true; obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase); } } return obj; } // lock(Reader) } // The last parameter indicates whether the lookup required a // case-insensitive lookup to succeed, indicating we shouldn't add // the ResourceLocation to our case-sensitive cache. private Object ResolveResourceLocator(ResourceLocator resLocation, String key, Dictionary<String, ResourceLocator> copyOfCache, bool keyInWrongCase) { // We need to explicitly resolve loosely linked manifest // resources, and we need to resolve ResourceLocators with null objects. Object value = resLocation.Value; if (value == null) { ResourceTypeCode typeCode; lock (Reader) { value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode); } if (!keyInWrongCase && ResourceLocator.CanCache(typeCode)) { resLocation.Value = value; copyOfCache[key] = resLocation; } } return value; } } }
using System; using System.Collections; using System.Globalization; using System.IO; using System.Linq; using System.Web; using System.Xml; using System.Xml.Serialization; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Portals; using DotNetNuke.Framework; using DotNetNuke.Modules.UserDefinedTable.Interfaces; using DotNetNuke.Security.Permissions; using DotNetNuke.Security.Roles; using DotNetNuke.Services.EventQueue; namespace DotNetNuke.Modules.UserDefinedTable.Serialization { public class ModuleSerializationController { #region Private Shared Methods static void AddContent(XmlNode nodeModule, ModuleInfo module, int maxNumberOfRecords) { if (module.DesktopModule.BusinessControllerClass != "" && module.DesktopModule.IsPortable) { try { var businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); var content = string.Empty; if (businessController is IPortable2) { content = Convert.ToString(((IPortable2) businessController).ExportModule(module.ModuleID, module.TabID, maxNumberOfRecords)); } else if (businessController is IPortable) { content = Convert.ToString(((IPortable) businessController).ExportModule(module.ModuleID)); } if (content != "") { // add attributes to XML document // ReSharper disable PossibleNullReferenceException XmlNode newnode = nodeModule.OwnerDocument.CreateElement("content"); var xmlattr = nodeModule.OwnerDocument.CreateAttribute("type"); xmlattr.Value = Globals.CleanName(module.DesktopModule.ModuleName); newnode.Attributes.Append(xmlattr); xmlattr = nodeModule.OwnerDocument.CreateAttribute("version"); xmlattr.Value = module.DesktopModule.Version; newnode.Attributes.Append(xmlattr); try { var doc = new XmlDocument(); doc.LoadXml(content); // ReSharper disable AssignNullToNotNullAttribute newnode.AppendChild(newnode.OwnerDocument.ImportNode(doc.DocumentElement, true)); // ReSharper restore AssignNullToNotNullAttribute } // ReSharper restore PossibleNullReferenceException catch (Exception) { //only for invalid xhtml content = HttpContext.Current.Server.HtmlEncode(content); newnode.InnerXml = XmlUtils.XMLEncode(content); } nodeModule.AppendChild(newnode); } } catch { //ignore errors } } } static void AddSettings(XmlNode nodeModule, ModuleInfo module) { var objModuleController = new ModuleController(); var moduleSettings = objModuleController.GetModuleSettings(module.ModuleID); var tabModuleSettings = objModuleController.GetTabModuleSettings(module.TabModuleID); var handleModuleSettings = true; var handleTabModuleSettings = true; if (module.DesktopModule.BusinessControllerClass != "" && module.DesktopModule.IsPortable) { try { var businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); if (businessController is IPortable2) { handleModuleSettings = Convert.ToBoolean(!(((IPortable2) businessController).ManagesModuleSettings)); handleTabModuleSettings = Convert.ToBoolean(!(((IPortable2) businessController).ManagesTabModuleSettings)); } } catch { } } XmlAttribute xmlattr; if (moduleSettings.Count > 0 && handleModuleSettings) { // ReSharper disable PossibleNullReferenceException XmlNode settingsNode = nodeModule.OwnerDocument.CreateElement("modulesettings"); foreach (string key in moduleSettings.Keys) { XmlNode settingNode = nodeModule.OwnerDocument.CreateElement("setting"); xmlattr = nodeModule.OwnerDocument.CreateAttribute("name"); xmlattr.Value = key; settingNode.Attributes.Append(xmlattr); // ReSharper restore PossibleNullReferenceException xmlattr = nodeModule.OwnerDocument.CreateAttribute("value"); xmlattr.Value = moduleSettings[key].ToString(); settingNode.Attributes.Append(xmlattr); settingsNode.AppendChild(settingNode); } nodeModule.AppendChild(settingsNode); } if (tabModuleSettings.Count > 0 && handleTabModuleSettings) { // ReSharper disable PossibleNullReferenceException XmlNode settingsNode = nodeModule.OwnerDocument.CreateElement("tabmodulesettings"); // ReSharper restore PossibleNullReferenceException foreach (string key in tabModuleSettings.Keys) { XmlNode settingNode = nodeModule.OwnerDocument.CreateElement("setting"); xmlattr = nodeModule.OwnerDocument.CreateAttribute("name"); xmlattr.Value = key; // ReSharper disable PossibleNullReferenceException settingNode.Attributes.Append(xmlattr); // ReSharper restore PossibleNullReferenceException xmlattr = nodeModule.OwnerDocument.CreateAttribute("value"); xmlattr.Value = tabModuleSettings[key].ToString(); settingNode.Attributes.Append(xmlattr); settingsNode.AppendChild(settingNode); } nodeModule.AppendChild(settingsNode); } } static bool CheckIsInstance(int templateModuleId, Hashtable hModules) { // will be instance or module var isInstance = false; if (templateModuleId > 0) { if (hModules[templateModuleId] != null) { // this module has already been processed -> process as instance isInstance = true; } } return isInstance; } static void CreateEventQueueMessage(ModuleInfo module, string content, string version, int userId) { var oAppStartMessage = new EventMessage { Priority = MessagePriority.High, ExpirationDate = DateTime.Now.AddYears(Convert.ToInt32(- 1)), SentDate = DateTime.Now, Body = "", ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", ProcessorCommand = "ImportModule" }; //Add custom Attributes for this message oAppStartMessage.Attributes.Add("BusinessControllerClass", module.DesktopModule.BusinessControllerClass); oAppStartMessage.Attributes.Add("ModuleId", module.ModuleID.ToString(CultureInfo.InvariantCulture)); oAppStartMessage.Attributes.Add("Content", content); oAppStartMessage.Attributes.Add("Version", version); oAppStartMessage.Attributes.Add("UserID", userId.ToString(CultureInfo.InvariantCulture)); //send it to occur on next App_Start Event EventQueueController.SendMessage(oAppStartMessage, "Application_Start"); } static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, int moduleDefId) { //Create New Module var objModule = new ModuleInfo { PortalID = portalId, TabID = tabId, ModuleOrder = - 1, ModuleTitle = XmlUtils.GetNodeValue(nodeModule, "title", ""), PaneName = XmlUtils.GetNodeValue(nodePane, "name", ""), ModuleDefID = moduleDefId, CacheTime = XmlUtils.GetNodeValueInt(nodeModule, "cachetime"), Alignment = XmlUtils.GetNodeValue(nodeModule, "alignment", ""), IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeModule, "iconfile", "")), AllTabs = XmlUtils.GetNodeValueBoolean(nodeModule, "alltabs") }; switch (XmlUtils.GetNodeValue(nodeModule, "visibility", "")) { case "Maximized": objModule.Visibility = VisibilityState.Maximized; break; case "Minimized": objModule.Visibility = VisibilityState.Minimized; break; case "None": objModule.Visibility = VisibilityState.None; break; } objModule.Color = XmlUtils.GetNodeValue(nodeModule, "color", ""); objModule.Border = XmlUtils.GetNodeValue(nodeModule, "border", ""); objModule.Header = XmlUtils.GetNodeValue(nodeModule, "header", ""); objModule.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", ""); objModule.InheritViewPermissions = XmlUtils.GetNodeValueBoolean(nodeModule, "inheritviewpermissions", false); objModule.StartDate = XmlUtils.GetNodeValueDate(nodeModule, "startdate", Null.NullDate); objModule.EndDate = XmlUtils.GetNodeValueDate(nodeModule, "enddate", Null.NullDate); if (XmlUtils.GetNodeValue(nodeModule, "containersrc", "") != "") { objModule.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", ""); } objModule.DisplayTitle = XmlUtils.GetNodeValueBoolean(nodeModule, "displaytitle", true); objModule.DisplayPrint = XmlUtils.GetNodeValueBoolean(nodeModule, "displayprint", true); objModule.DisplaySyndicate = XmlUtils.GetNodeValueBoolean(nodeModule, "displaysyndicate", false); objModule.IsWebSlice = XmlUtils.GetNodeValueBoolean(nodeModule, "iswebslice", false); if (objModule.IsWebSlice) { objModule.WebSliceTitle = XmlUtils.GetNodeValue(nodeModule, "webslicetitle", objModule.ModuleTitle); objModule.WebSliceExpiryDate = XmlUtils.GetNodeValueDate(nodeModule, "websliceexpirydate", objModule.EndDate); objModule.WebSliceTTL = XmlUtils.GetNodeValueInt(nodeModule, "webslicettl", Convert.ToInt32(objModule.CacheTime/60)); } return objModule; } static void DeserializeModulePermissions(XmlNodeList nodeModulePermissions, int portalId, ModuleInfo module) { var objRoleController = new RoleController(); var objPermissionController = new PermissionController(); foreach (XmlNode node in nodeModulePermissions) { var permissionKey = XmlUtils.GetNodeValue(node, "permissionkey", ""); var permissionCode = XmlUtils.GetNodeValue(node, "permissioncode", ""); var roleName = XmlUtils.GetNodeValue(node, "rolename", ""); var allowAccess = XmlUtils.GetNodeValueBoolean(node, "allowaccess"); var roleId = int.MinValue; switch (roleName) { case Globals.glbRoleAllUsersName: roleId = Convert.ToInt32(Globals.glbRoleAllUsers); break; case Globals.glbRoleUnauthUserName: roleId = Convert.ToInt32(Globals.glbRoleUnauthUser); break; default: var objRole = objRoleController.GetRoleByName(portalId, roleName); if (objRole != null) { roleId = objRole.RoleID; } break; } if (roleId != int.MinValue) { var permissionId = Convert.ToInt32(- 1); var arrPermissions = objPermissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); int i; for (i = 0; i <= arrPermissions.Count - 1; i++) { var permission = (PermissionInfo) (arrPermissions[i]); permissionId = permission.PermissionID; } // if role was found add, otherwise ignore if (permissionId != - 1) { var modulePermission = new ModulePermissionInfo { ModuleID = module.ModuleID, PermissionID = permissionId, RoleID = roleId, AllowAccess = allowAccess }; module.ModulePermissions.Add(modulePermission); } } } } static void DeserializeModuleSettings(XmlNodeList nodeModuleSettings, int moduleId) { var objModules = new ModuleController(); var applySettings = Convert.ToBoolean(objModules.GetModuleSettings(moduleId).Count == 0); foreach (XmlElement nodeSetting in nodeModuleSettings) { var name = nodeSetting.GetAttribute("name"); var value = nodeSetting.GetAttribute("value"); if (applySettings || nodeSetting.GetAttribute("installmode").ToLowerInvariant() == "force") { objModules.UpdateModuleSetting(moduleId, name, value); } } } static void DeserializeTabModuleSettings(XmlNodeList nodeTabModuleSettings, int moduleId, int tabId) { var objModules = new ModuleController(); var tabModuleId = objModules.GetModule(moduleId, tabId).TabModuleID; var applySettings = Convert.ToBoolean(objModules.GetTabModuleSettings(tabModuleId).Count == 0); foreach (XmlElement nodeSetting in nodeTabModuleSettings) { var name = nodeSetting.Attributes["name"].Value; var value = nodeSetting.Attributes["value"].Value; if (applySettings || nodeSetting.GetAttribute("installmode").ToLowerInvariant() == "force") { objModules.UpdateTabModuleSetting(tabModuleId, name, value); } } } static bool FindModule(XmlNode nodeModule, int tabId, PortalTemplateModuleAction mergeTabs) { var modules = new ModuleController(); var tabModules = modules.GetTabModules(tabId); var moduleFound = false; var modTitle = XmlUtils.GetNodeValue(nodeModule, "title", ""); if (mergeTabs == PortalTemplateModuleAction.Merge) { if (tabModules.Select(kvp => kvp.Value).Any(module => modTitle == module.ModuleTitle)) { moduleFound = true; } } return moduleFound; } static void GetModuleContent(XmlNode nodeModule, int moduleId, int tabId, int portalId, bool isInstance) { var moduleController = new ModuleController(); var module = moduleController.GetModule(moduleId, tabId, true); var contentNode = nodeModule.SelectSingleNode("content[@type]"); var strVersion = contentNode.Attributes["version"].Value; var strcontent = contentNode.InnerXml; if (strcontent.StartsWith("<![CDATA[")) { strcontent = strcontent.Substring(9, strcontent.Length - 12); strcontent = HttpContext.Current.Server.HtmlDecode(strcontent); } if (module.DesktopModule.BusinessControllerClass != "" && strcontent != "") { var portalController = new PortalController(); var portal = portalController.GetPortal(portalId); //Determine if the Module is copmpletely installed //(ie are we running in the same request that installed the module). if (module.DesktopModule.SupportedFeatures == Null.NullInteger) { // save content in eventqueue for processing after an app restart, // as modules Supported Features are not updated yet so we // cannot determine if the module supports IsPortable strcontent = HttpContext.Current.Server.HtmlEncode(strcontent); CreateEventQueueMessage(module, strcontent, strVersion, portal.AdministratorId); } else { if (module.DesktopModule.IsPortable) { try { var objObject = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); if (objObject is IPortable2) { ((IPortable2) objObject).ImportModule(moduleId, tabId, strcontent, strVersion, portal.AdministratorId, isInstance); } else if (objObject is IPortable && ! isInstance) { ((IPortable) objObject).ImportModule(moduleId, strcontent, strVersion, portal.AdministratorId); } } catch { //ignore errors } } } } } static ModuleDefinitionInfo GetModuleDefinition(XmlNode nodeModule) { ModuleDefinitionInfo objModuleDefinition = null; // Templates prior to v4.3.5 only have the <definition> node to define the Module Type // This <definition> node was populated with the DesktopModuleInfo.ModuleName property // Thus there is no mechanism to determine to which module definition the module belongs. // // Template from v4.3.5 on also have the <moduledefinition> element that is populated // with the ModuleDefinitionInfo.FriendlyName. Therefore the module Instance identifies // which Module Definition it belongs to. //Get the DesktopModule defined by the <definition> element var objDesktopModule = DesktopModuleController.GetDesktopModuleByModuleName( XmlUtils.GetNodeValue(nodeModule, "definition", ""), Null.NullInteger); if (objDesktopModule != null) { //Get the moduleDefinition from the <moduledefinition> element var friendlyName = XmlUtils.GetNodeValue(nodeModule, "moduledefinition", ""); if (string.IsNullOrEmpty(friendlyName)) { //Module is pre 4.3.5 so get the first Module Definition (at least it won't throw an error then) var moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID( objDesktopModule.DesktopModuleID).Values; foreach ( var moduleDefinition in moduleDefinitions) { objModuleDefinition = moduleDefinition; break; } } else { //Module is 4.3.5 or later so get the Module Definition by its friendly name objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName, objDesktopModule. DesktopModuleID); } } return objModuleDefinition; } #endregion #region Public Shared Methods public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) { var moduleController = new ModuleController(); var objModuleDefinition = GetModuleDefinition(nodeModule); // will be instance or module var templateModuleId = XmlUtils.GetNodeValueInt(nodeModule, "moduleID"); var isInstance = CheckIsInstance(templateModuleId, hModules); //remove containersrc node if container is missing var containerNode = nodeModule.SelectSingleNode("containersrc"); if (containerNode != null) { var container = containerNode.Value; if (! File.Exists(HttpContext.Current.Server.MapPath(container))) { nodeModule.RemoveChild(containerNode); } } if (objModuleDefinition != null) { //If Mode is Merge Check if Module exists if (! FindModule(nodeModule, tabId, mergeTabs)) { var module = DeserializeModule(nodeModule, nodePane, portalId, tabId, objModuleDefinition.ModuleDefID); int intModuleId; if (! isInstance) { //Add new module intModuleId = moduleController.AddModule(module); if (templateModuleId > 0) { hModules.Add(templateModuleId, intModuleId); } } else { //Add instance module.ModuleID = Convert.ToInt32(hModules[templateModuleId]); intModuleId = moduleController.AddModule(module); } if (XmlUtils.GetNodeValue(nodeModule, "content", "") != "") { GetModuleContent(nodeModule, intModuleId, tabId, portalId, isInstance); } // Process permissions and moduleSettings only once if (! isInstance) { var nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); DeserializeModulePermissions(nodeModulePermissions, portalId, module); //Persist the permissions to the Data base ModulePermissionController.SaveModulePermissions(module); var nodeModuleSettings = nodeModule.SelectNodes("modulesettings/setting"); DeserializeModuleSettings(nodeModuleSettings, intModuleId); } //apply TabModuleSettings var nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/setting"); DeserializeTabModuleSettings(nodeTabModuleSettings, intModuleId, tabId); } } } /// <summary> /// SerializeModule /// </summary> /// <param name="xmlModule"> The Xml Document to use for the Module </param> /// <param name="objModule"> The ModuleInfo object to serialize </param> /// <param name="includeContent"> A flak that determines whether the content of the module is serialised. </param> public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo objModule, bool includeContent) { return SerializeModule(xmlModule, objModule, includeContent, Null.NullInteger); } /// <summary> /// SerializeModule /// </summary> /// <param name="xmlModule"> The Xml Document to use for the Module </param> /// <param name="objModule"> The ModuleInfo object to serialize </param> /// <param name="includeContent"> A flak that determines whether the content of the module is serialised. </param> /// <param name="maxNumberofRecords"> Numer of reords. Choose Null.NullInteger (-1) to include all records </param> public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo objModule, bool includeContent, int maxNumberofRecords) { var xserModules = new XmlSerializer(typeof (ModuleInfo)); using (var sw = new StringWriter()) { xserModules.Serialize(sw, objModule); xmlModule.LoadXml((sw.GetStringBuilder().ToString())); } var nodeModule = xmlModule.SelectSingleNode("module"); // ReSharper disable PossibleNullReferenceException nodeModule.Attributes.Remove(nodeModule.Attributes["xmlns:xsd"]); nodeModule.Attributes.Remove(nodeModule.Attributes["xmlns:xsi"]); //remove unwanted elements // ReSharper disable AssignNullToNotNullAttribute nodeModule.RemoveChild(nodeModule.SelectSingleNode("portalid")); nodeModule.RemoveChild(nodeModule.SelectSingleNode("tabid")); nodeModule.RemoveChild(nodeModule.SelectSingleNode("tabmoduleid")); nodeModule.RemoveChild(nodeModule.SelectSingleNode("moduleorder")); nodeModule.RemoveChild(nodeModule.SelectSingleNode("panename")); nodeModule.RemoveChild(nodeModule.SelectSingleNode("isdeleted")); foreach (XmlNode nodePermission in nodeModule.SelectNodes("modulepermissions/permission")) { nodePermission.RemoveChild(nodePermission.SelectSingleNode("modulepermissionid")); nodePermission.RemoveChild(nodePermission.SelectSingleNode("permissionid")); nodePermission.RemoveChild(nodePermission.SelectSingleNode("moduleid")); nodePermission.RemoveChild(nodePermission.SelectSingleNode("roleid")); nodePermission.RemoveChild(nodePermission.SelectSingleNode("userid")); nodePermission.RemoveChild(nodePermission.SelectSingleNode("username")); nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); } // ReSharper restore AssignNullToNotNullAttribute // ReSharper restore PossibleNullReferenceException if (includeContent) { AddContent(nodeModule, objModule, maxNumberofRecords); AddSettings(nodeModule, objModule); } XmlNode newnode = xmlModule.CreateElement("definition"); var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(objModule.ModuleDefID); newnode.InnerText = DesktopModuleController.GetDesktopModule(objModuleDef.DesktopModuleID, objModule.PortalID).ModuleName; nodeModule.AppendChild(newnode); //Add Module Definition Info XmlNode nodeDefinition = xmlModule.CreateElement("moduledefinition"); nodeDefinition.InnerText = objModuleDef.FriendlyName; nodeModule.AppendChild(nodeDefinition); return nodeModule; } #endregion } }
// Copyright ? 2013 - 2014, Alain Metge. All rights reserved. // // This file is part of Hyperstore (http://www.hyperstore.org) // // 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 Xunit; using System; using System.Threading.Tasks; using Hyperstore.Modeling; using System.Diagnostics; using Hyperstore.Modeling.MemoryStore; using System.Linq; using Hyperstore.Modeling.Domain; using Hyperstore.Modeling.Metadata; using System.Globalization; using Hyperstore.Tests.Model; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #endif namespace Hyperstore.Tests { public class DomainModelTest : HyperstoreTestBase { [Fact] public async Task ReferenceInRelationshipTest() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); XReferencesY rel = null; using (var s = store.BeginSession()) { var start = new XExtendsBaseClass(dm); var end = new YClass(dm); rel = new XReferencesY(start, end); rel.YRelation = end; s.AcceptChanges(); } Assert.NotNull(rel); Assert.NotNull(rel.YRelation); } [Fact] public async Task SetReferenceTest() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); XExtendsBaseClass x = null; YClass y = null; using (var s = store.BeginSession()) { x = new XExtendsBaseClass(dm); y = new YClass(dm) { Name = "1" }; x.YRelation = y; s.AcceptChanges(); } Assert.Equal(x.YRelation, y); Assert.Equal(x.YRelation.X, x); Assert.Equal(y.X, x); var rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); Assert.Equal(rel.Start, x); Assert.Equal(rel.End, y); using (var s = store.BeginSession()) { y = new YClass(dm) { Name = "2" }; x.YRelation = y; s.AcceptChanges(); } Assert.Equal(x.YRelation, y); Assert.Equal(x.YRelation.X, x); Assert.Equal(x.GetRelationships<XReferencesY>().Count(), 1); rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); Assert.Equal(rel.Start, x); Assert.Equal(rel.End, y); } [Fact] public async Task SetReferenceFromOppositeTest() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); XExtendsBaseClass x = null; YClass y = null; using (var s = store.BeginSession()) { x = new XExtendsBaseClass(dm); y = new YClass(dm) { Name = "1" }; y.X = x; s.AcceptChanges(); } Assert.Equal(x.YRelation, y); Assert.Equal(x.YRelation.X, x); Assert.Equal(y.X, x); var rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); Assert.Equal(rel.Start, x); Assert.Equal(rel.End, y); using (var s = store.BeginSession()) { y = new YClass(dm) { Name = "2" }; x.YRelation = y; s.AcceptChanges(); } Assert.Equal(x.YRelation, y); Assert.Equal(x.YRelation.X, x); Assert.Equal(x.GetRelationships<XReferencesY>().Count(), 1); rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); Assert.Equal(rel.Start, x); Assert.Equal(rel.End, y); } [Fact] public async Task PropertyChangedOnSetReferenceTest() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().UsingIdGenerator(r => new LongIdGenerator()).CreateAsync("Test"); XExtendsBaseClass x = null; YClass y = null; var yrelationChanges = 0; var allPropertychanges = 0; using (var s = store.BeginSession()) { x = new XExtendsBaseClass(dm); s.AcceptChanges(); } x.PropertyChanged += (sender, e) => { allPropertychanges++; if (e.PropertyName == "YRelation") yrelationChanges++; }; using (var s = store.BeginSession()) { y = new YClass(dm) { Name = "1" }; x.YRelation = y; s.AcceptChanges(); } using (var s = store.BeginSession()) { y = new YClass(dm) { Name = "2" }; x.YRelation = y; s.AcceptChanges(); } var rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); using (var s = store.BeginSession()) { x.YRelation = null; s.AcceptChanges(); } Assert.Equal(3, yrelationChanges); Assert.Equal(3, allPropertychanges); } [Fact] public async Task SetReferenceToNullTest() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); XExtendsBaseClass x = null; YClass y = null; using (var s = store.BeginSession()) { x = new XExtendsBaseClass(dm); y = new YClass(dm) { Name = "1" }; x.YRelation = y; s.AcceptChanges(); } var rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); using (var s = store.BeginSession()) { x.YRelation = null; s.AcceptChanges(); } Assert.Equal(x.YRelation, null); Assert.Equal(((IModelElement)y).Status, ModelElementStatus.Disposed); Assert.Equal(x.GetRelationships<XReferencesY>().Count(), 0); } [Fact] public async Task SetReferenceToNullFromOppositeTest() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); XExtendsBaseClass x = null; YClass y = null; using (var s = store.BeginSession()) { x = new XExtendsBaseClass(dm); y = new YClass(dm) { Name = "1" }; x.YRelation = y; s.AcceptChanges(); } var rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); using (var s = store.BeginSession()) { y.X = null; s.AcceptChanges(); } Assert.Equal(x.YRelation, null); Assert.Equal(((IModelElement)y).Status, ModelElementStatus.Disposed); Assert.Equal(x.GetRelationships<XReferencesY>().Count(), 0); } [Fact] public async Task SetReferenceToNullFromOpposite2Test() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); XExtendsBaseClass x = null; YClass y = null; using (var s = store.BeginSession()) { x = new XExtendsBaseClass(dm); y = new YClass(dm) { Name = "1" }; new XReferencesY(x, y); s.AcceptChanges(); } var rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); using (var s = store.BeginSession()) { y.X = null; // TODO Since it's an embedded relationship and y is the opposite, y is deleted. Is it the wright behavior ??? s.AcceptChanges(); } Assert.Equal(x.YRelation, null); Assert.Equal(x.GetRelationships<XReferencesY>().Count(), 0); using (var s = store.BeginSession()) { y = new YClass(dm) { Name = "1" }; new XReferencesY(x, y); s.AcceptChanges(); } rel = x.GetRelationships<XReferencesY>().FirstOrDefault(); using (var s = store.BeginSession()) { x.YRelation = null; s.AcceptChanges(); } Assert.Equal(x.YRelation, null); Assert.Equal(((IModelElement)y).Status, ModelElementStatus.Disposed); Assert.Equal(x.GetRelationships<XReferencesY>().Count(), 0); } [Fact] public async Task EmbeddedRelationship() { var store = await StoreBuilder.New().CreateAsync(); var schema = await store.Schemas.New<LibraryDefinition>().CreateAsync(); var dm = await store.DomainModels.New().CreateAsync("Test"); Library lib; Book b; using (var s = store.BeginSession()) { lib = new Library(dm); lib.Name = "Library"; b = new Book(dm); b.Title = "book"; b.Copies = 1; lib.Books.Add(b); s.AcceptChanges(); } using (var s = store.BeginSession()) { lib.Books.Remove(b); s.AcceptChanges(); } Assert.Null(dm.GetElement<Book>(((IModelElement)b).Id)); Assert.Equal(0, lib.Books.Count()); } } }
// // assembly: System // namespace: System.Text.RegularExpressions // file: interpreter.cs // // author: Dan Lewis (dlewis@gmx.co.uk) // (c) 2002 // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { class Interpreter : IMachine { public Interpreter (ushort[] program) { this.program = program; this.qs = null; // process info block //Debug.Assert ((OpCode)program[0] == OpCode.Info, "Regex", "Cant' find info block"); this.group_count = program[1] + 1; this.match_min = program[2]; //this.match_max = program[3]; // setup this.program_start = 4; this.groups = new int [group_count]; } // IMachine implementation public Match Scan (Regex regex, string text, int start, int end) { this.text = text; this.text_end = end; this.scan_ptr = start; if (Eval (Mode.Match, ref scan_ptr, program_start)) return GenerateMatch (regex); return Match.Empty; } // private methods private void Reset () { ResetGroups (); fast = repeat = null; } private bool Eval (Mode mode, ref int ref_ptr, int pc) { int ptr = ref_ptr; Begin: for (;;) { ushort word = program[pc]; OpCode op = (OpCode)(word & 0x00ff); OpFlags flags = (OpFlags)(word & 0xff00); switch (op) { case OpCode.Anchor: { int skip = program[pc + 1]; int anch_offset = program[pc + 2]; bool anch_reverse = (flags & OpFlags.RightToLeft) != 0; int anch_ptr = anch_reverse ? ptr - anch_offset : ptr + anch_offset; int anch_end = text_end - match_min + anch_offset; // maximum anchor position int anch_begin = 0; // the general case for an anchoring expression is at the bottom, however we // do some checks for the common cases before to save processing time. the current // optimizer only outputs three types of anchoring expressions: fixed position, // fixed substring, and no anchor. OpCode anch_op = (OpCode)(program[pc + 3] & 0x00ff); if (anch_op == OpCode.Position && skip == 6) { // position anchor // Anchor // Position // True switch ((Position)program[pc + 4]) { case Position.StartOfString: if (anch_reverse || anch_offset == 0) { ptr = anch_offset; if (TryMatch (ref ptr, pc + skip)) goto Pass; } break; case Position.StartOfLine: if (anch_ptr == 0) { ptr = 0; if (TryMatch (ref ptr, pc + skip)) goto Pass; ++ anch_ptr; } while ((anch_reverse && anch_ptr >= 0) || (!anch_reverse && anch_ptr <= anch_end)) { if (anch_ptr == 0 || text[anch_ptr - 1] == '\n') { if (anch_reverse) ptr = anch_ptr == anch_end ? anch_ptr : anch_ptr + anch_offset; else ptr = anch_ptr == 0 ? anch_ptr : anch_ptr - anch_offset; if (TryMatch (ref ptr, pc + skip)) goto Pass; } if (anch_reverse) -- anch_ptr; else ++ anch_ptr; } break; case Position.StartOfScan: if (anch_ptr == scan_ptr) { ptr = anch_reverse ? scan_ptr + anch_offset : scan_ptr - anch_offset; if (TryMatch (ref ptr, pc + skip)) goto Pass; } break; default: // FIXME break; } } else if (qs != null || (anch_op == OpCode.String && skip == 6 + program[pc + 4])) { // substring anchor // Anchor // String // True bool reverse = ((OpFlags)program[pc + 3] & OpFlags.RightToLeft) != 0; string substring = GetString (pc + 3); if (qs == null) { bool ignore = ((OpFlags)program[pc + 3] & OpFlags.IgnoreCase) != 0; qs = new QuickSearch (substring, ignore, reverse); } while ((anch_reverse && anch_ptr >= anch_begin) || (!anch_reverse && anch_ptr <= anch_end)) { if (reverse) { anch_ptr = qs.Search (text, anch_ptr, anch_begin); if (anch_ptr != -1) anch_ptr += substring.Length ; } else anch_ptr = qs.Search (text, anch_ptr, anch_end); if (anch_ptr < 0) break; ptr = reverse ? anch_ptr + anch_offset : anch_ptr - anch_offset; if (TryMatch (ref ptr, pc + skip)) goto Pass; if (reverse) anch_ptr -= 2; else ++ anch_ptr; } } else if (anch_op == OpCode.True) { // no anchor // Anchor // True while ((anch_reverse && anch_ptr >= anch_begin) || (!anch_reverse && anch_ptr <= anch_end)) { ptr = anch_ptr; if (TryMatch (ref ptr, pc + skip)) goto Pass; if (anch_reverse) -- anch_ptr; else ++ anch_ptr; } } else { // general case // Anchor // <expr> // True while ((anch_reverse && anch_ptr >= anch_begin) || (!anch_reverse && anch_ptr <= anch_end)) { ptr = anch_ptr; if (Eval (Mode.Match, ref ptr, pc + 3)) { // anchor expression passed: try real expression at the correct offset ptr = anch_reverse ? anch_ptr + anch_offset : anch_ptr - anch_offset; if (TryMatch (ref ptr, pc + skip)) goto Pass; } if (anch_reverse) -- anch_ptr; else ++ anch_ptr; } } goto Fail; } case OpCode.False: { goto Fail; } case OpCode.True: { goto Pass; } case OpCode.Position: { if (!IsPosition ((Position)program[pc + 1], ptr)) goto Fail; pc += 2; break; } case OpCode.String: { bool reverse = (flags & OpFlags.RightToLeft) != 0; bool ignore = (flags & OpFlags.IgnoreCase) != 0; int len = program[pc + 1]; if (reverse) { ptr -= len; if (ptr < 0) goto Fail; } else if (ptr + len > text_end) goto Fail; pc += 2; for (int i = 0; i < len; ++ i) { char c = text[ptr + i]; if (ignore) c = Char.ToLower (c); if (c != (char)program[pc ++]) goto Fail; } if (!reverse) ptr += len; break; } case OpCode.Reference: { bool reverse = (flags & OpFlags.RightToLeft) != 0; bool ignore = (flags & OpFlags.IgnoreCase) != 0; int m = GetLastDefined (program [pc + 1]); if (m < 0) goto Fail; int str = marks [m].Index; int len = marks [m].Length; if (reverse) { ptr -= len; if (ptr < 0) goto Fail; } else if (ptr + len > text_end) goto Fail; pc += 2; for (int i = 0; i < len; ++ i) { if (ignore) { if (Char.ToLower (text[ptr + i]) != Char.ToLower (text[str + i])) goto Fail; } else { if (text[ptr + i] != text[str + i]) goto Fail; } } if (!reverse) ptr += len; break; } case OpCode.Character: case OpCode.Category: case OpCode.Range: case OpCode.Set: { if (!EvalChar (mode, ref ptr, ref pc, false)) goto Fail; break; } case OpCode.In: { int target = pc + program[pc + 1]; pc += 2; if (!EvalChar (mode, ref ptr, ref pc, true)) goto Fail; pc = target; break; } case OpCode.Open: { Open (program[pc + 1], ptr); pc += 2; break; } case OpCode.Close: { Close (program[pc + 1], ptr); pc += 2; break; } case OpCode.BalanceStart: { int start = ptr; //point before the balancing group if (!Eval (Mode.Match, ref ptr, pc + 5)) goto Fail; if(!Balance (program[pc + 1], program[pc + 2], (program[pc + 3] == 1 ? true : false) , start)) { goto Fail; } pc += program[pc + 4]; break; } case OpCode.Balance: { goto Pass; } case OpCode.IfDefined: { int m = GetLastDefined (program [pc + 2]); if (m < 0) pc += program[pc + 1]; else pc += 3; break; } case OpCode.Sub: { if (!Eval (Mode.Match, ref ptr, pc + 2)) goto Fail; pc += program[pc + 1]; break; } case OpCode.Test: { int cp = Checkpoint (); int test_ptr = ptr; if (Eval (Mode.Match, ref test_ptr, pc + 3)) pc += program[pc + 1]; else { Backtrack (cp); pc += program[pc + 2]; } break; } case OpCode.Branch: { OpCode branch_op; do { int cp = Checkpoint (); if (Eval (Mode.Match, ref ptr, pc + 2)) goto Pass; Backtrack (cp); pc += program[pc + 1]; branch_op = (OpCode)(program[pc] & 0xff); } while (branch_op != OpCode.False); goto Fail; } case OpCode.Jump: { pc += program[pc + 1]; break; } case OpCode.Repeat: { this.repeat = new RepeatContext ( this.repeat, // previous context program[pc + 2], // minimum program[pc + 3], // maximum (flags & OpFlags.Lazy) != 0, // lazy pc + 4 // subexpression ); if (Eval (Mode.Match, ref ptr, pc + program[pc + 1])) goto Pass; else { this.repeat = this.repeat.Previous; goto Fail; } } case OpCode.Until: { RepeatContext current = this.repeat; int start = current.Start; if (!current.IsMinimum) { ++ current.Count; current.Start = ptr; if (Eval (Mode.Match, ref ptr, repeat.Expression)) goto Pass; current.Start = start; -- current.Count; goto Fail; } if (ptr == current.Start) { // degenerate match ... match tail or fail this.repeat = current.Previous; if (Eval (Mode.Match, ref ptr, pc + 1)) goto Pass; this.repeat = current; goto Fail; } if (current.IsLazy) { // match tail first ... this.repeat = current.Previous; int cp = Checkpoint (); if (Eval (Mode.Match, ref ptr, pc + 1)) goto Pass; Backtrack (cp); // ... then match more this.repeat = current; if (!current.IsMaximum) { ++ current.Count; current.Start = ptr; if (Eval (Mode.Match, ref ptr, current.Expression)) goto Pass; current.Start = start; -- current.Count; goto Fail; } return false; } else { // match more first ... if (!current.IsMaximum) { int cp = Checkpoint (); ++ current.Count; current.Start = ptr; if (Eval (Mode.Match, ref ptr, current.Expression)) goto Pass; current.Start = start; -- current.Count; Backtrack (cp); } // ... then match tail this.repeat = current.Previous; if (Eval (Mode.Match, ref ptr, pc + 1)) goto Pass; this.repeat = current; goto Fail; } } case OpCode.FastRepeat: { this.fast = new RepeatContext ( fast, program[pc + 2], // minimum program[pc + 3], // maximum (flags & OpFlags.Lazy) != 0, // lazy pc + 4 // subexpression ); fast.Start = ptr; int cp = Checkpoint (); pc += program[pc + 1]; // tail expression ushort tail_word = program[pc]; int c1, c2; // first character of tail operator int coff; // 0 or -1 depending on direction OpCode tail_op = (OpCode)(tail_word & 0xff); if (tail_op == OpCode.Character || tail_op == OpCode.String) { OpFlags tail_flags = (OpFlags)(tail_word & 0xff00); if (tail_op == OpCode.String) { int offset = 0; if ((tail_flags & OpFlags.RightToLeft) != 0) { offset = program[pc + 1] - 1 ; } c1 = program[pc + 2 + offset]; // first char of string } else c1 = program[pc + 1]; // character if ((tail_flags & OpFlags.IgnoreCase) != 0) c2 = Char.ToUpper ((char)c1); // ignore case else c2 = c1; if ((tail_flags & OpFlags.RightToLeft) != 0) coff = -1; // reverse else coff = 0; } else { c1 = c2 = -1; coff = 0; } if (fast.IsLazy) { if (!fast.IsMinimum && !Eval (Mode.Count, ref ptr, fast.Expression)) { //Console.WriteLine ("lazy fast: failed mininum."); fast = fast.Previous; goto Fail; } while (true) { int p = ptr + coff; if ((c1 < 0 || (p >= 0 && p < text_end && (c1 == text[p] || c2 == text[p]))) && Eval (Mode.Match, ref ptr, pc)) break; if (fast.IsMaximum) { //Console.WriteLine ("lazy fast: failed with maximum."); fast = fast.Previous; goto Fail; } Backtrack (cp); if (!Eval (Mode.Count, ref ptr, fast.Expression)) { //Console.WriteLine ("lazy fast: no more."); fast = fast.Previous; goto Fail; } } fast = fast.Previous; goto Pass; } else { if (!Eval (Mode.Count, ref ptr, fast.Expression)) { fast = fast.Previous; goto Fail; } int width; if (fast.Count > 0) width = (ptr - fast.Start) / fast.Count; else width = 0; while (true) { int p = ptr + coff; if ((c1 < 0 || (p >= 0 && p < text_end && (c1 == text[p] || c2 == text[p]))) && Eval (Mode.Match, ref ptr, pc)) break; -- fast.Count; if (!fast.IsMinimum) { fast = fast.Previous; goto Fail; } ptr -= width; Backtrack (cp); } fast = fast.Previous; goto Pass; } } case OpCode.Info: { //Debug.Assert (false, "Regex", "Info block found in pattern"); goto Fail; } } } Pass: ref_ptr = ptr; switch (mode) { case Mode.Match: return true; case Mode.Count: { ++ fast.Count; if (fast.IsMaximum || (fast.IsLazy && fast.IsMinimum)) return true; pc = fast.Expression; goto Begin; } } Fail: switch (mode) { case Mode.Match: return false; case Mode.Count: { if (!fast.IsLazy && fast.IsMinimum) return true; ref_ptr = fast.Start; return false; } } return false; } private bool EvalChar (Mode mode, ref int ptr, ref int pc, bool multi) { bool consumed = false; char c = '\0'; bool negate; bool ignore; do { ushort word = program[pc]; OpCode op = (OpCode)(word & 0x00ff); OpFlags flags = (OpFlags)(word & 0xff00); ++ pc; ignore = (flags & OpFlags.IgnoreCase) != 0; // consume character: the direction of an In construct is // determined by the direction of its first op if (!consumed) { if ((flags & OpFlags.RightToLeft) != 0) { if (ptr <= 0) return false; c = text[-- ptr]; } else { if (ptr >= text_end) return false; c = text[ptr ++]; } if (ignore) c = Char.ToLower (c); consumed = true; } // negate flag negate = (flags & OpFlags.Negate) != 0; // execute op switch (op) { case OpCode.True: return true; case OpCode.False: return false; case OpCode.Character: { if (c == (char)program[pc ++]) return !negate; break; } case OpCode.Category: { if (CategoryUtils.IsCategory ((Category)program[pc ++], c)) return !negate; break; } case OpCode.Range: { int lo = (char)program[pc ++]; int hi = (char)program[pc ++]; if (lo <= c && c <= hi) return !negate; break; } case OpCode.Set: { int lo = (char)program[pc ++]; int len = (char)program[pc ++]; int bits = pc; pc += len; int i = (int)c - lo; if (i < 0 || i >= len << 4) break; if ((program[bits + (i >> 4)] & (1 << (i & 0xf))) != 0) return !negate; break; } } } while (multi); return negate; } private bool TryMatch (ref int ref_ptr, int pc) { Reset (); int ptr = ref_ptr; marks [groups [0]].Start = ptr; if (Eval (Mode.Match, ref ptr, pc)) { marks [groups [0]].End = ptr; ref_ptr = ptr; return true; } return false; } private bool IsPosition (Position pos, int ptr) { switch (pos) { case Position.Start: case Position.StartOfString: return ptr == 0; case Position.StartOfLine: return ptr == 0 || text[ptr - 1] == '\n'; case Position.StartOfScan: return ptr == scan_ptr; case Position.End: return ptr == text_end || (ptr == text_end - 1 && text[ptr] == '\n'); case Position.EndOfLine: return ptr == text_end || text[ptr] == '\n'; case Position.EndOfString: return ptr == text_end; case Position.Boundary: if (text_end == 0) return false; if (ptr == 0) return IsWordChar (text[ptr]); else if (ptr == text_end) return IsWordChar (text[ptr - 1]); else return IsWordChar (text[ptr]) != IsWordChar (text[ptr - 1]); case Position.NonBoundary: if (text_end == 0) return false; if (ptr == 0) return !IsWordChar (text[ptr]); else if (ptr == text_end) return !IsWordChar (text[ptr - 1]); else return IsWordChar (text[ptr]) == IsWordChar (text[ptr - 1]); default: return false; } } private bool IsWordChar (char c) { return CategoryUtils.IsCategory (Category.Word, c); } private string GetString (int pc) { int len = program[pc + 1]; int str = pc + 2; char[] cs = new char[len]; for (int i = 0; i < len; ++ i) cs[i] = (char)program[str ++]; return new string (cs); } // capture management private void Open (int gid, int ptr) { int m = groups [gid]; if (m < mark_start || marks [m].IsDefined) { m = CreateMark (m); groups [gid] = m; } marks [m].Start = ptr; } private void Close (int gid, int ptr) { marks [groups [gid]].End = ptr; } private bool Balance (int gid, int balance_gid, bool capture, int ptr) { int b = groups [balance_gid]; if(b == -1 || marks[b].Index < 0) { //Group not previously matched return false; } //Debug.Assert (marks [b].IsDefined, "Regex", "Balancng group not closed"); if (gid > 0 && capture){ Open (gid, marks [b].Index + marks [b].Length); Close (gid, ptr); } groups [balance_gid] = marks[b].Previous; return true; } private int Checkpoint () { mark_start = mark_end; return mark_start; } private void Backtrack (int cp) { //Debug.Assert (cp > mark_start, "Regex", "Attempt to backtrack forwards"); for (int i = 0; i < groups.Length; ++ i) { int m = groups [i]; while (cp <= m) m = marks [m].Previous; groups [i] = m; } } private void ResetGroups () { int n = groups.Length; if (marks == null) marks = new Mark [n * 10]; for (int i = 0; i < n; ++ i) { groups [i] = i; marks [i].Start = -1; marks [i].End = -1; marks [i].Previous = -1; } mark_start = 0; mark_end = n; } private int GetLastDefined (int gid) { int m = groups [gid]; while (m >= 0 && !marks [m].IsDefined) m = marks [m].Previous; return m; } private int CreateMark (int previous) { if (mark_end == marks.Length) { Mark [] dest = new Mark [marks.Length * 2]; marks.CopyTo (dest, 0); marks = dest; } int m = mark_end ++; marks [m].Start = marks [m].End = -1; marks [m].Previous = previous; return m; } private void GetGroupInfo (int gid, out int first_mark_index, out int n_caps) { first_mark_index = -1; bool first = true; n_caps = 0; for (int m = groups [gid]; m >= 0; m = marks [m].Previous) { if (!marks [m].IsDefined) continue; ++n_caps; if (first) { first = false; first_mark_index = m; } } } private void PopulateGroup (Group g, int first_mark_index, int n_caps) { int i = 1; for (int m = marks [first_mark_index].Previous; m >= 0; m = marks [m].Previous) { if (!marks [m].IsDefined) continue; Capture cap = new Capture (text, marks [m].Index, marks [m].Length); g.Captures.SetValue (cap, n_caps - 1 - i); ++i; } } private Match GenerateMatch (Regex regex) { int n_caps, first_mark_index; Group g; GetGroupInfo (0, out first_mark_index, out n_caps); Match retval = new Match (regex, this, text, text_end, groups.Length, marks [first_mark_index].Index, marks [first_mark_index].Length, n_caps); PopulateGroup (retval, first_mark_index, n_caps); for (int gid = 1; gid < groups.Length; ++ gid) { GetGroupInfo (gid, out first_mark_index, out n_caps); if (first_mark_index < 0) { g = Group.Fail; } else { g = new Group (text, marks [first_mark_index].Index, marks [first_mark_index].Length, n_caps); PopulateGroup (g, first_mark_index, n_caps); } retval.Groups.SetValue (g, gid); } return retval; } // interpreter attributes private ushort[] program; // regex program private int program_start; // first instruction after info block private string text; // input text private int text_end; // end of input text (last character + 1) private int group_count; // number of capturing groups private int match_min;//, match_max; // match width information private QuickSearch qs; // fast substring matcher // match state private int scan_ptr; // start of scan private RepeatContext repeat; // current repeat context private RepeatContext fast; // fast repeat context private Mark[] marks = null; // mark stack private int mark_start; // start of current checkpoint private int mark_end; // end of checkpoint/next free mark private int[] groups; // current group definitions // private classes /* private struct Mark { public int Start, End; public int Previous; public bool IsDefined { get { return Start >= 0 && End >= 0; } } public int Index { get { return Start < End ? Start : End; } } public int Length { get { return Start < End ? End - Start : Start - End; } } } */ private class RepeatContext { public RepeatContext (RepeatContext previous, int min, int max, bool lazy, int expr_pc) { this.previous = previous; this.min = min; this.max = max; this.lazy = lazy; this.expr_pc = expr_pc; this.start = -1; this.count = 0; } public int Count { get { return count; } set { count = value; } } public int Start { get { return start; } set { start = value; } } public bool IsMinimum { get { return min <= count; } } public bool IsMaximum { get { return max <= count; } } public bool IsLazy { get { return lazy; } } public int Expression { get { return expr_pc; } } public RepeatContext Previous { get { return previous; } } private int start; private int min, max; private bool lazy; private int expr_pc; private RepeatContext previous; private int count; } private enum Mode { Search, Match, Count } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="ChangeStatusServiceClient"/> instances.</summary> public sealed partial class ChangeStatusServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ChangeStatusServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ChangeStatusServiceSettings"/>.</returns> public static ChangeStatusServiceSettings GetDefault() => new ChangeStatusServiceSettings(); /// <summary>Constructs a new <see cref="ChangeStatusServiceSettings"/> object with default settings.</summary> public ChangeStatusServiceSettings() { } private ChangeStatusServiceSettings(ChangeStatusServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetChangeStatusSettings = existing.GetChangeStatusSettings; OnCopy(existing); } partial void OnCopy(ChangeStatusServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ChangeStatusServiceClient.GetChangeStatus</c> and <c>ChangeStatusServiceClient.GetChangeStatusAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetChangeStatusSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ChangeStatusServiceSettings"/> object.</returns> public ChangeStatusServiceSettings Clone() => new ChangeStatusServiceSettings(this); } /// <summary> /// Builder class for <see cref="ChangeStatusServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class ChangeStatusServiceClientBuilder : gaxgrpc::ClientBuilderBase<ChangeStatusServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ChangeStatusServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ChangeStatusServiceClientBuilder() { UseJwtAccessWithScopes = ChangeStatusServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ChangeStatusServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ChangeStatusServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ChangeStatusServiceClient Build() { ChangeStatusServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ChangeStatusServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ChangeStatusServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ChangeStatusServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ChangeStatusServiceClient.Create(callInvoker, Settings); } private async stt::Task<ChangeStatusServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ChangeStatusServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ChangeStatusServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ChangeStatusServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ChangeStatusServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ChangeStatusService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch change statuses. /// </remarks> public abstract partial class ChangeStatusServiceClient { /// <summary> /// The default endpoint for the ChangeStatusService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ChangeStatusService scopes.</summary> /// <remarks> /// The default ChangeStatusService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ChangeStatusServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="ChangeStatusServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ChangeStatusServiceClient"/>.</returns> public static stt::Task<ChangeStatusServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ChangeStatusServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ChangeStatusServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="ChangeStatusServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ChangeStatusServiceClient"/>.</returns> public static ChangeStatusServiceClient Create() => new ChangeStatusServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ChangeStatusServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ChangeStatusServiceSettings"/>.</param> /// <returns>The created <see cref="ChangeStatusServiceClient"/>.</returns> internal static ChangeStatusServiceClient Create(grpccore::CallInvoker callInvoker, ChangeStatusServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ChangeStatusService.ChangeStatusServiceClient grpcClient = new ChangeStatusService.ChangeStatusServiceClient(callInvoker); return new ChangeStatusServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ChangeStatusService client</summary> public virtual ChangeStatusService.ChangeStatusServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ChangeStatus GetChangeStatus(GetChangeStatusRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(GetChangeStatusRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(GetChangeStatusRequest request, st::CancellationToken cancellationToken) => GetChangeStatusAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the change status to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ChangeStatus GetChangeStatus(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetChangeStatus(new GetChangeStatusRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the change status to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetChangeStatusAsync(new GetChangeStatusRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the change status to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(string resourceName, st::CancellationToken cancellationToken) => GetChangeStatusAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the change status to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ChangeStatus GetChangeStatus(gagvr::ChangeStatusName resourceName, gaxgrpc::CallSettings callSettings = null) => GetChangeStatus(new GetChangeStatusRequest { ResourceNameAsChangeStatusName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the change status to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(gagvr::ChangeStatusName resourceName, gaxgrpc::CallSettings callSettings = null) => GetChangeStatusAsync(new GetChangeStatusRequest { ResourceNameAsChangeStatusName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the change status to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(gagvr::ChangeStatusName resourceName, st::CancellationToken cancellationToken) => GetChangeStatusAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ChangeStatusService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch change statuses. /// </remarks> public sealed partial class ChangeStatusServiceClientImpl : ChangeStatusServiceClient { private readonly gaxgrpc::ApiCall<GetChangeStatusRequest, gagvr::ChangeStatus> _callGetChangeStatus; /// <summary> /// Constructs a client wrapper for the ChangeStatusService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ChangeStatusServiceSettings"/> used within this client.</param> public ChangeStatusServiceClientImpl(ChangeStatusService.ChangeStatusServiceClient grpcClient, ChangeStatusServiceSettings settings) { GrpcClient = grpcClient; ChangeStatusServiceSettings effectiveSettings = settings ?? ChangeStatusServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetChangeStatus = clientHelper.BuildApiCall<GetChangeStatusRequest, gagvr::ChangeStatus>(grpcClient.GetChangeStatusAsync, grpcClient.GetChangeStatus, effectiveSettings.GetChangeStatusSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetChangeStatus); Modify_GetChangeStatusApiCall(ref _callGetChangeStatus); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetChangeStatusApiCall(ref gaxgrpc::ApiCall<GetChangeStatusRequest, gagvr::ChangeStatus> call); partial void OnConstruction(ChangeStatusService.ChangeStatusServiceClient grpcClient, ChangeStatusServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ChangeStatusService client</summary> public override ChangeStatusService.ChangeStatusServiceClient GrpcClient { get; } partial void Modify_GetChangeStatusRequest(ref GetChangeStatusRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::ChangeStatus GetChangeStatus(GetChangeStatusRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetChangeStatusRequest(ref request, ref callSettings); return _callGetChangeStatus.Sync(request, callSettings); } /// <summary> /// Returns the requested change status in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::ChangeStatus> GetChangeStatusAsync(GetChangeStatusRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetChangeStatusRequest(ref request, ref callSettings); return _callGetChangeStatus.Async(request, callSettings); } } }